1 | //! [![github]](https://github.com/dtolnay/syn) [![crates-io]](https://crates.io/crates/syn) [![docs-rs]](crate) |
2 | //! |
3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github |
4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust |
5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs |
6 | //! |
7 | //! <br> |
8 | //! |
9 | //! Syn is a parsing library for parsing a stream of Rust tokens into a syntax |
10 | //! tree of Rust source code. |
11 | //! |
12 | //! Currently this library is geared toward use in Rust procedural macros, but |
13 | //! contains some APIs that may be useful more generally. |
14 | //! |
15 | //! - **Data structures** — Syn provides a complete syntax tree that can |
16 | //! represent any valid Rust source code. The syntax tree is rooted at |
17 | //! [`syn::File`] which represents a full source file, but there are other |
18 | //! entry points that may be useful to procedural macros including |
19 | //! [`syn::Item`], [`syn::Expr`] and [`syn::Type`]. |
20 | //! |
21 | //! - **Derives** — Of particular interest to derive macros is |
22 | //! [`syn::DeriveInput`] which is any of the three legal input items to a |
23 | //! derive macro. An example below shows using this type in a library that can |
24 | //! derive implementations of a user-defined trait. |
25 | //! |
26 | //! - **Parsing** — Parsing in Syn is built around [parser functions] with the |
27 | //! signature `fn(ParseStream) -> Result<T>`. Every syntax tree node defined |
28 | //! by Syn is individually parsable and may be used as a building block for |
29 | //! custom syntaxes, or you may dream up your own brand new syntax without |
30 | //! involving any of our syntax tree types. |
31 | //! |
32 | //! - **Location information** — Every token parsed by Syn is associated with a |
33 | //! `Span` that tracks line and column information back to the source of that |
34 | //! token. These spans allow a procedural macro to display detailed error |
35 | //! messages pointing to all the right places in the user's code. There is an |
36 | //! example of this below. |
37 | //! |
38 | //! - **Feature flags** — Functionality is aggressively feature gated so your |
39 | //! procedural macros enable only what they need, and do not pay in compile |
40 | //! time for all the rest. |
41 | //! |
42 | //! [`syn::File`]: File |
43 | //! [`syn::Item`]: Item |
44 | //! [`syn::Expr`]: Expr |
45 | //! [`syn::Type`]: Type |
46 | //! [`syn::DeriveInput`]: DeriveInput |
47 | //! [parser functions]: mod@parse |
48 | //! |
49 | //! <br> |
50 | //! |
51 | //! # Example of a derive macro |
52 | //! |
53 | //! The canonical derive macro using Syn looks like this. We write an ordinary |
54 | //! Rust function tagged with a `proc_macro_derive` attribute and the name of |
55 | //! the trait we are deriving. Any time that derive appears in the user's code, |
56 | //! the Rust compiler passes their data structure as tokens into our macro. We |
57 | //! get to execute arbitrary Rust code to figure out what to do with those |
58 | //! tokens, then hand some tokens back to the compiler to compile into the |
59 | //! user's crate. |
60 | //! |
61 | //! [`TokenStream`]: proc_macro::TokenStream |
62 | //! |
63 | //! ```toml |
64 | //! [dependencies] |
65 | //! syn = "2.0" |
66 | //! quote = "1.0" |
67 | //! |
68 | //! [lib] |
69 | //! proc-macro = true |
70 | //! ``` |
71 | //! |
72 | //! ``` |
73 | //! # extern crate proc_macro; |
74 | //! # |
75 | //! use proc_macro::TokenStream; |
76 | //! use quote::quote; |
77 | //! use syn::{parse_macro_input, DeriveInput}; |
78 | //! |
79 | //! # const IGNORE_TOKENS: &str = stringify! { |
80 | //! #[proc_macro_derive(MyMacro)] |
81 | //! # }; |
82 | //! pub fn my_macro(input: TokenStream) -> TokenStream { |
83 | //! // Parse the input tokens into a syntax tree |
84 | //! let input = parse_macro_input!(input as DeriveInput); |
85 | //! |
86 | //! // Build the output, possibly using quasi-quotation |
87 | //! let expanded = quote! { |
88 | //! // ... |
89 | //! }; |
90 | //! |
91 | //! // Hand the output tokens back to the compiler |
92 | //! TokenStream::from(expanded) |
93 | //! } |
94 | //! ``` |
95 | //! |
96 | //! The [`heapsize`] example directory shows a complete working implementation |
97 | //! of a derive macro. The example derives a `HeapSize` trait which computes an |
98 | //! estimate of the amount of heap memory owned by a value. |
99 | //! |
100 | //! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize |
101 | //! |
102 | //! ``` |
103 | //! pub trait HeapSize { |
104 | //! /// Total number of bytes of heap memory owned by `self`. |
105 | //! fn heap_size_of_children(&self) -> usize; |
106 | //! } |
107 | //! ``` |
108 | //! |
109 | //! The derive macro allows users to write `#[derive(HeapSize)]` on data |
110 | //! structures in their program. |
111 | //! |
112 | //! ``` |
113 | //! # const IGNORE_TOKENS: &str = stringify! { |
114 | //! #[derive(HeapSize)] |
115 | //! # }; |
116 | //! struct Demo<'a, T: ?Sized> { |
117 | //! a: Box<T>, |
118 | //! b: u8, |
119 | //! c: &'a str, |
120 | //! d: String, |
121 | //! } |
122 | //! ``` |
123 | //! |
124 | //! <p><br></p> |
125 | //! |
126 | //! # Spans and error reporting |
127 | //! |
128 | //! The token-based procedural macro API provides great control over where the |
129 | //! compiler's error messages are displayed in user code. Consider the error the |
130 | //! user sees if one of their field types does not implement `HeapSize`. |
131 | //! |
132 | //! ``` |
133 | //! # const IGNORE_TOKENS: &str = stringify! { |
134 | //! #[derive(HeapSize)] |
135 | //! # }; |
136 | //! struct Broken { |
137 | //! ok: String, |
138 | //! bad: std::thread::Thread, |
139 | //! } |
140 | //! ``` |
141 | //! |
142 | //! By tracking span information all the way through the expansion of a |
143 | //! procedural macro as shown in the `heapsize` example, token-based macros in |
144 | //! Syn are able to trigger errors that directly pinpoint the source of the |
145 | //! problem. |
146 | //! |
147 | //! ```text |
148 | //! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied |
149 | //! --> src/main.rs:7:5 |
150 | //! | |
151 | //! 7 | bad: std::thread::Thread, |
152 | //! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread` |
153 | //! ``` |
154 | //! |
155 | //! <br> |
156 | //! |
157 | //! # Parsing a custom syntax |
158 | //! |
159 | //! The [`lazy-static`] example directory shows the implementation of a |
160 | //! `functionlike!(...)` procedural macro in which the input tokens are parsed |
161 | //! using Syn's parsing API. |
162 | //! |
163 | //! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static |
164 | //! |
165 | //! The example reimplements the popular `lazy_static` crate from crates.io as a |
166 | //! procedural macro. |
167 | //! |
168 | //! ``` |
169 | //! # macro_rules! lazy_static { |
170 | //! # ($($tt:tt)*) => {} |
171 | //! # } |
172 | //! # |
173 | //! lazy_static! { |
174 | //! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$" ).unwrap(); |
175 | //! } |
176 | //! ``` |
177 | //! |
178 | //! The implementation shows how to trigger custom warnings and error messages |
179 | //! on the macro input. |
180 | //! |
181 | //! ```text |
182 | //! warning: come on, pick a more creative name |
183 | //! --> src/main.rs:10:16 |
184 | //! | |
185 | //! 10 | static ref FOO: String = "lazy_static".to_owned(); |
186 | //! | ^^^ |
187 | //! ``` |
188 | //! |
189 | //! <br> |
190 | //! |
191 | //! # Testing |
192 | //! |
193 | //! When testing macros, we often care not just that the macro can be used |
194 | //! successfully but also that when the macro is provided with invalid input it |
195 | //! produces maximally helpful error messages. Consider using the [`trybuild`] |
196 | //! crate to write tests for errors that are emitted by your macro or errors |
197 | //! detected by the Rust compiler in the expanded code following misuse of the |
198 | //! macro. Such tests help avoid regressions from later refactors that |
199 | //! mistakenly make an error no longer trigger or be less helpful than it used |
200 | //! to be. |
201 | //! |
202 | //! [`trybuild`]: https://github.com/dtolnay/trybuild |
203 | //! |
204 | //! <br> |
205 | //! |
206 | //! # Debugging |
207 | //! |
208 | //! When developing a procedural macro it can be helpful to look at what the |
209 | //! generated code looks like. Use `cargo rustc -- -Zunstable-options |
210 | //! --pretty=expanded` or the [`cargo expand`] subcommand. |
211 | //! |
212 | //! [`cargo expand`]: https://github.com/dtolnay/cargo-expand |
213 | //! |
214 | //! To show the expanded code for some crate that uses your procedural macro, |
215 | //! run `cargo expand` from that crate. To show the expanded code for one of |
216 | //! your own test cases, run `cargo expand --test the_test_case` where the last |
217 | //! argument is the name of the test file without the `.rs` extension. |
218 | //! |
219 | //! This write-up by Brandon W Maister discusses debugging in more detail: |
220 | //! [Debugging Rust's new Custom Derive system][debugging]. |
221 | //! |
222 | //! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ |
223 | //! |
224 | //! <br> |
225 | //! |
226 | //! # Optional features |
227 | //! |
228 | //! Syn puts a lot of functionality behind optional features in order to |
229 | //! optimize compile time for the most common use cases. The following features |
230 | //! are available. |
231 | //! |
232 | //! - **`derive`** *(enabled by default)* — Data structures for representing the |
233 | //! possible input to a derive macro, including structs and enums and types. |
234 | //! - **`full`** — Data structures for representing the syntax tree of all valid |
235 | //! Rust source code, including items and expressions. |
236 | //! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into |
237 | //! a syntax tree node of a chosen type. |
238 | //! - **`printing`** *(enabled by default)* — Ability to print a syntax tree |
239 | //! node as tokens of Rust source code. |
240 | //! - **`visit`** — Trait for traversing a syntax tree. |
241 | //! - **`visit-mut`** — Trait for traversing and mutating in place a syntax |
242 | //! tree. |
243 | //! - **`fold`** — Trait for transforming an owned syntax tree. |
244 | //! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree |
245 | //! types. |
246 | //! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree |
247 | //! types. |
248 | //! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the |
249 | //! dynamic library libproc_macro from rustc toolchain. |
250 | |
251 | // Syn types in rustdoc of other crates get linked to here. |
252 | #![doc (html_root_url = "https://docs.rs/syn/2.0.53" )] |
253 | #![cfg_attr (doc_cfg, feature(doc_cfg))] |
254 | #![deny (unsafe_op_in_unsafe_fn)] |
255 | #![allow (non_camel_case_types)] |
256 | #![allow ( |
257 | clippy::bool_to_int_with_if, |
258 | clippy::cast_lossless, |
259 | clippy::cast_possible_truncation, |
260 | clippy::cast_possible_wrap, |
261 | clippy::cast_ptr_alignment, |
262 | clippy::default_trait_access, |
263 | clippy::derivable_impls, |
264 | clippy::diverging_sub_expression, |
265 | clippy::doc_markdown, |
266 | clippy::expl_impl_clone_on_copy, |
267 | clippy::explicit_auto_deref, |
268 | clippy::if_not_else, |
269 | clippy::inherent_to_string, |
270 | clippy::into_iter_without_iter, |
271 | clippy::items_after_statements, |
272 | clippy::large_enum_variant, |
273 | clippy::let_underscore_untyped, // https://github.com/rust-lang/rust-clippy/issues/10410 |
274 | clippy::manual_assert, |
275 | clippy::manual_let_else, |
276 | clippy::match_like_matches_macro, |
277 | clippy::match_on_vec_items, |
278 | clippy::match_same_arms, |
279 | clippy::match_wildcard_for_single_variants, // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984 |
280 | clippy::missing_errors_doc, |
281 | clippy::missing_panics_doc, |
282 | clippy::module_name_repetitions, |
283 | clippy::must_use_candidate, |
284 | clippy::needless_doctest_main, |
285 | clippy::needless_pass_by_value, |
286 | clippy::never_loop, |
287 | clippy::range_plus_one, |
288 | clippy::redundant_else, |
289 | clippy::return_self_not_must_use, |
290 | clippy::similar_names, |
291 | clippy::single_match_else, |
292 | clippy::too_many_arguments, |
293 | clippy::too_many_lines, |
294 | clippy::trivially_copy_pass_by_ref, |
295 | clippy::unconditional_recursion, // https://github.com/rust-lang/rust-clippy/issues/12133 |
296 | clippy::uninhabited_references, |
297 | clippy::uninlined_format_args, |
298 | clippy::unnecessary_box_returns, |
299 | clippy::unnecessary_unwrap, |
300 | clippy::used_underscore_binding, |
301 | clippy::wildcard_imports, |
302 | )] |
303 | |
304 | #[cfg (feature = "proc-macro" )] |
305 | extern crate proc_macro; |
306 | |
307 | #[macro_use ] |
308 | mod macros; |
309 | |
310 | #[cfg (feature = "parsing" )] |
311 | #[macro_use ] |
312 | mod group; |
313 | |
314 | #[macro_use ] |
315 | pub mod token; |
316 | |
317 | #[cfg (any(feature = "full" , feature = "derive" ))] |
318 | mod attr; |
319 | #[cfg (any(feature = "full" , feature = "derive" ))] |
320 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
321 | pub use crate::attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue}; |
322 | |
323 | mod bigint; |
324 | |
325 | #[cfg (feature = "parsing" )] |
326 | #[cfg_attr (doc_cfg, doc(cfg(feature = "parsing" )))] |
327 | pub mod buffer; |
328 | |
329 | mod custom_keyword; |
330 | |
331 | mod custom_punctuation; |
332 | |
333 | #[cfg (any(feature = "full" , feature = "derive" ))] |
334 | mod data; |
335 | #[cfg (any(feature = "full" , feature = "derive" ))] |
336 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
337 | pub use crate::data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant}; |
338 | |
339 | #[cfg (any(feature = "full" , feature = "derive" ))] |
340 | mod derive; |
341 | #[cfg (feature = "derive" )] |
342 | #[cfg_attr (doc_cfg, doc(cfg(feature = "derive" )))] |
343 | pub use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; |
344 | |
345 | mod drops; |
346 | |
347 | mod error; |
348 | pub use crate::error::{Error, Result}; |
349 | |
350 | #[cfg (any(feature = "full" , feature = "derive" ))] |
351 | mod expr; |
352 | #[cfg (feature = "full" )] |
353 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
354 | pub use crate::expr::{Arm, Label, RangeLimits}; |
355 | #[cfg (any(feature = "full" , feature = "derive" ))] |
356 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
357 | pub use crate::expr::{ |
358 | Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprIndex, ExprLit, ExprMacro, ExprMethodCall, |
359 | ExprParen, ExprPath, ExprReference, ExprStruct, ExprUnary, FieldValue, Index, Member, |
360 | }; |
361 | #[cfg (any(feature = "full" , feature = "derive" ))] |
362 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
363 | pub use crate::expr::{ |
364 | ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure, ExprConst, |
365 | ExprContinue, ExprForLoop, ExprGroup, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch, |
366 | ExprRange, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, ExprWhile, |
367 | ExprYield, |
368 | }; |
369 | |
370 | #[cfg (feature = "parsing" )] |
371 | #[cfg_attr (doc_cfg, doc(cfg(feature = "parsing" )))] |
372 | pub mod ext; |
373 | |
374 | #[cfg (feature = "full" )] |
375 | mod file; |
376 | #[cfg (feature = "full" )] |
377 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
378 | pub use crate::file::File; |
379 | |
380 | #[cfg (any(feature = "full" , feature = "derive" ))] |
381 | mod generics; |
382 | #[cfg (any(feature = "full" , feature = "derive" ))] |
383 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
384 | pub use crate::generics::{ |
385 | BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeParam, PredicateLifetime, |
386 | PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, WhereClause, |
387 | WherePredicate, |
388 | }; |
389 | #[cfg (all(any(feature = "full" , feature = "derive" ), feature = "printing" ))] |
390 | #[cfg_attr ( |
391 | doc_cfg, |
392 | doc(cfg(all(any(feature = "full" , feature = "derive" ), feature = "printing" ))) |
393 | )] |
394 | pub use crate::generics::{ImplGenerics, Turbofish, TypeGenerics}; |
395 | |
396 | mod ident; |
397 | #[doc (inline)] |
398 | pub use crate::ident::Ident; |
399 | |
400 | #[cfg (feature = "full" )] |
401 | mod item; |
402 | #[cfg (feature = "full" )] |
403 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
404 | pub use crate::item::{ |
405 | FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, |
406 | ImplItem, ImplItemConst, ImplItemFn, ImplItemMacro, ImplItemType, ImplRestriction, Item, |
407 | ItemConst, ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMod, |
408 | ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, |
409 | Signature, StaticMutability, TraitItem, TraitItemConst, TraitItemFn, TraitItemMacro, |
410 | TraitItemType, UseGlob, UseGroup, UseName, UsePath, UseRename, UseTree, Variadic, |
411 | }; |
412 | |
413 | mod lifetime; |
414 | #[doc (inline)] |
415 | pub use crate::lifetime::Lifetime; |
416 | |
417 | mod lit; |
418 | #[doc (hidden)] // https://github.com/dtolnay/syn/issues/1566 |
419 | pub use crate::lit::StrStyle; |
420 | #[doc (inline)] |
421 | pub use crate::lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; |
422 | |
423 | #[cfg (feature = "parsing" )] |
424 | mod lookahead; |
425 | |
426 | #[cfg (any(feature = "full" , feature = "derive" ))] |
427 | mod mac; |
428 | #[cfg (any(feature = "full" , feature = "derive" ))] |
429 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
430 | pub use crate::mac::{Macro, MacroDelimiter}; |
431 | |
432 | #[cfg (all(feature = "parsing" , any(feature = "full" , feature = "derive" )))] |
433 | #[cfg_attr ( |
434 | doc_cfg, |
435 | doc(cfg(all(feature = "parsing" , any(feature = "full" , feature = "derive" )))) |
436 | )] |
437 | pub mod meta; |
438 | |
439 | #[cfg (any(feature = "full" , feature = "derive" ))] |
440 | mod op; |
441 | #[cfg (any(feature = "full" , feature = "derive" ))] |
442 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
443 | pub use crate::op::{BinOp, UnOp}; |
444 | |
445 | #[cfg (feature = "parsing" )] |
446 | #[cfg_attr (doc_cfg, doc(cfg(feature = "parsing" )))] |
447 | pub mod parse; |
448 | |
449 | #[cfg (all(feature = "parsing" , feature = "proc-macro" ))] |
450 | mod parse_macro_input; |
451 | |
452 | #[cfg (all(feature = "parsing" , feature = "printing" ))] |
453 | mod parse_quote; |
454 | |
455 | #[cfg (feature = "full" )] |
456 | mod pat; |
457 | #[cfg (feature = "full" )] |
458 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
459 | pub use crate::pat::{ |
460 | FieldPat, Pat, PatConst, PatIdent, PatLit, PatMacro, PatOr, PatParen, PatPath, PatRange, |
461 | PatReference, PatRest, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatType, PatWild, |
462 | }; |
463 | |
464 | #[cfg (any(feature = "full" , feature = "derive" ))] |
465 | mod path; |
466 | #[cfg (any(feature = "full" , feature = "derive" ))] |
467 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
468 | pub use crate::path::{ |
469 | AngleBracketedGenericArguments, AssocConst, AssocType, Constraint, GenericArgument, |
470 | ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf, |
471 | }; |
472 | |
473 | #[cfg (all(any(feature = "full" , feature = "derive" ), feature = "printing" ))] |
474 | mod print; |
475 | |
476 | pub mod punctuated; |
477 | |
478 | #[cfg (any(feature = "full" , feature = "derive" ))] |
479 | mod restriction; |
480 | #[cfg (any(feature = "full" , feature = "derive" ))] |
481 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
482 | pub use crate::restriction::{FieldMutability, VisRestricted, Visibility}; |
483 | |
484 | mod sealed; |
485 | |
486 | mod span; |
487 | |
488 | #[cfg (all(feature = "parsing" , feature = "printing" ))] |
489 | #[cfg_attr (doc_cfg, doc(cfg(all(feature = "parsing" , feature = "printing" ))))] |
490 | pub mod spanned; |
491 | |
492 | #[cfg (feature = "full" )] |
493 | mod stmt; |
494 | #[cfg (feature = "full" )] |
495 | #[cfg_attr (doc_cfg, doc(cfg(feature = "full" )))] |
496 | pub use crate::stmt::{Block, Local, LocalInit, Stmt, StmtMacro}; |
497 | |
498 | mod thread; |
499 | |
500 | #[cfg (all(any(feature = "full" , feature = "derive" ), feature = "extra-traits" ))] |
501 | mod tt; |
502 | |
503 | #[cfg (any(feature = "full" , feature = "derive" ))] |
504 | mod ty; |
505 | #[cfg (any(feature = "full" , feature = "derive" ))] |
506 | #[cfg_attr (doc_cfg, doc(cfg(any(feature = "full" , feature = "derive" ))))] |
507 | pub use crate::ty::{ |
508 | Abi, BareFnArg, BareVariadic, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, |
509 | TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference, |
510 | TypeSlice, TypeTraitObject, TypeTuple, |
511 | }; |
512 | |
513 | #[cfg (all(any(feature = "full" , feature = "derive" ), feature = "parsing" ))] |
514 | mod verbatim; |
515 | |
516 | #[cfg (all(feature = "parsing" , feature = "full" ))] |
517 | mod whitespace; |
518 | |
519 | mod gen { |
520 | /// Syntax tree traversal to transform the nodes of an owned syntax tree. |
521 | /// |
522 | /// Each method of the [`Fold`] trait is a hook that can be overridden to |
523 | /// customize the behavior when transforming the corresponding type of node. |
524 | /// By default, every method recursively visits the substructure of the |
525 | /// input by invoking the right visitor method of each of its fields. |
526 | /// |
527 | /// [`Fold`]: fold::Fold |
528 | /// |
529 | /// ``` |
530 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
531 | /// # |
532 | /// pub trait Fold { |
533 | /// /* ... */ |
534 | /// |
535 | /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { |
536 | /// fold_expr_binary(self, node) |
537 | /// } |
538 | /// |
539 | /// /* ... */ |
540 | /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; |
541 | /// # fn fold_expr(&mut self, node: Expr) -> Expr; |
542 | /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; |
543 | /// } |
544 | /// |
545 | /// pub fn fold_expr_binary<V>(v: &mut V, node: ExprBinary) -> ExprBinary |
546 | /// where |
547 | /// V: Fold + ?Sized, |
548 | /// { |
549 | /// ExprBinary { |
550 | /// attrs: node |
551 | /// .attrs |
552 | /// .into_iter() |
553 | /// .map(|attr| v.fold_attribute(attr)) |
554 | /// .collect(), |
555 | /// left: Box::new(v.fold_expr(*node.left)), |
556 | /// op: v.fold_bin_op(node.op), |
557 | /// right: Box::new(v.fold_expr(*node.right)), |
558 | /// } |
559 | /// } |
560 | /// |
561 | /// /* ... */ |
562 | /// ``` |
563 | /// |
564 | /// <br> |
565 | /// |
566 | /// # Example |
567 | /// |
568 | /// This fold inserts parentheses to fully parenthesizes any expression. |
569 | /// |
570 | /// ``` |
571 | /// // [dependencies] |
572 | /// // quote = "1.0" |
573 | /// // syn = { version = "2.0", features = ["fold", "full"] } |
574 | /// |
575 | /// use quote::quote; |
576 | /// use syn::fold::{fold_expr, Fold}; |
577 | /// use syn::{token, Expr, ExprParen}; |
578 | /// |
579 | /// struct ParenthesizeEveryExpr; |
580 | /// |
581 | /// impl Fold for ParenthesizeEveryExpr { |
582 | /// fn fold_expr(&mut self, expr: Expr) -> Expr { |
583 | /// Expr::Paren(ExprParen { |
584 | /// attrs: Vec::new(), |
585 | /// expr: Box::new(fold_expr(self, expr)), |
586 | /// paren_token: token::Paren::default(), |
587 | /// }) |
588 | /// } |
589 | /// } |
590 | /// |
591 | /// fn main() { |
592 | /// let code = quote! { a() + b(1) * c.d }; |
593 | /// let expr: Expr = syn::parse2(code).unwrap(); |
594 | /// let parenthesized = ParenthesizeEveryExpr.fold_expr(expr); |
595 | /// println!("{}" , quote!(#parenthesized)); |
596 | /// |
597 | /// // Output: (((a)()) + (((b)((1))) * ((c).d))) |
598 | /// } |
599 | /// ``` |
600 | #[cfg (feature = "fold" )] |
601 | #[cfg_attr (doc_cfg, doc(cfg(feature = "fold" )))] |
602 | #[rustfmt::skip] |
603 | pub mod fold; |
604 | |
605 | /// Syntax tree traversal to walk a shared borrow of a syntax tree. |
606 | /// |
607 | /// Each method of the [`Visit`] trait is a hook that can be overridden to |
608 | /// customize the behavior when visiting the corresponding type of node. By |
609 | /// default, every method recursively visits the substructure of the input |
610 | /// by invoking the right visitor method of each of its fields. |
611 | /// |
612 | /// [`Visit`]: visit::Visit |
613 | /// |
614 | /// ``` |
615 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
616 | /// # |
617 | /// pub trait Visit<'ast> { |
618 | /// /* ... */ |
619 | /// |
620 | /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { |
621 | /// visit_expr_binary(self, node); |
622 | /// } |
623 | /// |
624 | /// /* ... */ |
625 | /// # fn visit_attribute(&mut self, node: &'ast Attribute); |
626 | /// # fn visit_expr(&mut self, node: &'ast Expr); |
627 | /// # fn visit_bin_op(&mut self, node: &'ast BinOp); |
628 | /// } |
629 | /// |
630 | /// pub fn visit_expr_binary<'ast, V>(v: &mut V, node: &'ast ExprBinary) |
631 | /// where |
632 | /// V: Visit<'ast> + ?Sized, |
633 | /// { |
634 | /// for attr in &node.attrs { |
635 | /// v.visit_attribute(attr); |
636 | /// } |
637 | /// v.visit_expr(&*node.left); |
638 | /// v.visit_bin_op(&node.op); |
639 | /// v.visit_expr(&*node.right); |
640 | /// } |
641 | /// |
642 | /// /* ... */ |
643 | /// ``` |
644 | /// |
645 | /// <br> |
646 | /// |
647 | /// # Example |
648 | /// |
649 | /// This visitor will print the name of every freestanding function in the |
650 | /// syntax tree, including nested functions. |
651 | /// |
652 | /// ``` |
653 | /// // [dependencies] |
654 | /// // quote = "1.0" |
655 | /// // syn = { version = "2.0", features = ["full", "visit"] } |
656 | /// |
657 | /// use quote::quote; |
658 | /// use syn::visit::{self, Visit}; |
659 | /// use syn::{File, ItemFn}; |
660 | /// |
661 | /// struct FnVisitor; |
662 | /// |
663 | /// impl<'ast> Visit<'ast> for FnVisitor { |
664 | /// fn visit_item_fn(&mut self, node: &'ast ItemFn) { |
665 | /// println!("Function with name={}" , node.sig.ident); |
666 | /// |
667 | /// // Delegate to the default impl to visit any nested functions. |
668 | /// visit::visit_item_fn(self, node); |
669 | /// } |
670 | /// } |
671 | /// |
672 | /// fn main() { |
673 | /// let code = quote! { |
674 | /// pub fn f() { |
675 | /// fn g() {} |
676 | /// } |
677 | /// }; |
678 | /// |
679 | /// let syntax_tree: File = syn::parse2(code).unwrap(); |
680 | /// FnVisitor.visit_file(&syntax_tree); |
681 | /// } |
682 | /// ``` |
683 | /// |
684 | /// The `'ast` lifetime on the input references means that the syntax tree |
685 | /// outlives the complete recursive visit call, so the visitor is allowed to |
686 | /// hold on to references into the syntax tree. |
687 | /// |
688 | /// ``` |
689 | /// use quote::quote; |
690 | /// use syn::visit::{self, Visit}; |
691 | /// use syn::{File, ItemFn}; |
692 | /// |
693 | /// struct FnVisitor<'ast> { |
694 | /// functions: Vec<&'ast ItemFn>, |
695 | /// } |
696 | /// |
697 | /// impl<'ast> Visit<'ast> for FnVisitor<'ast> { |
698 | /// fn visit_item_fn(&mut self, node: &'ast ItemFn) { |
699 | /// self.functions.push(node); |
700 | /// visit::visit_item_fn(self, node); |
701 | /// } |
702 | /// } |
703 | /// |
704 | /// fn main() { |
705 | /// let code = quote! { |
706 | /// pub fn f() { |
707 | /// fn g() {} |
708 | /// } |
709 | /// }; |
710 | /// |
711 | /// let syntax_tree: File = syn::parse2(code).unwrap(); |
712 | /// let mut visitor = FnVisitor { functions: Vec::new() }; |
713 | /// visitor.visit_file(&syntax_tree); |
714 | /// for f in visitor.functions { |
715 | /// println!("Function with name={}" , f.sig.ident); |
716 | /// } |
717 | /// } |
718 | /// ``` |
719 | #[cfg (feature = "visit" )] |
720 | #[cfg_attr (doc_cfg, doc(cfg(feature = "visit" )))] |
721 | #[rustfmt::skip] |
722 | pub mod visit; |
723 | |
724 | /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in |
725 | /// place. |
726 | /// |
727 | /// Each method of the [`VisitMut`] trait is a hook that can be overridden |
728 | /// to customize the behavior when mutating the corresponding type of node. |
729 | /// By default, every method recursively visits the substructure of the |
730 | /// input by invoking the right visitor method of each of its fields. |
731 | /// |
732 | /// [`VisitMut`]: visit_mut::VisitMut |
733 | /// |
734 | /// ``` |
735 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
736 | /// # |
737 | /// pub trait VisitMut { |
738 | /// /* ... */ |
739 | /// |
740 | /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { |
741 | /// visit_expr_binary_mut(self, node); |
742 | /// } |
743 | /// |
744 | /// /* ... */ |
745 | /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); |
746 | /// # fn visit_expr_mut(&mut self, node: &mut Expr); |
747 | /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); |
748 | /// } |
749 | /// |
750 | /// pub fn visit_expr_binary_mut<V>(v: &mut V, node: &mut ExprBinary) |
751 | /// where |
752 | /// V: VisitMut + ?Sized, |
753 | /// { |
754 | /// for attr in &mut node.attrs { |
755 | /// v.visit_attribute_mut(attr); |
756 | /// } |
757 | /// v.visit_expr_mut(&mut *node.left); |
758 | /// v.visit_bin_op_mut(&mut node.op); |
759 | /// v.visit_expr_mut(&mut *node.right); |
760 | /// } |
761 | /// |
762 | /// /* ... */ |
763 | /// ``` |
764 | /// |
765 | /// <br> |
766 | /// |
767 | /// # Example |
768 | /// |
769 | /// This mut visitor replace occurrences of u256 suffixed integer literals |
770 | /// like `999u256` with a macro invocation `bigint::u256!(999)`. |
771 | /// |
772 | /// ``` |
773 | /// // [dependencies] |
774 | /// // quote = "1.0" |
775 | /// // syn = { version = "2.0", features = ["full", "visit-mut"] } |
776 | /// |
777 | /// use quote::quote; |
778 | /// use syn::visit_mut::{self, VisitMut}; |
779 | /// use syn::{parse_quote, Expr, File, Lit, LitInt}; |
780 | /// |
781 | /// struct BigintReplace; |
782 | /// |
783 | /// impl VisitMut for BigintReplace { |
784 | /// fn visit_expr_mut(&mut self, node: &mut Expr) { |
785 | /// if let Expr::Lit(expr) = &node { |
786 | /// if let Lit::Int(int) = &expr.lit { |
787 | /// if int.suffix() == "u256" { |
788 | /// let digits = int.base10_digits(); |
789 | /// let unsuffixed: LitInt = syn::parse_str(digits).unwrap(); |
790 | /// *node = parse_quote!(bigint::u256!(#unsuffixed)); |
791 | /// return; |
792 | /// } |
793 | /// } |
794 | /// } |
795 | /// |
796 | /// // Delegate to the default impl to visit nested expressions. |
797 | /// visit_mut::visit_expr_mut(self, node); |
798 | /// } |
799 | /// } |
800 | /// |
801 | /// fn main() { |
802 | /// let code = quote! { |
803 | /// fn main() { |
804 | /// let _ = 999u256; |
805 | /// } |
806 | /// }; |
807 | /// |
808 | /// let mut syntax_tree: File = syn::parse2(code).unwrap(); |
809 | /// BigintReplace.visit_file_mut(&mut syntax_tree); |
810 | /// println!("{}" , quote!(#syntax_tree)); |
811 | /// } |
812 | /// ``` |
813 | #[cfg (feature = "visit-mut" )] |
814 | #[cfg_attr (doc_cfg, doc(cfg(feature = "visit-mut" )))] |
815 | #[rustfmt::skip] |
816 | pub mod visit_mut; |
817 | |
818 | #[cfg (feature = "clone-impls" )] |
819 | #[rustfmt::skip] |
820 | mod clone; |
821 | |
822 | #[cfg (feature = "extra-traits" )] |
823 | #[rustfmt::skip] |
824 | mod debug; |
825 | |
826 | #[cfg (feature = "extra-traits" )] |
827 | #[rustfmt::skip] |
828 | mod eq; |
829 | |
830 | #[cfg (feature = "extra-traits" )] |
831 | #[rustfmt::skip] |
832 | mod hash; |
833 | |
834 | #[cfg (any(feature = "full" , feature = "derive" ))] |
835 | #[path = "../gen_helper.rs" ] |
836 | mod helper; |
837 | } |
838 | |
839 | #[cfg (feature = "fold" )] |
840 | #[cfg_attr (doc_cfg, doc(cfg(feature = "fold" )))] |
841 | pub use crate::gen::fold; |
842 | |
843 | #[cfg (feature = "visit" )] |
844 | #[cfg_attr (doc_cfg, doc(cfg(feature = "visit" )))] |
845 | pub use crate::gen::visit; |
846 | |
847 | #[cfg (feature = "visit-mut" )] |
848 | #[cfg_attr (doc_cfg, doc(cfg(feature = "visit-mut" )))] |
849 | pub use crate::gen::visit_mut; |
850 | |
851 | // Not public API. |
852 | #[doc (hidden)] |
853 | #[path = "export.rs" ] |
854 | pub mod __private; |
855 | |
856 | /// Parse tokens of source code into the chosen syntax tree node. |
857 | /// |
858 | /// This is preferred over parsing a string because tokens are able to preserve |
859 | /// information about where in the user's code they were originally written (the |
860 | /// "span" of the token), possibly allowing the compiler to produce better error |
861 | /// messages. |
862 | /// |
863 | /// This function parses a `proc_macro::TokenStream` which is the type used for |
864 | /// interop with the compiler in a procedural macro. To parse a |
865 | /// `proc_macro2::TokenStream`, use [`syn::parse2`] instead. |
866 | /// |
867 | /// [`syn::parse2`]: parse2 |
868 | /// |
869 | /// # Examples |
870 | /// |
871 | /// ``` |
872 | /// # extern crate proc_macro; |
873 | /// # |
874 | /// use proc_macro::TokenStream; |
875 | /// use quote::quote; |
876 | /// use syn::DeriveInput; |
877 | /// |
878 | /// # const IGNORE_TOKENS: &str = stringify! { |
879 | /// #[proc_macro_derive(MyMacro)] |
880 | /// # }; |
881 | /// pub fn my_macro(input: TokenStream) -> TokenStream { |
882 | /// // Parse the tokens into a syntax tree |
883 | /// let ast: DeriveInput = syn::parse(input).unwrap(); |
884 | /// |
885 | /// // Build the output, possibly using quasi-quotation |
886 | /// let expanded = quote! { |
887 | /// /* ... */ |
888 | /// }; |
889 | /// |
890 | /// // Convert into a token stream and return it |
891 | /// expanded.into() |
892 | /// } |
893 | /// ``` |
894 | #[cfg (all(feature = "parsing" , feature = "proc-macro" ))] |
895 | #[cfg_attr (doc_cfg, doc(cfg(all(feature = "parsing" , feature = "proc-macro" ))))] |
896 | pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T> { |
897 | parse::Parser::parse(T::parse, tokens) |
898 | } |
899 | |
900 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
901 | /// |
902 | /// This function will check that the input is fully parsed. If there are |
903 | /// any unparsed tokens at the end of the stream, an error is returned. |
904 | /// |
905 | /// This function parses a `proc_macro2::TokenStream` which is commonly useful |
906 | /// when the input comes from a node of the Syn syntax tree, for example the |
907 | /// body tokens of a [`Macro`] node. When in a procedural macro parsing the |
908 | /// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`] |
909 | /// instead. |
910 | /// |
911 | /// [`syn::parse`]: parse() |
912 | #[cfg (feature = "parsing" )] |
913 | #[cfg_attr (doc_cfg, doc(cfg(feature = "parsing" )))] |
914 | pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T> { |
915 | parse::Parser::parse2(T::parse, tokens) |
916 | } |
917 | |
918 | /// Parse a string of Rust code into the chosen syntax tree node. |
919 | /// |
920 | /// # Hygiene |
921 | /// |
922 | /// Every span in the resulting syntax tree will be set to resolve at the macro |
923 | /// call site. |
924 | /// |
925 | /// # Examples |
926 | /// |
927 | /// ``` |
928 | /// use syn::{Expr, Result}; |
929 | /// |
930 | /// fn run() -> Result<()> { |
931 | /// let code = "assert_eq!(u8::max_value(), 255)" ; |
932 | /// let expr = syn::parse_str::<Expr>(code)?; |
933 | /// println!("{:#?}" , expr); |
934 | /// Ok(()) |
935 | /// } |
936 | /// # |
937 | /// # run().unwrap(); |
938 | /// ``` |
939 | #[cfg (feature = "parsing" )] |
940 | #[cfg_attr (doc_cfg, doc(cfg(feature = "parsing" )))] |
941 | pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> { |
942 | parse::Parser::parse_str(T::parse, s) |
943 | } |
944 | |
945 | // FIXME the name parse_file makes it sound like you might pass in a path to a |
946 | // file, rather than the content. |
947 | /// Parse the content of a file of Rust code. |
948 | /// |
949 | /// This is different from `syn::parse_str::<File>(content)` in two ways: |
950 | /// |
951 | /// - It discards a leading byte order mark `\u{FEFF}` if the file has one. |
952 | /// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. |
953 | /// |
954 | /// If present, either of these would be an error using `from_str`. |
955 | /// |
956 | /// # Examples |
957 | /// |
958 | /// ```no_run |
959 | /// use std::error::Error; |
960 | /// use std::fs::File; |
961 | /// use std::io::Read; |
962 | /// |
963 | /// fn run() -> Result<(), Box<dyn Error>> { |
964 | /// let mut file = File::open("path/to/code.rs" )?; |
965 | /// let mut content = String::new(); |
966 | /// file.read_to_string(&mut content)?; |
967 | /// |
968 | /// let ast = syn::parse_file(&content)?; |
969 | /// if let Some(shebang) = ast.shebang { |
970 | /// println!("{}" , shebang); |
971 | /// } |
972 | /// println!("{} items" , ast.items.len()); |
973 | /// |
974 | /// Ok(()) |
975 | /// } |
976 | /// # |
977 | /// # run().unwrap(); |
978 | /// ``` |
979 | #[cfg (all(feature = "parsing" , feature = "full" ))] |
980 | #[cfg_attr (doc_cfg, doc(cfg(all(feature = "parsing" , feature = "full" ))))] |
981 | pub fn parse_file(mut content: &str) -> Result<File> { |
982 | // Strip the BOM if it is present |
983 | const BOM: &str = " \u{feff}" ; |
984 | if content.starts_with(BOM) { |
985 | content = &content[BOM.len()..]; |
986 | } |
987 | |
988 | let mut shebang = None; |
989 | if content.starts_with("#!" ) { |
990 | let rest = whitespace::skip(&content[2..]); |
991 | if !rest.starts_with('[' ) { |
992 | if let Some(idx) = content.find(' \n' ) { |
993 | shebang = Some(content[..idx].to_string()); |
994 | content = &content[idx..]; |
995 | } else { |
996 | shebang = Some(content.to_string()); |
997 | content = "" ; |
998 | } |
999 | } |
1000 | } |
1001 | |
1002 | let mut file: File = parse_str(content)?; |
1003 | file.shebang = shebang; |
1004 | Ok(file) |
1005 | } |
1006 | |