Skip to main content

syn_impersonated/
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.18")]
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::match_same_arms,
269    clippy::missing_errors_doc,
270    clippy::module_name_repetitions,
271    clippy::must_use_candidate,
272    clippy::shadow_unrelated,
273    clippy::similar_names,
274    clippy::single_match_else,
275    clippy::too_many_lines,
276    clippy::unseparated_literal_suffix,
277    clippy::use_self,
278    clippy::used_underscore_binding,
279    clippy::wildcard_imports
280)]
281
282#[cfg(all(
283    not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
284    feature = "proc-macro"
285))]
286extern crate proc_macro;
287extern crate proc_macro2_impersonated as proc_macro2;
288extern crate unicode_xid;
289
290#[cfg(feature = "printing")]
291extern crate quote_impersonated as quote;
292
293#[macro_use]
294mod macros;
295
296// Not public API.
297#[cfg(feature = "parsing")]
298#[doc(hidden)]
299#[macro_use]
300pub mod group;
301
302#[macro_use]
303pub mod token;
304
305mod ident;
306pub use crate::ident::Ident;
307
308#[cfg(any(feature = "full", feature = "derive"))]
309mod attr;
310#[cfg(any(feature = "full", feature = "derive"))]
311pub use crate::attr::{
312    AttrStyle, Attribute, AttributeArgs, Meta, MetaList, MetaNameValue, NestedMeta,
313};
314
315mod bigint;
316
317#[cfg(any(feature = "full", feature = "derive"))]
318mod data;
319#[cfg(any(feature = "full", feature = "derive"))]
320pub use crate::data::{
321    Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted,
322    Visibility,
323};
324
325#[cfg(any(feature = "full", feature = "derive"))]
326mod expr;
327#[cfg(feature = "full")]
328pub use crate::expr::{
329    Arm, FieldValue, GenericMethodArgument, Label, MethodTurbofish, RangeLimits,
330};
331#[cfg(any(feature = "full", feature = "derive"))]
332pub use crate::expr::{
333    Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprAwait, ExprBinary, ExprBlock,
334    ExprBox, ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop,
335    ExprGroup, ExprIf, ExprIndex, ExprLet, ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall,
336    ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn, ExprStruct, ExprTry,
337    ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprWhile, ExprYield, Index, Member,
338};
339
340#[cfg(any(feature = "full", feature = "derive"))]
341mod generics;
342#[cfg(any(feature = "full", feature = "derive"))]
343pub use crate::generics::{
344    BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
345    PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound,
346    WhereClause, WherePredicate,
347};
348#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
349pub use crate::generics::{ImplGenerics, Turbofish, TypeGenerics};
350
351#[cfg(feature = "full")]
352mod item;
353#[cfg(feature = "full")]
354pub use crate::item::{
355    FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType,
356    ImplItem, ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, Item, ItemConst,
357    ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2, ItemMod,
358    ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver,
359    Signature, TraitItem, TraitItemConst, TraitItemMacro, TraitItemMethod, TraitItemType, UseGlob,
360    UseGroup, UseName, UsePath, UseRename, UseTree,
361};
362
363#[cfg(feature = "full")]
364mod file;
365#[cfg(feature = "full")]
366pub use crate::file::File;
367
368mod lifetime;
369pub use crate::lifetime::Lifetime;
370
371mod lit;
372pub use crate::lit::{
373    Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr, StrStyle,
374};
375
376#[cfg(any(feature = "full", feature = "derive"))]
377mod mac;
378#[cfg(any(feature = "full", feature = "derive"))]
379pub use crate::mac::{Macro, MacroDelimiter};
380
381#[cfg(any(feature = "full", feature = "derive"))]
382mod derive;
383#[cfg(feature = "derive")]
384pub use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
385
386#[cfg(any(feature = "full", feature = "derive"))]
387mod op;
388#[cfg(any(feature = "full", feature = "derive"))]
389pub use crate::op::{BinOp, UnOp};
390
391#[cfg(feature = "full")]
392mod stmt;
393#[cfg(feature = "full")]
394pub use crate::stmt::{Block, Local, Stmt};
395
396#[cfg(any(feature = "full", feature = "derive"))]
397mod ty;
398#[cfg(any(feature = "full", feature = "derive"))]
399pub use crate::ty::{
400    Abi, BareFnArg, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, TypeImplTrait, TypeInfer,
401    TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject,
402    TypeTuple, Variadic,
403};
404
405#[cfg(feature = "full")]
406mod pat;
407#[cfg(feature = "full")]
408pub use crate::pat::{
409    FieldPat, Pat, PatBox, PatIdent, PatLit, PatMacro, PatOr, PatPath, PatRange, PatReference,
410    PatRest, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatType, PatWild,
411};
412
413#[cfg(any(feature = "full", feature = "derive"))]
414mod path;
415#[cfg(any(feature = "full", feature = "derive"))]
416pub use crate::path::{
417    AngleBracketedGenericArguments, Binding, Constraint, GenericArgument,
418    ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf,
419};
420
421#[cfg(feature = "parsing")]
422pub mod buffer;
423#[cfg(feature = "parsing")]
424pub mod ext;
425pub mod punctuated;
426#[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))]
427mod tt;
428
429// Not public API except the `parse_quote!` macro.
430#[cfg(feature = "parsing")]
431#[doc(hidden)]
432pub mod parse_quote;
433
434// Not public API except the `parse_macro_input!` macro.
435#[cfg(all(
436    not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
437    feature = "parsing",
438    feature = "proc-macro"
439))]
440#[doc(hidden)]
441pub mod parse_macro_input;
442
443#[cfg(all(feature = "parsing", feature = "printing"))]
444pub mod spanned;
445
446mod gen {
447    /// Syntax tree traversal to walk a shared borrow of a syntax tree.
448    ///
449    /// Each method of the [`Visit`] trait is a hook that can be overridden to
450    /// customize the behavior when visiting the corresponding type of node. By
451    /// default, every method recursively visits the substructure of the input
452    /// by invoking the right visitor method of each of its fields.
453    ///
454    /// [`Visit`]: visit::Visit
455    ///
456    /// ```
457    /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
458    /// #
459    /// pub trait Visit<'ast> {
460    ///     /* ... */
461    ///
462    ///     fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
463    ///         visit_expr_binary(self, node);
464    ///     }
465    ///
466    ///     /* ... */
467    ///     # fn visit_attribute(&mut self, node: &'ast Attribute);
468    ///     # fn visit_expr(&mut self, node: &'ast Expr);
469    ///     # fn visit_bin_op(&mut self, node: &'ast BinOp);
470    /// }
471    ///
472    /// pub fn visit_expr_binary<'ast, V>(v: &mut V, node: &'ast ExprBinary)
473    /// where
474    ///     V: Visit<'ast> + ?Sized,
475    /// {
476    ///     for attr in &node.attrs {
477    ///         v.visit_attribute(attr);
478    ///     }
479    ///     v.visit_expr(&*node.left);
480    ///     v.visit_bin_op(&node.op);
481    ///     v.visit_expr(&*node.right);
482    /// }
483    ///
484    /// /* ... */
485    /// ```
486    ///
487    /// *This module is available if Syn is built with the `"visit"` feature.*
488    ///
489    /// <br>
490    ///
491    /// # Example
492    ///
493    /// This visitor will print the name of every freestanding function in the
494    /// syntax tree, including nested functions.
495    ///
496    /// ```
497    /// // [dependencies]
498    /// // quote = "1.0"
499    /// // syn = { version = "1.0", features = ["full", "visit"] }
500    ///
501    /// use quote::quote;
502    /// use syn::visit::{self, Visit};
503    /// use syn::{File, ItemFn};
504    ///
505    /// struct FnVisitor;
506    ///
507    /// impl<'ast> Visit<'ast> for FnVisitor {
508    ///     fn visit_item_fn(&mut self, node: &'ast ItemFn) {
509    ///         println!("Function with name={}", node.sig.ident);
510    ///
511    ///         // Delegate to the default impl to visit any nested functions.
512    ///         visit::visit_item_fn(self, node);
513    ///     }
514    /// }
515    ///
516    /// fn main() {
517    ///     let code = quote! {
518    ///         pub fn f() {
519    ///             fn g() {}
520    ///         }
521    ///     };
522    ///
523    ///     let syntax_tree: File = syn::parse2(code).unwrap();
524    ///     FnVisitor.visit_file(&syntax_tree);
525    /// }
526    /// ```
527    ///
528    /// The `'ast` lifetime on the input references means that the syntax tree
529    /// outlives the complete recursive visit call, so the visitor is allowed to
530    /// hold on to references into the syntax tree.
531    ///
532    /// ```
533    /// use quote::quote;
534    /// use syn::visit::{self, Visit};
535    /// use syn::{File, ItemFn};
536    ///
537    /// struct FnVisitor<'ast> {
538    ///     functions: Vec<&'ast ItemFn>,
539    /// }
540    ///
541    /// impl<'ast> Visit<'ast> for FnVisitor<'ast> {
542    ///     fn visit_item_fn(&mut self, node: &'ast ItemFn) {
543    ///         self.functions.push(node);
544    ///         visit::visit_item_fn(self, node);
545    ///     }
546    /// }
547    ///
548    /// fn main() {
549    ///     let code = quote! {
550    ///         pub fn f() {
551    ///             fn g() {}
552    ///         }
553    ///     };
554    ///
555    ///     let syntax_tree: File = syn::parse2(code).unwrap();
556    ///     let mut visitor = FnVisitor { functions: Vec::new() };
557    ///     visitor.visit_file(&syntax_tree);
558    ///     for f in visitor.functions {
559    ///         println!("Function with name={}", f.sig.ident);
560    ///     }
561    /// }
562    /// ```
563    #[cfg(feature = "visit")]
564    #[rustfmt::skip]
565    pub mod visit;
566
567    /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
568    /// place.
569    ///
570    /// Each method of the [`VisitMut`] trait is a hook that can be overridden
571    /// to customize the behavior when mutating the corresponding type of node.
572    /// By default, every method recursively visits the substructure of the
573    /// input by invoking the right visitor method of each of its fields.
574    ///
575    /// [`VisitMut`]: visit_mut::VisitMut
576    ///
577    /// ```
578    /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
579    /// #
580    /// pub trait VisitMut {
581    ///     /* ... */
582    ///
583    ///     fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) {
584    ///         visit_expr_binary_mut(self, node);
585    ///     }
586    ///
587    ///     /* ... */
588    ///     # fn visit_attribute_mut(&mut self, node: &mut Attribute);
589    ///     # fn visit_expr_mut(&mut self, node: &mut Expr);
590    ///     # fn visit_bin_op_mut(&mut self, node: &mut BinOp);
591    /// }
592    ///
593    /// pub fn visit_expr_binary_mut<V>(v: &mut V, node: &mut ExprBinary)
594    /// where
595    ///     V: VisitMut + ?Sized,
596    /// {
597    ///     for attr in &mut node.attrs {
598    ///         v.visit_attribute_mut(attr);
599    ///     }
600    ///     v.visit_expr_mut(&mut *node.left);
601    ///     v.visit_bin_op_mut(&mut node.op);
602    ///     v.visit_expr_mut(&mut *node.right);
603    /// }
604    ///
605    /// /* ... */
606    /// ```
607    ///
608    /// *This module is available if Syn is built with the `"visit-mut"`
609    /// feature.*
610    ///
611    /// <br>
612    ///
613    /// # Example
614    ///
615    /// This mut visitor replace occurrences of u256 suffixed integer literals
616    /// like `999u256` with a macro invocation `bigint::u256!(999)`.
617    ///
618    /// ```
619    /// // [dependencies]
620    /// // quote = "1.0"
621    /// // syn = { version = "1.0", features = ["full", "visit-mut"] }
622    ///
623    /// use quote::quote;
624    /// use syn::visit_mut::{self, VisitMut};
625    /// use syn::{parse_quote, Expr, File, Lit, LitInt};
626    ///
627    /// struct BigintReplace;
628    ///
629    /// impl VisitMut for BigintReplace {
630    ///     fn visit_expr_mut(&mut self, node: &mut Expr) {
631    ///         if let Expr::Lit(expr) = &node {
632    ///             if let Lit::Int(int) = &expr.lit {
633    ///                 if int.suffix() == "u256" {
634    ///                     let digits = int.base10_digits();
635    ///                     let unsuffixed: LitInt = syn::parse_str(digits).unwrap();
636    ///                     *node = parse_quote!(bigint::u256!(#unsuffixed));
637    ///                     return;
638    ///                 }
639    ///             }
640    ///         }
641    ///
642    ///         // Delegate to the default impl to visit nested expressions.
643    ///         visit_mut::visit_expr_mut(self, node);
644    ///     }
645    /// }
646    ///
647    /// fn main() {
648    ///     let code = quote! {
649    ///         fn main() {
650    ///             let _ = 999u256;
651    ///         }
652    ///     };
653    ///
654    ///     let mut syntax_tree: File = syn::parse2(code).unwrap();
655    ///     BigintReplace.visit_file_mut(&mut syntax_tree);
656    ///     println!("{}", quote!(#syntax_tree));
657    /// }
658    /// ```
659    #[cfg(feature = "visit-mut")]
660    #[rustfmt::skip]
661    pub mod visit_mut;
662
663    /// Syntax tree traversal to transform the nodes of an owned syntax tree.
664    ///
665    /// Each method of the [`Fold`] trait is a hook that can be overridden to
666    /// customize the behavior when transforming the corresponding type of node.
667    /// By default, every method recursively visits the substructure of the
668    /// input by invoking the right visitor method of each of its fields.
669    ///
670    /// [`Fold`]: fold::Fold
671    ///
672    /// ```
673    /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
674    /// #
675    /// pub trait Fold {
676    ///     /* ... */
677    ///
678    ///     fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
679    ///         fold_expr_binary(self, node)
680    ///     }
681    ///
682    ///     /* ... */
683    ///     # fn fold_attribute(&mut self, node: Attribute) -> Attribute;
684    ///     # fn fold_expr(&mut self, node: Expr) -> Expr;
685    ///     # fn fold_bin_op(&mut self, node: BinOp) -> BinOp;
686    /// }
687    ///
688    /// pub fn fold_expr_binary<V>(v: &mut V, node: ExprBinary) -> ExprBinary
689    /// where
690    ///     V: Fold + ?Sized,
691    /// {
692    ///     ExprBinary {
693    ///         attrs: node
694    ///             .attrs
695    ///             .into_iter()
696    ///             .map(|attr| v.fold_attribute(attr))
697    ///             .collect(),
698    ///         left: Box::new(v.fold_expr(*node.left)),
699    ///         op: v.fold_bin_op(node.op),
700    ///         right: Box::new(v.fold_expr(*node.right)),
701    ///     }
702    /// }
703    ///
704    /// /* ... */
705    /// ```
706    ///
707    /// *This module is available if Syn is built with the `"fold"` feature.*
708    ///
709    /// <br>
710    ///
711    /// # Example
712    ///
713    /// This fold inserts parentheses to fully parenthesizes any expression.
714    ///
715    /// ```
716    /// // [dependencies]
717    /// // quote = "1.0"
718    /// // syn = { version = "1.0", features = ["fold", "full"] }
719    ///
720    /// use quote::quote;
721    /// use syn::fold::{fold_expr, Fold};
722    /// use syn::{token, Expr, ExprParen};
723    ///
724    /// struct ParenthesizeEveryExpr;
725    ///
726    /// impl Fold for ParenthesizeEveryExpr {
727    ///     fn fold_expr(&mut self, expr: Expr) -> Expr {
728    ///         Expr::Paren(ExprParen {
729    ///             attrs: Vec::new(),
730    ///             expr: Box::new(fold_expr(self, expr)),
731    ///             paren_token: token::Paren::default(),
732    ///         })
733    ///     }
734    /// }
735    ///
736    /// fn main() {
737    ///     let code = quote! { a() + b(1) * c.d };
738    ///     let expr: Expr = syn::parse2(code).unwrap();
739    ///     let parenthesized = ParenthesizeEveryExpr.fold_expr(expr);
740    ///     println!("{}", quote!(#parenthesized));
741    ///
742    ///     // Output: (((a)()) + (((b)((1))) * ((c).d)))
743    /// }
744    /// ```
745    #[cfg(feature = "fold")]
746    #[rustfmt::skip]
747    pub mod fold;
748
749    #[cfg(any(feature = "full", feature = "derive"))]
750    #[path = "../gen_helper.rs"]
751    mod helper;
752}
753pub use crate::gen::*;
754
755// Not public API.
756#[doc(hidden)]
757pub mod export;
758
759mod custom_keyword;
760mod custom_punctuation;
761mod sealed;
762mod span;
763mod thread;
764
765#[cfg(feature = "parsing")]
766mod lookahead;
767
768#[cfg(feature = "parsing")]
769pub mod parse;
770
771#[cfg(all(feature = "parsing", feature = "full"))]
772mod verbatim;
773
774#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
775mod print;
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_impersonated::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_impersonated::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_impersonated::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}