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