blob: f3752f478b5f3e1eec5f967a261de3c689eee382 [file] [log] [blame]
David Tolnayad2836d2017-04-20 10:11:43 -07001#![doc(html_root_url = "https://dtolnay.github.io/syn")]
David Tolnay51382052017-12-27 13:46:21 -05002#![cfg_attr(feature = "cargo-clippy",
3 allow(const_static_lifetime, doc_markdown, large_enum_variant, match_bool,
4 redundant_closure))]
David Tolnayad2836d2017-04-20 10:11:43 -07005
Alex Crichtonccbb45d2017-05-23 10:58:24 -07006extern crate proc_macro2;
David Tolnay51382052017-12-27 13:46:21 -05007extern crate proc_macro;
David Tolnay570695e2017-06-03 16:15:13 -07008extern crate unicode_xid;
Alex Crichtonccbb45d2017-05-23 10:58:24 -07009
David Tolnay1cf80912017-12-31 18:35:12 -050010#[cfg(feature = "printing")]
David Tolnay87d0b442016-09-04 11:52:12 -070011extern crate quote;
12
David Tolnay1b752fb2017-12-26 21:41:39 -050013#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -080014#[macro_use]
David Tolnayc5ab8c62017-12-26 16:43:39 -050015#[doc(hidden)]
16pub mod parsers;
David Tolnay35161ff2016-09-03 11:33:15 -070017
Alex Crichton62a0a592017-05-22 13:58:53 -070018#[macro_use]
19mod macros;
20
David Tolnayc5ab8c62017-12-26 16:43:39 -050021#[macro_use]
David Tolnay32954ef2017-12-26 22:43:16 -050022pub mod token;
David Tolnayc5ab8c62017-12-26 16:43:39 -050023
David Tolnay3cfd1d32018-01-03 00:22:08 -080024#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -070025mod attr;
David Tolnay3cfd1d32018-01-03 00:22:08 -080026#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay51382052017-12-27 13:46:21 -050027pub use attr::{AttrStyle, Attribute, MetaItem, MetaItemList, MetaNameValue, NestedMetaItem};
David Tolnay35161ff2016-09-03 11:33:15 -070028
David Tolnay3cfd1d32018-01-03 00:22:08 -080029#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf38cdf62016-09-23 19:07:09 -070030mod data;
David Tolnay3cfd1d32018-01-03 00:22:08 -080031#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay61037c62018-01-05 16:21:03 -080032pub use data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic,
33 VisRestricted, Visibility};
David Tolnayf38cdf62016-09-23 19:07:09 -070034
David Tolnay3cfd1d32018-01-03 00:22:08 -080035#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070036mod expr;
David Tolnay3cfd1d32018-01-03 00:22:08 -080037#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay51382052017-12-27 13:46:21 -050038pub use expr::{Expr, ExprAddrOf, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock,
39 ExprBox, ExprBreak, ExprCall, ExprCast, ExprCatch, ExprClosure, ExprContinue,
40 ExprField, ExprForLoop, ExprGroup, ExprIf, ExprIfLet, ExprInPlace, ExprIndex,
David Tolnay61037c62018-01-05 16:21:03 -080041 ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath,
42 ExprRange, ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTuple, ExprType,
43 ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield, Index,
44 Member};
Michael Layzell734adb42017-06-07 16:58:31 -040045
46#[cfg(feature = "full")]
David Tolnaybcd498f2017-12-29 12:02:33 -050047pub use expr::{Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local,
David Tolnay61037c62018-01-05 16:21:03 -080048 MethodTurbofish, Pat, PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange,
49 PatRef, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatVerbatim, PatWild,
50 RangeLimits, Stmt};
David Tolnayf4bbbd92016-09-23 14:41:55 -070051
David Tolnay3cfd1d32018-01-03 00:22:08 -080052#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -070053mod generics;
David Tolnay3cfd1d32018-01-03 00:22:08 -080054#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay61037c62018-01-05 16:21:03 -080055pub use generics::{BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq,
56 PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam,
57 TypeParamBound, WhereClause, WherePredicate};
David Tolnay3cfd1d32018-01-03 00:22:08 -080058#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnayfd6bf5c2017-11-12 09:41:14 -080059pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -070060
David Tolnay55337722016-09-11 12:58:56 -070061mod ident;
David Tolnaydaaf7742016-10-03 11:11:43 -070062pub use ident::Ident;
David Tolnay55337722016-09-11 12:58:56 -070063
David Tolnayf38cdf62016-09-23 19:07:09 -070064#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -070065mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -070066#[cfg(feature = "full")]
David Tolnay61037c62018-01-05 16:21:03 -080067pub use item::{ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn,
68 ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst,
69 ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item, ItemConst,
70 ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2,
71 ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemType, ItemUnion, ItemUse,
72 ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro,
73 TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseList, UsePath,
74 UseTree};
David Tolnay35161ff2016-09-03 11:33:15 -070075
David Tolnay631cb8c2016-11-10 17:16:41 -080076#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070077mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -080078#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070079pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -080080
David Tolnay3cfd1d32018-01-03 00:22:08 -080081#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -070082mod lifetime;
David Tolnay3cfd1d32018-01-03 00:22:08 -080083#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -070084pub use lifetime::Lifetime;
85
David Tolnay3cfd1d32018-01-03 00:22:08 -080086#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070087mod lit;
David Tolnay3cfd1d32018-01-03 00:22:08 -080088#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay61037c62018-01-05 16:21:03 -080089pub use lit::{FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat,
90 LitInt, LitStr, LitVerbatim, StrStyle};
David Tolnayf4bbbd92016-09-23 14:41:55 -070091
David Tolnay3cfd1d32018-01-03 00:22:08 -080092#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070093mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -080094#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -050095pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -070096
David Tolnay3cfd1d32018-01-03 00:22:08 -080097#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -050098mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -080099#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -0500100pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -0700101
David Tolnay3cfd1d32018-01-03 00:22:08 -0800102#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700103mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800104#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700105pub use op::{BinOp, UnOp};
106
David Tolnay3cfd1d32018-01-03 00:22:08 -0800107#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700108mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800109#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay61037c62018-01-05 16:21:03 -0800110pub use ty::{Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup,
111 TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr,
112 TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim};
David Tolnay056de302018-01-05 14:29:05 -0800113
114#[cfg(any(feature = "full", feature = "derive"))]
115mod path;
116#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay61037c62018-01-05 16:21:03 -0800117pub use path::{AngleBracketedGenericArguments, Binding, GenericArgument,
118 ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf};
David Tolnay3cfd1d32018-01-03 00:22:08 -0800119#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnay056de302018-01-05 14:29:05 -0800120pub use path::PathTokens;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700121
David Tolnay1b752fb2017-12-26 21:41:39 -0500122#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500123mod cursor;
David Tolnay1b752fb2017-12-26 21:41:39 -0500124#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500125pub mod synom;
David Tolnayf2cfd722017-12-31 18:02:51 -0500126pub mod punctuated;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800127#[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))]
David Tolnaye0824032017-12-27 15:25:56 -0500128mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500129
David Tolnay4d942b42018-01-02 22:14:04 -0800130#[cfg(all(feature = "parsing", feature = "printing"))]
David Tolnayf790b612017-12-31 18:46:57 -0500131pub mod spanned;
132
Nika Layzella6f46c42017-10-26 15:26:16 -0400133mod gen {
134 #[cfg(feature = "visit")]
135 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700136
Nika Layzella6f46c42017-10-26 15:26:16 -0400137 #[cfg(feature = "visit_mut")]
138 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400139
Nika Layzella6f46c42017-10-26 15:26:16 -0400140 #[cfg(feature = "fold")]
141 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500142
David Tolnay0a0d78c2018-01-05 15:24:01 -0800143 #[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf60f4262017-12-28 19:17:58 -0500144 #[path = "../gen_helper.rs"]
145 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400146}
147pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100148
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700149////////////////////////////////////////////////////////////////////////////////
150
David Tolnay55337722016-09-11 12:58:56 -0700151#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500152use synom::Synom;
153#[cfg(feature = "parsing")]
154use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700155
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700156#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500157mod error;
158#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500159use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500160
161// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500162#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500163#[doc(hidden)]
164pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400165
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700166/// Parse tokens of source code into the chosen syn data type.
167///
168/// This is preferred over parsing a string because tokens are able to preserve
169/// information about where in the user's code they were originally written (the
170/// "span" of the token), possibly allowing the compiler to produce better error
171/// messages.
172///
173/// # Examples
174///
David Tolnaybcf26022017-12-25 22:10:52 -0500175/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700176/// extern crate proc_macro;
177/// use proc_macro::TokenStream;
178///
179/// extern crate syn;
180///
181/// #[macro_use]
182/// extern crate quote;
183///
184/// use syn::DeriveInput;
185///
David Tolnaybcf26022017-12-25 22:10:52 -0500186/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700187/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500188/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700189/// pub fn my_macro(input: TokenStream) -> TokenStream {
190/// // Parse the tokens into a syntax tree
191/// let ast: DeriveInput = syn::parse(input).unwrap();
192///
193/// // Build the output, possibly using quasi-quotation
194/// let expanded = quote! {
195/// /* ... */
196/// };
197///
David Tolnaybcf26022017-12-25 22:10:52 -0500198/// // Convert into a token stream and return it
199/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700200/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500201/// #
202/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700203/// ```
204#[cfg(feature = "parsing")]
205pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500206where
207 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700208{
209 _parse(tokens.into())
210}
211
212#[cfg(feature = "parsing")]
213fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500214where
215 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700216{
217 let buf = SynomBuffer::new(tokens);
218 let result = T::parse(buf.begin());
219 let err = match result {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500220 Ok((t, rest)) => {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700221 if rest.eof() {
222 return Ok(t);
223 } else if rest == buf.begin() {
224 // parsed nothing
225 ParseError::new("failed to parse anything")
226 } else {
227 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700228 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700229 }
230 Err(err) => err,
231 };
232 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700233 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700234 None => Err(err),
235 }
236}
Alex Crichton954046c2017-05-30 21:49:42 -0700237
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700238/// Parse a string of Rust code into the chosen syn data type.
239///
240/// # Examples
241///
242/// ```rust
243/// extern crate syn;
244/// #
David Tolnay9174b972017-11-09 22:27:50 -0800245/// #
246/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700247///
248/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700249///
250/// fn run() -> Result<()> {
251/// let code = "assert_eq!(u8::max_value(), 255)";
252/// let expr = syn::parse_str::<Expr>(code)?;
253/// println!("{:#?}", expr);
254/// Ok(())
255/// }
256/// #
257/// # fn main() { run().unwrap() }
258/// ```
259#[cfg(feature = "parsing")]
260pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500261 match s.parse() {
262 Ok(tts) => _parse(tts),
263 Err(_) => Err(ParseError::new("error while lexing input string")),
264 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700265}
Alex Crichton954046c2017-05-30 21:49:42 -0700266
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700267// FIXME the name parse_file makes it sound like you might pass in a path to a
268// file, rather than the content.
269/// Parse the content of a file of Rust code.
270///
271/// This is different from `syn::parse_str::<File>(content)` in two ways:
272///
273/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
274/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
275///
276/// If present, either of these would be an error using `from_str`.
277///
278/// # Examples
279///
280/// ```rust,no_run
281/// extern crate syn;
282/// #
David Tolnay9174b972017-11-09 22:27:50 -0800283/// #
284/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700285///
286/// use std::fs::File;
287/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700288///
289/// fn run() -> Result<()> {
290/// let mut file = File::open("path/to/code.rs")?;
291/// let mut content = String::new();
292/// file.read_to_string(&mut content)?;
293///
294/// let ast = syn::parse_file(&content)?;
295/// if let Some(shebang) = ast.shebang {
296/// println!("{}", shebang);
297/// }
298/// println!("{} items", ast.items.len());
299///
300/// Ok(())
301/// }
302/// #
303/// # fn main() { run().unwrap() }
304/// ```
305#[cfg(all(feature = "parsing", feature = "full"))]
306pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
307 // Strip the BOM if it is present
308 const BOM: &'static str = "\u{feff}";
309 if content.starts_with(BOM) {
310 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700311 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500312
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700313 let mut shebang = None;
314 if content.starts_with("#!") && !content.starts_with("#![") {
315 if let Some(idx) = content.find('\n') {
316 shebang = Some(content[..idx].to_string());
317 content = &content[idx..];
318 } else {
319 shebang = Some(content.to_string());
320 content = "";
321 }
Alex Crichton954046c2017-05-30 21:49:42 -0700322 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800323
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700324 let mut file: File = parse_str(content)?;
325 file.shebang = shebang;
326 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500327}
Alex Crichton259ee532017-07-14 06:51:02 -0700328
David Tolnay01cc0202018-01-02 11:13:07 -0800329#[cfg(all(feature = "parsing", feature = "printing"))]
330#[macro_export]
331macro_rules! parse_quote {
332 ($($tt:tt)*) => {
333 ::std::result::Result::unwrap(
334 $crate::parse(
335 ::std::convert::Into::into(
336 quote!($($tt)*))))
337 };
338}
339
David Tolnay3cfd1d32018-01-03 00:22:08 -0800340#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700341struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
342
David Tolnay3cfd1d32018-01-03 00:22:08 -0800343#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700344impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500345where
346 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700347{
348 fn to_tokens(&self, tokens: &mut quote::Tokens) {
349 match *self.0 {
350 Some(ref t) => t.to_tokens(tokens),
351 None => T::default().to_tokens(tokens),
352 }
353 }
354}