blob: 3f150b75142f92628772c7cfccb20297dca70ac3 [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 Tolnayf8db7ba2017-11-11 22:52:16 -080017#[macro_use]
David Tolnayc5ab8c62017-12-26 16:43:39 -050018#[doc(hidden)]
19pub mod parsers;
David Tolnay35161ff2016-09-03 11:33:15 -070020
Alex Crichton62a0a592017-05-22 13:58:53 -070021#[macro_use]
22mod macros;
23
David Tolnayc5ab8c62017-12-26 16:43:39 -050024#[cfg(feature = "parsing")]
25#[doc(hidden)]
26#[macro_use]
27pub mod helper;
28
29#[macro_use]
30pub mod tokens;
31
David Tolnayb79ee962016-09-04 09:39:20 -070032mod attr;
Alex Crichton62a0a592017-05-22 13:58:53 -070033pub use attr::{Attribute, AttrStyle, MetaItem, NestedMetaItem, MetaItemList,
34 MetaNameValue};
David Tolnay35161ff2016-09-03 11:33:15 -070035
David Tolnayf38cdf62016-09-23 19:07:09 -070036mod data;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070037pub use data::{Field, Variant, VariantData, Visibility, VisRestricted, VisCrate,
38 VisPublic, VisInherited};
David Tolnayf38cdf62016-09-23 19:07:09 -070039
David Tolnayf4bbbd92016-09-23 14:41:55 -070040mod expr;
Michael Layzell734adb42017-06-07 16:58:31 -040041pub use expr::{Expr, ExprKind, ExprBox, ExprInPlace, ExprArray, ExprCall,
David Tolnay05362582017-12-26 01:33:57 -050042 ExprMethodCall, ExprTuple, ExprBinary, ExprUnary, ExprCast,
Michael Layzell734adb42017-06-07 16:58:31 -040043 ExprType, ExprIf, ExprIfLet, ExprWhile, ExprWhileLet,
Alex Crichton62a0a592017-05-22 13:58:53 -070044 ExprForLoop, ExprLoop, ExprMatch, ExprClosure, ExprBlock,
45 ExprAssign, ExprAssignOp, ExprField, ExprTupField, ExprIndex,
46 ExprRange, ExprPath, ExprAddrOf, ExprBreak, ExprContinue,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070047 ExprRet, ExprStruct, ExprRepeat, ExprParen, ExprTry, ExprCatch,
Nika Layzell640832a2017-12-04 13:37:09 -050048 ExprGroup, ExprYield, ExprUnsafe};
Michael Layzell734adb42017-06-07 16:58:31 -040049
50#[cfg(feature = "full")]
51pub use expr::{Arm, BindingMode, Block, CaptureBy, FieldPat, FieldValue, Local,
52 MacStmtStyle, Pat, RangeLimits, Stmt, PatIdent, PatWild,
53 PatStruct, PatTuple, PatTupleStruct, PatPath, PatBox, PatRef,
54 PatLit, PatRange, PatSlice, InPlaceKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070055
David Tolnayb79ee962016-09-04 09:39:20 -070056mod generics;
David Tolnayc2f1aba2017-11-12 20:29:22 -080057pub use generics::{Generics, GenericParam, LifetimeDef, TraitBoundModifier, TypeParam, TypeParamBound,
David Tolnayfa23f572017-01-23 00:19:11 -080058 WhereBoundPredicate, WhereClause, WhereEqPredicate, WherePredicate,
Nika Layzellf1fdc0b2017-12-04 19:58:32 -050059 WhereRegionPredicate, BoundLifetimes, ConstParam};
David Tolnaye7678922016-10-13 20:44:03 -070060#[cfg(feature = "printing")]
David Tolnayfd6bf5c2017-11-12 09:41:14 -080061pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -070062
David Tolnay55337722016-09-11 12:58:56 -070063mod ident;
David Tolnaydaaf7742016-10-03 11:11:43 -070064pub use ident::Ident;
David Tolnay55337722016-09-11 12:58:56 -070065
David Tolnayf38cdf62016-09-23 19:07:09 -070066#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -070067mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -070068#[cfg(feature = "full")]
David Tolnay8894f602017-11-11 12:11:04 -080069pub use item::{Constness, Defaultness, FnArg, FnDecl, ForeignItem, ItemForeignMod,
David Tolnay5f332a92017-12-26 00:42:45 -050070 ImplItem, ImplPolarity, Item, MethodSig,
71 TraitItem, ItemExternCrate, ItemUse,
David Tolnay500d8322017-12-18 00:32:51 -080072 ItemStatic, ItemConst, ItemFn, ItemMacro, ItemMacro2, ItemMod, ItemType, ItemEnum,
Alex Crichton62a0a592017-05-22 13:58:53 -070073 ItemStruct, ItemUnion, ItemTrait, ItemDefaultImpl, ItemImpl,
David Tolnay5f332a92017-12-26 00:42:45 -050074 UsePath, UseGlob, UseList, ForeignItemFn, ForeignItemStatic, ForeignItemType,
David Tolnaydecf28d2017-11-11 11:56:45 -080075 TraitItemConst, TraitItemMacro, TraitItemMethod, TraitItemType,
David Tolnay857628c2017-11-11 12:25:31 -080076 ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, ArgSelfRef,
David Tolnay5f332a92017-12-26 00:42:45 -050077 ArgSelf, ArgCaptured, UseTree};
David Tolnay35161ff2016-09-03 11:33:15 -070078
David Tolnay631cb8c2016-11-10 17:16:41 -080079#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070080mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -080081#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070082pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -080083
David Tolnay63e3dee2017-06-03 20:13:17 -070084mod lifetime;
85pub use lifetime::Lifetime;
86
David Tolnayf4bbbd92016-09-23 14:41:55 -070087mod lit;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070088pub use lit::{Lit, LitKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070089
David Tolnayf4bbbd92016-09-23 14:41:55 -070090mod mac;
David Tolnaydecf28d2017-11-11 11:56:45 -080091pub use mac::{Macro, TokenTree};
David Tolnayf4bbbd92016-09-23 14:41:55 -070092
David Tolnay0e837402016-12-22 17:25:55 -050093mod derive;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070094pub use derive::{Body, DeriveInput, BodyEnum, BodyStruct};
David Tolnayf38cdf62016-09-23 19:07:09 -070095
David Tolnay3cb23a92016-10-07 23:02:21 -070096mod op;
97pub use op::{BinOp, UnOp};
98
David Tolnayb79ee962016-09-04 09:39:20 -070099mod ty;
Nika Layzellc08227a2017-12-04 16:30:17 -0500100pub use ty::{Abi, AbiKind, AngleBracketedGenericArguments, BareFnArg,
101 BareFnArgName, BareFnType, ReturnType, MutType, Mutability,
102 ParenthesizedGenericArguments, Path, PathArguments, PathSegment,
103 PolyTraitRef, QSelf, Type, TypeBinding, Unsafety, TypeSlice,
David Tolnay05362582017-12-26 01:33:57 -0500104 TypeArray, TypePtr, TypeReference, TypeBareFn, TypeNever, TypeTuple,
Nika Layzellc08227a2017-12-04 16:30:17 -0500105 TypePath, TypeTraitObject, TypeImplTrait, TypeParen, TypeInfer,
106 TypeGroup, GenericArgument};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700107#[cfg(feature = "printing")]
108pub use ty::PathTokens;
109
David Tolnayc5ab8c62017-12-26 16:43:39 -0500110mod cursor;
111pub mod synom;
112pub mod delimited;
113
114mod span;
115pub use span::Span;
David Tolnay35161ff2016-09-03 11:33:15 -0700116
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.
142#[doc(hidden)]
143pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400144
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700145/// Parse tokens of source code into the chosen syn data type.
146///
147/// This is preferred over parsing a string because tokens are able to preserve
148/// information about where in the user's code they were originally written (the
149/// "span" of the token), possibly allowing the compiler to produce better error
150/// messages.
151///
152/// # Examples
153///
David Tolnaybcf26022017-12-25 22:10:52 -0500154/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700155/// extern crate proc_macro;
156/// use proc_macro::TokenStream;
157///
158/// extern crate syn;
159///
160/// #[macro_use]
161/// extern crate quote;
162///
163/// use syn::DeriveInput;
164///
David Tolnaybcf26022017-12-25 22:10:52 -0500165/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700166/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500167/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700168/// pub fn my_macro(input: TokenStream) -> TokenStream {
169/// // Parse the tokens into a syntax tree
170/// let ast: DeriveInput = syn::parse(input).unwrap();
171///
172/// // Build the output, possibly using quasi-quotation
173/// let expanded = quote! {
174/// /* ... */
175/// };
176///
David Tolnaybcf26022017-12-25 22:10:52 -0500177/// // Convert into a token stream and return it
178/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700179/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500180/// #
181/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700182/// ```
183#[cfg(feature = "parsing")]
184pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
185 where T: Synom,
186{
187 _parse(tokens.into())
188}
189
190#[cfg(feature = "parsing")]
191fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
192 where T: Synom,
193{
194 let buf = SynomBuffer::new(tokens);
195 let result = T::parse(buf.begin());
196 let err = match result {
197 Ok((rest, t)) => {
198 if rest.eof() {
199 return Ok(t);
200 } else if rest == buf.begin() {
201 // parsed nothing
202 ParseError::new("failed to parse anything")
203 } else {
204 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700205 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700206 }
207 Err(err) => err,
208 };
209 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700210 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700211 None => Err(err),
212 }
213}
Alex Crichton954046c2017-05-30 21:49:42 -0700214
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400215/// Parse a `quote::Tokens` of Rust code into the chosen syn data type.
216///
217/// # Examples
218///
219/// ```rust
220/// extern crate syn;
221/// #
222/// # #[macro_use]
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400223/// # extern crate quote;
David Tolnay9174b972017-11-09 22:27:50 -0800224/// #
225/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400226///
227/// use syn::Expr;
Nika Layzellcda7ebd2017-10-24 23:10:44 -0400228///
229/// fn run() -> Result<()> {
230/// let code = quote!(assert_eq!(u8::max_value(), 255));
231/// let expr = syn::parse_tokens::<Expr>(code)?;
232/// println!("{:#?}", expr);
233/// Ok(())
234/// }
235/// #
236/// # fn main() { run().unwrap() }
237/// ```
238#[cfg(feature = "parsing")]
239pub fn parse_tokens<T: Synom>(tokens: quote::Tokens) -> Result<T, ParseError> {
240 _parse(tokens.into())
241}
242
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700243/// Parse a string of Rust code into the chosen syn data type.
244///
245/// # Examples
246///
247/// ```rust
248/// extern crate syn;
249/// #
David Tolnay9174b972017-11-09 22:27:50 -0800250/// #
251/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700252///
253/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700254///
255/// fn run() -> Result<()> {
256/// let code = "assert_eq!(u8::max_value(), 255)";
257/// let expr = syn::parse_str::<Expr>(code)?;
258/// println!("{:#?}", expr);
259/// Ok(())
260/// }
261/// #
262/// # fn main() { run().unwrap() }
263/// ```
264#[cfg(feature = "parsing")]
265pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
266 _parse(s.parse()?)
267}
Alex Crichton954046c2017-05-30 21:49:42 -0700268
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700269// FIXME the name parse_file makes it sound like you might pass in a path to a
270// file, rather than the content.
271/// Parse the content of a file of Rust code.
272///
273/// This is different from `syn::parse_str::<File>(content)` in two ways:
274///
275/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
276/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
277///
278/// If present, either of these would be an error using `from_str`.
279///
280/// # Examples
281///
282/// ```rust,no_run
283/// extern crate syn;
284/// #
David Tolnay9174b972017-11-09 22:27:50 -0800285/// #
286/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700287///
288/// use std::fs::File;
289/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700290///
291/// fn run() -> Result<()> {
292/// let mut file = File::open("path/to/code.rs")?;
293/// let mut content = String::new();
294/// file.read_to_string(&mut content)?;
295///
296/// let ast = syn::parse_file(&content)?;
297/// if let Some(shebang) = ast.shebang {
298/// println!("{}", shebang);
299/// }
300/// println!("{} items", ast.items.len());
301///
302/// Ok(())
303/// }
304/// #
305/// # fn main() { run().unwrap() }
306/// ```
307#[cfg(all(feature = "parsing", feature = "full"))]
308pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
309 // Strip the BOM if it is present
310 const BOM: &'static str = "\u{feff}";
311 if content.starts_with(BOM) {
312 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700313 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500314
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700315 let mut shebang = None;
316 if content.starts_with("#!") && !content.starts_with("#![") {
317 if let Some(idx) = content.find('\n') {
318 shebang = Some(content[..idx].to_string());
319 content = &content[idx..];
320 } else {
321 shebang = Some(content.to_string());
322 content = "";
323 }
Alex Crichton954046c2017-05-30 21:49:42 -0700324 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800325
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700326 let mut file: File = parse_str(content)?;
327 file.shebang = shebang;
328 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500329}
Alex Crichton259ee532017-07-14 06:51:02 -0700330
331#[cfg(feature = "printing")]
332struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
333
334#[cfg(feature = "printing")]
335impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
336 where T: quote::ToTokens + Default,
337{
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}