blob: 30d46df668dd474b31c90e5ec32595147ba42593 [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
139 #[path = "../gen_helper.rs"]
140 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400141}
142pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100143
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700144////////////////////////////////////////////////////////////////////////////////
145
David Tolnay55337722016-09-11 12:58:56 -0700146#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500147use synom::Synom;
148#[cfg(feature = "parsing")]
149use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700150
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700151#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500152mod error;
153#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500154use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500155
156// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500157#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500158#[doc(hidden)]
159pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400160
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700161/// Parse tokens of source code into the chosen syn data type.
162///
163/// This is preferred over parsing a string because tokens are able to preserve
164/// information about where in the user's code they were originally written (the
165/// "span" of the token), possibly allowing the compiler to produce better error
166/// messages.
167///
168/// # Examples
169///
David Tolnaybcf26022017-12-25 22:10:52 -0500170/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700171/// extern crate proc_macro;
172/// use proc_macro::TokenStream;
173///
174/// extern crate syn;
175///
176/// #[macro_use]
177/// extern crate quote;
178///
179/// use syn::DeriveInput;
180///
David Tolnaybcf26022017-12-25 22:10:52 -0500181/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700182/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500183/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700184/// pub fn my_macro(input: TokenStream) -> TokenStream {
185/// // Parse the tokens into a syntax tree
186/// let ast: DeriveInput = syn::parse(input).unwrap();
187///
188/// // Build the output, possibly using quasi-quotation
189/// let expanded = quote! {
190/// /* ... */
191/// };
192///
David Tolnaybcf26022017-12-25 22:10:52 -0500193/// // Convert into a token stream and return it
194/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700195/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500196/// #
197/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700198/// ```
199#[cfg(feature = "parsing")]
200pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500201where
202 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700203{
204 _parse(tokens.into())
205}
206
207#[cfg(feature = "parsing")]
208fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500209where
210 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700211{
212 let buf = SynomBuffer::new(tokens);
213 let result = T::parse(buf.begin());
214 let err = match result {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500215 Ok((t, rest)) => {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700216 if rest.eof() {
217 return Ok(t);
218 } else if rest == buf.begin() {
219 // parsed nothing
220 ParseError::new("failed to parse anything")
221 } else {
222 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700223 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700224 }
225 Err(err) => err,
226 };
227 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700228 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700229 None => Err(err),
230 }
231}
Alex Crichton954046c2017-05-30 21:49:42 -0700232
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700233/// Parse a string of Rust code into the chosen syn data type.
234///
235/// # Examples
236///
237/// ```rust
238/// extern crate syn;
239/// #
David Tolnay9174b972017-11-09 22:27:50 -0800240/// #
241/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700242///
243/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700244///
245/// fn run() -> Result<()> {
246/// let code = "assert_eq!(u8::max_value(), 255)";
247/// let expr = syn::parse_str::<Expr>(code)?;
248/// println!("{:#?}", expr);
249/// Ok(())
250/// }
251/// #
252/// # fn main() { run().unwrap() }
253/// ```
254#[cfg(feature = "parsing")]
255pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500256 match s.parse() {
257 Ok(tts) => _parse(tts),
258 Err(_) => Err(ParseError::new("error while lexing input string")),
259 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700260}
Alex Crichton954046c2017-05-30 21:49:42 -0700261
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700262// FIXME the name parse_file makes it sound like you might pass in a path to a
263// file, rather than the content.
264/// Parse the content of a file of Rust code.
265///
266/// This is different from `syn::parse_str::<File>(content)` in two ways:
267///
268/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
269/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
270///
271/// If present, either of these would be an error using `from_str`.
272///
273/// # Examples
274///
275/// ```rust,no_run
276/// extern crate syn;
277/// #
David Tolnay9174b972017-11-09 22:27:50 -0800278/// #
279/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700280///
281/// use std::fs::File;
282/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700283///
284/// fn run() -> Result<()> {
285/// let mut file = File::open("path/to/code.rs")?;
286/// let mut content = String::new();
287/// file.read_to_string(&mut content)?;
288///
289/// let ast = syn::parse_file(&content)?;
290/// if let Some(shebang) = ast.shebang {
291/// println!("{}", shebang);
292/// }
293/// println!("{} items", ast.items.len());
294///
295/// Ok(())
296/// }
297/// #
298/// # fn main() { run().unwrap() }
299/// ```
300#[cfg(all(feature = "parsing", feature = "full"))]
301pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
302 // Strip the BOM if it is present
303 const BOM: &'static str = "\u{feff}";
304 if content.starts_with(BOM) {
305 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700306 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500307
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700308 let mut shebang = None;
309 if content.starts_with("#!") && !content.starts_with("#![") {
310 if let Some(idx) = content.find('\n') {
311 shebang = Some(content[..idx].to_string());
312 content = &content[idx..];
313 } else {
314 shebang = Some(content.to_string());
315 content = "";
316 }
Alex Crichton954046c2017-05-30 21:49:42 -0700317 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800318
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700319 let mut file: File = parse_str(content)?;
320 file.shebang = shebang;
321 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500322}
Alex Crichton259ee532017-07-14 06:51:02 -0700323
David Tolnay01cc0202018-01-02 11:13:07 -0800324#[cfg(all(feature = "parsing", feature = "printing"))]
325#[macro_export]
326macro_rules! parse_quote {
327 ($($tt:tt)*) => {
328 ::std::result::Result::unwrap(
329 $crate::parse(
330 ::std::convert::Into::into(
331 quote!($($tt)*))))
332 };
333}
334
David Tolnay3cfd1d32018-01-03 00:22:08 -0800335#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700336struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
337
David Tolnay3cfd1d32018-01-03 00:22:08 -0800338#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))]
Alex Crichton259ee532017-07-14 06:51:02 -0700339impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500340where
341 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700342{
343 fn to_tokens(&self, tokens: &mut quote::Tokens) {
344 match *self.0 {
345 Some(ref t) => t.to_tokens(tokens),
346 None => T::default().to_tokens(tokens),
347 }
348 }
349}