blob: ae5fe08387c999d48e932498ffb7009237f5029a [file] [log] [blame]
David Tolnayad2836d2017-04-20 10:11:43 -07001#![doc(html_root_url = "https://dtolnay.github.io/syn")]
2
David Tolnaybb4ca9f2017-12-26 12:28:58 -05003#![cfg_attr(feature = "cargo-clippy", allow(
4 const_static_lifetime,
5 doc_markdown,
6 large_enum_variant,
7 redundant_closure,
8))]
David Tolnayaed77b02016-09-23 20:50:31 -07009
David Tolnayc7a5d3d2017-06-04 12:11:05 -070010extern crate proc_macro;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070011extern crate proc_macro2;
David Tolnay570695e2017-06-03 16:15:13 -070012extern crate unicode_xid;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070013
Nika Layzell7f5fc682017-10-25 00:47:10 -040014#[cfg(any(feature = "printing", feature = "parsing"))]
David Tolnay87d0b442016-09-04 11:52:12 -070015extern crate quote;
16
David Tolnay1b752fb2017-12-26 21:41:39 -050017#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -080018#[macro_use]
David Tolnayc5ab8c62017-12-26 16:43:39 -050019#[doc(hidden)]
20pub mod parsers;
David Tolnay35161ff2016-09-03 11:33:15 -070021
Alex Crichton62a0a592017-05-22 13:58:53 -070022#[macro_use]
23mod macros;
24
David Tolnayc5ab8c62017-12-26 16:43:39 -050025#[cfg(feature = "parsing")]
26#[doc(hidden)]
27#[macro_use]
28pub mod helper;
29
30#[macro_use]
David Tolnay32954ef2017-12-26 22:43:16 -050031pub mod token;
David Tolnayc5ab8c62017-12-26 16:43:39 -050032
David Tolnayb79ee962016-09-04 09:39:20 -070033mod attr;
Alex Crichton62a0a592017-05-22 13:58:53 -070034pub use attr::{Attribute, AttrStyle, MetaItem, NestedMetaItem, MetaItemList,
35 MetaNameValue};
David Tolnay35161ff2016-09-03 11:33:15 -070036
David Tolnayf38cdf62016-09-23 19:07:09 -070037mod data;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070038pub use data::{Field, Variant, VariantData, Visibility, VisRestricted, VisCrate,
39 VisPublic, VisInherited};
David Tolnayf38cdf62016-09-23 19:07:09 -070040
David Tolnayf4bbbd92016-09-23 14:41:55 -070041mod expr;
Michael Layzell734adb42017-06-07 16:58:31 -040042pub use expr::{Expr, ExprKind, ExprBox, ExprInPlace, ExprArray, ExprCall,
David Tolnay05362582017-12-26 01:33:57 -050043 ExprMethodCall, ExprTuple, ExprBinary, ExprUnary, ExprCast,
Michael Layzell734adb42017-06-07 16:58:31 -040044 ExprType, ExprIf, ExprIfLet, ExprWhile, ExprWhileLet,
Alex Crichton62a0a592017-05-22 13:58:53 -070045 ExprForLoop, ExprLoop, ExprMatch, ExprClosure, ExprBlock,
46 ExprAssign, ExprAssignOp, ExprField, ExprTupField, ExprIndex,
47 ExprRange, ExprPath, ExprAddrOf, ExprBreak, ExprContinue,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070048 ExprRet, ExprStruct, ExprRepeat, ExprParen, ExprTry, ExprCatch,
Nika Layzell640832a2017-12-04 13:37:09 -050049 ExprGroup, ExprYield, ExprUnsafe};
Michael Layzell734adb42017-06-07 16:58:31 -040050
51#[cfg(feature = "full")]
52pub use expr::{Arm, BindingMode, Block, CaptureBy, FieldPat, FieldValue, Local,
53 MacStmtStyle, Pat, RangeLimits, Stmt, PatIdent, PatWild,
54 PatStruct, PatTuple, PatTupleStruct, PatPath, PatBox, PatRef,
55 PatLit, PatRange, PatSlice, InPlaceKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070056
David Tolnayb79ee962016-09-04 09:39:20 -070057mod generics;
David Tolnayc2f1aba2017-11-12 20:29:22 -080058pub use generics::{Generics, GenericParam, LifetimeDef, TraitBoundModifier, TypeParam, TypeParamBound,
David Tolnayfa23f572017-01-23 00:19:11 -080059 WhereBoundPredicate, WhereClause, WhereEqPredicate, WherePredicate,
Nika Layzellf1fdc0b2017-12-04 19:58:32 -050060 WhereRegionPredicate, BoundLifetimes, ConstParam};
David Tolnaye7678922016-10-13 20:44:03 -070061#[cfg(feature = "printing")]
David Tolnayfd6bf5c2017-11-12 09:41:14 -080062pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -070063
David Tolnay55337722016-09-11 12:58:56 -070064mod ident;
David Tolnaydaaf7742016-10-03 11:11:43 -070065pub use ident::Ident;
David Tolnay55337722016-09-11 12:58:56 -070066
David Tolnayf38cdf62016-09-23 19:07:09 -070067#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -070068mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -070069#[cfg(feature = "full")]
David Tolnay8894f602017-11-11 12:11:04 -080070pub use item::{Constness, Defaultness, FnArg, FnDecl, ForeignItem, ItemForeignMod,
David Tolnay5f332a92017-12-26 00:42:45 -050071 ImplItem, ImplPolarity, Item, MethodSig,
72 TraitItem, ItemExternCrate, ItemUse,
David Tolnay500d8322017-12-18 00:32:51 -080073 ItemStatic, ItemConst, ItemFn, ItemMacro, ItemMacro2, ItemMod, ItemType, ItemEnum,
Alex Crichton62a0a592017-05-22 13:58:53 -070074 ItemStruct, ItemUnion, ItemTrait, ItemDefaultImpl, ItemImpl,
David Tolnay5f332a92017-12-26 00:42:45 -050075 UsePath, UseGlob, UseList, ForeignItemFn, ForeignItemStatic, ForeignItemType,
David Tolnaydecf28d2017-11-11 11:56:45 -080076 TraitItemConst, TraitItemMacro, TraitItemMethod, TraitItemType,
David Tolnay857628c2017-11-11 12:25:31 -080077 ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, ArgSelfRef,
David Tolnay5f332a92017-12-26 00:42:45 -050078 ArgSelf, ArgCaptured, UseTree};
David Tolnay35161ff2016-09-03 11:33:15 -070079
David Tolnay631cb8c2016-11-10 17:16:41 -080080#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070081mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -080082#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070083pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -080084
David Tolnay63e3dee2017-06-03 20:13:17 -070085mod lifetime;
86pub use lifetime::Lifetime;
87
David Tolnayf4bbbd92016-09-23 14:41:55 -070088mod lit;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070089pub use lit::{Lit, LitKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070090
David Tolnayf4bbbd92016-09-23 14:41:55 -070091mod mac;
David Tolnaydecf28d2017-11-11 11:56:45 -080092pub use mac::{Macro, TokenTree};
David Tolnayf4bbbd92016-09-23 14:41:55 -070093
David Tolnay0e837402016-12-22 17:25:55 -050094mod derive;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070095pub use derive::{Body, DeriveInput, BodyEnum, BodyStruct};
David Tolnayf38cdf62016-09-23 19:07:09 -070096
David Tolnay3cb23a92016-10-07 23:02:21 -070097mod op;
98pub use op::{BinOp, UnOp};
99
David Tolnayb79ee962016-09-04 09:39:20 -0700100mod ty;
Nika Layzellc08227a2017-12-04 16:30:17 -0500101pub use ty::{Abi, AbiKind, AngleBracketedGenericArguments, BareFnArg,
102 BareFnArgName, BareFnType, ReturnType, MutType, Mutability,
103 ParenthesizedGenericArguments, Path, PathArguments, PathSegment,
104 PolyTraitRef, QSelf, Type, TypeBinding, Unsafety, TypeSlice,
David Tolnay05362582017-12-26 01:33:57 -0500105 TypeArray, TypePtr, TypeReference, TypeBareFn, TypeNever, TypeTuple,
Nika Layzellc08227a2017-12-04 16:30:17 -0500106 TypePath, TypeTraitObject, TypeImplTrait, TypeParen, TypeInfer,
107 TypeGroup, GenericArgument};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700108#[cfg(feature = "printing")]
109pub use ty::PathTokens;
110
David Tolnay1b752fb2017-12-26 21:41:39 -0500111#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500112mod cursor;
David Tolnay1b752fb2017-12-26 21:41:39 -0500113#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500114pub mod synom;
115pub mod delimited;
116
Nika Layzella6f46c42017-10-26 15:26:16 -0400117mod gen {
118 #[cfg(feature = "visit")]
119 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700120
Nika Layzella6f46c42017-10-26 15:26:16 -0400121 #[cfg(feature = "visit_mut")]
122 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400123
Nika Layzella6f46c42017-10-26 15:26:16 -0400124 #[cfg(feature = "fold")]
125 pub mod fold;
126}
127pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100128
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700129////////////////////////////////////////////////////////////////////////////////
130
David Tolnay55337722016-09-11 12:58:56 -0700131#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500132use synom::Synom;
133#[cfg(feature = "parsing")]
134use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700135
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700136#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500137mod error;
138#[cfg(feature = "parsing")]
139pub use error::{PResult, ParseError};
140
141// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500142#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500143#[doc(hidden)]
144pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400145
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700146/// Parse tokens of source code into the chosen syn data type.
147///
148/// This is preferred over parsing a string because tokens are able to preserve
149/// information about where in the user's code they were originally written (the
150/// "span" of the token), possibly allowing the compiler to produce better error
151/// messages.
152///
153/// # Examples
154///
David Tolnaybcf26022017-12-25 22:10:52 -0500155/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700156/// extern crate proc_macro;
157/// use proc_macro::TokenStream;
158///
159/// extern crate syn;
160///
161/// #[macro_use]
162/// extern crate quote;
163///
164/// use syn::DeriveInput;
165///
David Tolnaybcf26022017-12-25 22:10:52 -0500166/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700167/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500168/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700169/// pub fn my_macro(input: TokenStream) -> TokenStream {
170/// // Parse the tokens into a syntax tree
171/// let ast: DeriveInput = syn::parse(input).unwrap();
172///
173/// // Build the output, possibly using quasi-quotation
174/// let expanded = quote! {
175/// /* ... */
176/// };
177///
David Tolnaybcf26022017-12-25 22:10:52 -0500178/// // Convert into a token stream and return it
179/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700180/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500181/// #
182/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700183/// ```
184#[cfg(feature = "parsing")]
185pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
186 where T: Synom,
187{
188 _parse(tokens.into())
189}
190
191#[cfg(feature = "parsing")]
192fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
193 where T: Synom,
194{
195 let buf = SynomBuffer::new(tokens);
196 let result = T::parse(buf.begin());
197 let err = match result {
198 Ok((rest, t)) => {
199 if rest.eof() {
200 return Ok(t);
201 } else if rest == buf.begin() {
202 // parsed nothing
203 ParseError::new("failed to parse anything")
204 } else {
205 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700206 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700207 }
208 Err(err) => err,
209 };
210 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700211 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700212 None => Err(err),
213 }
214}
Alex Crichton954046c2017-05-30 21:49:42 -0700215
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400216/// Parse a `quote::Tokens` of Rust code into the chosen syn data type.
217///
218/// # Examples
219///
220/// ```rust
221/// extern crate syn;
222/// #
223/// # #[macro_use]
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400224/// # extern crate quote;
David Tolnay9174b972017-11-09 22:27:50 -0800225/// #
226/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400227///
228/// use syn::Expr;
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400229///
230/// fn run() -> Result<()> {
231/// let code = quote!(assert_eq!(u8::max_value(), 255));
David Tolnay32954ef2017-12-26 22:43:16 -0500232/// let expr = syn::parse_token::<Expr>(code)?;
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400233/// println!("{:#?}", expr);
234/// Ok(())
235/// }
236/// #
237/// # fn main() { run().unwrap() }
238/// ```
239#[cfg(feature = "parsing")]
240pub fn parse_tokens<T: Synom>(tokens: quote::Tokens) -> Result<T, ParseError> {
241 _parse(tokens.into())
242}
243
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700244/// Parse a string of Rust code into the chosen syn data type.
245///
246/// # Examples
247///
248/// ```rust
249/// extern crate syn;
250/// #
David Tolnay9174b972017-11-09 22:27:50 -0800251/// #
252/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700253///
254/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700255///
256/// fn run() -> Result<()> {
257/// let code = "assert_eq!(u8::max_value(), 255)";
258/// let expr = syn::parse_str::<Expr>(code)?;
259/// println!("{:#?}", expr);
260/// Ok(())
261/// }
262/// #
263/// # fn main() { run().unwrap() }
264/// ```
265#[cfg(feature = "parsing")]
266pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
267 _parse(s.parse()?)
268}
Alex Crichton954046c2017-05-30 21:49:42 -0700269
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700270// FIXME the name parse_file makes it sound like you might pass in a path to a
271// file, rather than the content.
272/// Parse the content of a file of Rust code.
273///
274/// This is different from `syn::parse_str::<File>(content)` in two ways:
275///
276/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
277/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
278///
279/// If present, either of these would be an error using `from_str`.
280///
281/// # Examples
282///
283/// ```rust,no_run
284/// extern crate syn;
285/// #
David Tolnay9174b972017-11-09 22:27:50 -0800286/// #
287/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700288///
289/// use std::fs::File;
290/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700291///
292/// fn run() -> Result<()> {
293/// let mut file = File::open("path/to/code.rs")?;
294/// let mut content = String::new();
295/// file.read_to_string(&mut content)?;
296///
297/// let ast = syn::parse_file(&content)?;
298/// if let Some(shebang) = ast.shebang {
299/// println!("{}", shebang);
300/// }
301/// println!("{} items", ast.items.len());
302///
303/// Ok(())
304/// }
305/// #
306/// # fn main() { run().unwrap() }
307/// ```
308#[cfg(all(feature = "parsing", feature = "full"))]
309pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
310 // Strip the BOM if it is present
311 const BOM: &'static str = "\u{feff}";
312 if content.starts_with(BOM) {
313 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700314 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500315
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700316 let mut shebang = None;
317 if content.starts_with("#!") && !content.starts_with("#![") {
318 if let Some(idx) = content.find('\n') {
319 shebang = Some(content[..idx].to_string());
320 content = &content[idx..];
321 } else {
322 shebang = Some(content.to_string());
323 content = "";
324 }
Alex Crichton954046c2017-05-30 21:49:42 -0700325 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800326
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700327 let mut file: File = parse_str(content)?;
328 file.shebang = shebang;
329 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500330}
Alex Crichton259ee532017-07-14 06:51:02 -0700331
332#[cfg(feature = "printing")]
333struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
334
335#[cfg(feature = "printing")]
336impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
337 where T: quote::ToTokens + Default,
338{
339 fn to_tokens(&self, tokens: &mut quote::Tokens) {
340 match *self.0 {
341 Some(ref t) => t.to_tokens(tokens),
342 None => T::default().to_tokens(tokens),
343 }
344 }
345}