syn/
lib.rs

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