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.85")]
254 #![cfg_attr(doc_cfg, feature(doc_cfg))]
255 #![allow(non_camel_case_types)]
256 // Ignored clippy lints.
257 #![allow(
258     clippy::cast_lossless,
259     clippy::collapsible_match, // https://github.com/rust-lang/rust-clippy/issues/7575
260     clippy::doc_markdown,
261     clippy::eval_order_dependence,
262     clippy::inherent_to_string,
263     clippy::large_enum_variant,
264     clippy::let_underscore_drop,
265     clippy::manual_assert,
266     clippy::manual_map, // https://github.com/rust-lang/rust-clippy/issues/6795
267     clippy::match_on_vec_items,
268     clippy::missing_panics_doc,
269     clippy::needless_doctest_main,
270     clippy::needless_pass_by_value,
271     clippy::never_loop,
272     clippy::return_self_not_must_use,
273     clippy::too_many_arguments,
274     clippy::trivially_copy_pass_by_ref,
275     clippy::unnecessary_unwrap,
276     // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6983
277     clippy::wrong_self_convention
278 )]
279 // Ignored clippy_pedantic lints.
280 #![allow(
281     clippy::cast_possible_truncation,
282     // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7127
283     clippy::cloned_instead_of_copied,
284     clippy::default_trait_access,
285     clippy::empty_enum,
286     clippy::expl_impl_clone_on_copy,
287     clippy::if_not_else,
288     clippy::match_same_arms,
289     // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984
290     clippy::match_wildcard_for_single_variants,
291     clippy::missing_errors_doc,
292     clippy::module_name_repetitions,
293     clippy::must_use_candidate,
294     clippy::option_if_let_else,
295     clippy::redundant_else,
296     clippy::shadow_unrelated,
297     clippy::similar_names,
298     clippy::single_match_else,
299     clippy::too_many_lines,
300     clippy::unseparated_literal_suffix,
301     clippy::used_underscore_binding,
302     clippy::wildcard_imports
303 )]
304 
305 #[cfg(all(
306     not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
307     feature = "proc-macro"
308 ))]
309 extern crate proc_macro;
310 extern crate proc_macro2;
311 extern crate unicode_xid;
312 
313 #[cfg(feature = "printing")]
314 extern crate quote;
315 
316 #[macro_use]
317 mod macros;
318 
319 // Not public API.
320 #[cfg(feature = "parsing")]
321 #[doc(hidden)]
322 #[macro_use]
323 pub mod group;
324 
325 #[macro_use]
326 pub mod token;
327 
328 mod ident;
329 pub use crate::ident::Ident;
330 
331 #[cfg(any(feature = "full", feature = "derive"))]
332 mod attr;
333 #[cfg(any(feature = "full", feature = "derive"))]
334 pub use crate::attr::{
335     AttrStyle, Attribute, AttributeArgs, Meta, MetaList, MetaNameValue, NestedMeta,
336 };
337 
338 mod bigint;
339 
340 #[cfg(any(feature = "full", feature = "derive"))]
341 mod data;
342 #[cfg(any(feature = "full", feature = "derive"))]
343 pub use crate::data::{
344     Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted,
345     Visibility,
346 };
347 
348 #[cfg(any(feature = "full", feature = "derive"))]
349 mod expr;
350 #[cfg(feature = "full")]
351 pub use crate::expr::{
352     Arm, FieldValue, GenericMethodArgument, Label, MethodTurbofish, RangeLimits,
353 };
354 #[cfg(any(feature = "full", feature = "derive"))]
355 pub use crate::expr::{
356     Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprAwait, ExprBinary, ExprBlock,
357     ExprBox, ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop,
358     ExprGroup, ExprIf, ExprIndex, ExprLet, ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall,
359     ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn, ExprStruct, ExprTry,
360     ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprWhile, ExprYield, Index, Member,
361 };
362 
363 #[cfg(any(feature = "full", feature = "derive"))]
364 mod generics;
365 #[cfg(any(feature = "full", feature = "derive"))]
366 pub use crate::generics::{
367     BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
368     PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound,
369     WhereClause, WherePredicate,
370 };
371 #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
372 pub use crate::generics::{ImplGenerics, Turbofish, TypeGenerics};
373 
374 #[cfg(feature = "full")]
375 mod item;
376 #[cfg(feature = "full")]
377 pub use crate::item::{
378     FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType,
379     ImplItem, ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, Item, ItemConst,
380     ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2, ItemMod,
381     ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver,
382     Signature, TraitItem, TraitItemConst, TraitItemMacro, TraitItemMethod, TraitItemType, UseGlob,
383     UseGroup, UseName, UsePath, UseRename, UseTree,
384 };
385 
386 #[cfg(feature = "full")]
387 mod file;
388 #[cfg(feature = "full")]
389 pub use crate::file::File;
390 
391 mod lifetime;
392 pub use crate::lifetime::Lifetime;
393 
394 mod lit;
395 pub use crate::lit::{
396     Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr, StrStyle,
397 };
398 
399 #[cfg(any(feature = "full", feature = "derive"))]
400 mod mac;
401 #[cfg(any(feature = "full", feature = "derive"))]
402 pub use crate::mac::{Macro, MacroDelimiter};
403 
404 #[cfg(any(feature = "full", feature = "derive"))]
405 mod derive;
406 #[cfg(feature = "derive")]
407 pub use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
408 
409 #[cfg(any(feature = "full", feature = "derive"))]
410 mod op;
411 #[cfg(any(feature = "full", feature = "derive"))]
412 pub use crate::op::{BinOp, UnOp};
413 
414 #[cfg(feature = "full")]
415 mod stmt;
416 #[cfg(feature = "full")]
417 pub use crate::stmt::{Block, Local, Stmt};
418 
419 #[cfg(any(feature = "full", feature = "derive"))]
420 mod ty;
421 #[cfg(any(feature = "full", feature = "derive"))]
422 pub use crate::ty::{
423     Abi, BareFnArg, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, TypeImplTrait, TypeInfer,
424     TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject,
425     TypeTuple, Variadic,
426 };
427 
428 #[cfg(feature = "full")]
429 mod pat;
430 #[cfg(feature = "full")]
431 pub use crate::pat::{
432     FieldPat, Pat, PatBox, PatIdent, PatLit, PatMacro, PatOr, PatPath, PatRange, PatReference,
433     PatRest, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatType, PatWild,
434 };
435 
436 #[cfg(any(feature = "full", feature = "derive"))]
437 mod path;
438 #[cfg(any(feature = "full", feature = "derive"))]
439 pub use crate::path::{
440     AngleBracketedGenericArguments, Binding, Constraint, GenericArgument,
441     ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf,
442 };
443 
444 #[cfg(feature = "parsing")]
445 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
446 pub mod buffer;
447 #[cfg(feature = "parsing")]
448 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
449 pub mod ext;
450 pub mod punctuated;
451 #[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))]
452 mod tt;
453 
454 // Not public API except the `parse_quote!` macro.
455 #[cfg(feature = "parsing")]
456 #[doc(hidden)]
457 pub mod parse_quote;
458 
459 // Not public API except the `parse_macro_input!` macro.
460 #[cfg(all(
461     not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
462     feature = "parsing",
463     feature = "proc-macro"
464 ))]
465 #[doc(hidden)]
466 pub mod parse_macro_input;
467 
468 #[cfg(all(feature = "parsing", feature = "printing"))]
469 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "printing"))))]
470 pub mod spanned;
471 
472 #[cfg(all(feature = "parsing", feature = "full"))]
473 mod whitespace;
474 
475 mod gen {
476     /// Syntax tree traversal to walk a shared borrow of a syntax tree.
477     ///
478     /// Each method of the [`Visit`] trait is a hook that can be overridden to
479     /// customize the behavior when visiting the corresponding type of node. By
480     /// default, every method recursively visits the substructure of the input
481     /// by invoking the right visitor method of each of its fields.
482     ///
483     /// [`Visit`]: visit::Visit
484     ///
485     /// ```
486     /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
487     /// #
488     /// pub trait Visit<'ast> {
489     ///     /* ... */
490     ///
491     ///     fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
492     ///         visit_expr_binary(self, node);
493     ///     }
494     ///
495     ///     /* ... */
496     ///     # fn visit_attribute(&mut self, node: &'ast Attribute);
497     ///     # fn visit_expr(&mut self, node: &'ast Expr);
498     ///     # fn visit_bin_op(&mut self, node: &'ast BinOp);
499     /// }
500     ///
501     /// pub fn visit_expr_binary<'ast, V>(v: &mut V, node: &'ast ExprBinary)
502     /// where
503     ///     V: Visit<'ast> + ?Sized,
504     /// {
505     ///     for attr in &node.attrs {
506     ///         v.visit_attribute(attr);
507     ///     }
508     ///     v.visit_expr(&*node.left);
509     ///     v.visit_bin_op(&node.op);
510     ///     v.visit_expr(&*node.right);
511     /// }
512     ///
513     /// /* ... */
514     /// ```
515     ///
516     /// *This module is available only if Syn is built with the `"visit"` feature.*
517     ///
518     /// <br>
519     ///
520     /// # Example
521     ///
522     /// This visitor will print the name of every freestanding function in the
523     /// syntax tree, including nested functions.
524     ///
525     /// ```
526     /// // [dependencies]
527     /// // quote = "1.0"
528     /// // syn = { version = "1.0", features = ["full", "visit"] }
529     ///
530     /// use quote::quote;
531     /// use syn::visit::{self, Visit};
532     /// use syn::{File, ItemFn};
533     ///
534     /// struct FnVisitor;
535     ///
536     /// impl<'ast> Visit<'ast> for FnVisitor {
537     ///     fn visit_item_fn(&mut self, node: &'ast ItemFn) {
538     ///         println!("Function with name={}", node.sig.ident);
539     ///
540     ///         // Delegate to the default impl to visit any nested functions.
541     ///         visit::visit_item_fn(self, node);
542     ///     }
543     /// }
544     ///
545     /// fn main() {
546     ///     let code = quote! {
547     ///         pub fn f() {
548     ///             fn g() {}
549     ///         }
550     ///     };
551     ///
552     ///     let syntax_tree: File = syn::parse2(code).unwrap();
553     ///     FnVisitor.visit_file(&syntax_tree);
554     /// }
555     /// ```
556     ///
557     /// The `'ast` lifetime on the input references means that the syntax tree
558     /// outlives the complete recursive visit call, so the visitor is allowed to
559     /// hold on to references into the syntax tree.
560     ///
561     /// ```
562     /// use quote::quote;
563     /// use syn::visit::{self, Visit};
564     /// use syn::{File, ItemFn};
565     ///
566     /// struct FnVisitor<'ast> {
567     ///     functions: Vec<&'ast ItemFn>,
568     /// }
569     ///
570     /// impl<'ast> Visit<'ast> for FnVisitor<'ast> {
571     ///     fn visit_item_fn(&mut self, node: &'ast ItemFn) {
572     ///         self.functions.push(node);
573     ///         visit::visit_item_fn(self, node);
574     ///     }
575     /// }
576     ///
577     /// fn main() {
578     ///     let code = quote! {
579     ///         pub fn f() {
580     ///             fn g() {}
581     ///         }
582     ///     };
583     ///
584     ///     let syntax_tree: File = syn::parse2(code).unwrap();
585     ///     let mut visitor = FnVisitor { functions: Vec::new() };
586     ///     visitor.visit_file(&syntax_tree);
587     ///     for f in visitor.functions {
588     ///         println!("Function with name={}", f.sig.ident);
589     ///     }
590     /// }
591     /// ```
592     #[cfg(feature = "visit")]
593     #[cfg_attr(doc_cfg, doc(cfg(feature = "visit")))]
594     #[rustfmt::skip]
595     pub mod visit;
596 
597     /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
598     /// place.
599     ///
600     /// Each method of the [`VisitMut`] trait is a hook that can be overridden
601     /// to customize the behavior when mutating the corresponding type of node.
602     /// By default, every method recursively visits the substructure of the
603     /// input by invoking the right visitor method of each of its fields.
604     ///
605     /// [`VisitMut`]: visit_mut::VisitMut
606     ///
607     /// ```
608     /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
609     /// #
610     /// pub trait VisitMut {
611     ///     /* ... */
612     ///
613     ///     fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) {
614     ///         visit_expr_binary_mut(self, node);
615     ///     }
616     ///
617     ///     /* ... */
618     ///     # fn visit_attribute_mut(&mut self, node: &mut Attribute);
619     ///     # fn visit_expr_mut(&mut self, node: &mut Expr);
620     ///     # fn visit_bin_op_mut(&mut self, node: &mut BinOp);
621     /// }
622     ///
623     /// pub fn visit_expr_binary_mut<V>(v: &mut V, node: &mut ExprBinary)
624     /// where
625     ///     V: VisitMut + ?Sized,
626     /// {
627     ///     for attr in &mut node.attrs {
628     ///         v.visit_attribute_mut(attr);
629     ///     }
630     ///     v.visit_expr_mut(&mut *node.left);
631     ///     v.visit_bin_op_mut(&mut node.op);
632     ///     v.visit_expr_mut(&mut *node.right);
633     /// }
634     ///
635     /// /* ... */
636     /// ```
637     ///
638     /// *This module is available only if Syn is built with the `"visit-mut"`
639     /// feature.*
640     ///
641     /// <br>
642     ///
643     /// # Example
644     ///
645     /// This mut visitor replace occurrences of u256 suffixed integer literals
646     /// like `999u256` with a macro invocation `bigint::u256!(999)`.
647     ///
648     /// ```
649     /// // [dependencies]
650     /// // quote = "1.0"
651     /// // syn = { version = "1.0", features = ["full", "visit-mut"] }
652     ///
653     /// use quote::quote;
654     /// use syn::visit_mut::{self, VisitMut};
655     /// use syn::{parse_quote, Expr, File, Lit, LitInt};
656     ///
657     /// struct BigintReplace;
658     ///
659     /// impl VisitMut for BigintReplace {
660     ///     fn visit_expr_mut(&mut self, node: &mut Expr) {
661     ///         if let Expr::Lit(expr) = &node {
662     ///             if let Lit::Int(int) = &expr.lit {
663     ///                 if int.suffix() == "u256" {
664     ///                     let digits = int.base10_digits();
665     ///                     let unsuffixed: LitInt = syn::parse_str(digits).unwrap();
666     ///                     *node = parse_quote!(bigint::u256!(#unsuffixed));
667     ///                     return;
668     ///                 }
669     ///             }
670     ///         }
671     ///
672     ///         // Delegate to the default impl to visit nested expressions.
673     ///         visit_mut::visit_expr_mut(self, node);
674     ///     }
675     /// }
676     ///
677     /// fn main() {
678     ///     let code = quote! {
679     ///         fn main() {
680     ///             let _ = 999u256;
681     ///         }
682     ///     };
683     ///
684     ///     let mut syntax_tree: File = syn::parse2(code).unwrap();
685     ///     BigintReplace.visit_file_mut(&mut syntax_tree);
686     ///     println!("{}", quote!(#syntax_tree));
687     /// }
688     /// ```
689     #[cfg(feature = "visit-mut")]
690     #[cfg_attr(doc_cfg, doc(cfg(feature = "visit-mut")))]
691     #[rustfmt::skip]
692     pub mod visit_mut;
693 
694     /// Syntax tree traversal to transform the nodes of an owned syntax tree.
695     ///
696     /// Each method of the [`Fold`] trait is a hook that can be overridden to
697     /// customize the behavior when transforming the corresponding type of node.
698     /// By default, every method recursively visits the substructure of the
699     /// input by invoking the right visitor method of each of its fields.
700     ///
701     /// [`Fold`]: fold::Fold
702     ///
703     /// ```
704     /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
705     /// #
706     /// pub trait Fold {
707     ///     /* ... */
708     ///
709     ///     fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
710     ///         fold_expr_binary(self, node)
711     ///     }
712     ///
713     ///     /* ... */
714     ///     # fn fold_attribute(&mut self, node: Attribute) -> Attribute;
715     ///     # fn fold_expr(&mut self, node: Expr) -> Expr;
716     ///     # fn fold_bin_op(&mut self, node: BinOp) -> BinOp;
717     /// }
718     ///
719     /// pub fn fold_expr_binary<V>(v: &mut V, node: ExprBinary) -> ExprBinary
720     /// where
721     ///     V: Fold + ?Sized,
722     /// {
723     ///     ExprBinary {
724     ///         attrs: node
725     ///             .attrs
726     ///             .into_iter()
727     ///             .map(|attr| v.fold_attribute(attr))
728     ///             .collect(),
729     ///         left: Box::new(v.fold_expr(*node.left)),
730     ///         op: v.fold_bin_op(node.op),
731     ///         right: Box::new(v.fold_expr(*node.right)),
732     ///     }
733     /// }
734     ///
735     /// /* ... */
736     /// ```
737     ///
738     /// *This module is available only if Syn is built with the `"fold"` feature.*
739     ///
740     /// <br>
741     ///
742     /// # Example
743     ///
744     /// This fold inserts parentheses to fully parenthesizes any expression.
745     ///
746     /// ```
747     /// // [dependencies]
748     /// // quote = "1.0"
749     /// // syn = { version = "1.0", features = ["fold", "full"] }
750     ///
751     /// use quote::quote;
752     /// use syn::fold::{fold_expr, Fold};
753     /// use syn::{token, Expr, ExprParen};
754     ///
755     /// struct ParenthesizeEveryExpr;
756     ///
757     /// impl Fold for ParenthesizeEveryExpr {
758     ///     fn fold_expr(&mut self, expr: Expr) -> Expr {
759     ///         Expr::Paren(ExprParen {
760     ///             attrs: Vec::new(),
761     ///             expr: Box::new(fold_expr(self, expr)),
762     ///             paren_token: token::Paren::default(),
763     ///         })
764     ///     }
765     /// }
766     ///
767     /// fn main() {
768     ///     let code = quote! { a() + b(1) * c.d };
769     ///     let expr: Expr = syn::parse2(code).unwrap();
770     ///     let parenthesized = ParenthesizeEveryExpr.fold_expr(expr);
771     ///     println!("{}", quote!(#parenthesized));
772     ///
773     ///     // Output: (((a)()) + (((b)((1))) * ((c).d)))
774     /// }
775     /// ```
776     #[cfg(feature = "fold")]
777     #[cfg_attr(doc_cfg, doc(cfg(feature = "fold")))]
778     #[rustfmt::skip]
779     pub mod fold;
780 
781     #[cfg(feature = "clone-impls")]
782     #[rustfmt::skip]
783     mod clone;
784 
785     #[cfg(feature = "extra-traits")]
786     #[rustfmt::skip]
787     mod eq;
788 
789     #[cfg(feature = "extra-traits")]
790     #[rustfmt::skip]
791     mod hash;
792 
793     #[cfg(feature = "extra-traits")]
794     #[rustfmt::skip]
795     mod debug;
796 
797     #[cfg(any(feature = "full", feature = "derive"))]
798     #[path = "../gen_helper.rs"]
799     mod helper;
800 }
801 pub use crate::gen::*;
802 
803 // Not public API.
804 #[doc(hidden)]
805 #[path = "export.rs"]
806 pub mod __private;
807 
808 mod custom_keyword;
809 mod custom_punctuation;
810 mod sealed;
811 mod span;
812 mod thread;
813 
814 #[cfg(feature = "parsing")]
815 mod lookahead;
816 
817 #[cfg(feature = "parsing")]
818 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
819 pub mod parse;
820 
821 #[cfg(feature = "full")]
822 mod reserved;
823 
824 #[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))]
825 mod verbatim;
826 
827 #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
828 mod print;
829 
830 #[cfg(any(feature = "full", feature = "derive"))]
831 use crate::__private::private;
832 
833 ////////////////////////////////////////////////////////////////////////////////
834 
835 // https://github.com/rust-lang/rust/issues/62830
836 #[cfg(feature = "parsing")]
837 mod rustdoc_workaround {
838     pub use crate::parse::{self as parse_module};
839 }
840 
841 ////////////////////////////////////////////////////////////////////////////////
842 
843 mod error;
844 pub use crate::error::{Error, Result};
845 
846 /// Parse tokens of source code into the chosen syntax tree node.
847 ///
848 /// This is preferred over parsing a string because tokens are able to preserve
849 /// information about where in the user's code they were originally written (the
850 /// "span" of the token), possibly allowing the compiler to produce better error
851 /// messages.
852 ///
853 /// This function parses a `proc_macro::TokenStream` which is the type used for
854 /// interop with the compiler in a procedural macro. To parse a
855 /// `proc_macro2::TokenStream`, use [`syn::parse2`] instead.
856 ///
857 /// [`syn::parse2`]: parse2
858 ///
859 /// *This function is available only if Syn is built with both the `"parsing"` and
860 /// `"proc-macro"` features.*
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// # extern crate proc_macro;
866 /// #
867 /// use proc_macro::TokenStream;
868 /// use quote::quote;
869 /// use syn::DeriveInput;
870 ///
871 /// # const IGNORE_TOKENS: &str = stringify! {
872 /// #[proc_macro_derive(MyMacro)]
873 /// # };
874 /// pub fn my_macro(input: TokenStream) -> TokenStream {
875 ///     // Parse the tokens into a syntax tree
876 ///     let ast: DeriveInput = syn::parse(input).unwrap();
877 ///
878 ///     // Build the output, possibly using quasi-quotation
879 ///     let expanded = quote! {
880 ///         /* ... */
881 ///     };
882 ///
883 ///     // Convert into a token stream and return it
884 ///     expanded.into()
885 /// }
886 /// ```
887 #[cfg(all(
888     not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
889     feature = "parsing",
890     feature = "proc-macro"
891 ))]
892 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "proc-macro"))))]
parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T>893 pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T> {
894     parse::Parser::parse(T::parse, tokens)
895 }
896 
897 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
898 ///
899 /// This function will check that the input is fully parsed. If there are
900 /// any unparsed tokens at the end of the stream, an error is returned.
901 ///
902 /// This function parses a `proc_macro2::TokenStream` which is commonly useful
903 /// when the input comes from a node of the Syn syntax tree, for example the
904 /// body tokens of a [`Macro`] node. When in a procedural macro parsing the
905 /// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`]
906 /// instead.
907 ///
908 /// [`syn::parse`]: parse()
909 ///
910 /// *This function is available only if Syn is built with the `"parsing"` feature.*
911 #[cfg(feature = "parsing")]
912 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T>913 pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T> {
914     parse::Parser::parse2(T::parse, tokens)
915 }
916 
917 /// Parse a string of Rust code into the chosen syntax tree node.
918 ///
919 /// *This function is available only if Syn is built with the `"parsing"` feature.*
920 ///
921 /// # Hygiene
922 ///
923 /// Every span in the resulting syntax tree will be set to resolve at the macro
924 /// call site.
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// use syn::{Expr, Result};
930 ///
931 /// fn run() -> Result<()> {
932 ///     let code = "assert_eq!(u8::max_value(), 255)";
933 ///     let expr = syn::parse_str::<Expr>(code)?;
934 ///     println!("{:#?}", expr);
935 ///     Ok(())
936 /// }
937 /// #
938 /// # run().unwrap();
939 /// ```
940 #[cfg(feature = "parsing")]
941 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
parse_str<T: parse::Parse>(s: &str) -> Result<T>942 pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T> {
943     parse::Parser::parse_str(T::parse, s)
944 }
945 
946 // FIXME the name parse_file makes it sound like you might pass in a path to a
947 // file, rather than the content.
948 /// Parse the content of a file of Rust code.
949 ///
950 /// This is different from `syn::parse_str::<File>(content)` in two ways:
951 ///
952 /// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
953 /// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
954 ///
955 /// If present, either of these would be an error using `from_str`.
956 ///
957 /// *This function is available only if Syn is built with the `"parsing"` and
958 /// `"full"` features.*
959 ///
960 /// # Examples
961 ///
962 /// ```no_run
963 /// use std::error::Error;
964 /// use std::fs::File;
965 /// use std::io::Read;
966 ///
967 /// fn run() -> Result<(), Box<Error>> {
968 ///     let mut file = File::open("path/to/code.rs")?;
969 ///     let mut content = String::new();
970 ///     file.read_to_string(&mut content)?;
971 ///
972 ///     let ast = syn::parse_file(&content)?;
973 ///     if let Some(shebang) = ast.shebang {
974 ///         println!("{}", shebang);
975 ///     }
976 ///     println!("{} items", ast.items.len());
977 ///
978 ///     Ok(())
979 /// }
980 /// #
981 /// # run().unwrap();
982 /// ```
983 #[cfg(all(feature = "parsing", feature = "full"))]
984 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "parsing", feature = "full"))))]
parse_file(mut content: &str) -> Result<File>985 pub fn parse_file(mut content: &str) -> Result<File> {
986     // Strip the BOM if it is present
987     const BOM: &str = "\u{feff}";
988     if content.starts_with(BOM) {
989         content = &content[BOM.len()..];
990     }
991 
992     let mut shebang = None;
993     if content.starts_with("#!") {
994         let rest = whitespace::skip(&content[2..]);
995         if !rest.starts_with('[') {
996             if let Some(idx) = content.find('\n') {
997                 shebang = Some(content[..idx].to_string());
998                 content = &content[idx..];
999             } else {
1000                 shebang = Some(content.to_string());
1001                 content = "";
1002             }
1003         }
1004     }
1005 
1006     let mut file: File = parse_str(content)?;
1007     file.shebang = shebang;
1008     Ok(file)
1009 }
1010