blob: eb3eb1ec57b4e7b3e80e44fec8ff5d29a718b02a [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 Tolnaye3d41b72017-12-31 15:24:00 -050032pub use data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted, Visibility};
David Tolnayf38cdf62016-09-23 19:07:09 -070033
David Tolnay3cfd1d32018-01-03 00:22:08 -080034#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070035mod expr;
David Tolnay3cfd1d32018-01-03 00:22:08 -080036#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay51382052017-12-27 13:46:21 -050037pub use expr::{Expr, ExprAddrOf, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock,
38 ExprBox, ExprBreak, ExprCall, ExprCast, ExprCatch, ExprClosure, ExprContinue,
39 ExprField, ExprForLoop, ExprGroup, ExprIf, ExprIfLet, ExprInPlace, ExprIndex,
David Tolnay8c91b882017-12-28 23:04:32 -050040 ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath, ExprRange,
David Tolnayc246cd32017-12-28 23:14:32 -050041 ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTuple, ExprType,
David Tolnay2ae520a2017-12-29 11:19:50 -050042 ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield, Index, Member};
Michael Layzell734adb42017-06-07 16:58:31 -040043
44#[cfg(feature = "full")]
David Tolnaybcd498f2017-12-29 12:02:33 -050045pub use expr::{Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local,
David Tolnay323279a2017-12-29 11:26:32 -050046 MethodTurbofish, Pat, PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice,
David Tolnay2ae520a2017-12-29 11:19:50 -050047 PatStruct, PatTuple, PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt};
David Tolnayf4bbbd92016-09-23 14:41:55 -070048
David Tolnay3cfd1d32018-01-03 00:22:08 -080049#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -070050mod generics;
David Tolnay3cfd1d32018-01-03 00:22:08 -080051#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay51382052017-12-27 13:46:21 -050052pub use generics::{BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef,
David Tolnay40fb8ce2018-01-02 10:53:46 -080053 PredicateEq, PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier,
David Tolnayd4add852018-01-01 20:13:24 -080054 TypeParam, TypeParamBound, WhereClause, WherePredicate};
David Tolnay3cfd1d32018-01-03 00:22:08 -080055#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnayfd6bf5c2017-11-12 09:41:14 -080056pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -070057
David Tolnay55337722016-09-11 12:58:56 -070058mod ident;
David Tolnaydaaf7742016-10-03 11:11:43 -070059pub use ident::Ident;
David Tolnay55337722016-09-11 12:58:56 -070060
David Tolnayf38cdf62016-09-23 19:07:09 -070061#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -070062mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -070063#[cfg(feature = "full")]
David Tolnay360a6342017-12-29 02:22:11 -050064pub use item::{ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl,
David Tolnay2ae520a2017-12-29 11:19:50 -050065 ForeignItem, ForeignItemFn, ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem,
66 ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item,
David Tolnay03342952017-12-29 11:52:00 -050067 ItemConst, ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod,
David Tolnay51382052017-12-27 13:46:21 -050068 ItemImpl, ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait,
David Tolnay2ae520a2017-12-29 11:19:50 -050069 ItemType, ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro,
70 TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseList, UsePath, UseTree};
David Tolnay35161ff2016-09-03 11:33:15 -070071
David Tolnay631cb8c2016-11-10 17:16:41 -080072#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070073mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -080074#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070075pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -080076
David Tolnay3cfd1d32018-01-03 00:22:08 -080077#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -070078mod lifetime;
David Tolnay3cfd1d32018-01-03 00:22:08 -080079#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay63e3dee2017-06-03 20:13:17 -070080pub use lifetime::Lifetime;
81
David Tolnay3cfd1d32018-01-03 00:22:08 -080082#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070083mod lit;
David Tolnay3cfd1d32018-01-03 00:22:08 -080084#[cfg(any(feature = "full", feature = "derive"))]
Alex Crichtonccbb45d2017-05-23 10:58:24 -070085pub use lit::{Lit, LitKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070086
David Tolnay3cfd1d32018-01-03 00:22:08 -080087#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070088mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -080089#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -050090pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -070091
David Tolnay3cfd1d32018-01-03 00:22:08 -080092#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -050093mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -080094#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -050095pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -070096
David Tolnay3cfd1d32018-01-03 00:22:08 -080097#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -070098mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -080099#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700100pub use op::{BinOp, UnOp};
101
David Tolnay3cfd1d32018-01-03 00:22:08 -0800102#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700103mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800104#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayd5125762017-12-29 02:42:17 -0500105pub use ty::{Abi, AngleBracketedGenericArguments, BareFnArg, BareFnArgName,
David Tolnay506e43a2017-12-29 11:34:36 -0500106 Binding, GenericArgument, ParenthesizedGenericArguments, Path,
David Tolnay40fb8ce2018-01-02 10:53:46 -0800107 PathArguments, PathSegment, QSelf, ReturnType, Type, TypeArray,
David Tolnay506e43a2017-12-29 11:34:36 -0500108 TypeBareFn, TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen,
David Tolnay2ae520a2017-12-29 11:19:50 -0500109 TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim};
David Tolnay3cfd1d32018-01-03 00:22:08 -0800110#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700111pub use ty::PathTokens;
112
David Tolnay1b752fb2017-12-26 21:41:39 -0500113#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500114mod cursor;
David Tolnay1b752fb2017-12-26 21:41:39 -0500115#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500116pub mod synom;
David Tolnayf2cfd722017-12-31 18:02:51 -0500117pub mod punctuated;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800118#[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))]
David Tolnaye0824032017-12-27 15:25:56 -0500119mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500120
David Tolnay4d942b42018-01-02 22:14:04 -0800121#[cfg(all(feature = "parsing", feature = "printing"))]
David Tolnayf790b612017-12-31 18:46:57 -0500122pub mod spanned;
123
Nika Layzella6f46c42017-10-26 15:26:16 -0400124mod gen {
125 #[cfg(feature = "visit")]
126 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700127
Nika Layzella6f46c42017-10-26 15:26:16 -0400128 #[cfg(feature = "visit_mut")]
129 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400130
Nika Layzella6f46c42017-10-26 15:26:16 -0400131 #[cfg(feature = "fold")]
132 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500133
134 #[path = "../gen_helper.rs"]
135 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400136}
137pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100138
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700139////////////////////////////////////////////////////////////////////////////////
140
David Tolnay55337722016-09-11 12:58:56 -0700141#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500142use synom::Synom;
143#[cfg(feature = "parsing")]
144use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700145
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700146#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500147mod error;
148#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500149use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500150
151// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500152#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500153#[doc(hidden)]
154pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400155
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700156/// Parse tokens of source code into the chosen syn data type.
157///
158/// This is preferred over parsing a string because tokens are able to preserve
159/// information about where in the user's code they were originally written (the
160/// "span" of the token), possibly allowing the compiler to produce better error
161/// messages.
162///
163/// # Examples
164///
David Tolnaybcf26022017-12-25 22:10:52 -0500165/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700166/// extern crate proc_macro;
167/// use proc_macro::TokenStream;
168///
169/// extern crate syn;
170///
171/// #[macro_use]
172/// extern crate quote;
173///
174/// use syn::DeriveInput;
175///
David Tolnaybcf26022017-12-25 22:10:52 -0500176/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700177/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500178/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700179/// pub fn my_macro(input: TokenStream) -> TokenStream {
180/// // Parse the tokens into a syntax tree
181/// let ast: DeriveInput = syn::parse(input).unwrap();
182///
183/// // Build the output, possibly using quasi-quotation
184/// let expanded = quote! {
185/// /* ... */
186/// };
187///
David Tolnaybcf26022017-12-25 22:10:52 -0500188/// // Convert into a token stream and return it
189/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700190/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500191/// #
192/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700193/// ```
194#[cfg(feature = "parsing")]
195pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500196where
197 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700198{
199 _parse(tokens.into())
200}
201
202#[cfg(feature = "parsing")]
203fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500204where
205 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700206{
207 let buf = SynomBuffer::new(tokens);
208 let result = T::parse(buf.begin());
209 let err = match result {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500210 Ok((t, rest)) => {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700211 if rest.eof() {
212 return Ok(t);
213 } else if rest == buf.begin() {
214 // parsed nothing
215 ParseError::new("failed to parse anything")
216 } else {
217 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700218 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700219 }
220 Err(err) => err,
221 };
222 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700223 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700224 None => Err(err),
225 }
226}
Alex Crichton954046c2017-05-30 21:49:42 -0700227
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700228/// Parse a string of Rust code into the chosen syn data type.
229///
230/// # Examples
231///
232/// ```rust
233/// extern crate syn;
234/// #
David Tolnay9174b972017-11-09 22:27:50 -0800235/// #
236/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700237///
238/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700239///
240/// fn run() -> Result<()> {
241/// let code = "assert_eq!(u8::max_value(), 255)";
242/// let expr = syn::parse_str::<Expr>(code)?;
243/// println!("{:#?}", expr);
244/// Ok(())
245/// }
246/// #
247/// # fn main() { run().unwrap() }
248/// ```
249#[cfg(feature = "parsing")]
250pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500251 match s.parse() {
252 Ok(tts) => _parse(tts),
253 Err(_) => Err(ParseError::new("error while lexing input string")),
254 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700255}
Alex Crichton954046c2017-05-30 21:49:42 -0700256
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700257// FIXME the name parse_file makes it sound like you might pass in a path to a
258// file, rather than the content.
259/// Parse the content of a file of Rust code.
260///
261/// This is different from `syn::parse_str::<File>(content)` in two ways:
262///
263/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
264/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
265///
266/// If present, either of these would be an error using `from_str`.
267///
268/// # Examples
269///
270/// ```rust,no_run
271/// extern crate syn;
272/// #
David Tolnay9174b972017-11-09 22:27:50 -0800273/// #
274/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700275///
276/// use std::fs::File;
277/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700278///
279/// fn run() -> Result<()> {
280/// let mut file = File::open("path/to/code.rs")?;
281/// let mut content = String::new();
282/// file.read_to_string(&mut content)?;
283///
284/// let ast = syn::parse_file(&content)?;
285/// if let Some(shebang) = ast.shebang {
286/// println!("{}", shebang);
287/// }
288/// println!("{} items", ast.items.len());
289///
290/// Ok(())
291/// }
292/// #
293/// # fn main() { run().unwrap() }
294/// ```
295#[cfg(all(feature = "parsing", feature = "full"))]
296pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
297 // Strip the BOM if it is present
298 const BOM: &'static str = "\u{feff}";
299 if content.starts_with(BOM) {
300 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700301 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500302
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700303 let mut shebang = None;
304 if content.starts_with("#!") && !content.starts_with("#![") {
305 if let Some(idx) = content.find('\n') {
306 shebang = Some(content[..idx].to_string());
307 content = &content[idx..];
308 } else {
309 shebang = Some(content.to_string());
310 content = "";
311 }
Alex Crichton954046c2017-05-30 21:49:42 -0700312 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800313
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700314 let mut file: File = parse_str(content)?;
315 file.shebang = shebang;
316 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500317}
Alex Crichton259ee532017-07-14 06:51:02 -0700318
David Tolnay01cc0202018-01-02 11:13:07 -0800319#[cfg(all(feature = "parsing", feature = "printing"))]
320#[macro_export]
321macro_rules! parse_quote {
322 ($($tt:tt)*) => {
323 ::std::result::Result::unwrap(
324 $crate::parse(
325 ::std::convert::Into::into(
326 quote!($($tt)*))))
327 };
328}
329
David Tolnay3cfd1d32018-01-03 00:22:08 -0800330#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700331struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
332
David Tolnay3cfd1d32018-01-03 00:22:08 -0800333#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700334impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500335where
336 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700337{
338 fn to_tokens(&self, tokens: &mut quote::Tokens) {
339 match *self.0 {
340 Some(ref t) => t.to_tokens(tokens),
341 None => T::default().to_tokens(tokens),
342 }
343 }
344}