blob: 4e45405af3c9946c7c97fe6fb90edb79ecc80294 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnay5e84e972018-01-05 17:51:06 -08009//! Syn is a parsing library for parsing a stream of Rust tokens into a syntax
10//! tree of Rust source code.
11//!
David Tolnay6b889eb2018-09-01 18:12:17 -070012//! Currently this library is geared toward use in Rust procedural macros, but
13//! contains some APIs that may be useful more generally.
David Tolnay5e84e972018-01-05 17:51:06 -080014//!
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//! - **Custom derives** — Of particular interest to custom derives 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 trait of your own.
25//!
David Tolnay6b889eb2018-09-01 18:12:17 -070026//! - **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.
David Tolnay5e84e972018-01-05 17:51:06 -080031//!
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`]: struct.File.html
43//! [`syn::Item`]: enum.Item.html
44//! [`syn::Expr`]: enum.Expr.html
45//! [`syn::Type`]: enum.Type.html
46//! [`syn::DeriveInput`]: struct.DeriveInput.html
David Tolnay6b889eb2018-09-01 18:12:17 -070047//! [parser functions]: parse/index.html
David Tolnay5e84e972018-01-05 17:51:06 -080048//!
49//! *Version requirement: Syn supports any compiler version back to Rust's very
50//! first support for procedural macros in Rust 1.15.0. Some features especially
51//! around error reporting are only available in newer compilers or on the
52//! nightly channel.*
53//!
54//! ## Example of a custom derive
55//!
56//! The canonical custom derive using Syn looks like this. We write an ordinary
57//! Rust function tagged with a `proc_macro_derive` attribute and the name of
58//! the trait we are deriving. Any time that derive appears in the user's code,
59//! the Rust compiler passes their data structure as tokens into our macro. We
60//! get to execute arbitrary Rust code to figure out what to do with those
61//! tokens, then hand some tokens back to the compiler to compile into the
62//! user's crate.
63//!
64//! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html
65//!
66//! ```toml
67//! [dependencies]
David Tolnayb28acf32018-09-06 09:01:40 -070068//! syn = "0.15"
David Tolnay87003d02018-05-20 19:45:13 -070069//! quote = "0.6"
David Tolnay5e84e972018-01-05 17:51:06 -080070//!
71//! [lib]
72//! proc-macro = true
73//! ```
74//!
75//! ```rust
David Tolnaya1c98072018-09-06 08:58:10 -070076//! #[macro_use]
77//! extern crate quote;
78//! #[macro_use]
79//! extern crate syn;
80//!
81//! extern crate proc_macro;
82//!
David Tolnay5e84e972018-01-05 17:51:06 -080083//! use proc_macro::TokenStream;
David Tolnaya1c98072018-09-06 08:58:10 -070084//! use syn::DeriveInput;
David Tolnay5e84e972018-01-05 17:51:06 -080085//!
86//! # const IGNORE_TOKENS: &str = stringify! {
87//! #[proc_macro_derive(MyMacro)]
88//! # };
89//! pub fn my_macro(input: TokenStream) -> TokenStream {
90//! // Parse the input tokens into a syntax tree
David Tolnay6b889eb2018-09-01 18:12:17 -070091//! let input = parse_macro_input!(input as DeriveInput);
David Tolnay5e84e972018-01-05 17:51:06 -080092//!
93//! // Build the output, possibly using quasi-quotation
94//! let expanded = quote! {
95//! // ...
96//! };
97//!
98//! // Hand the output tokens back to the compiler
David Tolnay35b498e2018-09-01 20:10:40 -070099//! TokenStream::from(expanded)
David Tolnay5e84e972018-01-05 17:51:06 -0800100//! }
101//! #
102//! # fn main() {}
103//! ```
104//!
105//! The [`heapsize`] example directory shows a complete working Macros 1.1
David Tolnayb4f57242018-10-28 17:57:08 -0700106//! implementation of a custom derive. It works on any Rust compiler 1.15+.
David Tolnay5e84e972018-01-05 17:51:06 -0800107//! The example derives a `HeapSize` trait which computes an estimate of the
108//! amount of heap memory owned by a value.
109//!
110//! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize
111//!
112//! ```rust
113//! pub trait HeapSize {
114//! /// Total number of bytes of heap memory owned by `self`.
115//! fn heap_size_of_children(&self) -> usize;
116//! }
117//! ```
118//!
119//! The custom derive allows users to write `#[derive(HeapSize)]` on data
120//! structures in their program.
121//!
122//! ```rust
123//! # const IGNORE_TOKENS: &str = stringify! {
124//! #[derive(HeapSize)]
125//! # };
126//! struct Demo<'a, T: ?Sized> {
127//! a: Box<T>,
128//! b: u8,
129//! c: &'a str,
130//! d: String,
131//! }
132//! ```
133//!
134//! ## Spans and error reporting
135//!
David Tolnay5e84e972018-01-05 17:51:06 -0800136//! The token-based procedural macro API provides great control over where the
137//! compiler's error messages are displayed in user code. Consider the error the
138//! user sees if one of their field types does not implement `HeapSize`.
139//!
140//! ```rust
141//! # const IGNORE_TOKENS: &str = stringify! {
142//! #[derive(HeapSize)]
143//! # };
144//! struct Broken {
145//! ok: String,
146//! bad: std::thread::Thread,
147//! }
148//! ```
149//!
David Tolnay5e84e972018-01-05 17:51:06 -0800150//! By tracking span information all the way through the expansion of a
David Tolnay3be1b782018-10-28 17:41:41 -0700151//! procedural macro as shown in the `heapsize` example, token-based macros in
David Tolnay5e84e972018-01-05 17:51:06 -0800152//! Syn are able to trigger errors that directly pinpoint the source of the
153//! problem.
154//!
155//! ```text
156//! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied
157//! --> src/main.rs:7:5
158//! |
159//! 7 | bad: std::thread::Thread,
David Tolnayefff2ff2018-01-07 11:49:52 -0800160//! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread`
David Tolnay5e84e972018-01-05 17:51:06 -0800161//! ```
162//!
David Tolnay6b889eb2018-09-01 18:12:17 -0700163//! ## Parsing a custom syntax
David Tolnay5e84e972018-01-05 17:51:06 -0800164//!
165//! The [`lazy-static`] example directory shows the implementation of a
166//! `functionlike!(...)` procedural macro in which the input tokens are parsed
David Tolnay6b889eb2018-09-01 18:12:17 -0700167//! using Syn's parsing API.
David Tolnay5e84e972018-01-05 17:51:06 -0800168//!
169//! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static
David Tolnay5e84e972018-01-05 17:51:06 -0800170//!
171//! The example reimplements the popular `lazy_static` crate from crates.io as a
172//! procedural macro.
173//!
174//! ```
175//! # macro_rules! lazy_static {
176//! # ($($tt:tt)*) => {}
177//! # }
178//! #
179//! lazy_static! {
180//! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap();
181//! }
182//! ```
183//!
184//! The implementation shows how to trigger custom warnings and error messages
185//! on the macro input.
186//!
187//! ```text
188//! warning: come on, pick a more creative name
189//! --> src/main.rs:10:16
190//! |
191//! 10 | static ref FOO: String = "lazy_static".to_owned();
192//! | ^^^
193//! ```
194//!
195//! ## Debugging
196//!
197//! When developing a procedural macro it can be helpful to look at what the
198//! generated code looks like. Use `cargo rustc -- -Zunstable-options
199//! --pretty=expanded` or the [`cargo expand`] subcommand.
200//!
David Tolnay324db2d2018-01-07 11:51:09 -0800201//! [`cargo expand`]: https://github.com/dtolnay/cargo-expand
David Tolnay5e84e972018-01-05 17:51:06 -0800202//!
203//! To show the expanded code for some crate that uses your procedural macro,
204//! run `cargo expand` from that crate. To show the expanded code for one of
205//! your own test cases, run `cargo expand --test the_test_case` where the last
206//! argument is the name of the test file without the `.rs` extension.
207//!
208//! This write-up by Brandon W Maister discusses debugging in more detail:
209//! [Debugging Rust's new Custom Derive system][debugging].
210//!
211//! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/
212//!
213//! ## Optional features
214//!
215//! Syn puts a lot of functionality behind optional features in order to
216//! optimize compile time for the most common use cases. The following features
217//! are available.
218//!
219//! - **`derive`** *(enabled by default)* — Data structures for representing the
220//! possible input to a custom derive, including structs and enums and types.
221//! - **`full`** — Data structures for representing the syntax tree of all valid
222//! Rust source code, including items and expressions.
223//! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into
224//! a syntax tree node of a chosen type.
225//! - **`printing`** *(enabled by default)* — Ability to print a syntax tree
226//! node as tokens of Rust source code.
227//! - **`visit`** — Trait for traversing a syntax tree.
David Tolnay34981cf2018-01-06 16:22:35 -0800228//! - **`visit-mut`** — Trait for traversing and mutating in place a syntax
David Tolnay5e84e972018-01-05 17:51:06 -0800229//! tree.
230//! - **`fold`** — Trait for transforming an owned syntax tree.
231//! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree
232//! types.
233//! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree
234//! types.
hcpl4b72a382018-04-04 14:50:24 +0300235//! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the
236//! dynamic library libproc_macro from rustc toolchain.
David Tolnay5e84e972018-01-05 17:51:06 -0800237
David Tolnay4cf7db82018-01-07 15:22:01 -0800238// Syn types in rustdoc of other crates get linked to here.
David Tolnay89596522018-10-27 23:26:02 -0700239#![doc(html_root_url = "https://docs.rs/syn/0.15.15")]
David Tolnay46b17c02018-09-22 13:27:40 -0700240#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
David Tolnay34071ba2018-05-20 20:00:41 -0700241#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
David Tolnay34071ba2018-05-20 20:00:41 -0700242// Ignored clippy lints.
David Tolnay94d2b792018-04-29 12:26:10 -0700243#![cfg_attr(
244 feature = "cargo-clippy",
245 allow(
David Tolnay4831ac62018-08-30 21:04:16 -0700246 block_in_if_condition_stmt,
David Tolnay0cec3e62018-07-21 09:08:30 -0700247 const_static_lifetime,
David Tolnay24b079d2018-08-27 08:28:10 -0700248 cyclomatic_complexity,
David Tolnay0cec3e62018-07-21 09:08:30 -0700249 doc_markdown,
David Tolnay24b079d2018-08-27 08:28:10 -0700250 eval_order_dependence,
David Tolnay0cec3e62018-07-21 09:08:30 -0700251 large_enum_variant,
252 match_bool,
David Tolnay6fb87462018-09-01 16:51:49 -0700253 never_loop,
David Tolnay0cec3e62018-07-21 09:08:30 -0700254 redundant_closure,
255 needless_pass_by_value,
256 redundant_field_names,
257 trivially_copy_pass_by_ref
David Tolnay94d2b792018-04-29 12:26:10 -0700258 )
259)]
David Tolnay34071ba2018-05-20 20:00:41 -0700260// Ignored clippy_pedantic lints.
261#![cfg_attr(
262 feature = "cargo-clippy",
263 allow(
David Tolnay0cec3e62018-07-21 09:08:30 -0700264 cast_possible_truncation,
265 cast_possible_wrap,
David Tolnayb1617752018-08-24 21:16:33 -0400266 empty_enum,
David Tolnay0cec3e62018-07-21 09:08:30 -0700267 if_not_else,
268 indexing_slicing,
269 items_after_statements,
David Tolnay151f92f2018-08-14 22:44:53 -0700270 shadow_unrelated,
David Tolnay0cec3e62018-07-21 09:08:30 -0700271 similar_names,
272 single_match_else,
273 stutter,
274 unseparated_literal_suffix,
275 use_self,
276 used_underscore_binding
David Tolnay34071ba2018-05-20 20:00:41 -0700277 )
278)]
David Tolnayb503da62018-10-12 21:29:26 -0700279// False positive: https://github.com/rust-lang-nursery/rust-clippy/issues/3274
280#![cfg_attr(feature = "cargo-clippy", allow(map_clone))]
David Tolnayad2836d2017-04-20 10:11:43 -0700281
David Tolnay278f9e32018-08-14 22:41:11 -0700282#[cfg(all(
283 not(all(target_arch = "wasm32", target_os = "unknown")),
284 feature = "proc-macro"
285))]
David Tolnay51382052017-12-27 13:46:21 -0500286extern crate proc_macro;
David Tolnay94d2b792018-04-29 12:26:10 -0700287extern crate proc_macro2;
David Tolnay570695e2017-06-03 16:15:13 -0700288extern crate unicode_xid;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700289
David Tolnay1cf80912017-12-31 18:35:12 -0500290#[cfg(feature = "printing")]
David Tolnay87d0b442016-09-04 11:52:12 -0700291extern crate quote;
292
Alex Crichton62a0a592017-05-22 13:58:53 -0700293#[macro_use]
294mod macros;
295
David Tolnay734079e2018-09-01 02:03:37 -0700296// Not public API.
David Tolnay852bff72018-08-27 08:24:02 -0700297#[cfg(feature = "parsing")]
David Tolnay734079e2018-09-01 02:03:37 -0700298#[doc(hidden)]
David Tolnay852bff72018-08-27 08:24:02 -0700299#[macro_use]
David Tolnay734079e2018-09-01 02:03:37 -0700300pub mod group;
David Tolnay852bff72018-08-27 08:24:02 -0700301
David Tolnayc5ab8c62017-12-26 16:43:39 -0500302#[macro_use]
David Tolnay32954ef2017-12-26 22:43:16 -0500303pub mod token;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500304
David Tolnay4fb71232018-08-25 23:14:50 -0400305mod ident;
306pub use ident::Ident;
David Tolnaye303b7c2018-05-20 16:46:35 -0700307
David Tolnay3cfd1d32018-01-03 00:22:08 -0800308#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700309mod attr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800310#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay161f2de2018-10-13 14:38:20 -0700311pub use attr::{AttrStyle, Attribute, AttributeArgs, Meta, MetaList, MetaNameValue, NestedMeta};
David Tolnay35161ff2016-09-03 11:33:15 -0700312
David Tolnay3cfd1d32018-01-03 00:22:08 -0800313#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf38cdf62016-09-23 19:07:09 -0700314mod data;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800315#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700316pub use data::{
317 Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted,
318 Visibility,
319};
David Tolnayf38cdf62016-09-23 19:07:09 -0700320
David Tolnay3cfd1d32018-01-03 00:22:08 -0800321#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700322mod expr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800323#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700324pub use expr::{
David Tolnay02a9c6f2018-08-24 18:58:45 -0400325 Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprBinary, ExprBlock, ExprBox,
326 ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprGroup,
David Tolnay9c119122018-09-01 18:47:02 -0700327 ExprIf, ExprInPlace, ExprIndex, ExprLet, ExprLit, ExprLoop, ExprMacro, ExprMatch,
David Tolnay02a9c6f2018-08-24 18:58:45 -0400328 ExprMethodCall, ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn,
329 ExprStruct, ExprTry, ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprVerbatim,
David Tolnay9c119122018-09-01 18:47:02 -0700330 ExprWhile, ExprYield, Index, Member,
David Tolnayb57c8492018-05-05 00:32:04 -0700331};
Michael Layzell734adb42017-06-07 16:58:31 -0400332
333#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700334pub use expr::{
335 Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, MethodTurbofish, Pat,
336 PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice, PatStruct, PatTuple,
337 PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt,
338};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700339
David Tolnay3cfd1d32018-01-03 00:22:08 -0800340#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700341mod generics;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800342#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700343pub use generics::{
344 BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
345 PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound,
346 WhereClause, WherePredicate,
347};
David Tolnaye614f282018-10-27 22:50:12 -0700348#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800349pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -0700350
David Tolnayf38cdf62016-09-23 19:07:09 -0700351#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -0700352mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -0700353#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700354pub use item::{
David Tolnay435c1782018-08-24 16:15:44 -0400355 ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, ForeignItemMacro,
356 ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst,
David Tolnaybb82ef02018-08-24 20:15:45 -0400357 ImplItemExistential, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item,
358 ItemConst, ItemEnum, ItemExistential, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl,
David Tolnayc6b04dd2018-08-30 23:22:51 -0700359 ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType,
360 ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro,
361 TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName, UsePath,
362 UseRename, UseTree,
David Tolnayb57c8492018-05-05 00:32:04 -0700363};
David Tolnay35161ff2016-09-03 11:33:15 -0700364
David Tolnay631cb8c2016-11-10 17:16:41 -0800365#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700366mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -0800367#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700368pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -0800369
David Tolnay63e3dee2017-06-03 20:13:17 -0700370mod lifetime;
371pub use lifetime::Lifetime;
372
David Tolnay3cfd1d32018-01-03 00:22:08 -0800373#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700374mod lit;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800375#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700376pub use lit::{
377 FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr,
378 LitVerbatim, StrStyle,
379};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700380
David Tolnay3cfd1d32018-01-03 00:22:08 -0800381#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700382mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800383#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -0500384pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700385
David Tolnay3cfd1d32018-01-03 00:22:08 -0800386#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -0500387mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800388#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -0500389pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -0700390
David Tolnay3cfd1d32018-01-03 00:22:08 -0800391#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700392mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800393#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700394pub use op::{BinOp, UnOp};
395
David Tolnay3cfd1d32018-01-03 00:22:08 -0800396#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700397mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800398#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700399pub use ty::{
400 Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup,
401 TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference,
402 TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim,
403};
David Tolnay056de302018-01-05 14:29:05 -0800404
405#[cfg(any(feature = "full", feature = "derive"))]
406mod path;
407#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700408pub use path::{
David Tolnay9d0882a2018-09-01 19:49:14 -0700409 AngleBracketedGenericArguments, Binding, Constraint, GenericArgument,
410 ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf,
David Tolnayb57c8492018-05-05 00:32:04 -0700411};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700412
David Tolnay1b752fb2017-12-26 21:41:39 -0500413#[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800414pub mod buffer;
David Tolnay94d304f2018-08-30 23:43:53 -0700415#[cfg(feature = "parsing")]
416pub mod ext;
David Tolnay94d2b792018-04-29 12:26:10 -0700417pub mod punctuated;
David Tolnaye614f282018-10-27 22:50:12 -0700418#[cfg(all(any(feature = "full", feature = "derive"), feature = "extra-traits"))]
David Tolnaye0824032017-12-27 15:25:56 -0500419mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500420
David Tolnaye83ef5a2018-01-11 15:18:36 -0800421// Not public API except the `parse_quote!` macro.
David Tolnay491680a2018-01-23 00:34:40 -0800422#[cfg(feature = "parsing")]
David Tolnaye83ef5a2018-01-11 15:18:36 -0800423#[doc(hidden)]
424pub mod parse_quote;
425
David Tolnayf98865f2018-10-13 14:37:07 -0700426// Not public API except the `parse_macro_input!` macro.
427#[cfg(all(
428 not(all(target_arch = "wasm32", target_os = "unknown")),
429 feature = "parsing",
430 feature = "proc-macro"
431))]
432#[doc(hidden)]
433pub mod parse_macro_input;
434
David Tolnay4d942b42018-01-02 22:14:04 -0800435#[cfg(all(feature = "parsing", feature = "printing"))]
David Tolnayf790b612017-12-31 18:46:57 -0500436pub mod spanned;
437
Nika Layzella6f46c42017-10-26 15:26:16 -0400438mod gen {
David Tolnayded2d682018-01-06 18:53:53 -0800439 /// Syntax tree traversal to walk a shared borrow of a syntax tree.
440 ///
441 /// Each method of the [`Visit`] trait is a hook that can be overridden to
442 /// customize the behavior when visiting the corresponding type of node. By
443 /// default, every method recursively visits the substructure of the input
444 /// by invoking the right visitor method of each of its fields.
445 ///
446 /// [`Visit`]: trait.Visit.html
447 ///
448 /// ```rust
449 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
450 /// #
451 /// pub trait Visit<'ast> {
452 /// /* ... */
453 ///
454 /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
455 /// for attr in &node.attrs {
456 /// self.visit_attribute(attr);
457 /// }
458 /// self.visit_expr(&*node.left);
459 /// self.visit_bin_op(&node.op);
460 /// self.visit_expr(&*node.right);
461 /// }
462 ///
463 /// /* ... */
464 /// # fn visit_attribute(&mut self, node: &'ast Attribute);
465 /// # fn visit_expr(&mut self, node: &'ast Expr);
466 /// # fn visit_bin_op(&mut self, node: &'ast BinOp);
467 /// }
468 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800469 ///
470 /// *This module is available if Syn is built with the `"visit"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400471 #[cfg(feature = "visit")]
472 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700473
David Tolnayded2d682018-01-06 18:53:53 -0800474 /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
475 /// place.
476 ///
477 /// Each method of the [`VisitMut`] trait is a hook that can be overridden
478 /// to customize the behavior when mutating the corresponding type of node.
479 /// By default, every method recursively visits the substructure of the
480 /// input by invoking the right visitor method of each of its fields.
481 ///
482 /// [`VisitMut`]: trait.VisitMut.html
483 ///
484 /// ```rust
485 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
486 /// #
487 /// pub trait VisitMut {
488 /// /* ... */
489 ///
490 /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) {
491 /// for attr in &mut node.attrs {
492 /// self.visit_attribute_mut(attr);
493 /// }
494 /// self.visit_expr_mut(&mut *node.left);
495 /// self.visit_bin_op_mut(&mut node.op);
496 /// self.visit_expr_mut(&mut *node.right);
497 /// }
498 ///
499 /// /* ... */
500 /// # fn visit_attribute_mut(&mut self, node: &mut Attribute);
501 /// # fn visit_expr_mut(&mut self, node: &mut Expr);
502 /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp);
503 /// }
504 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800505 ///
506 /// *This module is available if Syn is built with the `"visit-mut"`
507 /// feature.*
David Tolnay9df02c42018-01-06 13:52:48 -0800508 #[cfg(feature = "visit-mut")]
Nika Layzella6f46c42017-10-26 15:26:16 -0400509 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400510
David Tolnayded2d682018-01-06 18:53:53 -0800511 /// Syntax tree traversal to transform the nodes of an owned syntax tree.
512 ///
513 /// Each method of the [`Fold`] trait is a hook that can be overridden to
514 /// customize the behavior when transforming the corresponding type of node.
515 /// By default, every method recursively visits the substructure of the
516 /// input by invoking the right visitor method of each of its fields.
517 ///
518 /// [`Fold`]: trait.Fold.html
519 ///
520 /// ```rust
521 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
522 /// #
523 /// pub trait Fold {
524 /// /* ... */
525 ///
526 /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
527 /// ExprBinary {
528 /// attrs: node.attrs
529 /// .into_iter()
530 /// .map(|attr| self.fold_attribute(attr))
531 /// .collect(),
532 /// left: Box::new(self.fold_expr(*node.left)),
533 /// op: self.fold_bin_op(node.op),
534 /// right: Box::new(self.fold_expr(*node.right)),
535 /// }
536 /// }
537 ///
538 /// /* ... */
539 /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute;
540 /// # fn fold_expr(&mut self, node: Expr) -> Expr;
541 /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp;
542 /// }
543 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800544 ///
545 /// *This module is available if Syn is built with the `"fold"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400546 #[cfg(feature = "fold")]
547 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500548
David Tolnay0a0d78c2018-01-05 15:24:01 -0800549 #[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf60f4262017-12-28 19:17:58 -0500550 #[path = "../gen_helper.rs"]
551 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400552}
553pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100554
David Tolnay456c9822018-08-25 08:09:46 -0400555// Not public API.
556#[doc(hidden)]
557pub mod export;
558
David Tolnay7fb11e72018-09-06 01:02:27 -0700559mod keyword;
David Tolnayb6254182018-08-25 08:44:54 -0400560
561#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700562mod lookahead;
Louis Kureuil Personc0beaf32018-09-05 00:12:43 +0200563
564#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400565pub mod parse;
566
David Tolnay776f8e02018-08-24 22:32:10 -0400567mod span;
568
David Tolnaye614f282018-10-27 22:50:12 -0700569#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnay64023912018-08-31 09:51:12 -0700570mod print;
571
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700572////////////////////////////////////////////////////////////////////////////////
573
David Tolnayaa77a852018-08-31 11:15:10 -0700574#[cfg(any(feature = "parsing", feature = "full", feature = "derive"))]
David Tolnay94f06632018-08-31 10:17:17 -0700575#[allow(non_camel_case_types)]
David Tolnay10951d52018-08-31 10:27:39 -0700576struct private;
David Tolnay94f06632018-08-31 10:17:17 -0700577
578////////////////////////////////////////////////////////////////////////////////
579
David Tolnay55337722016-09-11 12:58:56 -0700580#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400581mod error;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500582#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400583use error::Error;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500584
David Tolnayccab0be2018-01-06 22:24:47 -0800585/// Parse tokens of source code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700586///
587/// This is preferred over parsing a string because tokens are able to preserve
588/// information about where in the user's code they were originally written (the
589/// "span" of the token), possibly allowing the compiler to produce better error
590/// messages.
591///
David Tolnayccab0be2018-01-06 22:24:47 -0800592/// This function parses a `proc_macro::TokenStream` which is the type used for
593/// interop with the compiler in a procedural macro. To parse a
594/// `proc_macro2::TokenStream`, use [`syn::parse2`] instead.
595///
596/// [`syn::parse2`]: fn.parse2.html
597///
hcpl4b72a382018-04-04 14:50:24 +0300598/// *This function is available if Syn is built with both the `"parsing"` and
599/// `"proc-macro"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800600///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700601/// # Examples
602///
David Tolnaybcf26022017-12-25 22:10:52 -0500603/// ```rust
David Tolnaya1c98072018-09-06 08:58:10 -0700604/// #[macro_use]
605/// extern crate quote;
606///
607/// extern crate proc_macro;
608/// extern crate syn;
609///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700610/// use proc_macro::TokenStream;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700611/// use syn::DeriveInput;
612///
David Tolnaybcf26022017-12-25 22:10:52 -0500613/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700614/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500615/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700616/// pub fn my_macro(input: TokenStream) -> TokenStream {
617/// // Parse the tokens into a syntax tree
618/// let ast: DeriveInput = syn::parse(input).unwrap();
619///
620/// // Build the output, possibly using quasi-quotation
621/// let expanded = quote! {
622/// /* ... */
623/// };
624///
David Tolnaybcf26022017-12-25 22:10:52 -0500625/// // Convert into a token stream and return it
626/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700627/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500628/// #
629/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700630/// ```
David Tolnay278f9e32018-08-14 22:41:11 -0700631#[cfg(all(
632 not(all(target_arch = "wasm32", target_os = "unknown")),
633 feature = "parsing",
634 feature = "proc-macro"
635))]
David Tolnaye82a2b12018-08-30 16:31:10 -0700636pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700637 parse::Parser::parse(T::parse, tokens)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700638}
639
David Tolnayccab0be2018-01-06 22:24:47 -0800640/// Parse a proc-macro2 token stream into the chosen syntax tree node.
641///
642/// This function parses a `proc_macro2::TokenStream` which is commonly useful
643/// when the input comes from a node of the Syn syntax tree, for example the tts
644/// of a [`Macro`] node. When in a procedural macro parsing the
645/// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`]
646/// instead.
647///
648/// [`Macro`]: struct.Macro.html
649/// [`syn::parse`]: fn.parse.html
David Tolnay461d98e2018-01-07 11:07:19 -0800650///
651/// *This function is available if Syn is built with the `"parsing"` feature.*
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700652#[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -0700653pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700654 parse::Parser::parse2(T::parse, tokens)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700655}
Alex Crichton954046c2017-05-30 21:49:42 -0700656
David Tolnayccab0be2018-01-06 22:24:47 -0800657/// Parse a string of Rust code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700658///
David Tolnay461d98e2018-01-07 11:07:19 -0800659/// *This function is available if Syn is built with the `"parsing"` feature.*
660///
David Tolnay3f5b06f2018-01-11 21:02:00 -0800661/// # Hygiene
662///
663/// Every span in the resulting syntax tree will be set to resolve at the macro
664/// call site.
665///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700666/// # Examples
667///
668/// ```rust
David Tolnay9b00f652018-09-01 10:31:02 -0700669/// # extern crate syn;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700670/// #
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700671/// use syn::Expr;
David Tolnay9b00f652018-09-01 10:31:02 -0700672/// use syn::parse::Result;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700673///
674/// fn run() -> Result<()> {
675/// let code = "assert_eq!(u8::max_value(), 255)";
676/// let expr = syn::parse_str::<Expr>(code)?;
677/// println!("{:#?}", expr);
678/// Ok(())
679/// }
680/// #
681/// # fn main() { run().unwrap() }
682/// ```
683#[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -0700684pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700685 parse::Parser::parse_str(T::parse, s)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700686}
Alex Crichton954046c2017-05-30 21:49:42 -0700687
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700688// FIXME the name parse_file makes it sound like you might pass in a path to a
689// file, rather than the content.
690/// Parse the content of a file of Rust code.
691///
692/// This is different from `syn::parse_str::<File>(content)` in two ways:
693///
694/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
695/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
696///
697/// If present, either of these would be an error using `from_str`.
698///
Christopher Serr9727ef22018-02-03 16:42:12 +0100699/// *This function is available if Syn is built with the `"parsing"` and `"full"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800700///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700701/// # Examples
702///
703/// ```rust,no_run
David Tolnay9b00f652018-09-01 10:31:02 -0700704/// # extern crate syn;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700705/// #
David Tolnay9b00f652018-09-01 10:31:02 -0700706/// use std::error::Error;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700707/// use std::fs::File;
708/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700709///
David Tolnay9b00f652018-09-01 10:31:02 -0700710/// fn run() -> Result<(), Box<Error>> {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700711/// let mut file = File::open("path/to/code.rs")?;
712/// let mut content = String::new();
713/// file.read_to_string(&mut content)?;
714///
715/// let ast = syn::parse_file(&content)?;
716/// if let Some(shebang) = ast.shebang {
717/// println!("{}", shebang);
718/// }
719/// println!("{} items", ast.items.len());
720///
721/// Ok(())
722/// }
723/// #
724/// # fn main() { run().unwrap() }
725/// ```
726#[cfg(all(feature = "parsing", feature = "full"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400727pub fn parse_file(mut content: &str) -> Result<File, Error> {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700728 // Strip the BOM if it is present
729 const BOM: &'static str = "\u{feff}";
730 if content.starts_with(BOM) {
731 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700732 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500733
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700734 let mut shebang = None;
735 if content.starts_with("#!") && !content.starts_with("#![") {
736 if let Some(idx) = content.find('\n') {
737 shebang = Some(content[..idx].to_string());
738 content = &content[idx..];
739 } else {
740 shebang = Some(content.to_string());
741 content = "";
742 }
Alex Crichton954046c2017-05-30 21:49:42 -0700743 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800744
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700745 let mut file: File = parse_str(content)?;
746 file.shebang = shebang;
747 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500748}