blob: ed04e7c571c6abd0809a386b9e5d99d5db2c5ee5 [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 Tolnay87003d02018-05-20 19:45:13 -070068//! syn = "0.14"
69//! quote = "0.6"
David Tolnay5e84e972018-01-05 17:51:06 -080070//!
71//! [lib]
72//! proc-macro = true
73//! ```
74//!
75//! ```rust
David Tolnay9b00f652018-09-01 10:31:02 -070076//! # extern crate proc_macro;
77//! # extern crate quote;
78//! # extern crate syn;
79//! #
David Tolnay5e84e972018-01-05 17:51:06 -080080//! use proc_macro::TokenStream;
David Tolnay9b00f652018-09-01 10:31:02 -070081//! use quote::quote;
David Tolnay6b889eb2018-09-01 18:12:17 -070082//! use syn::{parse_macro_input, DeriveInput};
David Tolnay5e84e972018-01-05 17:51:06 -080083//!
84//! # const IGNORE_TOKENS: &str = stringify! {
85//! #[proc_macro_derive(MyMacro)]
86//! # };
87//! pub fn my_macro(input: TokenStream) -> TokenStream {
88//! // Parse the input tokens into a syntax tree
David Tolnay6b889eb2018-09-01 18:12:17 -070089//! let input = parse_macro_input!(input as DeriveInput);
David Tolnay5e84e972018-01-05 17:51:06 -080090//!
91//! // Build the output, possibly using quasi-quotation
92//! let expanded = quote! {
93//! // ...
94//! };
95//!
96//! // Hand the output tokens back to the compiler
David Tolnay35b498e2018-09-01 20:10:40 -070097//! TokenStream::from(expanded)
David Tolnay5e84e972018-01-05 17:51:06 -080098//! }
99//! #
100//! # fn main() {}
101//! ```
102//!
103//! The [`heapsize`] example directory shows a complete working Macros 1.1
104//! implementation of a custom derive. It works on any Rust compiler \>=1.15.0.
105//! The example derives a `HeapSize` trait which computes an estimate of the
106//! amount of heap memory owned by a value.
107//!
108//! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize
109//!
110//! ```rust
111//! pub trait HeapSize {
112//! /// Total number of bytes of heap memory owned by `self`.
113//! fn heap_size_of_children(&self) -> usize;
114//! }
115//! ```
116//!
117//! The custom derive allows users to write `#[derive(HeapSize)]` on data
118//! structures in their program.
119//!
120//! ```rust
121//! # const IGNORE_TOKENS: &str = stringify! {
122//! #[derive(HeapSize)]
123//! # };
124//! struct Demo<'a, T: ?Sized> {
125//! a: Box<T>,
126//! b: u8,
127//! c: &'a str,
128//! d: String,
129//! }
130//! ```
131//!
132//! ## Spans and error reporting
133//!
134//! The [`heapsize2`] example directory is an extension of the `heapsize`
135//! example that demonstrates some of the hygiene and error reporting properties
136//! of Macros 2.0. This example currently requires a nightly Rust compiler
137//! \>=1.24.0-nightly but we are working to stabilize all of the APIs involved.
138//!
139//! [`heapsize2`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize2
140//!
141//! The token-based procedural macro API provides great control over where the
142//! compiler's error messages are displayed in user code. Consider the error the
143//! user sees if one of their field types does not implement `HeapSize`.
144//!
145//! ```rust
146//! # const IGNORE_TOKENS: &str = stringify! {
147//! #[derive(HeapSize)]
148//! # };
149//! struct Broken {
150//! ok: String,
151//! bad: std::thread::Thread,
152//! }
153//! ```
154//!
155//! In the Macros 1.1 string-based procedural macro world, the resulting error
156//! would point unhelpfully to the invocation of the derive macro and not to the
157//! actual problematic field.
158//!
159//! ```text
160//! error[E0599]: no method named `heap_size_of_children` found for type `std::thread::Thread` in the current scope
161//! --> src/main.rs:4:10
162//! |
163//! 4 | #[derive(HeapSize)]
164//! | ^^^^^^^^
165//! ```
166//!
167//! By tracking span information all the way through the expansion of a
168//! procedural macro as shown in the `heapsize2` example, token-based macros in
169//! Syn are able to trigger errors that directly pinpoint the source of the
170//! problem.
171//!
172//! ```text
173//! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied
174//! --> src/main.rs:7:5
175//! |
176//! 7 | bad: std::thread::Thread,
David Tolnayefff2ff2018-01-07 11:49:52 -0800177//! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread`
David Tolnay5e84e972018-01-05 17:51:06 -0800178//! ```
179//!
David Tolnay6b889eb2018-09-01 18:12:17 -0700180//! ## Parsing a custom syntax
David Tolnay5e84e972018-01-05 17:51:06 -0800181//!
182//! The [`lazy-static`] example directory shows the implementation of a
183//! `functionlike!(...)` procedural macro in which the input tokens are parsed
David Tolnay6b889eb2018-09-01 18:12:17 -0700184//! using Syn's parsing API.
David Tolnay5e84e972018-01-05 17:51:06 -0800185//!
186//! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static
David Tolnay5e84e972018-01-05 17:51:06 -0800187//!
188//! The example reimplements the popular `lazy_static` crate from crates.io as a
189//! procedural macro.
190//!
191//! ```
192//! # macro_rules! lazy_static {
193//! # ($($tt:tt)*) => {}
194//! # }
195//! #
196//! lazy_static! {
197//! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap();
198//! }
199//! ```
200//!
201//! The implementation shows how to trigger custom warnings and error messages
202//! on the macro input.
203//!
204//! ```text
205//! warning: come on, pick a more creative name
206//! --> src/main.rs:10:16
207//! |
208//! 10 | static ref FOO: String = "lazy_static".to_owned();
209//! | ^^^
210//! ```
211//!
212//! ## Debugging
213//!
214//! When developing a procedural macro it can be helpful to look at what the
215//! generated code looks like. Use `cargo rustc -- -Zunstable-options
216//! --pretty=expanded` or the [`cargo expand`] subcommand.
217//!
David Tolnay324db2d2018-01-07 11:51:09 -0800218//! [`cargo expand`]: https://github.com/dtolnay/cargo-expand
David Tolnay5e84e972018-01-05 17:51:06 -0800219//!
220//! To show the expanded code for some crate that uses your procedural macro,
221//! run `cargo expand` from that crate. To show the expanded code for one of
222//! your own test cases, run `cargo expand --test the_test_case` where the last
223//! argument is the name of the test file without the `.rs` extension.
224//!
225//! This write-up by Brandon W Maister discusses debugging in more detail:
226//! [Debugging Rust's new Custom Derive system][debugging].
227//!
228//! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/
229//!
230//! ## Optional features
231//!
232//! Syn puts a lot of functionality behind optional features in order to
233//! optimize compile time for the most common use cases. The following features
234//! are available.
235//!
236//! - **`derive`** *(enabled by default)* — Data structures for representing the
237//! possible input to a custom derive, including structs and enums and types.
238//! - **`full`** — Data structures for representing the syntax tree of all valid
239//! Rust source code, including items and expressions.
240//! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into
241//! a syntax tree node of a chosen type.
242//! - **`printing`** *(enabled by default)* — Ability to print a syntax tree
243//! node as tokens of Rust source code.
244//! - **`visit`** — Trait for traversing a syntax tree.
David Tolnay34981cf2018-01-06 16:22:35 -0800245//! - **`visit-mut`** — Trait for traversing and mutating in place a syntax
David Tolnay5e84e972018-01-05 17:51:06 -0800246//! tree.
247//! - **`fold`** — Trait for transforming an owned syntax tree.
248//! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree
249//! types.
250//! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree
251//! types.
hcpl4b72a382018-04-04 14:50:24 +0300252//! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the
253//! dynamic library libproc_macro from rustc toolchain.
David Tolnay5e84e972018-01-05 17:51:06 -0800254
David Tolnay4cf7db82018-01-07 15:22:01 -0800255// Syn types in rustdoc of other crates get linked to here.
David Tolnay445f70a2018-09-02 13:36:04 -0700256#![doc(html_root_url = "https://docs.rs/syn-next/0.15.0-rc3")]
David Tolnay34071ba2018-05-20 20:00:41 -0700257#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
David Tolnay34071ba2018-05-20 20:00:41 -0700258// Ignored clippy lints.
David Tolnay94d2b792018-04-29 12:26:10 -0700259#![cfg_attr(
260 feature = "cargo-clippy",
261 allow(
David Tolnay4831ac62018-08-30 21:04:16 -0700262 block_in_if_condition_stmt,
David Tolnay0cec3e62018-07-21 09:08:30 -0700263 const_static_lifetime,
David Tolnay24b079d2018-08-27 08:28:10 -0700264 cyclomatic_complexity,
David Tolnay0cec3e62018-07-21 09:08:30 -0700265 doc_markdown,
David Tolnay24b079d2018-08-27 08:28:10 -0700266 eval_order_dependence,
David Tolnay0cec3e62018-07-21 09:08:30 -0700267 large_enum_variant,
268 match_bool,
David Tolnay6fb87462018-09-01 16:51:49 -0700269 never_loop,
David Tolnay0cec3e62018-07-21 09:08:30 -0700270 redundant_closure,
271 needless_pass_by_value,
272 redundant_field_names,
273 trivially_copy_pass_by_ref
David Tolnay94d2b792018-04-29 12:26:10 -0700274 )
275)]
David Tolnay34071ba2018-05-20 20:00:41 -0700276// Ignored clippy_pedantic lints.
277#![cfg_attr(
278 feature = "cargo-clippy",
279 allow(
David Tolnay0cec3e62018-07-21 09:08:30 -0700280 cast_possible_truncation,
281 cast_possible_wrap,
David Tolnayb1617752018-08-24 21:16:33 -0400282 empty_enum,
David Tolnay0cec3e62018-07-21 09:08:30 -0700283 if_not_else,
284 indexing_slicing,
285 items_after_statements,
David Tolnay151f92f2018-08-14 22:44:53 -0700286 shadow_unrelated,
David Tolnay0cec3e62018-07-21 09:08:30 -0700287 similar_names,
288 single_match_else,
289 stutter,
290 unseparated_literal_suffix,
291 use_self,
292 used_underscore_binding
David Tolnay34071ba2018-05-20 20:00:41 -0700293 )
294)]
David Tolnayad2836d2017-04-20 10:11:43 -0700295
David Tolnay278f9e32018-08-14 22:41:11 -0700296#[cfg(all(
297 not(all(target_arch = "wasm32", target_os = "unknown")),
298 feature = "proc-macro"
299))]
David Tolnay51382052017-12-27 13:46:21 -0500300extern crate proc_macro;
David Tolnay94d2b792018-04-29 12:26:10 -0700301extern crate proc_macro2;
David Tolnay570695e2017-06-03 16:15:13 -0700302extern crate unicode_xid;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700303
David Tolnay1cf80912017-12-31 18:35:12 -0500304#[cfg(feature = "printing")]
David Tolnay87d0b442016-09-04 11:52:12 -0700305extern crate quote;
306
Alex Crichton62a0a592017-05-22 13:58:53 -0700307#[macro_use]
308mod macros;
309
David Tolnay734079e2018-09-01 02:03:37 -0700310// Not public API.
David Tolnay852bff72018-08-27 08:24:02 -0700311#[cfg(feature = "parsing")]
David Tolnay734079e2018-09-01 02:03:37 -0700312#[doc(hidden)]
David Tolnay852bff72018-08-27 08:24:02 -0700313#[macro_use]
David Tolnay734079e2018-09-01 02:03:37 -0700314pub mod group;
David Tolnay852bff72018-08-27 08:24:02 -0700315
David Tolnayc5ab8c62017-12-26 16:43:39 -0500316#[macro_use]
David Tolnay32954ef2017-12-26 22:43:16 -0500317pub mod token;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500318
David Tolnay4fb71232018-08-25 23:14:50 -0400319mod ident;
320pub use ident::Ident;
David Tolnaye303b7c2018-05-20 16:46:35 -0700321
David Tolnay3cfd1d32018-01-03 00:22:08 -0800322#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700323mod attr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800324#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayaaadd782018-01-06 22:58:13 -0800325pub use attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue, NestedMeta};
David Tolnay35161ff2016-09-03 11:33:15 -0700326
David Tolnay3cfd1d32018-01-03 00:22:08 -0800327#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf38cdf62016-09-23 19:07:09 -0700328mod data;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800329#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700330pub use data::{
331 Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted,
332 Visibility,
333};
David Tolnayf38cdf62016-09-23 19:07:09 -0700334
David Tolnay3cfd1d32018-01-03 00:22:08 -0800335#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700336mod expr;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800337#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700338pub use expr::{
David Tolnay02a9c6f2018-08-24 18:58:45 -0400339 Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprBinary, ExprBlock, ExprBox,
340 ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprGroup,
David Tolnay9c119122018-09-01 18:47:02 -0700341 ExprIf, ExprInPlace, ExprIndex, ExprLet, ExprLit, ExprLoop, ExprMacro, ExprMatch,
David Tolnay02a9c6f2018-08-24 18:58:45 -0400342 ExprMethodCall, ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn,
343 ExprStruct, ExprTry, ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprVerbatim,
David Tolnay9c119122018-09-01 18:47:02 -0700344 ExprWhile, ExprYield, Index, Member,
David Tolnayb57c8492018-05-05 00:32:04 -0700345};
Michael Layzell734adb42017-06-07 16:58:31 -0400346
347#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700348pub use expr::{
349 Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, MethodTurbofish, Pat,
350 PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice, PatStruct, PatTuple,
351 PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt,
352};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700353
David Tolnay3cfd1d32018-01-03 00:22:08 -0800354#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700355mod generics;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800356#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700357pub use generics::{
358 BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
359 PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound,
360 WhereClause, WherePredicate,
361};
David Tolnay278f9e32018-08-14 22:41:11 -0700362#[cfg(all(
363 any(feature = "full", feature = "derive"),
364 feature = "printing"
365))]
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800366pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -0700367
David Tolnayf38cdf62016-09-23 19:07:09 -0700368#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -0700369mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -0700370#[cfg(feature = "full")]
David Tolnayb57c8492018-05-05 00:32:04 -0700371pub use item::{
David Tolnay435c1782018-08-24 16:15:44 -0400372 ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, ForeignItemMacro,
373 ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst,
David Tolnaybb82ef02018-08-24 20:15:45 -0400374 ImplItemExistential, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item,
375 ItemConst, ItemEnum, ItemExistential, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl,
David Tolnayc6b04dd2018-08-30 23:22:51 -0700376 ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType,
377 ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro,
378 TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName, UsePath,
379 UseRename, UseTree,
David Tolnayb57c8492018-05-05 00:32:04 -0700380};
David Tolnay35161ff2016-09-03 11:33:15 -0700381
David Tolnay631cb8c2016-11-10 17:16:41 -0800382#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700383mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -0800384#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700385pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -0800386
David Tolnay63e3dee2017-06-03 20:13:17 -0700387mod lifetime;
388pub use lifetime::Lifetime;
389
David Tolnay3cfd1d32018-01-03 00:22:08 -0800390#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700391mod lit;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800392#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700393pub use lit::{
394 FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr,
395 LitVerbatim, StrStyle,
396};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700397
David Tolnay3cfd1d32018-01-03 00:22:08 -0800398#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700399mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800400#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -0500401pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700402
David Tolnay3cfd1d32018-01-03 00:22:08 -0800403#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -0500404mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800405#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -0500406pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -0700407
David Tolnay3cfd1d32018-01-03 00:22:08 -0800408#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700409mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800410#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700411pub use op::{BinOp, UnOp};
412
David Tolnay3cfd1d32018-01-03 00:22:08 -0800413#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700414mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800415#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700416pub use ty::{
417 Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup,
418 TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference,
419 TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim,
420};
David Tolnay056de302018-01-05 14:29:05 -0800421
422#[cfg(any(feature = "full", feature = "derive"))]
423mod path;
424#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb57c8492018-05-05 00:32:04 -0700425pub use path::{
David Tolnay9d0882a2018-09-01 19:49:14 -0700426 AngleBracketedGenericArguments, Binding, Constraint, GenericArgument,
427 ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf,
David Tolnayb57c8492018-05-05 00:32:04 -0700428};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700429
David Tolnay1b752fb2017-12-26 21:41:39 -0500430#[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800431pub mod buffer;
David Tolnay94d304f2018-08-30 23:43:53 -0700432#[cfg(feature = "parsing")]
433pub mod ext;
David Tolnay94d2b792018-04-29 12:26:10 -0700434pub mod punctuated;
David Tolnay3779bb72018-08-26 18:46:07 -0700435#[cfg(all(
436 any(feature = "full", feature = "derive"),
437 feature = "extra-traits"
438))]
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
Nika Layzella6f46c42017-10-26 15:26:16 -0400449mod gen {
David Tolnayded2d682018-01-06 18:53:53 -0800450 /// Syntax tree traversal to walk a shared borrow of a syntax tree.
451 ///
452 /// Each method of the [`Visit`] trait is a hook that can be overridden to
453 /// customize the behavior when visiting the corresponding type of node. By
454 /// default, every method recursively visits the substructure of the input
455 /// by invoking the right visitor method of each of its fields.
456 ///
457 /// [`Visit`]: trait.Visit.html
458 ///
459 /// ```rust
460 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
461 /// #
462 /// pub trait Visit<'ast> {
463 /// /* ... */
464 ///
465 /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
466 /// for attr in &node.attrs {
467 /// self.visit_attribute(attr);
468 /// }
469 /// self.visit_expr(&*node.left);
470 /// self.visit_bin_op(&node.op);
471 /// self.visit_expr(&*node.right);
472 /// }
473 ///
474 /// /* ... */
475 /// # fn visit_attribute(&mut self, node: &'ast Attribute);
476 /// # fn visit_expr(&mut self, node: &'ast Expr);
477 /// # fn visit_bin_op(&mut self, node: &'ast BinOp);
478 /// }
479 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800480 ///
481 /// *This module is available if Syn is built with the `"visit"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400482 #[cfg(feature = "visit")]
483 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700484
David Tolnayded2d682018-01-06 18:53:53 -0800485 /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
486 /// place.
487 ///
488 /// Each method of the [`VisitMut`] trait is a hook that can be overridden
489 /// to customize the behavior when mutating the corresponding type of node.
490 /// By default, every method recursively visits the substructure of the
491 /// input by invoking the right visitor method of each of its fields.
492 ///
493 /// [`VisitMut`]: trait.VisitMut.html
494 ///
495 /// ```rust
496 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
497 /// #
498 /// pub trait VisitMut {
499 /// /* ... */
500 ///
501 /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) {
502 /// for attr in &mut node.attrs {
503 /// self.visit_attribute_mut(attr);
504 /// }
505 /// self.visit_expr_mut(&mut *node.left);
506 /// self.visit_bin_op_mut(&mut node.op);
507 /// self.visit_expr_mut(&mut *node.right);
508 /// }
509 ///
510 /// /* ... */
511 /// # fn visit_attribute_mut(&mut self, node: &mut Attribute);
512 /// # fn visit_expr_mut(&mut self, node: &mut Expr);
513 /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp);
514 /// }
515 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800516 ///
517 /// *This module is available if Syn is built with the `"visit-mut"`
518 /// feature.*
David Tolnay9df02c42018-01-06 13:52:48 -0800519 #[cfg(feature = "visit-mut")]
Nika Layzella6f46c42017-10-26 15:26:16 -0400520 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400521
David Tolnayded2d682018-01-06 18:53:53 -0800522 /// Syntax tree traversal to transform the nodes of an owned syntax tree.
523 ///
524 /// Each method of the [`Fold`] trait is a hook that can be overridden to
525 /// customize the behavior when transforming the corresponding type of node.
526 /// By default, every method recursively visits the substructure of the
527 /// input by invoking the right visitor method of each of its fields.
528 ///
529 /// [`Fold`]: trait.Fold.html
530 ///
531 /// ```rust
532 /// # use syn::{Attribute, BinOp, Expr, ExprBinary};
533 /// #
534 /// pub trait Fold {
535 /// /* ... */
536 ///
537 /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary {
538 /// ExprBinary {
539 /// attrs: node.attrs
540 /// .into_iter()
541 /// .map(|attr| self.fold_attribute(attr))
542 /// .collect(),
543 /// left: Box::new(self.fold_expr(*node.left)),
544 /// op: self.fold_bin_op(node.op),
545 /// right: Box::new(self.fold_expr(*node.right)),
546 /// }
547 /// }
548 ///
549 /// /* ... */
550 /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute;
551 /// # fn fold_expr(&mut self, node: Expr) -> Expr;
552 /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp;
553 /// }
554 /// ```
David Tolnay461d98e2018-01-07 11:07:19 -0800555 ///
556 /// *This module is available if Syn is built with the `"fold"` feature.*
Nika Layzella6f46c42017-10-26 15:26:16 -0400557 #[cfg(feature = "fold")]
558 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500559
David Tolnay0a0d78c2018-01-05 15:24:01 -0800560 #[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf60f4262017-12-28 19:17:58 -0500561 #[path = "../gen_helper.rs"]
562 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400563}
564pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100565
David Tolnay456c9822018-08-25 08:09:46 -0400566// Not public API.
567#[doc(hidden)]
568pub mod export;
569
David Tolnay7fb11e72018-09-06 01:02:27 -0700570mod keyword;
David Tolnayb6254182018-08-25 08:44:54 -0400571
572#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700573mod lookahead;
Louis Kureuil Personc0beaf32018-09-05 00:12:43 +0200574
575#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400576pub mod parse;
577
David Tolnay776f8e02018-08-24 22:32:10 -0400578mod span;
579
David Tolnay64023912018-08-31 09:51:12 -0700580#[cfg(all(
581 any(feature = "full", feature = "derive"),
582 feature = "printing"
583))]
584mod print;
585
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700586////////////////////////////////////////////////////////////////////////////////
587
David Tolnayaa77a852018-08-31 11:15:10 -0700588#[cfg(any(feature = "parsing", feature = "full", feature = "derive"))]
David Tolnay94f06632018-08-31 10:17:17 -0700589#[allow(non_camel_case_types)]
David Tolnay10951d52018-08-31 10:27:39 -0700590struct private;
David Tolnay94f06632018-08-31 10:17:17 -0700591
592////////////////////////////////////////////////////////////////////////////////
593
David Tolnay55337722016-09-11 12:58:56 -0700594#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400595mod error;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500596#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400597use error::Error;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500598
David Tolnayccab0be2018-01-06 22:24:47 -0800599/// Parse tokens of source code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700600///
601/// This is preferred over parsing a string because tokens are able to preserve
602/// information about where in the user's code they were originally written (the
603/// "span" of the token), possibly allowing the compiler to produce better error
604/// messages.
605///
David Tolnayccab0be2018-01-06 22:24:47 -0800606/// This function parses a `proc_macro::TokenStream` which is the type used for
607/// interop with the compiler in a procedural macro. To parse a
608/// `proc_macro2::TokenStream`, use [`syn::parse2`] instead.
609///
610/// [`syn::parse2`]: fn.parse2.html
611///
hcpl4b72a382018-04-04 14:50:24 +0300612/// *This function is available if Syn is built with both the `"parsing"` and
613/// `"proc-macro"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800614///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700615/// # Examples
616///
David Tolnaybcf26022017-12-25 22:10:52 -0500617/// ```rust
David Tolnay9b00f652018-09-01 10:31:02 -0700618/// # extern crate proc_macro;
619/// # extern crate quote;
620/// # extern crate syn;
621/// #
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700622/// use proc_macro::TokenStream;
David Tolnay9b00f652018-09-01 10:31:02 -0700623/// use quote::quote;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700624/// use syn::DeriveInput;
625///
David Tolnaybcf26022017-12-25 22:10:52 -0500626/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700627/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500628/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700629/// pub fn my_macro(input: TokenStream) -> TokenStream {
630/// // Parse the tokens into a syntax tree
631/// let ast: DeriveInput = syn::parse(input).unwrap();
632///
633/// // Build the output, possibly using quasi-quotation
634/// let expanded = quote! {
635/// /* ... */
636/// };
637///
David Tolnaybcf26022017-12-25 22:10:52 -0500638/// // Convert into a token stream and return it
639/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700640/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500641/// #
642/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700643/// ```
David Tolnay278f9e32018-08-14 22:41:11 -0700644#[cfg(all(
645 not(all(target_arch = "wasm32", target_os = "unknown")),
646 feature = "parsing",
647 feature = "proc-macro"
648))]
David Tolnaye82a2b12018-08-30 16:31:10 -0700649pub fn parse<T: parse::Parse>(tokens: proc_macro::TokenStream) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700650 parse::Parser::parse(T::parse, tokens)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700651}
652
David Tolnayccab0be2018-01-06 22:24:47 -0800653/// Parse a proc-macro2 token stream into the chosen syntax tree node.
654///
655/// This function parses a `proc_macro2::TokenStream` which is commonly useful
656/// when the input comes from a node of the Syn syntax tree, for example the tts
657/// of a [`Macro`] node. When in a procedural macro parsing the
658/// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`]
659/// instead.
660///
661/// [`Macro`]: struct.Macro.html
662/// [`syn::parse`]: fn.parse.html
David Tolnay461d98e2018-01-07 11:07:19 -0800663///
664/// *This function is available if Syn is built with the `"parsing"` feature.*
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700665#[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -0700666pub fn parse2<T: parse::Parse>(tokens: proc_macro2::TokenStream) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700667 parse::Parser::parse2(T::parse, tokens)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700668}
Alex Crichton954046c2017-05-30 21:49:42 -0700669
David Tolnayccab0be2018-01-06 22:24:47 -0800670/// Parse a string of Rust code into the chosen syntax tree node.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700671///
David Tolnay461d98e2018-01-07 11:07:19 -0800672/// *This function is available if Syn is built with the `"parsing"` feature.*
673///
David Tolnay3f5b06f2018-01-11 21:02:00 -0800674/// # Hygiene
675///
676/// Every span in the resulting syntax tree will be set to resolve at the macro
677/// call site.
678///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700679/// # Examples
680///
681/// ```rust
David Tolnay9b00f652018-09-01 10:31:02 -0700682/// # extern crate syn;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700683/// #
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700684/// use syn::Expr;
David Tolnay9b00f652018-09-01 10:31:02 -0700685/// use syn::parse::Result;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700686///
687/// fn run() -> Result<()> {
688/// let code = "assert_eq!(u8::max_value(), 255)";
689/// let expr = syn::parse_str::<Expr>(code)?;
690/// println!("{:#?}", expr);
691/// Ok(())
692/// }
693/// #
694/// # fn main() { run().unwrap() }
695/// ```
696#[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -0700697pub fn parse_str<T: parse::Parse>(s: &str) -> Result<T, Error> {
David Tolnay80a914f2018-08-30 23:49:53 -0700698 parse::Parser::parse_str(T::parse, s)
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700699}
Alex Crichton954046c2017-05-30 21:49:42 -0700700
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700701// FIXME the name parse_file makes it sound like you might pass in a path to a
702// file, rather than the content.
703/// Parse the content of a file of Rust code.
704///
705/// This is different from `syn::parse_str::<File>(content)` in two ways:
706///
707/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
708/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
709///
710/// If present, either of these would be an error using `from_str`.
711///
Christopher Serr9727ef22018-02-03 16:42:12 +0100712/// *This function is available if Syn is built with the `"parsing"` and `"full"` features.*
David Tolnay461d98e2018-01-07 11:07:19 -0800713///
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700714/// # Examples
715///
716/// ```rust,no_run
David Tolnay9b00f652018-09-01 10:31:02 -0700717/// # extern crate syn;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700718/// #
David Tolnay9b00f652018-09-01 10:31:02 -0700719/// use std::error::Error;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700720/// use std::fs::File;
721/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700722///
David Tolnay9b00f652018-09-01 10:31:02 -0700723/// fn run() -> Result<(), Box<Error>> {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700724/// let mut file = File::open("path/to/code.rs")?;
725/// let mut content = String::new();
726/// file.read_to_string(&mut content)?;
727///
728/// let ast = syn::parse_file(&content)?;
729/// if let Some(shebang) = ast.shebang {
730/// println!("{}", shebang);
731/// }
732/// println!("{} items", ast.items.len());
733///
734/// Ok(())
735/// }
736/// #
737/// # fn main() { run().unwrap() }
738/// ```
739#[cfg(all(feature = "parsing", feature = "full"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400740pub fn parse_file(mut content: &str) -> Result<File, Error> {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700741 // Strip the BOM if it is present
742 const BOM: &'static str = "\u{feff}";
743 if content.starts_with(BOM) {
744 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700745 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500746
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700747 let mut shebang = None;
748 if content.starts_with("#!") && !content.starts_with("#![") {
749 if let Some(idx) = content.find('\n') {
750 shebang = Some(content[..idx].to_string());
751 content = &content[idx..];
752 } else {
753 shebang = Some(content.to_string());
754 content = "";
755 }
Alex Crichton954046c2017-05-30 21:49:42 -0700756 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800757
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700758 let mut file: File = parse_str(content)?;
759 file.shebang = shebang;
760 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500761}
Alex Crichton259ee532017-07-14 06:51:02 -0700762
David Tolnayd641ee32018-08-30 17:11:09 -0700763/// Parse the input TokenStream of a macro, triggering a compile error if the
764/// tokens fail to parse.
765///
David Tolnay8580f972018-09-01 17:53:03 -0700766/// Refer to the [`parse` module] documentation for more details about parsing
767/// in Syn.
768///
769/// [`parse` module]: parse/index.html
770///
David Tolnayd641ee32018-08-30 17:11:09 -0700771/// # Intended usage
772///
773/// ```rust
774/// # extern crate proc_macro;
775/// # extern crate syn;
776/// #
777/// use proc_macro::TokenStream;
778/// use syn::parse_macro_input;
779/// use syn::parse::{Parse, ParseStream, Result};
780///
781/// struct MyMacroInput {
782/// /* ... */
783/// }
784///
785/// impl Parse for MyMacroInput {
786/// fn parse(input: ParseStream) -> Result<Self> {
787/// /* ... */
788/// # Ok(MyMacroInput {})
789/// }
790/// }
791///
792/// # const IGNORE: &str = stringify! {
793/// #[proc_macro]
794/// # };
795/// pub fn my_macro(tokens: TokenStream) -> TokenStream {
796/// let input = parse_macro_input!(tokens as MyMacroInput);
797///
798/// /* ... */
799/// # "".parse().unwrap()
800/// }
801/// #
802/// # fn main() {}
803/// ```
804#[cfg(feature = "proc-macro")]
805#[macro_export]
806macro_rules! parse_macro_input {
807 ($tokenstream:ident as $ty:ty) => {
David Tolnay02465352018-08-30 23:38:00 -0700808 match $crate::parse::<$ty>($tokenstream) {
David Tolnayd641ee32018-08-30 17:11:09 -0700809 $crate::export::Ok(data) => data,
810 $crate::export::Err(err) => {
David Tolnay24e21f92018-09-06 02:08:07 -0700811 return $crate::export::TokenStream::from(err.to_compile_error());
David Tolnayd641ee32018-08-30 17:11:09 -0700812 }
813 };
814 };
815}