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