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