blob: f73939ee48553e9a37112a611752d09b54595104 [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"))]
David Tolnay360efd22018-01-04 23:35:26 -080085pub use lit::{Lit, LitStr, LitByteStr, LitByte, LitChar, LitInt, LitFloat, LitBool, LitVerbatim,
86 StrStyle, IntSuffix, FloatSuffix};
David Tolnayf4bbbd92016-09-23 14:41:55 -070087
David Tolnay3cfd1d32018-01-03 00:22:08 -080088#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf4bbbd92016-09-23 14:41:55 -070089mod mac;
David Tolnay3cfd1d32018-01-03 00:22:08 -080090#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayab919512017-12-30 23:31:51 -050091pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -070092
David Tolnay3cfd1d32018-01-03 00:22:08 -080093#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay0e837402016-12-22 17:25:55 -050094mod derive;
David Tolnay3cfd1d32018-01-03 00:22:08 -080095#[cfg(feature = "derive")]
David Tolnaye3d41b72017-12-31 15:24:00 -050096pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -070097
David Tolnay3cfd1d32018-01-03 00:22:08 -080098#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -070099mod op;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800100#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay3cb23a92016-10-07 23:02:21 -0700101pub use op::{BinOp, UnOp};
102
David Tolnay3cfd1d32018-01-03 00:22:08 -0800103#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayb79ee962016-09-04 09:39:20 -0700104mod ty;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800105#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay056de302018-01-05 14:29:05 -0800106pub use ty::{Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray,
David Tolnay506e43a2017-12-29 11:34:36 -0500107 TypeBareFn, TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen,
David Tolnay2ae520a2017-12-29 11:19:50 -0500108 TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim};
David Tolnay056de302018-01-05 14:29:05 -0800109
110#[cfg(any(feature = "full", feature = "derive"))]
111mod path;
112#[cfg(any(feature = "full", feature = "derive"))]
113pub use path::{Path, PathSegment, PathArguments, GenericArgument, AngleBracketedGenericArguments,
114 Binding, ParenthesizedGenericArguments, QSelf};
David Tolnay3cfd1d32018-01-03 00:22:08 -0800115#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
David Tolnay056de302018-01-05 14:29:05 -0800116pub use path::PathTokens;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700117
David Tolnay1b752fb2017-12-26 21:41:39 -0500118#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500119mod cursor;
David Tolnay1b752fb2017-12-26 21:41:39 -0500120#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500121pub mod synom;
David Tolnayf2cfd722017-12-31 18:02:51 -0500122pub mod punctuated;
David Tolnay3cfd1d32018-01-03 00:22:08 -0800123#[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))]
David Tolnaye0824032017-12-27 15:25:56 -0500124mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500125
David Tolnay4d942b42018-01-02 22:14:04 -0800126#[cfg(all(feature = "parsing", feature = "printing"))]
David Tolnayf790b612017-12-31 18:46:57 -0500127pub mod spanned;
128
Nika Layzella6f46c42017-10-26 15:26:16 -0400129mod gen {
130 #[cfg(feature = "visit")]
131 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700132
Nika Layzella6f46c42017-10-26 15:26:16 -0400133 #[cfg(feature = "visit_mut")]
134 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400135
Nika Layzella6f46c42017-10-26 15:26:16 -0400136 #[cfg(feature = "fold")]
137 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500138
David Tolnay0a0d78c2018-01-05 15:24:01 -0800139 #[cfg(any(feature = "full", feature = "derive"))]
David Tolnayf60f4262017-12-28 19:17:58 -0500140 #[path = "../gen_helper.rs"]
141 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400142}
143pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100144
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700145////////////////////////////////////////////////////////////////////////////////
146
David Tolnay55337722016-09-11 12:58:56 -0700147#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500148use synom::Synom;
149#[cfg(feature = "parsing")]
150use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700151
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700152#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500153mod error;
154#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500155use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500156
157// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500158#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500159#[doc(hidden)]
160pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400161
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700162/// Parse tokens of source code into the chosen syn data type.
163///
164/// This is preferred over parsing a string because tokens are able to preserve
165/// information about where in the user's code they were originally written (the
166/// "span" of the token), possibly allowing the compiler to produce better error
167/// messages.
168///
169/// # Examples
170///
David Tolnaybcf26022017-12-25 22:10:52 -0500171/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700172/// extern crate proc_macro;
173/// use proc_macro::TokenStream;
174///
175/// extern crate syn;
176///
177/// #[macro_use]
178/// extern crate quote;
179///
180/// use syn::DeriveInput;
181///
David Tolnaybcf26022017-12-25 22:10:52 -0500182/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700183/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500184/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700185/// pub fn my_macro(input: TokenStream) -> TokenStream {
186/// // Parse the tokens into a syntax tree
187/// let ast: DeriveInput = syn::parse(input).unwrap();
188///
189/// // Build the output, possibly using quasi-quotation
190/// let expanded = quote! {
191/// /* ... */
192/// };
193///
David Tolnaybcf26022017-12-25 22:10:52 -0500194/// // Convert into a token stream and return it
195/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700196/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500197/// #
198/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700199/// ```
200#[cfg(feature = "parsing")]
201pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500202where
203 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700204{
205 _parse(tokens.into())
206}
207
208#[cfg(feature = "parsing")]
209fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500210where
211 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700212{
213 let buf = SynomBuffer::new(tokens);
214 let result = T::parse(buf.begin());
215 let err = match result {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500216 Ok((t, rest)) => {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700217 if rest.eof() {
218 return Ok(t);
219 } else if rest == buf.begin() {
220 // parsed nothing
221 ParseError::new("failed to parse anything")
222 } else {
223 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700224 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700225 }
226 Err(err) => err,
227 };
228 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700229 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700230 None => Err(err),
231 }
232}
Alex Crichton954046c2017-05-30 21:49:42 -0700233
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700234/// Parse a string of Rust code into the chosen syn data type.
235///
236/// # Examples
237///
238/// ```rust
239/// extern crate syn;
240/// #
David Tolnay9174b972017-11-09 22:27:50 -0800241/// #
242/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700243///
244/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700245///
246/// fn run() -> Result<()> {
247/// let code = "assert_eq!(u8::max_value(), 255)";
248/// let expr = syn::parse_str::<Expr>(code)?;
249/// println!("{:#?}", expr);
250/// Ok(())
251/// }
252/// #
253/// # fn main() { run().unwrap() }
254/// ```
255#[cfg(feature = "parsing")]
256pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500257 match s.parse() {
258 Ok(tts) => _parse(tts),
259 Err(_) => Err(ParseError::new("error while lexing input string")),
260 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700261}
Alex Crichton954046c2017-05-30 21:49:42 -0700262
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700263// FIXME the name parse_file makes it sound like you might pass in a path to a
264// file, rather than the content.
265/// Parse the content of a file of Rust code.
266///
267/// This is different from `syn::parse_str::<File>(content)` in two ways:
268///
269/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
270/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
271///
272/// If present, either of these would be an error using `from_str`.
273///
274/// # Examples
275///
276/// ```rust,no_run
277/// extern crate syn;
278/// #
David Tolnay9174b972017-11-09 22:27:50 -0800279/// #
280/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700281///
282/// use std::fs::File;
283/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700284///
285/// fn run() -> Result<()> {
286/// let mut file = File::open("path/to/code.rs")?;
287/// let mut content = String::new();
288/// file.read_to_string(&mut content)?;
289///
290/// let ast = syn::parse_file(&content)?;
291/// if let Some(shebang) = ast.shebang {
292/// println!("{}", shebang);
293/// }
294/// println!("{} items", ast.items.len());
295///
296/// Ok(())
297/// }
298/// #
299/// # fn main() { run().unwrap() }
300/// ```
301#[cfg(all(feature = "parsing", feature = "full"))]
302pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
303 // Strip the BOM if it is present
304 const BOM: &'static str = "\u{feff}";
305 if content.starts_with(BOM) {
306 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700307 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500308
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700309 let mut shebang = None;
310 if content.starts_with("#!") && !content.starts_with("#![") {
311 if let Some(idx) = content.find('\n') {
312 shebang = Some(content[..idx].to_string());
313 content = &content[idx..];
314 } else {
315 shebang = Some(content.to_string());
316 content = "";
317 }
Alex Crichton954046c2017-05-30 21:49:42 -0700318 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800319
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700320 let mut file: File = parse_str(content)?;
321 file.shebang = shebang;
322 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500323}
Alex Crichton259ee532017-07-14 06:51:02 -0700324
David Tolnay01cc0202018-01-02 11:13:07 -0800325#[cfg(all(feature = "parsing", feature = "printing"))]
326#[macro_export]
327macro_rules! parse_quote {
328 ($($tt:tt)*) => {
329 ::std::result::Result::unwrap(
330 $crate::parse(
331 ::std::convert::Into::into(
332 quote!($($tt)*))))
333 };
334}
335
David Tolnay3cfd1d32018-01-03 00:22:08 -0800336#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700337struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
338
David Tolnay3cfd1d32018-01-03 00:22:08 -0800339#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700340impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500341where
342 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700343{
344 fn to_tokens(&self, tokens: &mut quote::Tokens) {
345 match *self.0 {
346 Some(ref t) => t.to_tokens(tokens),
347 None => T::default().to_tokens(tokens),
348 }
349 }
350}