blob: 6299856e750eb83603723053ab09cffb21b4304e [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//!
12//! Currently this library is geared toward the [custom derive] use case but
13//! contains some APIs that may be useful for Rust procedural macros more
14//! generally.
15//!
16//! [custom derive]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md
17//!
18//! - **Data structures** — Syn provides a complete syntax tree that can
19//! represent any valid Rust source code. The syntax tree is rooted at
20//! [`syn::File`] which represents a full source file, but there are other
21//! entry points that may be useful to procedural macros including
22//! [`syn::Item`], [`syn::Expr`] and [`syn::Type`].
23//!
24//! - **Custom derives** — Of particular interest to custom derives is
25//! [`syn::DeriveInput`] which is any of the three legal input items to a
26//! derive macro. An example below shows using this type in a library that can
27//! derive implementations of a trait of your own.
28//!
29//! - **Parser combinators** — Parsing in Syn is built on a suite of public
30//! parser combinator macros that you can use for parsing any token-based
31//! syntax you dream up within a `functionlike!(...)` procedural macro. Every
32//! syntax tree node defined by Syn is individually parsable and may be used
33//! as a building block for custom syntaxes, or you may do it all yourself
34//! working from the most primitive tokens.
35//!
36//! - **Location information** — Every token parsed by Syn is associated with a
37//! `Span` that tracks line and column information back to the source of that
38//! token. These spans allow a procedural macro to display detailed error
39//! messages pointing to all the right places in the user's code. There is an
40//! example of this below.
41//!
42//! - **Feature flags** — Functionality is aggressively feature gated so your
43//! procedural macros enable only what they need, and do not pay in compile
44//! time for all the rest.
45//!
46//! [`syn::File`]: struct.File.html
47//! [`syn::Item`]: enum.Item.html
48//! [`syn::Expr`]: enum.Expr.html
49//! [`syn::Type`]: enum.Type.html
50//! [`syn::DeriveInput`]: struct.DeriveInput.html
51//!
52//! *Version requirement: Syn supports any compiler version back to Rust's very
53//! first support for procedural macros in Rust 1.15.0. Some features especially
54//! around error reporting are only available in newer compilers or on the
55//! nightly channel.*
56//!
57//! ## Example of a custom derive
58//!
59//! The canonical custom derive using Syn looks like this. We write an ordinary
60//! Rust function tagged with a `proc_macro_derive` attribute and the name of
61//! the trait we are deriving. Any time that derive appears in the user's code,
62//! the Rust compiler passes their data structure as tokens into our macro. We
63//! get to execute arbitrary Rust code to figure out what to do with those
64//! tokens, then hand some tokens back to the compiler to compile into the
65//! user's crate.
66//!
67//! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html
68//!
69//! ```toml
70//! [dependencies]
David Tolnay87003d02018-05-20 19:45:13 -070071//! syn = "0.14"
72//! quote = "0.6"
David Tolnay5e84e972018-01-05 17:51:06 -080073//!
74//! [lib]
75//! proc-macro = true
76//! ```
77//!
78//! ```rust
79//! extern crate proc_macro;
80//! extern crate syn;
81//!
82//! #[macro_use]
83//! extern crate quote;
84//!
85//! use proc_macro::TokenStream;
86//! use syn::DeriveInput;
87//!
88//! # const IGNORE_TOKENS: &str = stringify! {
89//! #[proc_macro_derive(MyMacro)]
90//! # };
91//! pub fn my_macro(input: TokenStream) -> TokenStream {
92//! // Parse the input tokens into a syntax tree
93//! let input: DeriveInput = syn::parse(input).unwrap();
94//!
95//! // Build the output, possibly using quasi-quotation
96//! let expanded = quote! {
97//! // ...
98//! };
99//!
100//! // Hand the output tokens back to the compiler
101//! expanded.into()
102//! }
103//! #
104//! # fn main() {}
105//! ```
106//!
107//! The [`heapsize`] example directory shows a complete working Macros 1.1
108//! implementation of a custom derive. It works on any Rust compiler \>=1.15.0.
109//! The example derives a `HeapSize` trait which computes an estimate of the
110//! amount of heap memory owned by a value.
111//!
112//! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize
113//!
114//! ```rust
115//! pub trait HeapSize {
116//! /// Total number of bytes of heap memory owned by `self`.
117//! fn heap_size_of_children(&self) -> usize;
118//! }
119//! ```
120//!
121//! The custom derive allows users to write `#[derive(HeapSize)]` on data
122//! structures in their program.
123//!
124//! ```rust
125//! # const IGNORE_TOKENS: &str = stringify! {
126//! #[derive(HeapSize)]
127//! # };
128//! struct Demo<'a, T: ?Sized> {
129//! a: Box<T>,
130//! b: u8,
131//! c: &'a str,
132//! d: String,
133//! }
134//! ```
135//!
136//! ## Spans and error reporting
137//!
138//! The [`heapsize2`] example directory is an extension of the `heapsize`
139//! example that demonstrates some of the hygiene and error reporting properties
140//! of Macros 2.0. This example currently requires a nightly Rust compiler
141//! \>=1.24.0-nightly but we are working to stabilize all of the APIs involved.
142//!
143//! [`heapsize2`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize2
144//!
145//! The token-based procedural macro API provides great control over where the
146//! compiler's error messages are displayed in user code. Consider the error the
147//! user sees if one of their field types does not implement `HeapSize`.
148//!
149//! ```rust
150//! # const IGNORE_TOKENS: &str = stringify! {
151//! #[derive(HeapSize)]
152//! # };
153//! struct Broken {
154//! ok: String,
155//! bad: std::thread::Thread,
156//! }
157//! ```
158//!
159//! In the Macros 1.1 string-based procedural macro world, the resulting error
160//! would point unhelpfully to the invocation of the derive macro and not to the
161//! actual problematic field.
162//!
163//! ```text
164//! error[E0599]: no method named `heap_size_of_children` found for type `std::thread::Thread` in the current scope
165//! --> src/main.rs:4:10
166//! |
167//! 4 | #[derive(HeapSize)]
168//! | ^^^^^^^^
169//! ```
170//!
171//! By tracking span information all the way through the expansion of a
172//! procedural macro as shown in the `heapsize2` example, token-based macros in
173//! Syn are able to trigger errors that directly pinpoint the source of the
174//! problem.
175//!
176//! ```text
177//! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied
178//! --> src/main.rs:7:5
179//! |
180//! 7 | bad: std::thread::Thread,
David Tolnayefff2ff2018-01-07 11:49:52 -0800181//! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread`
David Tolnay5e84e972018-01-05 17:51:06 -0800182//! ```
183//!
184//! ## Parsing a custom syntax using combinators
185//!
186//! The [`lazy-static`] example directory shows the implementation of a
187//! `functionlike!(...)` procedural macro in which the input tokens are parsed
188//! using [`nom`]-style parser combinators.
189//!
190//! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static
191//! [`nom`]: https://github.com/Geal/nom
192//!
193//! The example reimplements the popular `lazy_static` crate from crates.io as a
194//! procedural macro.
195//!
196//! ```
197//! # macro_rules! lazy_static {
198//! # ($($tt:tt)*) => {}
199//! # }
200//! #
201//! lazy_static! {
202//! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap();
203//! }
204//! ```
205//!
206//! The implementation shows how to trigger custom warnings and error messages
207//! on the macro input.
208//!
209//! ```text
210//! warning: come on, pick a more creative name
211//! --> src/main.rs:10:16
212//! |
213//! 10 | static ref FOO: String = "lazy_static".to_owned();
214//! | ^^^
215//! ```
216//!
217//! ## Debugging
218//!
219//! When developing a procedural macro it can be helpful to look at what the
220//! generated code looks like. Use `cargo rustc -- -Zunstable-options
221//! --pretty=expanded` or the [`cargo expand`] subcommand.
222//!
David Tolnay324db2d2018-01-07 11:51:09 -0800223//! [`cargo expand`]: https://github.com/dtolnay/cargo-expand
David Tolnay5e84e972018-01-05 17:51:06 -0800224//!
225//! To show the expanded code for some crate that uses your procedural macro,
226//! run `cargo expand` from that crate. To show the expanded code for one of
227//! your own test cases, run `cargo expand --test the_test_case` where the last
228//! argument is the name of the test file without the `.rs` extension.
229//!
230//! This write-up by Brandon W Maister discusses debugging in more detail:
231//! [Debugging Rust's new Custom Derive system][debugging].
232//!
233//! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/
234//!
235//! ## Optional features
236//!
237//! Syn puts a lot of functionality behind optional features in order to
238//! optimize compile time for the most common use cases. The following features
239//! are available.
240//!
241//! - **`derive`** *(enabled by default)* — Data structures for representing the
242//! possible input to a custom derive, including structs and enums and types.
243//! - **`full`** — Data structures for representing the syntax tree of all valid
244//! Rust source code, including items and expressions.
245//! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into
246//! a syntax tree node of a chosen type.
247//! - **`printing`** *(enabled by default)* — Ability to print a syntax tree
248//! node as tokens of Rust source code.
249//! - **`visit`** — Trait for traversing a syntax tree.
David Tolnay34981cf2018-01-06 16:22:35 -0800250//! - **`visit-mut`** — Trait for traversing and mutating in place a syntax
David Tolnay5e84e972018-01-05 17:51:06 -0800251//! tree.
252//! - **`fold`** — Trait for transforming an owned syntax tree.
253//! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree
254//! types.
255//! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree
256//! types.
hcpl4b72a382018-04-04 14:50:24 +0300257//! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the
258//! dynamic library libproc_macro from rustc toolchain.
David Tolnay5e84e972018-01-05 17:51:06 -0800259
David Tolnay4cf7db82018-01-07 15:22:01 -0800260// Syn types in rustdoc of other crates get linked to here.
David Tolnaydd8ae772018-08-12 10:02:20 -0700261#![doc(html_root_url = "https://docs.rs/syn/0.14.8")]
David Tolnay34071ba2018-05-20 20:00:41 -0700262#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
David Tolnay34071ba2018-05-20 20:00:41 -0700263// Ignored clippy lints.
David Tolnay94d2b792018-04-29 12:26:10 -0700264#![cfg_attr(
265 feature = "cargo-clippy",
266 allow(
David Tolnay0cec3e62018-07-21 09:08:30 -0700267 const_static_lifetime,
268 doc_markdown,
269 large_enum_variant,
270 match_bool,
271 redundant_closure,
272 needless_pass_by_value,
273 redundant_field_names,
274 trivially_copy_pass_by_ref
David Tolnay94d2b792018-04-29 12:26:10 -0700275 )
276)]
David Tolnay34071ba2018-05-20 20:00:41 -0700277// Ignored clippy_pedantic lints.
278#![cfg_attr(
279 feature = "cargo-clippy",
280 allow(
David Tolnay0cec3e62018-07-21 09:08:30 -0700281 cast_possible_truncation,
282 cast_possible_wrap,
283 if_not_else,
284 indexing_slicing,
285 items_after_statements,
286 similar_names,
287 single_match_else,
288 stutter,
289 unseparated_literal_suffix,
290 use_self,
291 used_underscore_binding
David Tolnay34071ba2018-05-20 20:00:41 -0700292 )
293)]
David Tolnayad2836d2017-04-20 10:11:43 -0700294
David Tolnay278f9e32018-08-14 22:41:11 -0700295#[cfg(all(
296 not(all(target_arch = "wasm32", target_os = "unknown")),
297 feature = "proc-macro"
298))]
David Tolnay51382052017-12-27 13:46:21 -0500299extern crate proc_macro;
David Tolnay94d2b792018-04-29 12:26:10 -0700300extern crate proc_macro2;
David Tolnay570695e2017-06-03 16:15:13 -0700301extern crate unicode_xid;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700302
David Tolnay1cf80912017-12-31 18:35:12 -0500303#[cfg(feature = "printing")]
David Tolnay87d0b442016-09-04 11:52:12 -0700304extern crate quote;
305
David Tolnay1b752fb2017-12-26 21:41:39 -0500306#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800307#[macro_use]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500308#[doc(hidden)]
309pub mod parsers;
David Tolnay35161ff2016-09-03 11:33:15 -0700310
Alex Crichton62a0a592017-05-22 13:58:53 -0700311#[macro_use]
312mod macros;
313
David Tolnayc5ab8c62017-12-26 16:43:39 -0500314#[macro_use]
David Tolnay32954ef2017-12-26 22:43:16 -0500315pub mod token;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500316
David Tolnaye303b7c2018-05-20 16:46:35 -0700317pub use proc_macro2::Ident;
318
David Tolnay3cfd1d32018-01-03 00:22:08 -0800319#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700320mod attr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800321#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayaaadd782018-01-06 22:58:13 -0800322pub use attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue, NestedMeta};
David Tolnay35161ff2016-09-03 11:33:15 -0700323
David Tolnay3cfd1d32018-01-03 00:22:08 -0800324#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf38cdf62016-09-23 19:07:09 -0700325mod data;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800326#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700327pub use data::{
328 Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted,
329 Visibility,
330};
David Tolnayf38cdf62016-09-23 19:07:09 -0700331
David Tolnay3cfd1d32018-01-03 00:22:08 -0800332#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700333mod expr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800334#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700335pub use expr::{
336 Expr, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox, ExprBreak, ExprCall,
337 ExprCast, ExprCatch, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprGroup, ExprIf,
338 ExprIfLet, ExprInPlace, ExprIndex, ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall,
339 ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn, ExprStruct, ExprTry,
340 ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield,
341 Index, Member,
342};
Michael Layzell734adb42017-06-07 16:58:31 -0400343
344#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700345pub use expr::{
346 Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, MethodTurbofish, Pat,
347 PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice, PatStruct, PatTuple,
348 PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt,
349};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700350
David Tolnay3cfd1d32018-01-03 00:22:08 -0800351#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700352mod generics;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800353#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700354pub use generics::{
355 BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
356 PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound,
357 WhereClause, WherePredicate,
358};
David Tolnay278f9e32018-08-14 22:41:11 -0700359#[cfg(all(
360 any(feature = "full", feature = "derive"),
361 feature = "printing"
362))]
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800363pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -0700364
David Tolnayf38cdf62016-09-23 19:07:09 -0700365#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -0700366mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -0700367#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700368pub use item::{
369 ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, ForeignItemStatic,
370 ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst, ImplItemMacro, ImplItemMethod,
371 ImplItemType, ImplItemVerbatim, Item, ItemConst, ItemEnum, ItemExternCrate, ItemFn,
372 ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait,
373 ItemType, ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst,
374 TraitItemMacro, TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName,
375 UsePath, UseRename, UseTree,
376};
David Tolnay35161ff2016-09-03 11:33:15 -0700377
David Tolnay631cb8c2016-11-10 17:16:41 -0800378#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700379mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -0800380#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700381pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -0800382
David Tolnay3cfd1d32018-01-03 00:22:08 -0800383#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -0700384mod lifetime;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800385#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -0700386pub use lifetime::Lifetime;
387
David Tolnay3cfd1d32018-01-03 00:22:08 -0800388#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700389mod lit;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800390#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700391pub use lit::{
392 FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr,
393 LitVerbatim, StrStyle,
394};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700395
David Tolnay3cfd1d32018-01-03 00:22:08 -0800396#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700397mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800398#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -0500399pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700400
David Tolnay3cfd1d32018-01-03 00:22:08 -0800401#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -0500402mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800403#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -0500404pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -0700405
David Tolnay3cfd1d32018-01-03 00:22:08 -0800406#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700407mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800408#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700409pub use op::{BinOp, UnOp};
410
David Tolnay3cfd1d32018-01-03 00:22:08 -0800411#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700412mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800413#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700414pub use ty::{
415 Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup,
416 TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference,
417 TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim,
418};
David Tolnay056de302018-01-05 14:29:05 -0800419
420#[cfg(any(feature = "full", feature = "derive"))]
421mod path;
David Tolnay278f9e32018-08-14 22:41:11 -0700422#[cfg(all(
423 any(feature = "full", feature = "derive"),
424 feature = "printing"
425))]
David Tolnay94d2b792018-04-29 12:26:10 -0700426pub use path::PathTokens;
David Tolnay056de302018-01-05 14:29:05 -0800427#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700428pub use path::{
429 AngleBracketedGenericArguments, Binding, GenericArgument, ParenthesizedGenericArguments, Path,
430 PathArguments, PathSegment, QSelf,
431};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700432
David Tolnay1b752fb2017-12-26 21:41:39 -0500433#[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800434pub mod buffer;
David Tolnay94d2b792018-04-29 12:26:10 -0700435pub mod punctuated;
David Tolnay1b752fb2017-12-26 21:41:39 -0500436#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500437pub mod synom;
David Tolnaycc543712018-01-08 11:29:54 -0800438#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaye0824032017-12-27 15:25:56 -0500439mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500440
David Tolnaye83ef5a2018-01-11 15:18:36 -0800441// Not public API except the `parse_quote!` macro.
David Tolnay491680a2018-01-23 00:34:40 -0800442#[cfg(feature = "parsing")]
David Tolnaye83ef5a2018-01-11 15:18:36 -0800443#[doc(hidden)]
444pub mod parse_quote;
445
David Tolnay4d942b42018-01-02 22:14:04 -0800446#[cfg(all(feature = "parsing", feature = "printing"))]
David Tolnayf790b612017-12-31 18:46:57 -0500447pub mod spanned;
448
David Tolnaydc3d6242018-08-01 00:30:47 -0700449#[cfg(all(feature = "parsing", feature = "full"))]
David Tolnay9be32582018-07-31 22:37:26 -0700450mod verbatim;
451
Nika Layzella6f46c42017-10-26 15:26:16 -0400452mod gen {
David Tolnayded2d682018-01-06 18:53:53 -0800453 /// Syntax tree traversal to walk a shared borrow of a syntax tree.
454 ///
455 /// Each method of the [`Visit`] trait is a hook that can be overridden to
456 /// customize the behavior when visiting the corresponding type of node. By
457 /// default, every method recursively visits the substructure of the input
458 /// by invoking the right visitor method of each of its fields.
459 ///
460 /// [`Visit`]: trait.Visit.html
461 ///
462 /// ```rust
463 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
464 /// #
465 /// pub trait Visit<'ast> {
466 /// /* ... */
467 ///
468 /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
469 /// for attr in &node.attrs {
470 /// self.visit_attribute(attr);
471 /// }
472 /// self.visit_expr(&*node.left);
473 /// self.visit_bin_op(&node.op);
474 /// self.visit_expr(&*node.right);
475 /// }
476 ///
477 /// /* ... */
478 /// # fn visit_attribute(&mut self, node: &'ast Attribute);
479 /// # fn visit_expr(&mut self, node: &'ast Expr);
480 /// # fn visit_bin_op(&mut self, node: &'ast BinOp);
481 /// }
482 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800483 ///
484 /// *This module is available if Syn is built with the `"visit"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400485 #[cfg(feature = "visit")]
486 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700487
David Tolnayded2d682018-01-06 18:53:53 -0800488 /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
489 /// place.
490 ///
491 /// Each method of the [`VisitMut`] trait is a hook that can be overridden
492 /// to customize the behavior when mutating the corresponding type of node.
493 /// By default, every method recursively visits the substructure of the
494 /// input by invoking the right visitor method of each of its fields.
495 ///
496 /// [`VisitMut`]: trait.VisitMut.html
497 ///
498 /// ```rust
499 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
500 /// #
501 /// pub trait VisitMut {
502 /// /* ... */
503 ///
504 /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) {
505 /// for attr in &mut node.attrs {
506 /// self.visit_attribute_mut(attr);
507 /// }
508 /// self.visit_expr_mut(&mut *node.left);
509 /// self.visit_bin_op_mut(&mut node.op);
510 /// self.visit_expr_mut(&mut *node.right);
511 /// }
512 ///
513 /// /* ... */
514 /// # fn visit_attribute_mut(&mut self, node: &mut Attribute);
515 /// # fn visit_expr_mut(&mut self, node: &mut Expr);
516 /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp);
517 /// }
518 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800519 ///
520 /// *This module is available if Syn is built with the `"visit-mut"`
521 /// feature.*
David Tolnay9df02c42018-01-06 13:52:48 -0800522 #[cfg(feature = "visit-mut")]
Nika Layzella6f46c42017-10-26 15:26:16 -0400523 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400524
David Tolnayded2d682018-01-06 18:53:53 -0800525 /// Syntax tree traversal to transform the nodes of an owned syntax tree.
526 ///
527 /// Each method of the [`Fold`] trait is a hook that can be overridden to
528 /// customize the behavior when transforming the corresponding type of node.
529 /// By default, every method recursively visits the substructure of the
530 /// input by invoking the right visitor method of each of its fields.
531 ///
532 /// [`Fold`]: trait.Fold.html
533 ///
534 /// ```rust
535 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
536 /// #
537 /// pub trait Fold {
538 /// /* ... */
539 ///
540 /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
541 /// ExprBinary {
542 /// attrs: node.attrs
543 /// .into_iter()
544 /// .map(|attr| self.fold_attribute(attr))
545 /// .collect(),
546 /// left: Box::new(self.fold_expr(*node.left)),
547 /// op: self.fold_bin_op(node.op),
548 /// right: Box::new(self.fold_expr(*node.right)),
549 /// }
550 /// }
551 ///
552 /// /* ... */
553 /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute;
554 /// # fn fold_expr(&mut self, node: Expr) -> Expr;
555 /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp;
556 /// }
557 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800558 ///
559 /// *This module is available if Syn is built with the `"fold"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400560 #[cfg(feature = "fold")]
561 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500562
David Tolnay0a0d78c2018-01-05 15:24:01 -0800563 #[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf60f4262017-12-28 19:17:58 -0500564 #[path = "../gen_helper.rs"]
565 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400566}
567pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100568
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700569////////////////////////////////////////////////////////////////////////////////
570
David Tolnay55337722016-09-11 12:58:56 -0700571#[cfg(feature = "parsing")]
David Tolnay94d2b792018-04-29 12:26:10 -0700572use synom::{Parser, Synom};
Ted Driggs054abbb2017-05-01 12:20:52 -0700573
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700574#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500575mod error;
576#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500577use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500578
579// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500580#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500581#[doc(hidden)]
582pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400583
David Tolnayccab0be2018-01-06 22:24:47 -0800584/// Parse tokens of source code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700585///
586/// This is preferred over parsing a string because tokens are able to preserve
587/// information about where in the user's code they were originally written (the
588/// "span" of the token), possibly allowing the compiler to produce better error
589/// messages.
590///
David Tolnayccab0be2018-01-06 22:24:47 -0800591/// This function parses a `proc_macro::TokenStream` which is the type used for
592/// interop with the compiler in a procedural macro. To parse a
593/// `proc_macro2::TokenStream`, use [`syn::parse2`] instead.
594///
595/// [`syn::parse2`]: fn.parse2.html
596///
hcpl4b72a382018-04-04 14:50:24 +0300597/// *This function is available if Syn is built with both the `"parsing"` and
598/// `"proc-macro"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800599///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700600/// # Examples
601///
David Tolnaybcf26022017-12-25 22:10:52 -0500602/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700603/// extern crate proc_macro;
604/// use proc_macro::TokenStream;
605///
606/// extern crate syn;
607///
608/// #[macro_use]
609/// extern crate quote;
610///
611/// 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 Tolnayc7a5d3d2017-06-04 12:11:05 -0700636pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500637where
638 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700639{
David Tolnay04c5dca2018-01-05 20:12:21 -0800640 parse2(tokens.into())
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700641}
642
David Tolnayccab0be2018-01-06 22:24:47 -0800643/// Parse a proc-macro2 token stream into the chosen syntax tree node.
644///
645/// This function parses a `proc_macro2::TokenStream` which is commonly useful
646/// when the input comes from a node of the Syn syntax tree, for example the tts
647/// of a [`Macro`] node. When in a procedural macro parsing the
648/// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`]
649/// instead.
650///
651/// [`Macro`]: struct.Macro.html
652/// [`syn::parse`]: fn.parse.html
David Tolnay461d98e2018-01-07 11:07:19 -0800653///
654/// *This function is available if Syn is built with the `"parsing"` feature.*
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700655#[cfg(feature = "parsing")]
David Tolnay04c5dca2018-01-05 20:12:21 -0800656pub fn parse2<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500657where
658 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700659{
David Tolnayca7cd972018-01-11 14:23:06 -0800660 let parser = T::parse;
David Tolnay94d2b792018-04-29 12:26:10 -0700661 parser.parse2(tokens).map_err(|err| match T::description() {
662 Some(s) => ParseError::new(format!("failed to parse {}: {}", s, err)),
663 None => err,
David Tolnayca7cd972018-01-11 14:23:06 -0800664 })
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700665}
Alex Crichton954046c2017-05-30 21:49:42 -0700666
David Tolnayccab0be2018-01-06 22:24:47 -0800667/// Parse a string of Rust code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700668///
David Tolnay461d98e2018-01-07 11:07:19 -0800669/// *This function is available if Syn is built with the `"parsing"` feature.*
670///
David Tolnay3f5b06f2018-01-11 21:02:00 -0800671/// # Hygiene
672///
673/// Every span in the resulting syntax tree will be set to resolve at the macro
674/// call site.
675///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700676/// # Examples
677///
678/// ```rust
679/// extern crate syn;
680/// #
David Tolnay9174b972017-11-09 22:27:50 -0800681/// #
682/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700683///
684/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700685///
686/// fn run() -> Result<()> {
687/// let code = "assert_eq!(u8::max_value(), 255)";
688/// let expr = syn::parse_str::<Expr>(code)?;
689/// println!("{:#?}", expr);
690/// Ok(())
691/// }
692/// #
693/// # fn main() { run().unwrap() }
694/// ```
695#[cfg(feature = "parsing")]
696pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500697 match s.parse() {
David Tolnay04c5dca2018-01-05 20:12:21 -0800698 Ok(tts) => parse2(tts),
David Tolnayffb1f4d2017-12-28 00:07:59 -0500699 Err(_) => Err(ParseError::new("error while lexing input string")),
700 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700701}
Alex Crichton954046c2017-05-30 21:49:42 -0700702
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700703// FIXME the name parse_file makes it sound like you might pass in a path to a
704// file, rather than the content.
705/// Parse the content of a file of Rust code.
706///
707/// This is different from `syn::parse_str::<File>(content)` in two ways:
708///
709/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
710/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
711///
712/// If present, either of these would be an error using `from_str`.
713///
Christopher Serr9727ef22018-02-03 16:42:12 +0100714/// *This function is available if Syn is built with the `"parsing"` and `"full"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800715///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700716/// # Examples
717///
718/// ```rust,no_run
719/// extern crate syn;
720/// #
David Tolnay9174b972017-11-09 22:27:50 -0800721/// #
722/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700723///
724/// use std::fs::File;
725/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700726///
727/// fn run() -> Result<()> {
728/// let mut file = File::open("path/to/code.rs")?;
729/// let mut content = String::new();
730/// file.read_to_string(&mut content)?;
731///
732/// let ast = syn::parse_file(&content)?;
733/// if let Some(shebang) = ast.shebang {
734/// println!("{}", shebang);
735/// }
736/// println!("{} items", ast.items.len());
737///
738/// Ok(())
739/// }
740/// #
741/// # fn main() { run().unwrap() }
742/// ```
743#[cfg(all(feature = "parsing", feature = "full"))]
744pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
745 // Strip the BOM if it is present
746 const BOM: &'static str = "\u{feff}";
747 if content.starts_with(BOM) {
748 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700749 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500750
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700751 let mut shebang = None;
752 if content.starts_with("#!") && !content.starts_with("#![") {
753 if let Some(idx) = content.find('\n') {
754 shebang = Some(content[..idx].to_string());
755 content = &content[idx..];
756 } else {
757 shebang = Some(content.to_string());
758 content = "";
759 }
Alex Crichton954046c2017-05-30 21:49:42 -0700760 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800761
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700762 let mut file: File = parse_str(content)?;
763 file.shebang = shebang;
764 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500765}
Alex Crichton259ee532017-07-14 06:51:02 -0700766
David Tolnay278f9e32018-08-14 22:41:11 -0700767#[cfg(all(
768 any(feature = "full", feature = "derive"),
769 feature = "printing"
770))]
Alex Crichton259ee532017-07-14 06:51:02 -0700771struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
772
David Tolnay278f9e32018-08-14 22:41:11 -0700773#[cfg(all(
774 any(feature = "full", feature = "derive"),
775 feature = "printing"
776))]
Alex Crichton259ee532017-07-14 06:51:02 -0700777impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500778where
779 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700780{
Alex Crichtona74a1c82018-05-16 10:20:44 -0700781 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
Alex Crichton259ee532017-07-14 06:51:02 -0700782 match *self.0 {
783 Some(ref t) => t.to_tokens(tokens),
784 None => T::default().to_tokens(tokens),
785 }
786 }
787}