Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/syn/src/lib.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / syn / src / lib.rs` 1132 lines · 38687 bytes Raw Blame History 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 //!
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 syntax tree that can represent most 16 //! stable Rust source code and some unstable syntax. The syntax tree is 17 //! rooted at [`syn::File`] which represents a full source file, but there are 18 //! other 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`. 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 //!
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 //! # Cargo.toml 65 //! [package] 66 //! ... 67 //! 68 //! [lib] 69 //! proc-macro = true 70 //! 71 //! [dependencies] 72 //! syn = "3" 73 //! quote = "1" 74 //! ``` 75 //! 76 //! ``` 77 //! # extern crate proc_macro; 78 //! # 79 //! use proc_macro::TokenStream; 80 //! use quote::quote; 81 //! use syn::{parse_macro_input, DeriveInput}; 82 //! 83 //! # const IGNORE_TOKENS: &str = stringify! { 84 //! #[proc_macro_derive(MyMacro)] 85 //! # }; 86 //! pub fn my_macro(input: TokenStream) -> TokenStream { 87 //! // Parse the input tokens into a syntax tree 88 //! let input = parse_macro_input!(input as DeriveInput); 89 //! 90 //! // Build the output, possibly using quasi-quotation 91 //! let expanded = quote! { 92 //! // ... 93 //! }; 94 //! 95 //! // Hand the output tokens back to the compiler 96 //! TokenStream::from(expanded) 97 //! } 98 //! ``` 99 //! 100 //! The [`heapsize`] example directory shows a complete working implementation 101 //! of a derive macro. The example derives a `HeapSize` trait which computes an 102 //! estimate of the amount of heap memory owned by a value. 103 //! 104 //! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize 105 //! 106 //! ``` 107 //! pub trait HeapSize { 108 //! /// Total number of bytes of heap memory owned by `self`. 109 //! fn heap_size_of_children(&self) -> usize; 110 //! } 111 //! ``` 112 //! 113 //! The derive macro allows users to write `#[derive(HeapSize)]` on data 114 //! structures in their program. 115 //! 116 //! ``` 117 //! # const IGNORE_TOKENS: &str = stringify! { 118 //! #[derive(HeapSize)] 119 //! # }; 120 //! struct Demo<'a, T: ?Sized> { 121 //! a: Box, 122 //! b: u8, 123 //! c: &'a str, 124 //! d: String, 125 //! } 126 //! ``` 127 //! 128 //!


129 //! 130 //! # Spans and error reporting 131 //! 132 //! The token-based procedural macro API provides great control over where the 133 //! compiler's error messages are displayed in user code. Consider the error the 134 //! user sees if one of their field types does not implement `HeapSize`. 135 //! 136 //! ``` 137 //! # const IGNORE_TOKENS: &str = stringify! { 138 //! #[derive(HeapSize)] 139 //! # }; 140 //! struct Broken { 141 //! ok: String, 142 //! bad: std::thread::Thread, 143 //! } 144 //! ``` 145 //! 146 //! By tracking span information all the way through the expansion of a 147 //! procedural macro as shown in the `heapsize` example, token-based macros in 148 //! Syn are able to trigger errors that directly pinpoint the source of the 149 //! problem. 150 //! 151 //! ```text 152 //! error[E0277]: the trait bound `Thread: HeapSize` is not satisfied 153 //! --> src/main.rs:9:5 154 //! | 155 //! 3 | #[derive(HeapSize)] 156 //! | -------- required by a bound introduced by this call 157 //! ... 158 //! 9 | bad: std::thread::Thread, 159 //! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread` 160 //! | 161 //! = help: the following other types implement trait `HeapSize`: 162 //! &'a T 163 //! Box 164 //! Demo<'a, T> 165 //! String 166 //! [T] 167 //! u8 168 //! ``` 169 //! 170 //!
171 //! 172 //! # Parsing a custom syntax 173 //! 174 //! The [`lazy-static`] example directory shows the implementation of a 175 //! `functionlike!(...)` procedural macro in which the input tokens are parsed 176 //! using Syn's parsing API. 177 //! 178 //! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static 179 //! 180 //! The example reimplements the popular `lazy_static` crate from crates.io as a 181 //! procedural macro. 182 //! 183 //! ``` 184 //! # macro_rules! lazy_static { 185 //! # ($($tt:tt)*) => {} 186 //! # } 187 //! # 188 //! lazy_static! { 189 //! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); 190 //! } 191 //! ``` 192 //! 193 //! The implementation shows how to trigger custom warnings and error messages 194 //! on the macro input. 195 //! 196 //! ```text 197 //! warning: come on, pick a more creative name 198 //! --> src/main.rs:10:16 199 //! | 200 //! 10 | static ref FOO: String = "lazy_static".to_owned(); 201 //! | ^^^ 202 //! ``` 203 //! 204 //!
205 //! 206 //! # Testing 207 //! 208 //! When testing macros, we often care not just that the macro can be used 209 //! successfully but also that when the macro is provided with invalid input it 210 //! produces maximally helpful error messages. Consider using the [`trybuild`] 211 //! crate to write tests for errors that are emitted by your macro or errors 212 //! detected by the Rust compiler in the expanded code following misuse of the 213 //! macro. Such tests help avoid regressions from later refactors that 214 //! mistakenly make an error no longer trigger or be less helpful than it used 215 //! to be. 216 //! 217 //! [`trybuild`]: https://github.com/dtolnay/trybuild 218 //! 219 //!
220 //! 221 //! # Debugging 222 //! 223 //! When developing a procedural macro it can be helpful to look at what the 224 //! generated code looks like. Use `cargo rustc -- -Zunstable-options 225 //! -Zunpretty=expanded` or the [`cargo expand`] subcommand. 226 //! 227 //! [`cargo expand`]: https://github.com/dtolnay/cargo-expand 228 //! 229 //! To show the expanded code for some crate that uses your procedural macro, 230 //! run `cargo expand` from that crate. To show the expanded code for one of 231 //! your own test cases, run `cargo expand --test the_test_case` where the last 232 //! argument is the name of the test file without the `.rs` extension. 233 //! 234 //! This write-up by Brandon W Maister discusses debugging in more detail: 235 //! [Debugging Rust's new Custom Derive system][debugging]. 236 //! 237 //! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ 238 //! 239 //!
240 //! 241 //! # Optional features 242 //! 243 //! Syn puts a lot of functionality behind optional features in order to 244 //! optimize compile time for the most common use cases. The following features 245 //! are available. 246 //! 247 //! - **`derive`** *(enabled by default)* — Data structures for representing the 248 //! possible input to a derive macro, including structs and enums and types. 249 //! - **`full`** — Data structures for representing the syntax tree of all valid 250 //! Rust source code, including items and expressions. 251 //! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into 252 //! a syntax tree node of a chosen type. 253 //! - **`printing`** *(enabled by default)* — Ability to print a syntax tree 254 //! node as tokens of Rust source code. 255 //! - **`visit`** — Trait for traversing a syntax tree. 256 //! - **`visit-mut`** — Trait for traversing and mutating in place a syntax 257 //! tree. 258 //! - **`fold`** — Trait for transforming an owned syntax tree. 259 //! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree 260 //! types. 261 //! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree 262 //! types. 263 //! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the 264 //! dynamic library libproc_macro from rustc toolchain. 265 //! 266 //!
267 //! 268 //! # Compatibility notes 269 //! 270 //! Syn is able to accommodate most kinds of Rust grammar changes without a new 271 //! major release through the following mechanisms. 272 //! 273 //! #### Modifiers 274 //! 275 //! Syntax tree structs which are expected to grow over the course of future 276 //! releases of the Rust language, such as [`ItemTrait`], contain a `modifiers` 277 //! field of one of several "Modifiers" types, in that case [`TraitModifiers`]. 278 //! 279 //! All modifiers structs have the following commonalities: 280 //! 281 //! - Type name ending with "Modifiers". 282 //! 283 //! - Implements [`Default`]. The default value is guaranteed to comprise no 284 //! tokens. 285 //! 286 //! - Non-exhaustive. Can only be instantiated by Syn's parser or by creating 287 //! and then mutating an empty default value. 288 //! 289 //! - Does not implement [`Parse`][parse::Parse]. When parsing, they are parsed 290 //! by the enclosing syntax tree node. 291 //! 292 //! - Does not implement [`ToTokens`][quote::ToTokens]. In some cases the syntax 293 //! that might be held in modifiers in the future is not necessarily 294 //! contiguous tokens. 295 //! 296 //! - Provides `.require_empty() -> Result<()>` which returns a meaningfully 297 //! spanned error if the modifiers are different from the empty default. This 298 //! enables a caller to reject syntax it does not recognize without knowing 299 //! what that syntax may be. 300 //! 301 //! Across major versions, fields may be promoted out of a "Modifiers" struct 302 //! into the enclosing syntax tree node(s), typically for syntax that has 303 //! already been incorporated into a stable release of Rust or is deemed 304 //! sufficiently on track for stabilization. 305 //! 306 //! #### Verbatim variants 307 //! 308 //! Syntax tree enums which are expected to grow over the course of future 309 //! releases of the Rust language are declared non-exhaustive and may contain a 310 //! variant named `Verbatim` that holds [`TokenStream`]. For example 311 //! [`Expr::Verbatim`]. 312 //! 313 //! Unstable language syntax for which a dedicated syntax tree node does not yet 314 //! exist will get parsed to `Verbatim`, thus allowing unstable syntax to 315 //! round-trip through parsing and printing of a syntax tree. For example you 316 //! might parse token input to [`ItemTrait`] (a trait definition) in order to 317 //! read or modify its method signatures, or insert associated types, or insert 318 //! default function bodies. All of this would work even if there is some 319 //! `Expr::Verbatim` syntax somewhere in one of the function bodies in the macro 320 //! input. 321 //! 322 //! Verbatim variants are not intended to be constructed other than by Syn's 323 //! parser. Do not rely on passing one containing arbitrary tokens through Syn's 324 //! `ToTokens` implementations or through any other library, as it may panic or 325 //! otherwise misbehave, such as failing to accurately parenthesize 326 //! subexpressions to preserve precedence. 327 //! 328 //! It is important not to write code that expects Syn's parser to continue to 329 //! produce `Verbatim` when parsing some particular syntax construct, as that 330 //! behavior changes across patch releases of Syn. Patch releases can promote 331 //! something that used to be parsed as `Verbatim` into a new dedicated syntax 332 //! tree node. Verbatim variants are specifically only for round-tripping code 333 //! not acted on by the caller. 334 //! 335 //! #### Non-exhaustive enums 336 //! 337 //! Some enums in the syntax tree are declared #\[non_exhaustive\] and cannot 338 //! be pattern-matched using an exhaustive match; a default case (`_ => ...`) is 339 //! required. New variants of these enums will be added over time corresponding 340 //! to new Rust syntax. 341 //! 342 //! For testing the exhaustiveness of a match on such an enum in downstream 343 //! code, it is recommended to use the following idiom. 344 //! 345 //! ``` 346 //! # use syn::Expr; 347 //! # 348 //! # fn example(expr: Expr) { 349 //! match expr { 350 //! #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))] 351 //! 352 //! Expr::Array(expr) => { /*...*/ } 353 //! Expr::Assign(expr) => { /*...*/ } 354 #![cfg_attr(not(doctest), doc = " ...")] 355 //! Expr::Yield(expr) => { /*...*/ } 356 //! 357 //! _ => { /* some sane fallback */ } 358 //! } 359 //! # } 360 //! ``` 361 //! 362 //! This way you will be notified by a test failure when a variant is added, so 363 //! that you can add code to handle it, but your library will continue to 364 //! compile and work for downstream users in the interim. 365 366 #![no_std] 367 #![doc(html_root_url = "https://docs.rs/syn/3.0.6")] 368 #![cfg_attr(docsrs, feature(doc_cfg), doc(auto_cfg = false))] 369 #![deny(unsafe_op_in_unsafe_fn)] 370 #![allow(non_camel_case_types)] 371 #![cfg_attr(not(check_cfg), allow(unexpected_cfgs))] 372 #![allow( 373 clippy::bool_to_int_with_if, 374 clippy::cast_lossless, 375 clippy::cast_possible_truncation, 376 clippy::cast_possible_wrap, 377 clippy::cast_ptr_alignment, 378 clippy::default_trait_access, 379 clippy::derivable_impls, 380 clippy::diverging_sub_expression, 381 clippy::doc_markdown, 382 clippy::elidable_lifetime_names, 383 clippy::enum_glob_use, 384 clippy::expl_impl_clone_on_copy, 385 clippy::explicit_auto_deref, 386 clippy::fn_params_excessive_bools, 387 clippy::if_not_else, 388 clippy::inherent_to_string, 389 clippy::into_iter_without_iter, 390 clippy::items_after_statements, 391 clippy::large_enum_variant, 392 clippy::let_underscore_untyped, // https://github.com/rust-lang/rust-clippy/issues/10410 393 clippy::manual_assert, 394 clippy::manual_let_else, 395 clippy::manual_map, 396 clippy::match_like_matches_macro, 397 clippy::match_same_arms, 398 clippy::match_wildcard_for_single_variants, // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984 399 clippy::missing_errors_doc, 400 clippy::missing_panics_doc, 401 clippy::module_name_repetitions, 402 clippy::must_use_candidate, 403 clippy::needless_doctest_main, 404 clippy::needless_lifetimes, 405 clippy::needless_pass_by_value, 406 clippy::needless_update, 407 clippy::never_loop, 408 clippy::range_plus_one, 409 clippy::redundant_else, 410 clippy::ref_option, 411 clippy::return_self_not_must_use, 412 clippy::similar_names, 413 clippy::single_match_else, 414 clippy::struct_excessive_bools, 415 clippy::too_many_arguments, 416 clippy::too_many_lines, 417 clippy::trivially_copy_pass_by_ref, 418 clippy::type_complexity, 419 clippy::unconditional_recursion, // https://github.com/rust-lang/rust-clippy/issues/12133 420 clippy::uninhabited_references, 421 clippy::uninlined_format_args, 422 clippy::unnecessary_box_returns, 423 clippy::unnecessary_unwrap, 424 clippy::used_underscore_binding, 425 clippy::wildcard_imports, 426 )] 427 #![allow(unknown_lints, mismatched_lifetime_syntaxes)] 428 429 extern crate alloc; 430 extern crate std; 431 432 extern crate self as syn; 433 434 #[cfg(feature = "proc-macro")] 435 extern crate proc_macro; 436 437 #[macro_use] 438 mod macros; 439 440 #[cfg(feature = "parsing")] 441 #[macro_use] 442 mod group; 443 444 #[macro_use] 445 pub mod token; 446 447 #[cfg(any(feature = "full", feature = "derive"))] 448 mod attr; 449 #[cfg(any(feature = "full", feature = "derive"))] 450 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 451 pub use crate::attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue}; 452 453 mod bigint; 454 455 #[cfg(feature = "parsing")] 456 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] 457 pub mod buffer; 458 459 #[cfg(any( 460 all(feature = "parsing", feature = "full"), 461 all(feature = "printing", any(feature = "full", feature = "derive")), 462 ))] 463 mod classify; 464 465 mod custom_keyword; 466 467 mod custom_punctuation; 468 469 #[cfg(any(feature = "full", feature = "derive"))] 470 mod data; 471 #[cfg(any(feature = "full", feature = "derive"))] 472 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 473 pub use crate::data::{Field, FieldModifiers, Fields, FieldsNamed, FieldsUnnamed, Variant}; 474 475 #[cfg(any(feature = "full", feature = "derive"))] 476 mod derive; 477 #[cfg(feature = "derive")] 478 #[cfg_attr(docsrs, doc(cfg(feature = "derive")))] 479 pub use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; 480 481 mod drops; 482 483 mod error; 484 pub use crate::error::{Error, Result}; 485 486 #[cfg(any(feature = "full", feature = "derive"))] 487 mod expr; 488 #[cfg(feature = "full")] 489 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 490 pub use crate::expr::{Arm, BlockModifiers, ClosureModifiers, Label, RangeLimits}; 491 #[cfg(any(feature = "full", feature = "derive"))] 492 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 493 pub use crate::expr::{ 494 Expr, ExprBinary, ExprCall, ExprCast, ExprField, ExprIndex, ExprLit, ExprMacro, ExprMethodCall, 495 ExprParen, ExprPath, ExprReference, ExprStruct, ExprUnary, FieldValue, Index, Member, 496 }; 497 #[cfg(any(feature = "full", feature = "derive"))] 498 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 499 pub use crate::expr::{ 500 ExprArray, ExprAssign, ExprAsync, ExprAwait, ExprBlock, ExprBreak, ExprClosure, ExprConst, 501 ExprContinue, ExprForLoop, ExprGroup, ExprIf, ExprInfer, ExprLet, ExprLoop, ExprMatch, 502 ExprRange, ExprRawAddr, ExprRepeat, ExprReturn, ExprTry, ExprTryBlock, ExprTuple, ExprUnsafe, 503 ExprWhile, ExprYield, 504 }; 505 506 pub mod ext; 507 508 #[cfg(feature = "full")] 509 mod file; 510 #[cfg(feature = "full")] 511 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 512 pub use crate::file::{File, Frontmatter}; 513 514 #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] 515 mod fixup; 516 517 #[cfg(any(feature = "full", feature = "derive"))] 518 mod generics; 519 #[cfg(any(feature = "full", feature = "derive"))] 520 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 521 pub use crate::generics::{ 522 BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeParam, PredicateLifetime, 523 PredicateType, TraitBound, TraitBoundModifiers, TypeParam, TypeParamBound, WhereClause, 524 WherePredicate, 525 }; 526 #[cfg(feature = "full")] 527 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 528 pub use crate::generics::{CapturedParam, PreciseCapture}; 529 #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] 530 #[cfg_attr( 531 docsrs, 532 doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))) 533 )] 534 pub use crate::generics::{ImplGenerics, Turbofish, TypeGenerics}; 535 536 mod ident; 537 #[doc(inline)] 538 pub use crate::ident::Ident; 539 540 #[cfg(feature = "full")] 541 mod item; 542 #[cfg(feature = "full")] 543 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 544 pub use crate::item::{ 545 ConstModifiers, FnArg, FnModifiers, ForeignItem, ForeignItemFn, ForeignItemMacro, 546 ForeignItemStatic, ForeignItemType, ImplItem, ImplItemConst, ImplItemFn, ImplItemMacro, 547 ImplItemType, ImplModifiers, Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn, 548 ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait, 549 ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, ReceiverKind, Safety, Signature, 550 StaticMutability, TraitItem, TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, 551 TraitModifiers, TypeModifiers, UseGlob, UseGroup, UseName, UsePath, UseRename, UseTree, 552 Variadic, WhereClausePlacement, 553 }; 554 555 mod lifetime; 556 #[doc(inline)] 557 pub use crate::lifetime::Lifetime; 558 559 mod lit; 560 #[doc(inline)] 561 pub use crate::lit::{ 562 Lit, LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitInt, LitStr, 563 }; 564 565 #[cfg(feature = "parsing")] 566 mod lookahead; 567 568 #[cfg(any(feature = "full", feature = "derive"))] 569 mod mac; 570 #[cfg(any(feature = "full", feature = "derive"))] 571 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 572 pub use crate::mac::{Macro, MacroDelimiter}; 573 574 #[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))] 575 #[cfg_attr( 576 docsrs, 577 doc(cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))) 578 )] 579 pub mod meta; 580 581 #[cfg(any(feature = "full", feature = "derive"))] 582 mod op; 583 #[cfg(any(feature = "full", feature = "derive"))] 584 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 585 pub use crate::op::{BinOp, UnOp}; 586 587 #[cfg(feature = "parsing")] 588 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] 589 pub mod parse; 590 591 #[cfg(all(feature = "parsing", feature = "proc-macro"))] 592 mod parse_macro_input; 593 594 #[cfg(all(feature = "parsing", feature = "printing"))] 595 mod parse_quote; 596 597 #[cfg(feature = "full")] 598 mod pat; 599 #[cfg(feature = "full")] 600 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 601 pub use crate::pat::{ 602 FieldPat, Pat, PatConst, PatGuard, PatIdent, PatLit, PatMacro, PatOr, PatParen, PatPath, 603 PatRange, PatReference, PatRest, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatType, 604 PatWild, 605 }; 606 607 #[cfg(any(feature = "full", feature = "derive"))] 608 mod path; 609 #[cfg(any(feature = "full", feature = "derive"))] 610 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 611 pub use crate::path::{ 612 AngleBracketedGenericArguments, AssocConst, AssocType, Constraint, GenericArgument, 613 ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf, 614 }; 615 616 #[cfg(all( 617 any(feature = "full", feature = "derive"), 618 any(feature = "parsing", feature = "printing") 619 ))] 620 mod precedence; 621 622 #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] 623 mod print; 624 625 pub mod punctuated; 626 627 #[cfg(any(feature = "full", feature = "derive"))] 628 mod restriction; 629 #[cfg(any(feature = "full", feature = "derive"))] 630 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 631 pub use crate::restriction::{VisRestricted, Visibility}; 632 633 mod sealed; 634 635 #[cfg(all(feature = "parsing", feature = "derive", not(feature = "full")))] 636 mod scan_expr; 637 638 mod span; 639 640 #[cfg(all(feature = "parsing", feature = "printing"))] 641 #[cfg_attr(docsrs, doc(cfg(all(feature = "parsing", feature = "printing"))))] 642 pub mod spanned; 643 644 #[cfg(feature = "full")] 645 mod stmt; 646 #[cfg(feature = "full")] 647 #[cfg_attr(docsrs, doc(cfg(feature = "full")))] 648 pub use crate::stmt::{Block, Local, LocalInit, LocalModifiers, Stmt, StmtMacro}; 649 650 mod thread; 651 652 #[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))] 653 mod tt; 654 655 #[cfg(any(feature = "full", feature = "derive"))] 656 mod ty; 657 #[cfg(any(feature = "full", feature = "derive"))] 658 #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))] 659 pub use crate::ty::{ 660 Abi, FnPtrVariadic, NamedArg, PointerMutability, ReturnType, Type, TypeArray, TypeFnPtr, 661 TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, 662 TypeReference, TypeSlice, TypeTraitObject, TypeTuple, 663 }; 664 665 #[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))] 666 mod verbatim; 667 668 #[cfg(all(feature = "parsing", feature = "full"))] 669 mod whitespace; 670 671 #[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/6176 672 mod gen { 673 /// Syntax tree traversal to transform the nodes of an owned syntax tree. 674 /// 675 /// Each method of the [`Fold`] trait is a hook that can be overridden to 676 /// customize the behavior when transforming the corresponding type of node. 677 /// By default, every method recursively visits the substructure of the 678 /// input by invoking the right visitor method of each of its fields. 679 /// 680 /// [`Fold`]: fold::Fold 681 /// 682 /// ``` 683 /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; 684 /// # 685 /// pub trait Fold { 686 /// /* ... */ 687 /// 688 /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { 689 /// fold_expr_binary(self, node) 690 /// } 691 /// 692 /// /* ... */ 693 /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; 694 /// # fn fold_expr(&mut self, node: Expr) -> Expr; 695 /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; 696 /// } 697 /// 698 /// pub fn fold_expr_binary(v: &mut V, node: ExprBinary) -> ExprBinary 699 /// where 700 /// V: Fold + ?Sized, 701 /// { 702 /// ExprBinary { 703 /// attrs: node 704 /// .attrs 705 /// .into_iter() 706 /// .map(|attr| v.fold_attribute(attr)) 707 /// .collect(), 708 /// left: Box::new(v.fold_expr(*node.left)), 709 /// op: v.fold_bin_op(node.op), 710 /// right: Box::new(v.fold_expr(*node.right)), 711 /// } 712 /// } 713 /// 714 /// /* ... */ 715 /// ``` 716 /// 717 ///
718 /// 719 /// # Example 720 /// 721 /// This fold inserts parentheses to fully parenthesizes any expression. 722 /// 723 /// ``` 724 /// // [dependencies] 725 /// // quote = "1" 726 /// // syn = { version = "3", features = ["fold", "full"] } 727 /// 728 /// use quote::quote; 729 /// use syn::fold::{fold_expr, Fold}; 730 /// use syn::{token, Expr, ExprParen}; 731 /// 732 /// struct ParenthesizeEveryExpr; 733 /// 734 /// impl Fold for ParenthesizeEveryExpr { 735 /// fn fold_expr(&mut self, expr: Expr) -> Expr { 736 /// Expr::Paren(ExprParen { 737 /// attrs: Vec::new(), 738 /// expr: Box::new(fold_expr(self, expr)), 739 /// paren_token: token::Paren::default(), 740 /// }) 741 /// } 742 /// } 743 /// 744 /// fn main() { 745 /// let code = quote! { a() + b(1) * c.d }; 746 /// let expr: Expr = syn::parse2(code).unwrap(); 747 /// let parenthesized = ParenthesizeEveryExpr.fold_expr(expr); 748 /// println!("{}", quote!(#parenthesized)); 749 /// 750 /// // Output: (((a)()) + (((b)((1))) * ((c).d))) 751 /// } 752 /// ``` 753 #[cfg(feature = "fold")] 754 #[cfg_attr(docsrs, doc(cfg(feature = "fold")))] 755 #[rustfmt::skip] 756 pub mod fold; 757 758 /// Syntax tree traversal to walk a shared borrow of a syntax tree. 759 /// 760 /// Each method of the [`Visit`] trait is a hook that can be overridden to 761 /// customize the behavior when visiting the corresponding type of node. By 762 /// default, every method recursively visits the substructure of the input 763 /// by invoking the right visitor method of each of its fields. 764 /// 765 /// [`Visit`]: visit::Visit 766 /// 767 /// ``` 768 /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; 769 /// # 770 /// pub trait Visit<'ast> { 771 /// /* ... */ 772 /// 773 /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { 774 /// visit_expr_binary(self, node); 775 /// } 776 /// 777 /// /* ... */ 778 /// # fn visit_attribute(&mut self, node: &'ast Attribute); 779 /// # fn visit_expr(&mut self, node: &'ast Expr); 780 /// # fn visit_bin_op(&mut self, node: &'ast BinOp); 781 /// } 782 /// 783 /// pub fn visit_expr_binary<'ast, V>(v: &mut V, node: &'ast ExprBinary) 784 /// where 785 /// V: Visit<'ast> + ?Sized, 786 /// { 787 /// for attr in &node.attrs { 788 /// v.visit_attribute(attr); 789 /// } 790 /// v.visit_expr(&*node.left); 791 /// v.visit_bin_op(&node.op); 792 /// v.visit_expr(&*node.right); 793 /// } 794 /// 795 /// /* ... */ 796 /// ``` 797 /// 798 ///
799 /// 800 /// # Example 801 /// 802 /// This visitor will print the name of every freestanding function in the 803 /// syntax tree, including nested functions. 804 /// 805 /// ``` 806 /// // [dependencies] 807 /// // quote = "1" 808 /// // syn = { version = "3", features = ["full", "visit"] } 809 /// 810 /// use quote::quote; 811 /// use syn::visit::{self, Visit}; 812 /// use syn::{File, ItemFn}; 813 /// 814 /// struct FnVisitor; 815 /// 816 /// impl<'ast> Visit<'ast> for FnVisitor { 817 /// fn visit_item_fn(&mut self, node: &'ast ItemFn) { 818 /// println!("Function with name={}", node.sig.ident); 819 /// 820 /// // Delegate to the default impl to visit any nested functions. 821 /// visit::visit_item_fn(self, node); 822 /// } 823 /// } 824 /// 825 /// fn main() { 826 /// let code = quote! { 827 /// pub fn f() { 828 /// fn g() {} 829 /// } 830 /// }; 831 /// 832 /// let syntax_tree: File = syn::parse2(code).unwrap(); 833 /// FnVisitor.visit_file(&syntax_tree); 834 /// } 835 /// ``` 836 /// 837 /// The `'ast` lifetime on the input references means that the syntax tree 838 /// outlives the complete recursive visit call, so the visitor is allowed to 839 /// hold on to references into the syntax tree. 840 /// 841 /// ``` 842 /// use quote::quote; 843 /// use syn::visit::{self, Visit}; 844 /// use syn::{File, ItemFn}; 845 /// 846 /// struct FnVisitor<'ast> { 847 /// functions: Vec<&'ast ItemFn>, 848 /// } 849 /// 850 /// impl<'ast> Visit<'ast> for FnVisitor<'ast> { 851 /// fn visit_item_fn(&mut self, node: &'ast ItemFn) { 852 /// self.functions.push(node); 853 /// visit::visit_item_fn(self, node); 854 /// } 855 /// } 856 /// 857 /// fn main() { 858 /// let code = quote! { 859 /// pub fn f() { 860 /// fn g() {} 861 /// } 862 /// }; 863 /// 864 /// let syntax_tree: File = syn::parse2(code).unwrap(); 865 /// let mut visitor = FnVisitor { functions: Vec::new() }; 866 /// visitor.visit_file(&syntax_tree); 867 /// for f in visitor.functions { 868 /// println!("Function with name={}", f.sig.ident); 869 /// } 870 /// } 871 /// ``` 872 #[cfg(feature = "visit")] 873 #[cfg_attr(docsrs, doc(cfg(feature = "visit")))] 874 #[rustfmt::skip] 875 pub mod visit; 876 877 /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in 878 /// place. 879 /// 880 /// Each method of the [`VisitMut`] trait is a hook that can be overridden 881 /// to customize the behavior when mutating the corresponding type of node. 882 /// By default, every method recursively visits the substructure of the 883 /// input by invoking the right visitor method of each of its fields. 884 /// 885 /// [`VisitMut`]: visit_mut::VisitMut 886 /// 887 /// ``` 888 /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; 889 /// # 890 /// pub trait VisitMut { 891 /// /* ... */ 892 /// 893 /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { 894 /// visit_expr_binary_mut(self, node); 895 /// } 896 /// 897 /// /* ... */ 898 /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); 899 /// # fn visit_expr_mut(&mut self, node: &mut Expr); 900 /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); 901 /// } 902 /// 903 /// pub fn visit_expr_binary_mut(v: &mut V, node: &mut ExprBinary) 904 /// where 905 /// V: VisitMut + ?Sized, 906 /// { 907 /// for attr in &mut node.attrs { 908 /// v.visit_attribute_mut(attr); 909 /// } 910 /// v.visit_expr_mut(&mut *node.left); 911 /// v.visit_bin_op_mut(&mut node.op); 912 /// v.visit_expr_mut(&mut *node.right); 913 /// } 914 /// 915 /// /* ... */ 916 /// ``` 917 /// 918 ///
919 /// 920 /// # Example 921 /// 922 /// This mut visitor replace occurrences of u256 suffixed integer literals 923 /// like `999u256` with a macro invocation `bigint::u256!(999)`. 924 /// 925 /// ``` 926 /// // [dependencies] 927 /// // quote = "1" 928 /// // syn = { version = "3", features = ["full", "visit-mut"] } 929 /// 930 /// use quote::quote; 931 /// use syn::visit_mut::{self, VisitMut}; 932 /// use syn::{parse_quote, Expr, File, Lit, LitInt}; 933 /// 934 /// struct BigintReplace; 935 /// 936 /// impl VisitMut for BigintReplace { 937 /// fn visit_expr_mut(&mut self, node: &mut Expr) { 938 /// if let Expr::Lit(expr) = &node { 939 /// if let Lit::Int(int) = &expr.lit { 940 /// if int.suffix() == "u256" { 941 /// let digits = int.base10_digits(); 942 /// let unsuffixed: LitInt = syn::parse_str(digits).unwrap(); 943 /// *node = parse_quote!(bigint::u256!(#unsuffixed)); 944 /// return; 945 /// } 946 /// } 947 /// } 948 /// 949 /// // Delegate to the default impl to visit nested expressions. 950 /// visit_mut::visit_expr_mut(self, node); 951 /// } 952 /// } 953 /// 954 /// fn main() { 955 /// let code = quote! { 956 /// fn main() { 957 /// let _ = 999u256; 958 /// } 959 /// }; 960 /// 961 /// let mut syntax_tree: File = syn::parse2(code).unwrap(); 962 /// BigintReplace.visit_file_mut(&mut syntax_tree); 963 /// println!("{}", quote!(#syntax_tree)); 964 /// } 965 /// ``` 966 #[cfg(feature = "visit-mut")] 967 #[cfg_attr(docsrs, doc(cfg(feature = "visit-mut")))] 968 #[rustfmt::skip] 969 pub mod visit_mut; 970 971 #[cfg(feature = "clone-impls")] 972 #[rustfmt::skip] 973 mod clone; 974 975 #[cfg(feature = "extra-traits")] 976 #[rustfmt::skip] 977 mod debug; 978 979 #[cfg(feature = "extra-traits")] 980 #[rustfmt::skip] 981 mod eq; 982 983 #[cfg(feature = "extra-traits")] 984 #[rustfmt::skip] 985 mod hash; 986 } 987 988 #[cfg(feature = "fold")] 989 #[cfg_attr(docsrs, doc(cfg(feature = "fold")))] 990 pub use crate::gen::fold; 991 992 #[cfg(feature = "visit")] 993 #[cfg_attr(docsrs, doc(cfg(feature = "visit")))] 994 pub use crate::gen::visit; 995 996 #[cfg(feature = "visit-mut")] 997 #[cfg_attr(docsrs, doc(cfg(feature = "visit-mut")))] 998 pub use crate::gen::visit_mut; 999 1000 // Not public API. 1001 #[doc(hidden)] 1002 #[path = "export.rs"] 1003 pub mod __private; 1004 1005 #[cfg(all(feature = "parsing", feature = "full"))] 1006 use alloc::string::ToString; 1007 1008 /// Parse tokens of source code into the chosen syntax tree node. 1009 /// 1010 /// This is preferred over parsing a string because tokens are able to preserve 1011 /// information about where in the user's code they were originally written (the 1012 /// "span" of the token), possibly allowing the compiler to produce better error 1013 /// messages. 1014 /// 1015 /// This function parses a `proc_macro::TokenStream` which is the type used for 1016 /// interop with the compiler in a procedural macro. To parse a 1017 /// `proc_macro2::TokenStream`, use [`syn::parse2`] instead. 1018 /// 1019 /// [`syn::parse2`]: parse2 1020 /// 1021 /// This function enforces that the input is fully parsed. If there are any 1022 /// unparsed tokens at the end of the stream, an error is returned. 1023 #[cfg(all(feature = "parsing", feature = "proc-macro"))] 1024 #[cfg_attr(docsrs, doc(cfg(all(feature = "parsing", feature = "proc-macro"))))] 1025 pub fn parse(tokens: proc_macro::TokenStream) -> Result { 1026 parse::Parser::parse(T::parse, tokens) 1027 } 1028 1029 /// Parse a proc-macro2 token stream into the chosen syntax tree node. 1030 /// 1031 /// This function parses a `proc_macro2::TokenStream` which is commonly useful 1032 /// when the input comes from a node of the Syn syntax tree, for example the 1033 /// body tokens of a [`Macro`] node. When in a procedural macro parsing the 1034 /// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`] 1035 /// instead. 1036 /// 1037 /// [`syn::parse`]: parse() 1038 /// 1039 /// This function enforces that the input is fully parsed. If there are any 1040 /// unparsed tokens at the end of the stream, an error is returned. 1041 #[cfg(feature = "parsing")] 1042 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] 1043 pub fn parse2(tokens: proc_macro2::TokenStream) -> Result { 1044 parse::Parser::parse2(T::parse, tokens) 1045 } 1046 1047 /// Parse a string of Rust code into the chosen syntax tree node. 1048 /// 1049 /// This function enforces that the input is fully parsed. If there are any 1050 /// unparsed tokens at the end of the stream, an error is returned. 1051 /// 1052 /// # Hygiene 1053 /// 1054 /// Every span in the resulting syntax tree will be set to resolve at the macro 1055 /// call site. 1056 /// 1057 /// # Examples 1058 /// 1059 /// ``` 1060 /// use syn::{Expr, Result}; 1061 /// 1062 /// fn run() -> Result<()> { 1063 /// let code = "assert_eq!(u8::max_value(), 255)"; 1064 /// let expr = syn::parse_str::(code)?; 1065 /// println!("{:#?}", expr); 1066 /// Ok(()) 1067 /// } 1068 /// # 1069 /// # run().unwrap(); 1070 /// ``` 1071 #[cfg(feature = "parsing")] 1072 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] 1073 pub fn parse_str(s: &str) -> Result { 1074 parse::Parser::parse_str(T::parse, s) 1075 } 1076 1077 /// Parse the content of a file of Rust code. 1078 /// 1079 /// This is different from `syn::parse_str::(content)` in two ways: 1080 /// 1081 /// - It discards a leading byte order mark `\u{FEFF}` if the file has one. 1082 /// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. 1083 /// 1084 /// If present, either of these would be an error using `from_str`. 1085 /// 1086 /// # Examples 1087 /// 1088 /// ```no_run 1089 /// use std::error::Error; 1090 /// use std::fs; 1091 /// use std::io::Read; 1092 /// 1093 /// fn run() -> Result<(), Box> { 1094 /// let content = fs::read_to_string("path/to/code.rs")?; 1095 /// let ast = syn::parse_file(&content)?; 1096 /// if let Some(shebang) = ast.shebang { 1097 /// println!("{}", shebang); 1098 /// } 1099 /// println!("{} items", ast.items.len()); 1100 /// 1101 /// Ok(()) 1102 /// } 1103 /// # 1104 /// # run().unwrap(); 1105 /// ``` 1106 #[cfg(all(feature = "parsing", feature = "full"))] 1107 #[cfg_attr(docsrs, doc(cfg(all(feature = "parsing", feature = "full"))))] 1108 pub fn parse_file(mut content: &str) -> Result { 1109 // Strip the BOM if it is present 1110 const BOM: &str = "\u{feff}"; 1111 if content.starts_with(BOM) { 1112 content = &content[BOM.len()..]; 1113 } 1114 1115 let mut shebang = None; 1116 if content.starts_with("#!") { 1117 let rest = whitespace::skip(&content[2..]); 1118 if !rest.starts_with('[') { 1119 if let Some(idx) = content.find('\n') { 1120 shebang = Some(content[..idx].to_string()); 1121 content = &content[idx..]; 1122 } else { 1123 shebang = Some(content.to_string()); 1124 content = ""; 1125 } 1126 } 1127 } 1128 1129 let mut file: File = parse_str(content)?; 1130 file.shebang = shebang; 1131 Ok(file) 1132 }