blob: 5ba8c205dc25c5b655287bc4c3a7121100da38aa [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 Tolnayb79ee962016-09-04 09:39:20 -070024mod attr;
David Tolnay51382052017-12-27 13:46:21 -050025pub use attr::{AttrStyle, Attribute, MetaItem, MetaItemList, MetaNameValue, NestedMetaItem};
David Tolnay35161ff2016-09-03 11:33:15 -070026
David Tolnayf38cdf62016-09-23 19:07:09 -070027mod data;
David Tolnaye3d41b72017-12-31 15:24:00 -050028pub use data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted, Visibility};
David Tolnayf38cdf62016-09-23 19:07:09 -070029
David Tolnayf4bbbd92016-09-23 14:41:55 -070030mod expr;
David Tolnay51382052017-12-27 13:46:21 -050031pub use expr::{Expr, ExprAddrOf, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock,
32 ExprBox, ExprBreak, ExprCall, ExprCast, ExprCatch, ExprClosure, ExprContinue,
33 ExprField, ExprForLoop, ExprGroup, ExprIf, ExprIfLet, ExprInPlace, ExprIndex,
David Tolnay8c91b882017-12-28 23:04:32 -050034 ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath, ExprRange,
David Tolnayc246cd32017-12-28 23:14:32 -050035 ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTuple, ExprType,
David Tolnay2ae520a2017-12-29 11:19:50 -050036 ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield, Index, Member};
Michael Layzell734adb42017-06-07 16:58:31 -040037
38#[cfg(feature = "full")]
David Tolnaybcd498f2017-12-29 12:02:33 -050039pub use expr::{Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local,
David Tolnay323279a2017-12-29 11:26:32 -050040 MethodTurbofish, Pat, PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice,
David Tolnay2ae520a2017-12-29 11:19:50 -050041 PatStruct, PatTuple, PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt};
David Tolnayf4bbbd92016-09-23 14:41:55 -070042
David Tolnayb79ee962016-09-04 09:39:20 -070043mod generics;
David Tolnay51382052017-12-27 13:46:21 -050044pub use generics::{BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef,
45 TraitBoundModifier, TypeParam, TypeParamBound, WhereBoundPredicate,
46 WhereClause, WhereEqPredicate, WherePredicate, WhereRegionPredicate};
David Tolnaye7678922016-10-13 20:44:03 -070047#[cfg(feature = "printing")]
David Tolnayfd6bf5c2017-11-12 09:41:14 -080048pub use generics::{ImplGenerics, Turbofish, TypeGenerics};
David Tolnay35161ff2016-09-03 11:33:15 -070049
David Tolnay55337722016-09-11 12:58:56 -070050mod ident;
David Tolnaydaaf7742016-10-03 11:11:43 -070051pub use ident::Ident;
David Tolnay55337722016-09-11 12:58:56 -070052
David Tolnayf38cdf62016-09-23 19:07:09 -070053#[cfg(feature = "full")]
David Tolnayb79ee962016-09-04 09:39:20 -070054mod item;
David Tolnayf38cdf62016-09-23 19:07:09 -070055#[cfg(feature = "full")]
David Tolnay360a6342017-12-29 02:22:11 -050056pub use item::{ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl,
David Tolnay2ae520a2017-12-29 11:19:50 -050057 ForeignItem, ForeignItemFn, ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem,
58 ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item,
David Tolnay03342952017-12-29 11:52:00 -050059 ItemConst, ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod,
David Tolnay51382052017-12-27 13:46:21 -050060 ItemImpl, ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait,
David Tolnay2ae520a2017-12-29 11:19:50 -050061 ItemType, ItemUnion, ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro,
62 TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseList, UsePath, UseTree};
David Tolnay35161ff2016-09-03 11:33:15 -070063
David Tolnay631cb8c2016-11-10 17:16:41 -080064#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070065mod file;
David Tolnay631cb8c2016-11-10 17:16:41 -080066#[cfg(feature = "full")]
David Tolnayc7a5d3d2017-06-04 12:11:05 -070067pub use file::File;
David Tolnay631cb8c2016-11-10 17:16:41 -080068
David Tolnay63e3dee2017-06-03 20:13:17 -070069mod lifetime;
70pub use lifetime::Lifetime;
71
David Tolnayf4bbbd92016-09-23 14:41:55 -070072mod lit;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070073pub use lit::{Lit, LitKind};
David Tolnayf4bbbd92016-09-23 14:41:55 -070074
David Tolnayf4bbbd92016-09-23 14:41:55 -070075mod mac;
David Tolnayab919512017-12-30 23:31:51 -050076pub use mac::{Macro, MacroDelimiter};
David Tolnayf4bbbd92016-09-23 14:41:55 -070077
David Tolnay0e837402016-12-22 17:25:55 -050078mod derive;
David Tolnaye3d41b72017-12-31 15:24:00 -050079pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
David Tolnayf38cdf62016-09-23 19:07:09 -070080
David Tolnay3cb23a92016-10-07 23:02:21 -070081mod op;
82pub use op::{BinOp, UnOp};
83
David Tolnayb79ee962016-09-04 09:39:20 -070084mod ty;
David Tolnayd5125762017-12-29 02:42:17 -050085pub use ty::{Abi, AngleBracketedGenericArguments, BareFnArg, BareFnArgName,
David Tolnay506e43a2017-12-29 11:34:36 -050086 Binding, GenericArgument, ParenthesizedGenericArguments, Path,
David Tolnay51382052017-12-27 13:46:21 -050087 PathArguments, PathSegment, PolyTraitRef, QSelf, ReturnType, Type, TypeArray,
David Tolnay506e43a2017-12-29 11:34:36 -050088 TypeBareFn, TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen,
David Tolnay2ae520a2017-12-29 11:19:50 -050089 TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim};
Alex Crichtonccbb45d2017-05-23 10:58:24 -070090#[cfg(feature = "printing")]
91pub use ty::PathTokens;
92
David Tolnay1b752fb2017-12-26 21:41:39 -050093#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -050094mod cursor;
David Tolnay1b752fb2017-12-26 21:41:39 -050095#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -050096pub mod synom;
David Tolnayf2cfd722017-12-31 18:02:51 -050097pub mod punctuated;
David Tolnaye0824032017-12-27 15:25:56 -050098#[cfg(feature = "parsing")]
99mod tt;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500100
Nika Layzella6f46c42017-10-26 15:26:16 -0400101mod gen {
102 #[cfg(feature = "visit")]
103 pub mod visit;
David Tolnay55337722016-09-11 12:58:56 -0700104
Nika Layzella6f46c42017-10-26 15:26:16 -0400105 #[cfg(feature = "visit_mut")]
106 pub mod visit_mut;
Nika Layzell27726662017-10-24 23:16:35 -0400107
Nika Layzella6f46c42017-10-26 15:26:16 -0400108 #[cfg(feature = "fold")]
109 pub mod fold;
David Tolnayf60f4262017-12-28 19:17:58 -0500110
111 #[path = "../gen_helper.rs"]
112 mod helper;
Nika Layzella6f46c42017-10-26 15:26:16 -0400113}
114pub use gen::*;
gnzlbg9ae88d82017-01-26 20:45:17 +0100115
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700116////////////////////////////////////////////////////////////////////////////////
117
David Tolnay55337722016-09-11 12:58:56 -0700118#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500119use synom::Synom;
120#[cfg(feature = "parsing")]
121use cursor::SynomBuffer;
Ted Driggs054abbb2017-05-01 12:20:52 -0700122
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700123#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500124mod error;
125#[cfg(feature = "parsing")]
David Tolnay203557a2017-12-27 23:59:33 -0500126use error::ParseError;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500127
128// Not public API.
David Tolnay1b752fb2017-12-26 21:41:39 -0500129#[cfg(feature = "parsing")]
David Tolnayc5ab8c62017-12-26 16:43:39 -0500130#[doc(hidden)]
131pub use error::parse_error;
Michael Layzell416724e2017-05-24 21:12:34 -0400132
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700133/// Parse tokens of source code into the chosen syn data type.
134///
135/// This is preferred over parsing a string because tokens are able to preserve
136/// information about where in the user's code they were originally written (the
137/// "span" of the token), possibly allowing the compiler to produce better error
138/// messages.
139///
140/// # Examples
141///
David Tolnaybcf26022017-12-25 22:10:52 -0500142/// ```rust
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700143/// extern crate proc_macro;
144/// use proc_macro::TokenStream;
145///
146/// extern crate syn;
147///
148/// #[macro_use]
149/// extern crate quote;
150///
151/// use syn::DeriveInput;
152///
David Tolnaybcf26022017-12-25 22:10:52 -0500153/// # const IGNORE_TOKENS: &str = stringify! {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700154/// #[proc_macro_derive(MyMacro)]
David Tolnaybcf26022017-12-25 22:10:52 -0500155/// # };
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700156/// pub fn my_macro(input: TokenStream) -> TokenStream {
157/// // Parse the tokens into a syntax tree
158/// let ast: DeriveInput = syn::parse(input).unwrap();
159///
160/// // Build the output, possibly using quasi-quotation
161/// let expanded = quote! {
162/// /* ... */
163/// };
164///
David Tolnaybcf26022017-12-25 22:10:52 -0500165/// // Convert into a token stream and return it
166/// expanded.into()
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700167/// }
David Tolnaybcf26022017-12-25 22:10:52 -0500168/// #
169/// # fn main() {}
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700170/// ```
171#[cfg(feature = "parsing")]
172pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500173where
174 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700175{
176 _parse(tokens.into())
177}
178
179#[cfg(feature = "parsing")]
180fn _parse<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError>
David Tolnay51382052017-12-27 13:46:21 -0500181where
182 T: Synom,
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700183{
184 let buf = SynomBuffer::new(tokens);
185 let result = T::parse(buf.begin());
186 let err = match result {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500187 Ok((t, rest)) => {
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700188 if rest.eof() {
189 return Ok(t);
190 } else if rest == buf.begin() {
191 // parsed nothing
192 ParseError::new("failed to parse anything")
193 } else {
194 ParseError::new("failed to parse all tokens")
David Tolnay55337722016-09-11 12:58:56 -0700195 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700196 }
197 Err(err) => err,
198 };
199 match T::description() {
Alex Crichtonc1b76f52017-07-06 15:04:24 -0700200 Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))),
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700201 None => Err(err),
202 }
203}
Alex Crichton954046c2017-05-30 21:49:42 -0700204
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700205/// Parse a string of Rust code into the chosen syn data type.
206///
207/// # Examples
208///
209/// ```rust
210/// extern crate syn;
211/// #
David Tolnay9174b972017-11-09 22:27:50 -0800212/// #
213/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700214///
215/// use syn::Expr;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700216///
217/// fn run() -> Result<()> {
218/// let code = "assert_eq!(u8::max_value(), 255)";
219/// let expr = syn::parse_str::<Expr>(code)?;
220/// println!("{:#?}", expr);
221/// Ok(())
222/// }
223/// #
224/// # fn main() { run().unwrap() }
225/// ```
226#[cfg(feature = "parsing")]
227pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> {
David Tolnayffb1f4d2017-12-28 00:07:59 -0500228 match s.parse() {
229 Ok(tts) => _parse(tts),
230 Err(_) => Err(ParseError::new("error while lexing input string")),
231 }
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700232}
Alex Crichton954046c2017-05-30 21:49:42 -0700233
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700234// FIXME the name parse_file makes it sound like you might pass in a path to a
235// file, rather than the content.
236/// Parse the content of a file of Rust code.
237///
238/// This is different from `syn::parse_str::<File>(content)` in two ways:
239///
240/// - It discards a leading byte order mark `\u{FEFF}` if the file has one.
241/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`.
242///
243/// If present, either of these would be an error using `from_str`.
244///
245/// # Examples
246///
247/// ```rust,no_run
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 std::fs::File;
254/// use std::io::Read;
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700255///
256/// fn run() -> Result<()> {
257/// let mut file = File::open("path/to/code.rs")?;
258/// let mut content = String::new();
259/// file.read_to_string(&mut content)?;
260///
261/// let ast = syn::parse_file(&content)?;
262/// if let Some(shebang) = ast.shebang {
263/// println!("{}", shebang);
264/// }
265/// println!("{} items", ast.items.len());
266///
267/// Ok(())
268/// }
269/// #
270/// # fn main() { run().unwrap() }
271/// ```
272#[cfg(all(feature = "parsing", feature = "full"))]
273pub fn parse_file(mut content: &str) -> Result<File, ParseError> {
274 // Strip the BOM if it is present
275 const BOM: &'static str = "\u{feff}";
276 if content.starts_with(BOM) {
277 content = &content[BOM.len()..];
David Tolnay35161ff2016-09-03 11:33:15 -0700278 }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500279
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700280 let mut shebang = None;
281 if content.starts_with("#!") && !content.starts_with("#![") {
282 if let Some(idx) = content.find('\n') {
283 shebang = Some(content[..idx].to_string());
284 content = &content[idx..];
285 } else {
286 shebang = Some(content.to_string());
287 content = "";
288 }
Alex Crichton954046c2017-05-30 21:49:42 -0700289 }
David Tolnay0a8972b2017-02-27 02:10:01 -0800290
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700291 let mut file: File = parse_str(content)?;
292 file.shebang = shebang;
293 Ok(file)
Michael Layzell5e107ff2017-01-24 19:58:39 -0500294}
Alex Crichton259ee532017-07-14 06:51:02 -0700295
296#[cfg(feature = "printing")]
297struct TokensOrDefault<'a, T: 'a>(&'a Option<T>);
298
299#[cfg(feature = "printing")]
300impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T>
David Tolnay51382052017-12-27 13:46:21 -0500301where
302 T: quote::ToTokens + Default,
Alex Crichton259ee532017-07-14 06:51:02 -0700303{
304 fn to_tokens(&self, tokens: &mut quote::Tokens) {
305 match *self.0 {
306 Some(ref t) => t.to_tokens(tokens),
307 None => T::default().to_tokens(tokens),
308 }
309 }
310}