David Tolnay | 5553501 | 2018-01-05 16:39:23 -0800 | [diff] [blame] | 1 | // Copyright 2018 Syn Developers |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | // option. This file may not be copied, modified, or distributed |
| 7 | // except according to those terms. |
| 8 | |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 9 | //! Syn is a parsing library for parsing a stream of Rust tokens into a syntax |
| 10 | //! tree of Rust source code. |
| 11 | //! |
| 12 | //! Currently this library is geared toward the [custom derive] use case but |
| 13 | //! contains some APIs that may be useful for Rust procedural macros more |
| 14 | //! generally. |
| 15 | //! |
| 16 | //! [custom derive]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md |
| 17 | //! |
| 18 | //! - **Data structures** — Syn provides a complete syntax tree that can |
| 19 | //! represent any valid Rust source code. The syntax tree is rooted at |
| 20 | //! [`syn::File`] which represents a full source file, but there are other |
| 21 | //! entry points that may be useful to procedural macros including |
| 22 | //! [`syn::Item`], [`syn::Expr`] and [`syn::Type`]. |
| 23 | //! |
| 24 | //! - **Custom derives** — Of particular interest to custom derives is |
| 25 | //! [`syn::DeriveInput`] which is any of the three legal input items to a |
| 26 | //! derive macro. An example below shows using this type in a library that can |
| 27 | //! derive implementations of a trait of your own. |
| 28 | //! |
| 29 | //! - **Parser combinators** — Parsing in Syn is built on a suite of public |
| 30 | //! parser combinator macros that you can use for parsing any token-based |
| 31 | //! syntax you dream up within a `functionlike!(...)` procedural macro. Every |
| 32 | //! syntax tree node defined by Syn is individually parsable and may be used |
| 33 | //! as a building block for custom syntaxes, or you may do it all yourself |
| 34 | //! working from the most primitive tokens. |
| 35 | //! |
| 36 | //! - **Location information** — Every token parsed by Syn is associated with a |
| 37 | //! `Span` that tracks line and column information back to the source of that |
| 38 | //! token. These spans allow a procedural macro to display detailed error |
| 39 | //! messages pointing to all the right places in the user's code. There is an |
| 40 | //! example of this below. |
| 41 | //! |
| 42 | //! - **Feature flags** — Functionality is aggressively feature gated so your |
| 43 | //! procedural macros enable only what they need, and do not pay in compile |
| 44 | //! time for all the rest. |
| 45 | //! |
| 46 | //! [`syn::File`]: struct.File.html |
| 47 | //! [`syn::Item`]: enum.Item.html |
| 48 | //! [`syn::Expr`]: enum.Expr.html |
| 49 | //! [`syn::Type`]: enum.Type.html |
| 50 | //! [`syn::DeriveInput`]: struct.DeriveInput.html |
| 51 | //! |
| 52 | //! *Version requirement: Syn supports any compiler version back to Rust's very |
| 53 | //! first support for procedural macros in Rust 1.15.0. Some features especially |
| 54 | //! around error reporting are only available in newer compilers or on the |
| 55 | //! nightly channel.* |
| 56 | //! |
| 57 | //! ## Example of a custom derive |
| 58 | //! |
| 59 | //! The canonical custom derive using Syn looks like this. We write an ordinary |
| 60 | //! Rust function tagged with a `proc_macro_derive` attribute and the name of |
| 61 | //! the trait we are deriving. Any time that derive appears in the user's code, |
| 62 | //! the Rust compiler passes their data structure as tokens into our macro. We |
| 63 | //! get to execute arbitrary Rust code to figure out what to do with those |
| 64 | //! tokens, then hand some tokens back to the compiler to compile into the |
| 65 | //! user's crate. |
| 66 | //! |
| 67 | //! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html |
| 68 | //! |
| 69 | //! ```toml |
| 70 | //! [dependencies] |
| 71 | //! syn = "0.12" |
| 72 | //! quote = "0.4" |
| 73 | //! |
| 74 | //! [lib] |
| 75 | //! proc-macro = true |
| 76 | //! ``` |
| 77 | //! |
| 78 | //! ```rust |
| 79 | //! extern crate proc_macro; |
| 80 | //! extern crate syn; |
| 81 | //! |
| 82 | //! #[macro_use] |
| 83 | //! extern crate quote; |
| 84 | //! |
| 85 | //! use proc_macro::TokenStream; |
| 86 | //! use syn::DeriveInput; |
| 87 | //! |
| 88 | //! # const IGNORE_TOKENS: &str = stringify! { |
| 89 | //! #[proc_macro_derive(MyMacro)] |
| 90 | //! # }; |
| 91 | //! pub fn my_macro(input: TokenStream) -> TokenStream { |
| 92 | //! // Parse the input tokens into a syntax tree |
| 93 | //! let input: DeriveInput = syn::parse(input).unwrap(); |
| 94 | //! |
| 95 | //! // Build the output, possibly using quasi-quotation |
| 96 | //! let expanded = quote! { |
| 97 | //! // ... |
| 98 | //! }; |
| 99 | //! |
| 100 | //! // Hand the output tokens back to the compiler |
| 101 | //! expanded.into() |
| 102 | //! } |
| 103 | //! # |
| 104 | //! # fn main() {} |
| 105 | //! ``` |
| 106 | //! |
| 107 | //! The [`heapsize`] example directory shows a complete working Macros 1.1 |
| 108 | //! implementation of a custom derive. It works on any Rust compiler \>=1.15.0. |
| 109 | //! The example derives a `HeapSize` trait which computes an estimate of the |
| 110 | //! amount of heap memory owned by a value. |
| 111 | //! |
| 112 | //! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize |
| 113 | //! |
| 114 | //! ```rust |
| 115 | //! pub trait HeapSize { |
| 116 | //! /// Total number of bytes of heap memory owned by `self`. |
| 117 | //! fn heap_size_of_children(&self) -> usize; |
| 118 | //! } |
| 119 | //! ``` |
| 120 | //! |
| 121 | //! The custom derive allows users to write `#[derive(HeapSize)]` on data |
| 122 | //! structures in their program. |
| 123 | //! |
| 124 | //! ```rust |
| 125 | //! # const IGNORE_TOKENS: &str = stringify! { |
| 126 | //! #[derive(HeapSize)] |
| 127 | //! # }; |
| 128 | //! struct Demo<'a, T: ?Sized> { |
| 129 | //! a: Box<T>, |
| 130 | //! b: u8, |
| 131 | //! c: &'a str, |
| 132 | //! d: String, |
| 133 | //! } |
| 134 | //! ``` |
| 135 | //! |
| 136 | //! ## Spans and error reporting |
| 137 | //! |
| 138 | //! The [`heapsize2`] example directory is an extension of the `heapsize` |
| 139 | //! example that demonstrates some of the hygiene and error reporting properties |
| 140 | //! of Macros 2.0. This example currently requires a nightly Rust compiler |
| 141 | //! \>=1.24.0-nightly but we are working to stabilize all of the APIs involved. |
| 142 | //! |
| 143 | //! [`heapsize2`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize2 |
| 144 | //! |
| 145 | //! The token-based procedural macro API provides great control over where the |
| 146 | //! compiler's error messages are displayed in user code. Consider the error the |
| 147 | //! user sees if one of their field types does not implement `HeapSize`. |
| 148 | //! |
| 149 | //! ```rust |
| 150 | //! # const IGNORE_TOKENS: &str = stringify! { |
| 151 | //! #[derive(HeapSize)] |
| 152 | //! # }; |
| 153 | //! struct Broken { |
| 154 | //! ok: String, |
| 155 | //! bad: std::thread::Thread, |
| 156 | //! } |
| 157 | //! ``` |
| 158 | //! |
| 159 | //! In the Macros 1.1 string-based procedural macro world, the resulting error |
| 160 | //! would point unhelpfully to the invocation of the derive macro and not to the |
| 161 | //! actual problematic field. |
| 162 | //! |
| 163 | //! ```text |
| 164 | //! error[E0599]: no method named `heap_size_of_children` found for type `std::thread::Thread` in the current scope |
| 165 | //! --> src/main.rs:4:10 |
| 166 | //! | |
| 167 | //! 4 | #[derive(HeapSize)] |
| 168 | //! | ^^^^^^^^ |
| 169 | //! ``` |
| 170 | //! |
| 171 | //! By tracking span information all the way through the expansion of a |
| 172 | //! procedural macro as shown in the `heapsize2` example, token-based macros in |
| 173 | //! Syn are able to trigger errors that directly pinpoint the source of the |
| 174 | //! problem. |
| 175 | //! |
| 176 | //! ```text |
| 177 | //! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied |
| 178 | //! --> src/main.rs:7:5 |
| 179 | //! | |
| 180 | //! 7 | bad: std::thread::Thread, |
| 181 | //! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `std::thread::Thread` |
| 182 | //! ``` |
| 183 | //! |
| 184 | //! ## Parsing a custom syntax using combinators |
| 185 | //! |
| 186 | //! The [`lazy-static`] example directory shows the implementation of a |
| 187 | //! `functionlike!(...)` procedural macro in which the input tokens are parsed |
| 188 | //! using [`nom`]-style parser combinators. |
| 189 | //! |
| 190 | //! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static |
| 191 | //! [`nom`]: https://github.com/Geal/nom |
| 192 | //! |
| 193 | //! The example reimplements the popular `lazy_static` crate from crates.io as a |
| 194 | //! procedural macro. |
| 195 | //! |
| 196 | //! ``` |
| 197 | //! # macro_rules! lazy_static { |
| 198 | //! # ($($tt:tt)*) => {} |
| 199 | //! # } |
| 200 | //! # |
| 201 | //! lazy_static! { |
| 202 | //! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); |
| 203 | //! } |
| 204 | //! ``` |
| 205 | //! |
| 206 | //! The implementation shows how to trigger custom warnings and error messages |
| 207 | //! on the macro input. |
| 208 | //! |
| 209 | //! ```text |
| 210 | //! warning: come on, pick a more creative name |
| 211 | //! --> src/main.rs:10:16 |
| 212 | //! | |
| 213 | //! 10 | static ref FOO: String = "lazy_static".to_owned(); |
| 214 | //! | ^^^ |
| 215 | //! ``` |
| 216 | //! |
| 217 | //! ## Debugging |
| 218 | //! |
| 219 | //! When developing a procedural macro it can be helpful to look at what the |
| 220 | //! generated code looks like. Use `cargo rustc -- -Zunstable-options |
| 221 | //! --pretty=expanded` or the [`cargo expand`] subcommand. |
| 222 | //! |
| 223 | //! [`cargo-expand`]: https://github.com/dtolnay/cargo-expand |
| 224 | //! |
| 225 | //! To show the expanded code for some crate that uses your procedural macro, |
| 226 | //! run `cargo expand` from that crate. To show the expanded code for one of |
| 227 | //! your own test cases, run `cargo expand --test the_test_case` where the last |
| 228 | //! argument is the name of the test file without the `.rs` extension. |
| 229 | //! |
| 230 | //! This write-up by Brandon W Maister discusses debugging in more detail: |
| 231 | //! [Debugging Rust's new Custom Derive system][debugging]. |
| 232 | //! |
| 233 | //! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ |
| 234 | //! |
| 235 | //! ## Optional features |
| 236 | //! |
| 237 | //! Syn puts a lot of functionality behind optional features in order to |
| 238 | //! optimize compile time for the most common use cases. The following features |
| 239 | //! are available. |
| 240 | //! |
| 241 | //! - **`derive`** *(enabled by default)* — Data structures for representing the |
| 242 | //! possible input to a custom derive, including structs and enums and types. |
| 243 | //! - **`full`** — Data structures for representing the syntax tree of all valid |
| 244 | //! Rust source code, including items and expressions. |
| 245 | //! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into |
| 246 | //! a syntax tree node of a chosen type. |
| 247 | //! - **`printing`** *(enabled by default)* — Ability to print a syntax tree |
| 248 | //! node as tokens of Rust source code. |
| 249 | //! - **`visit`** — Trait for traversing a syntax tree. |
David Tolnay | 34981cf | 2018-01-06 16:22:35 -0800 | [diff] [blame] | 250 | //! - **`visit-mut`** — Trait for traversing and mutating in place a syntax |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 251 | //! tree. |
| 252 | //! - **`fold`** — Trait for transforming an owned syntax tree. |
| 253 | //! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree |
| 254 | //! types. |
| 255 | //! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree |
| 256 | //! types. |
| 257 | |
David Tolnay | ad2836d | 2017-04-20 10:11:43 -0700 | [diff] [blame] | 258 | #![doc(html_root_url = "https://dtolnay.github.io/syn")] |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 259 | #![cfg_attr(feature = "cargo-clippy", |
| 260 | allow(const_static_lifetime, doc_markdown, large_enum_variant, match_bool, |
David Tolnay | 76ebcdd | 2018-01-05 17:07:26 -0800 | [diff] [blame] | 261 | redundant_closure, needless_pass_by_value))] |
David Tolnay | ad2836d | 2017-04-20 10:11:43 -0700 | [diff] [blame] | 262 | |
Alex Crichton | ccbb45d | 2017-05-23 10:58:24 -0700 | [diff] [blame] | 263 | extern crate proc_macro2; |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 264 | extern crate proc_macro; |
David Tolnay | 570695e | 2017-06-03 16:15:13 -0700 | [diff] [blame] | 265 | extern crate unicode_xid; |
Alex Crichton | ccbb45d | 2017-05-23 10:58:24 -0700 | [diff] [blame] | 266 | |
David Tolnay | 1cf8091 | 2017-12-31 18:35:12 -0500 | [diff] [blame] | 267 | #[cfg(feature = "printing")] |
David Tolnay | 87d0b44 | 2016-09-04 11:52:12 -0700 | [diff] [blame] | 268 | extern crate quote; |
| 269 | |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 270 | #[cfg(feature = "parsing")] |
David Tolnay | f8db7ba | 2017-11-11 22:52:16 -0800 | [diff] [blame] | 271 | #[macro_use] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 272 | #[doc(hidden)] |
| 273 | pub mod parsers; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 274 | |
Alex Crichton | 62a0a59 | 2017-05-22 13:58:53 -0700 | [diff] [blame] | 275 | #[macro_use] |
| 276 | mod macros; |
| 277 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 278 | #[macro_use] |
David Tolnay | 32954ef | 2017-12-26 22:43:16 -0500 | [diff] [blame] | 279 | pub mod token; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 280 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 281 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 282 | mod attr; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 283 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 284 | pub use attr::{AttrStyle, Attribute, MetaItem, MetaItemList, MetaNameValue, NestedMetaItem}; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 285 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 286 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 287 | mod data; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 288 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 289 | pub use data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, |
| 290 | VisRestricted, Visibility}; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 291 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 292 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 293 | mod expr; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 294 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 295 | pub use expr::{Expr, ExprAddrOf, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, |
| 296 | ExprBox, ExprBreak, ExprCall, ExprCast, ExprCatch, ExprClosure, ExprContinue, |
| 297 | ExprField, ExprForLoop, ExprGroup, ExprIf, ExprIfLet, ExprInPlace, ExprIndex, |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 298 | ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath, |
| 299 | ExprRange, ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTuple, ExprType, |
| 300 | ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield, Index, |
| 301 | Member}; |
Michael Layzell | 734adb4 | 2017-06-07 16:58:31 -0400 | [diff] [blame] | 302 | |
| 303 | #[cfg(feature = "full")] |
David Tolnay | bcd498f | 2017-12-29 12:02:33 -0500 | [diff] [blame] | 304 | pub use expr::{Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 305 | MethodTurbofish, Pat, PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, |
| 306 | PatRef, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatVerbatim, PatWild, |
| 307 | RangeLimits, Stmt}; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 308 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 309 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 310 | mod generics; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 311 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 312 | pub use generics::{BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq, |
| 313 | PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, |
| 314 | TypeParamBound, WhereClause, WherePredicate}; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 315 | #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] |
David Tolnay | fd6bf5c | 2017-11-12 09:41:14 -0800 | [diff] [blame] | 316 | pub use generics::{ImplGenerics, Turbofish, TypeGenerics}; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 317 | |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 318 | mod ident; |
David Tolnay | daaf774 | 2016-10-03 11:11:43 -0700 | [diff] [blame] | 319 | pub use ident::Ident; |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 320 | |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 321 | #[cfg(feature = "full")] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 322 | mod item; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 323 | #[cfg(feature = "full")] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 324 | pub use item::{ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, |
| 325 | ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst, |
| 326 | ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item, ItemConst, |
| 327 | ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2, |
| 328 | ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemType, ItemUnion, ItemUse, |
| 329 | ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro, |
| 330 | TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseList, UsePath, |
| 331 | UseTree}; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 332 | |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 333 | #[cfg(feature = "full")] |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 334 | mod file; |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 335 | #[cfg(feature = "full")] |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 336 | pub use file::File; |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 337 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 338 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 63e3dee | 2017-06-03 20:13:17 -0700 | [diff] [blame] | 339 | mod lifetime; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 340 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 63e3dee | 2017-06-03 20:13:17 -0700 | [diff] [blame] | 341 | pub use lifetime::Lifetime; |
| 342 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 343 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 344 | mod lit; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 345 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 346 | pub use lit::{FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, |
| 347 | LitInt, LitStr, LitVerbatim, StrStyle}; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 348 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 349 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 350 | mod mac; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 351 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | ab91951 | 2017-12-30 23:31:51 -0500 | [diff] [blame] | 352 | pub use mac::{Macro, MacroDelimiter}; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 353 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 354 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 0e83740 | 2016-12-22 17:25:55 -0500 | [diff] [blame] | 355 | mod derive; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 356 | #[cfg(feature = "derive")] |
David Tolnay | e3d41b7 | 2017-12-31 15:24:00 -0500 | [diff] [blame] | 357 | pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 358 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 359 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 3cb23a9 | 2016-10-07 23:02:21 -0700 | [diff] [blame] | 360 | mod op; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 361 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 3cb23a9 | 2016-10-07 23:02:21 -0700 | [diff] [blame] | 362 | pub use op::{BinOp, UnOp}; |
| 363 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 364 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 365 | mod ty; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 366 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 367 | pub use ty::{Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, |
| 368 | TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, |
| 369 | TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim}; |
David Tolnay | 056de30 | 2018-01-05 14:29:05 -0800 | [diff] [blame] | 370 | |
| 371 | #[cfg(any(feature = "full", feature = "derive"))] |
| 372 | mod path; |
| 373 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 61037c6 | 2018-01-05 16:21:03 -0800 | [diff] [blame] | 374 | pub use path::{AngleBracketedGenericArguments, Binding, GenericArgument, |
| 375 | ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf}; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 376 | #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] |
David Tolnay | 056de30 | 2018-01-05 14:29:05 -0800 | [diff] [blame] | 377 | pub use path::PathTokens; |
Alex Crichton | ccbb45d | 2017-05-23 10:58:24 -0700 | [diff] [blame] | 378 | |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 379 | #[cfg(feature = "parsing")] |
David Tolnay | dfc886b | 2018-01-06 08:03:09 -0800 | [diff] [blame] | 380 | pub mod buffer; |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 381 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 382 | pub mod synom; |
David Tolnay | f2cfd72 | 2017-12-31 18:02:51 -0500 | [diff] [blame] | 383 | pub mod punctuated; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 384 | #[cfg(all(any(feature = "full", feature = "derive"), feature = "parsing"))] |
David Tolnay | e082403 | 2017-12-27 15:25:56 -0500 | [diff] [blame] | 385 | mod tt; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 386 | |
David Tolnay | 4d942b4 | 2018-01-02 22:14:04 -0800 | [diff] [blame] | 387 | #[cfg(all(feature = "parsing", feature = "printing"))] |
David Tolnay | f790b61 | 2017-12-31 18:46:57 -0500 | [diff] [blame] | 388 | pub mod spanned; |
| 389 | |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 390 | mod gen { |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 391 | /// Syntax tree traversal to walk a shared borrow of a syntax tree. |
| 392 | /// |
| 393 | /// Each method of the [`Visit`] trait is a hook that can be overridden to |
| 394 | /// customize the behavior when visiting the corresponding type of node. By |
| 395 | /// default, every method recursively visits the substructure of the input |
| 396 | /// by invoking the right visitor method of each of its fields. |
| 397 | /// |
| 398 | /// [`Visit`]: trait.Visit.html |
| 399 | /// |
| 400 | /// ```rust |
| 401 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 402 | /// # |
| 403 | /// pub trait Visit<'ast> { |
| 404 | /// /* ... */ |
| 405 | /// |
| 406 | /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { |
| 407 | /// for attr in &node.attrs { |
| 408 | /// self.visit_attribute(attr); |
| 409 | /// } |
| 410 | /// self.visit_expr(&*node.left); |
| 411 | /// self.visit_bin_op(&node.op); |
| 412 | /// self.visit_expr(&*node.right); |
| 413 | /// } |
| 414 | /// |
| 415 | /// /* ... */ |
| 416 | /// # fn visit_attribute(&mut self, node: &'ast Attribute); |
| 417 | /// # fn visit_expr(&mut self, node: &'ast Expr); |
| 418 | /// # fn visit_bin_op(&mut self, node: &'ast BinOp); |
| 419 | /// } |
| 420 | /// ``` |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 421 | #[cfg(feature = "visit")] |
| 422 | pub mod visit; |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 423 | |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 424 | |
| 425 | /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in |
| 426 | /// place. |
| 427 | /// |
| 428 | /// Each method of the [`VisitMut`] trait is a hook that can be overridden |
| 429 | /// to customize the behavior when mutating the corresponding type of node. |
| 430 | /// By default, every method recursively visits the substructure of the |
| 431 | /// input by invoking the right visitor method of each of its fields. |
| 432 | /// |
| 433 | /// [`VisitMut`]: trait.VisitMut.html |
| 434 | /// |
| 435 | /// ```rust |
| 436 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 437 | /// # |
| 438 | /// pub trait VisitMut { |
| 439 | /// /* ... */ |
| 440 | /// |
| 441 | /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { |
| 442 | /// for attr in &mut node.attrs { |
| 443 | /// self.visit_attribute_mut(attr); |
| 444 | /// } |
| 445 | /// self.visit_expr_mut(&mut *node.left); |
| 446 | /// self.visit_bin_op_mut(&mut node.op); |
| 447 | /// self.visit_expr_mut(&mut *node.right); |
| 448 | /// } |
| 449 | /// |
| 450 | /// /* ... */ |
| 451 | /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); |
| 452 | /// # fn visit_expr_mut(&mut self, node: &mut Expr); |
| 453 | /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); |
| 454 | /// } |
| 455 | /// ``` |
David Tolnay | 9df02c4 | 2018-01-06 13:52:48 -0800 | [diff] [blame] | 456 | #[cfg(feature = "visit-mut")] |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 457 | pub mod visit_mut; |
Nika Layzell | 2772666 | 2017-10-24 23:16:35 -0400 | [diff] [blame] | 458 | |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 459 | /// Syntax tree traversal to transform the nodes of an owned syntax tree. |
| 460 | /// |
| 461 | /// Each method of the [`Fold`] trait is a hook that can be overridden to |
| 462 | /// customize the behavior when transforming the corresponding type of node. |
| 463 | /// By default, every method recursively visits the substructure of the |
| 464 | /// input by invoking the right visitor method of each of its fields. |
| 465 | /// |
| 466 | /// [`Fold`]: trait.Fold.html |
| 467 | /// |
| 468 | /// ```rust |
| 469 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 470 | /// # |
| 471 | /// pub trait Fold { |
| 472 | /// /* ... */ |
| 473 | /// |
| 474 | /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { |
| 475 | /// ExprBinary { |
| 476 | /// attrs: node.attrs |
| 477 | /// .into_iter() |
| 478 | /// .map(|attr| self.fold_attribute(attr)) |
| 479 | /// .collect(), |
| 480 | /// left: Box::new(self.fold_expr(*node.left)), |
| 481 | /// op: self.fold_bin_op(node.op), |
| 482 | /// right: Box::new(self.fold_expr(*node.right)), |
| 483 | /// } |
| 484 | /// } |
| 485 | /// |
| 486 | /// /* ... */ |
| 487 | /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; |
| 488 | /// # fn fold_expr(&mut self, node: Expr) -> Expr; |
| 489 | /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; |
| 490 | /// } |
| 491 | /// ``` |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 492 | #[cfg(feature = "fold")] |
| 493 | pub mod fold; |
David Tolnay | f60f426 | 2017-12-28 19:17:58 -0500 | [diff] [blame] | 494 | |
David Tolnay | 0a0d78c | 2018-01-05 15:24:01 -0800 | [diff] [blame] | 495 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f60f426 | 2017-12-28 19:17:58 -0500 | [diff] [blame] | 496 | #[path = "../gen_helper.rs"] |
| 497 | mod helper; |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 498 | } |
| 499 | pub use gen::*; |
gnzlbg | 9ae88d8 | 2017-01-26 20:45:17 +0100 | [diff] [blame] | 500 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 501 | //////////////////////////////////////////////////////////////////////////////// |
| 502 | |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 503 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 504 | use synom::Synom; |
| 505 | #[cfg(feature = "parsing")] |
David Tolnay | dfc886b | 2018-01-06 08:03:09 -0800 | [diff] [blame] | 506 | use buffer::TokenBuffer; |
Ted Driggs | 054abbb | 2017-05-01 12:20:52 -0700 | [diff] [blame] | 507 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 508 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 509 | mod error; |
| 510 | #[cfg(feature = "parsing")] |
David Tolnay | 203557a | 2017-12-27 23:59:33 -0500 | [diff] [blame] | 511 | use error::ParseError; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 512 | |
| 513 | // Not public API. |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 514 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 515 | #[doc(hidden)] |
| 516 | pub use error::parse_error; |
Michael Layzell | 416724e | 2017-05-24 21:12:34 -0400 | [diff] [blame] | 517 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 518 | /// Parse tokens of source code into the chosen syn data type. |
| 519 | /// |
| 520 | /// This is preferred over parsing a string because tokens are able to preserve |
| 521 | /// information about where in the user's code they were originally written (the |
| 522 | /// "span" of the token), possibly allowing the compiler to produce better error |
| 523 | /// messages. |
| 524 | /// |
| 525 | /// # Examples |
| 526 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 527 | /// ```rust |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 528 | /// extern crate proc_macro; |
| 529 | /// use proc_macro::TokenStream; |
| 530 | /// |
| 531 | /// extern crate syn; |
| 532 | /// |
| 533 | /// #[macro_use] |
| 534 | /// extern crate quote; |
| 535 | /// |
| 536 | /// use syn::DeriveInput; |
| 537 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 538 | /// # const IGNORE_TOKENS: &str = stringify! { |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 539 | /// #[proc_macro_derive(MyMacro)] |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 540 | /// # }; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 541 | /// pub fn my_macro(input: TokenStream) -> TokenStream { |
| 542 | /// // Parse the tokens into a syntax tree |
| 543 | /// let ast: DeriveInput = syn::parse(input).unwrap(); |
| 544 | /// |
| 545 | /// // Build the output, possibly using quasi-quotation |
| 546 | /// let expanded = quote! { |
| 547 | /// /* ... */ |
| 548 | /// }; |
| 549 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 550 | /// // Convert into a token stream and return it |
| 551 | /// expanded.into() |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 552 | /// } |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 553 | /// # |
| 554 | /// # fn main() {} |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 555 | /// ``` |
| 556 | #[cfg(feature = "parsing")] |
| 557 | pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 558 | where |
| 559 | T: Synom, |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 560 | { |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 561 | parse2(tokens.into()) |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 562 | } |
| 563 | |
| 564 | #[cfg(feature = "parsing")] |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 565 | pub fn parse2<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 566 | where |
| 567 | T: Synom, |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 568 | { |
David Tolnay | 7c3e77d | 2018-01-06 17:42:53 -0800 | [diff] [blame] | 569 | let buf = TokenBuffer::new2(tokens); |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 570 | let result = T::parse(buf.begin()); |
| 571 | let err = match result { |
David Tolnay | f4aa6b4 | 2017-12-31 16:40:33 -0500 | [diff] [blame] | 572 | Ok((t, rest)) => { |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 573 | if rest.eof() { |
| 574 | return Ok(t); |
| 575 | } else if rest == buf.begin() { |
| 576 | // parsed nothing |
| 577 | ParseError::new("failed to parse anything") |
| 578 | } else { |
| 579 | ParseError::new("failed to parse all tokens") |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 580 | } |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 581 | } |
| 582 | Err(err) => err, |
| 583 | }; |
| 584 | match T::description() { |
Alex Crichton | c1b76f5 | 2017-07-06 15:04:24 -0700 | [diff] [blame] | 585 | Some(s) => Err(ParseError::new(format!("failed to parse {}: {}", s, err))), |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 586 | None => Err(err), |
| 587 | } |
| 588 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 589 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 590 | /// Parse a string of Rust code into the chosen syn data type. |
| 591 | /// |
| 592 | /// # Examples |
| 593 | /// |
| 594 | /// ```rust |
| 595 | /// extern crate syn; |
| 596 | /// # |
David Tolnay | 9174b97 | 2017-11-09 22:27:50 -0800 | [diff] [blame] | 597 | /// # |
| 598 | /// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 599 | /// |
| 600 | /// use syn::Expr; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 601 | /// |
| 602 | /// fn run() -> Result<()> { |
| 603 | /// let code = "assert_eq!(u8::max_value(), 255)"; |
| 604 | /// let expr = syn::parse_str::<Expr>(code)?; |
| 605 | /// println!("{:#?}", expr); |
| 606 | /// Ok(()) |
| 607 | /// } |
| 608 | /// # |
| 609 | /// # fn main() { run().unwrap() } |
| 610 | /// ``` |
| 611 | #[cfg(feature = "parsing")] |
| 612 | pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> { |
David Tolnay | ffb1f4d | 2017-12-28 00:07:59 -0500 | [diff] [blame] | 613 | match s.parse() { |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 614 | Ok(tts) => parse2(tts), |
David Tolnay | ffb1f4d | 2017-12-28 00:07:59 -0500 | [diff] [blame] | 615 | Err(_) => Err(ParseError::new("error while lexing input string")), |
| 616 | } |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 617 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 618 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 619 | // FIXME the name parse_file makes it sound like you might pass in a path to a |
| 620 | // file, rather than the content. |
| 621 | /// Parse the content of a file of Rust code. |
| 622 | /// |
| 623 | /// This is different from `syn::parse_str::<File>(content)` in two ways: |
| 624 | /// |
| 625 | /// - It discards a leading byte order mark `\u{FEFF}` if the file has one. |
| 626 | /// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. |
| 627 | /// |
| 628 | /// If present, either of these would be an error using `from_str`. |
| 629 | /// |
| 630 | /// # Examples |
| 631 | /// |
| 632 | /// ```rust,no_run |
| 633 | /// extern crate syn; |
| 634 | /// # |
David Tolnay | 9174b97 | 2017-11-09 22:27:50 -0800 | [diff] [blame] | 635 | /// # |
| 636 | /// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 637 | /// |
| 638 | /// use std::fs::File; |
| 639 | /// use std::io::Read; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 640 | /// |
| 641 | /// fn run() -> Result<()> { |
| 642 | /// let mut file = File::open("path/to/code.rs")?; |
| 643 | /// let mut content = String::new(); |
| 644 | /// file.read_to_string(&mut content)?; |
| 645 | /// |
| 646 | /// let ast = syn::parse_file(&content)?; |
| 647 | /// if let Some(shebang) = ast.shebang { |
| 648 | /// println!("{}", shebang); |
| 649 | /// } |
| 650 | /// println!("{} items", ast.items.len()); |
| 651 | /// |
| 652 | /// Ok(()) |
| 653 | /// } |
| 654 | /// # |
| 655 | /// # fn main() { run().unwrap() } |
| 656 | /// ``` |
| 657 | #[cfg(all(feature = "parsing", feature = "full"))] |
| 658 | pub fn parse_file(mut content: &str) -> Result<File, ParseError> { |
| 659 | // Strip the BOM if it is present |
| 660 | const BOM: &'static str = "\u{feff}"; |
| 661 | if content.starts_with(BOM) { |
| 662 | content = &content[BOM.len()..]; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 663 | } |
Michael Layzell | 5e107ff | 2017-01-24 19:58:39 -0500 | [diff] [blame] | 664 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 665 | let mut shebang = None; |
| 666 | if content.starts_with("#!") && !content.starts_with("#![") { |
| 667 | if let Some(idx) = content.find('\n') { |
| 668 | shebang = Some(content[..idx].to_string()); |
| 669 | content = &content[idx..]; |
| 670 | } else { |
| 671 | shebang = Some(content.to_string()); |
| 672 | content = ""; |
| 673 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 674 | } |
David Tolnay | 0a8972b | 2017-02-27 02:10:01 -0800 | [diff] [blame] | 675 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 676 | let mut file: File = parse_str(content)?; |
| 677 | file.shebang = shebang; |
| 678 | Ok(file) |
Michael Layzell | 5e107ff | 2017-01-24 19:58:39 -0500 | [diff] [blame] | 679 | } |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 680 | |
David Tolnay | dace3f1 | 2018-01-06 21:33:29 -0800 | [diff] [blame^] | 681 | /// Quasi-quotation macro that accepts input like the [`quote!`] macro but uses |
| 682 | /// type inference to figure out a return type for those tokens. |
| 683 | /// |
| 684 | /// [`quote!`]: https://docs.rs/quote/0.4/quote/index.html |
| 685 | /// |
| 686 | /// The return type can be any syntax tree node that implements the [`Synom`] |
| 687 | /// trait. |
| 688 | /// |
| 689 | /// [`Synom`]: synom/trait.Synom.html |
| 690 | /// |
| 691 | /// ``` |
| 692 | /// #[macro_use] |
| 693 | /// extern crate syn; |
| 694 | /// |
| 695 | /// #[macro_use] |
| 696 | /// extern crate quote; |
| 697 | /// |
| 698 | /// use syn::Stmt; |
| 699 | /// |
| 700 | /// fn main() { |
| 701 | /// let name = quote!(v); |
| 702 | /// let ty = quote!(u8); |
| 703 | /// |
| 704 | /// let stmt: Stmt = parse_quote! { |
| 705 | /// let #name: #ty = Default::default(); |
| 706 | /// }; |
| 707 | /// |
| 708 | /// println!("{:#?}", stmt); |
| 709 | /// } |
| 710 | /// ``` |
| 711 | /// |
| 712 | /// # Example |
| 713 | /// |
| 714 | /// The following helper function adds a bound `T: HeapSize` to every type |
| 715 | /// parameter `T` in the input generics. |
| 716 | /// |
| 717 | /// ``` |
| 718 | /// # #[macro_use] |
| 719 | /// # extern crate syn; |
| 720 | /// # |
| 721 | /// # #[macro_use] |
| 722 | /// # extern crate quote; |
| 723 | /// # |
| 724 | /// # use syn::{Generics, GenericParam}; |
| 725 | /// # |
| 726 | /// // Add a bound `T: HeapSize` to every type parameter T. |
| 727 | /// fn add_trait_bounds(mut generics: Generics) -> Generics { |
| 728 | /// for param in &mut generics.params { |
| 729 | /// if let GenericParam::Type(ref mut type_param) = *param { |
| 730 | /// type_param.bounds.push(parse_quote!(HeapSize)); |
| 731 | /// } |
| 732 | /// } |
| 733 | /// generics |
| 734 | /// } |
| 735 | /// # |
| 736 | /// # fn main() {} |
| 737 | /// ``` |
| 738 | /// |
| 739 | /// # Panics |
| 740 | /// |
| 741 | /// Panics if the tokens fail to parse as the expected syntax tree type. The |
| 742 | /// caller is responsible for ensuring that the input tokens are syntactically |
| 743 | /// valid. |
David Tolnay | 01cc020 | 2018-01-02 11:13:07 -0800 | [diff] [blame] | 744 | #[cfg(all(feature = "parsing", feature = "printing"))] |
| 745 | #[macro_export] |
| 746 | macro_rules! parse_quote { |
| 747 | ($($tt:tt)*) => { |
| 748 | ::std::result::Result::unwrap( |
David Tolnay | dace3f1 | 2018-01-06 21:33:29 -0800 | [diff] [blame^] | 749 | $crate::parse2( |
David Tolnay | 01cc020 | 2018-01-02 11:13:07 -0800 | [diff] [blame] | 750 | ::std::convert::Into::into( |
| 751 | quote!($($tt)*)))) |
| 752 | }; |
| 753 | } |
| 754 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 755 | #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 756 | struct TokensOrDefault<'a, T: 'a>(&'a Option<T>); |
| 757 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 758 | #[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 759 | impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 760 | where |
| 761 | T: quote::ToTokens + Default, |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 762 | { |
| 763 | fn to_tokens(&self, tokens: &mut quote::Tokens) { |
| 764 | match *self.0 { |
| 765 | Some(ref t) => t.to_tokens(tokens), |
| 766 | None => T::default().to_tokens(tokens), |
| 767 | } |
| 768 | } |
| 769 | } |