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] |
David Tolnay | 87003d0 | 2018-05-20 19:45:13 -0700 | [diff] [blame] | 71 | //! syn = "0.14" |
| 72 | //! quote = "0.6" |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 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, |
David Tolnay | efff2ff | 2018-01-07 11:49:52 -0800 | [diff] [blame] | 181 | //! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread` |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 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 | //! |
David Tolnay | 324db2d | 2018-01-07 11:51:09 -0800 | [diff] [blame] | 223 | //! [`cargo expand`]: https://github.com/dtolnay/cargo-expand |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 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. |
hcpl | 4b72a38 | 2018-04-04 14:50:24 +0300 | [diff] [blame] | 257 | //! - **`proc-macro`** *(enabled by default)* — Runtime dependency on the |
| 258 | //! dynamic library libproc_macro from rustc toolchain. |
David Tolnay | 5e84e97 | 2018-01-05 17:51:06 -0800 | [diff] [blame] | 259 | |
David Tolnay | 4cf7db8 | 2018-01-07 15:22:01 -0800 | [diff] [blame] | 260 | // Syn types in rustdoc of other crates get linked to here. |
David Tolnay | e6ec9e0 | 2018-08-21 21:32:03 -0400 | [diff] [blame] | 261 | #![doc(html_root_url = "https://docs.rs/syn/0.14.9")] |
David Tolnay | 34071ba | 2018-05-20 20:00:41 -0700 | [diff] [blame] | 262 | #![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] |
David Tolnay | 34071ba | 2018-05-20 20:00:41 -0700 | [diff] [blame] | 263 | // Ignored clippy lints. |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 264 | #![cfg_attr( |
| 265 | feature = "cargo-clippy", |
| 266 | allow( |
David Tolnay | 0cec3e6 | 2018-07-21 09:08:30 -0700 | [diff] [blame] | 267 | const_static_lifetime, |
| 268 | doc_markdown, |
| 269 | large_enum_variant, |
| 270 | match_bool, |
| 271 | redundant_closure, |
| 272 | needless_pass_by_value, |
| 273 | redundant_field_names, |
| 274 | trivially_copy_pass_by_ref |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 275 | ) |
| 276 | )] |
David Tolnay | 34071ba | 2018-05-20 20:00:41 -0700 | [diff] [blame] | 277 | // Ignored clippy_pedantic lints. |
| 278 | #![cfg_attr( |
| 279 | feature = "cargo-clippy", |
| 280 | allow( |
David Tolnay | 0cec3e6 | 2018-07-21 09:08:30 -0700 | [diff] [blame] | 281 | cast_possible_truncation, |
| 282 | cast_possible_wrap, |
| 283 | if_not_else, |
| 284 | indexing_slicing, |
| 285 | items_after_statements, |
David Tolnay | 151f92f | 2018-08-14 22:44:53 -0700 | [diff] [blame] | 286 | shadow_unrelated, |
David Tolnay | 0cec3e6 | 2018-07-21 09:08:30 -0700 | [diff] [blame] | 287 | similar_names, |
| 288 | single_match_else, |
| 289 | stutter, |
| 290 | unseparated_literal_suffix, |
| 291 | use_self, |
| 292 | used_underscore_binding |
David Tolnay | 34071ba | 2018-05-20 20:00:41 -0700 | [diff] [blame] | 293 | ) |
| 294 | )] |
David Tolnay | ad2836d | 2017-04-20 10:11:43 -0700 | [diff] [blame] | 295 | |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 296 | #[cfg(all( |
| 297 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 298 | feature = "proc-macro" |
| 299 | ))] |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 300 | extern crate proc_macro; |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 301 | extern crate proc_macro2; |
David Tolnay | 570695e | 2017-06-03 16:15:13 -0700 | [diff] [blame] | 302 | extern crate unicode_xid; |
Alex Crichton | ccbb45d | 2017-05-23 10:58:24 -0700 | [diff] [blame] | 303 | |
David Tolnay | 1cf8091 | 2017-12-31 18:35:12 -0500 | [diff] [blame] | 304 | #[cfg(feature = "printing")] |
David Tolnay | 87d0b44 | 2016-09-04 11:52:12 -0700 | [diff] [blame] | 305 | extern crate quote; |
| 306 | |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 307 | #[cfg(feature = "parsing")] |
David Tolnay | f8db7ba | 2017-11-11 22:52:16 -0800 | [diff] [blame] | 308 | #[macro_use] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 309 | #[doc(hidden)] |
| 310 | pub mod parsers; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 311 | |
Alex Crichton | 62a0a59 | 2017-05-22 13:58:53 -0700 | [diff] [blame] | 312 | #[macro_use] |
| 313 | mod macros; |
| 314 | |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 315 | #[macro_use] |
David Tolnay | 32954ef | 2017-12-26 22:43:16 -0500 | [diff] [blame] | 316 | pub mod token; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 317 | |
David Tolnay | e303b7c | 2018-05-20 16:46:35 -0700 | [diff] [blame] | 318 | pub use proc_macro2::Ident; |
| 319 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 320 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 321 | mod attr; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 322 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | aaadd78 | 2018-01-06 22:58:13 -0800 | [diff] [blame] | 323 | pub use attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue, NestedMeta}; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 324 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 325 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 326 | mod data; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 327 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 328 | pub use data::{ |
| 329 | Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, VisRestricted, |
| 330 | Visibility, |
| 331 | }; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 332 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 333 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 334 | mod expr; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 335 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 336 | pub use expr::{ |
David Tolnay | 02a9c6f | 2018-08-24 18:58:45 -0400 | [diff] [blame] | 337 | Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprBinary, ExprBlock, ExprBox, |
| 338 | ExprBreak, ExprCall, ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprGroup, |
| 339 | ExprIf, ExprIfLet, ExprInPlace, ExprIndex, ExprLit, ExprLoop, ExprMacro, ExprMatch, |
| 340 | ExprMethodCall, ExprParen, ExprPath, ExprRange, ExprReference, ExprRepeat, ExprReturn, |
| 341 | ExprStruct, ExprTry, ExprTryBlock, ExprTuple, ExprType, ExprUnary, ExprUnsafe, ExprVerbatim, |
| 342 | ExprWhile, ExprWhileLet, ExprYield, Index, Member, |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 343 | }; |
Michael Layzell | 734adb4 | 2017-06-07 16:58:31 -0400 | [diff] [blame] | 344 | |
| 345 | #[cfg(feature = "full")] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 346 | pub use expr::{ |
| 347 | Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, MethodTurbofish, Pat, |
| 348 | PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, PatRef, PatSlice, PatStruct, PatTuple, |
| 349 | PatTupleStruct, PatVerbatim, PatWild, RangeLimits, Stmt, |
| 350 | }; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 351 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 352 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 353 | mod generics; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 354 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 355 | pub use generics::{ |
| 356 | BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq, |
| 357 | PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, |
| 358 | WhereClause, WherePredicate, |
| 359 | }; |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 360 | #[cfg(all( |
| 361 | any(feature = "full", feature = "derive"), |
| 362 | feature = "printing" |
| 363 | ))] |
David Tolnay | fd6bf5c | 2017-11-12 09:41:14 -0800 | [diff] [blame] | 364 | pub use generics::{ImplGenerics, Turbofish, TypeGenerics}; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 365 | |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 366 | #[cfg(feature = "full")] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 367 | mod item; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 368 | #[cfg(feature = "full")] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 369 | pub use item::{ |
David Tolnay | 435c178 | 2018-08-24 16:15:44 -0400 | [diff] [blame] | 370 | ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, ForeignItemMacro, |
| 371 | ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst, |
David Tolnay | bb82ef0 | 2018-08-24 20:15:45 -0400 | [diff] [blame^] | 372 | ImplItemExistential, ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item, |
| 373 | ItemConst, ItemEnum, ItemExistential, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, |
| 374 | ItemMacro, ItemMacro2, ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemType, ItemUnion, |
| 375 | ItemUse, ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemExistential, |
| 376 | TraitItemMacro, TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName, |
| 377 | UsePath, UseRename, UseTree, |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 378 | }; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 379 | |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 380 | #[cfg(feature = "full")] |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 381 | mod file; |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 382 | #[cfg(feature = "full")] |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 383 | pub use file::File; |
David Tolnay | 631cb8c | 2016-11-10 17:16:41 -0800 | [diff] [blame] | 384 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 385 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 63e3dee | 2017-06-03 20:13:17 -0700 | [diff] [blame] | 386 | mod lifetime; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 387 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 63e3dee | 2017-06-03 20:13:17 -0700 | [diff] [blame] | 388 | pub use lifetime::Lifetime; |
| 389 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 390 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 391 | mod lit; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 392 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 393 | pub use lit::{ |
| 394 | FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr, |
| 395 | LitVerbatim, StrStyle, |
| 396 | }; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 397 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 398 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 399 | mod mac; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 400 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | ab91951 | 2017-12-30 23:31:51 -0500 | [diff] [blame] | 401 | pub use mac::{Macro, MacroDelimiter}; |
David Tolnay | f4bbbd9 | 2016-09-23 14:41:55 -0700 | [diff] [blame] | 402 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 403 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 0e83740 | 2016-12-22 17:25:55 -0500 | [diff] [blame] | 404 | mod derive; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 405 | #[cfg(feature = "derive")] |
David Tolnay | e3d41b7 | 2017-12-31 15:24:00 -0500 | [diff] [blame] | 406 | pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; |
David Tolnay | f38cdf6 | 2016-09-23 19:07:09 -0700 | [diff] [blame] | 407 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 408 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 3cb23a9 | 2016-10-07 23:02:21 -0700 | [diff] [blame] | 409 | mod op; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 410 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | 3cb23a9 | 2016-10-07 23:02:21 -0700 | [diff] [blame] | 411 | pub use op::{BinOp, UnOp}; |
| 412 | |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 413 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b79ee96 | 2016-09-04 09:39:20 -0700 | [diff] [blame] | 414 | mod ty; |
David Tolnay | 3cfd1d3 | 2018-01-03 00:22:08 -0800 | [diff] [blame] | 415 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 416 | pub use ty::{ |
| 417 | Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, |
| 418 | TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, TypeReference, |
| 419 | TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim, |
| 420 | }; |
David Tolnay | 056de30 | 2018-01-05 14:29:05 -0800 | [diff] [blame] | 421 | |
| 422 | #[cfg(any(feature = "full", feature = "derive"))] |
| 423 | mod path; |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 424 | #[cfg(all( |
| 425 | any(feature = "full", feature = "derive"), |
| 426 | feature = "printing" |
| 427 | ))] |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 428 | pub use path::PathTokens; |
David Tolnay | 056de30 | 2018-01-05 14:29:05 -0800 | [diff] [blame] | 429 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | b57c849 | 2018-05-05 00:32:04 -0700 | [diff] [blame] | 430 | pub use path::{ |
| 431 | AngleBracketedGenericArguments, Binding, GenericArgument, ParenthesizedGenericArguments, Path, |
| 432 | PathArguments, PathSegment, QSelf, |
| 433 | }; |
Alex Crichton | ccbb45d | 2017-05-23 10:58:24 -0700 | [diff] [blame] | 434 | |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 435 | #[cfg(feature = "parsing")] |
David Tolnay | dfc886b | 2018-01-06 08:03:09 -0800 | [diff] [blame] | 436 | pub mod buffer; |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 437 | pub mod punctuated; |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 438 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 439 | pub mod synom; |
David Tolnay | cc54371 | 2018-01-08 11:29:54 -0800 | [diff] [blame] | 440 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | e082403 | 2017-12-27 15:25:56 -0500 | [diff] [blame] | 441 | mod tt; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 442 | |
David Tolnay | e83ef5a | 2018-01-11 15:18:36 -0800 | [diff] [blame] | 443 | // Not public API except the `parse_quote!` macro. |
David Tolnay | 491680a | 2018-01-23 00:34:40 -0800 | [diff] [blame] | 444 | #[cfg(feature = "parsing")] |
David Tolnay | e83ef5a | 2018-01-11 15:18:36 -0800 | [diff] [blame] | 445 | #[doc(hidden)] |
| 446 | pub mod parse_quote; |
| 447 | |
David Tolnay | 4d942b4 | 2018-01-02 22:14:04 -0800 | [diff] [blame] | 448 | #[cfg(all(feature = "parsing", feature = "printing"))] |
David Tolnay | f790b61 | 2017-12-31 18:46:57 -0500 | [diff] [blame] | 449 | pub mod spanned; |
| 450 | |
David Tolnay | dc3d624 | 2018-08-01 00:30:47 -0700 | [diff] [blame] | 451 | #[cfg(all(feature = "parsing", feature = "full"))] |
David Tolnay | 9be3258 | 2018-07-31 22:37:26 -0700 | [diff] [blame] | 452 | mod verbatim; |
| 453 | |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 454 | mod gen { |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 455 | /// Syntax tree traversal to walk a shared borrow of a syntax tree. |
| 456 | /// |
| 457 | /// Each method of the [`Visit`] trait is a hook that can be overridden to |
| 458 | /// customize the behavior when visiting the corresponding type of node. By |
| 459 | /// default, every method recursively visits the substructure of the input |
| 460 | /// by invoking the right visitor method of each of its fields. |
| 461 | /// |
| 462 | /// [`Visit`]: trait.Visit.html |
| 463 | /// |
| 464 | /// ```rust |
| 465 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 466 | /// # |
| 467 | /// pub trait Visit<'ast> { |
| 468 | /// /* ... */ |
| 469 | /// |
| 470 | /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { |
| 471 | /// for attr in &node.attrs { |
| 472 | /// self.visit_attribute(attr); |
| 473 | /// } |
| 474 | /// self.visit_expr(&*node.left); |
| 475 | /// self.visit_bin_op(&node.op); |
| 476 | /// self.visit_expr(&*node.right); |
| 477 | /// } |
| 478 | /// |
| 479 | /// /* ... */ |
| 480 | /// # fn visit_attribute(&mut self, node: &'ast Attribute); |
| 481 | /// # fn visit_expr(&mut self, node: &'ast Expr); |
| 482 | /// # fn visit_bin_op(&mut self, node: &'ast BinOp); |
| 483 | /// } |
| 484 | /// ``` |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 485 | /// |
| 486 | /// *This module is available if Syn is built with the `"visit"` feature.* |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 487 | #[cfg(feature = "visit")] |
| 488 | pub mod visit; |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 489 | |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 490 | /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in |
| 491 | /// place. |
| 492 | /// |
| 493 | /// Each method of the [`VisitMut`] trait is a hook that can be overridden |
| 494 | /// to customize the behavior when mutating the corresponding type of node. |
| 495 | /// By default, every method recursively visits the substructure of the |
| 496 | /// input by invoking the right visitor method of each of its fields. |
| 497 | /// |
| 498 | /// [`VisitMut`]: trait.VisitMut.html |
| 499 | /// |
| 500 | /// ```rust |
| 501 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 502 | /// # |
| 503 | /// pub trait VisitMut { |
| 504 | /// /* ... */ |
| 505 | /// |
| 506 | /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { |
| 507 | /// for attr in &mut node.attrs { |
| 508 | /// self.visit_attribute_mut(attr); |
| 509 | /// } |
| 510 | /// self.visit_expr_mut(&mut *node.left); |
| 511 | /// self.visit_bin_op_mut(&mut node.op); |
| 512 | /// self.visit_expr_mut(&mut *node.right); |
| 513 | /// } |
| 514 | /// |
| 515 | /// /* ... */ |
| 516 | /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); |
| 517 | /// # fn visit_expr_mut(&mut self, node: &mut Expr); |
| 518 | /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); |
| 519 | /// } |
| 520 | /// ``` |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 521 | /// |
| 522 | /// *This module is available if Syn is built with the `"visit-mut"` |
| 523 | /// feature.* |
David Tolnay | 9df02c4 | 2018-01-06 13:52:48 -0800 | [diff] [blame] | 524 | #[cfg(feature = "visit-mut")] |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 525 | pub mod visit_mut; |
Nika Layzell | 2772666 | 2017-10-24 23:16:35 -0400 | [diff] [blame] | 526 | |
David Tolnay | ded2d68 | 2018-01-06 18:53:53 -0800 | [diff] [blame] | 527 | /// Syntax tree traversal to transform the nodes of an owned syntax tree. |
| 528 | /// |
| 529 | /// Each method of the [`Fold`] trait is a hook that can be overridden to |
| 530 | /// customize the behavior when transforming the corresponding type of node. |
| 531 | /// By default, every method recursively visits the substructure of the |
| 532 | /// input by invoking the right visitor method of each of its fields. |
| 533 | /// |
| 534 | /// [`Fold`]: trait.Fold.html |
| 535 | /// |
| 536 | /// ```rust |
| 537 | /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; |
| 538 | /// # |
| 539 | /// pub trait Fold { |
| 540 | /// /* ... */ |
| 541 | /// |
| 542 | /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { |
| 543 | /// ExprBinary { |
| 544 | /// attrs: node.attrs |
| 545 | /// .into_iter() |
| 546 | /// .map(|attr| self.fold_attribute(attr)) |
| 547 | /// .collect(), |
| 548 | /// left: Box::new(self.fold_expr(*node.left)), |
| 549 | /// op: self.fold_bin_op(node.op), |
| 550 | /// right: Box::new(self.fold_expr(*node.right)), |
| 551 | /// } |
| 552 | /// } |
| 553 | /// |
| 554 | /// /* ... */ |
| 555 | /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; |
| 556 | /// # fn fold_expr(&mut self, node: Expr) -> Expr; |
| 557 | /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; |
| 558 | /// } |
| 559 | /// ``` |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 560 | /// |
| 561 | /// *This module is available if Syn is built with the `"fold"` feature.* |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 562 | #[cfg(feature = "fold")] |
| 563 | pub mod fold; |
David Tolnay | f60f426 | 2017-12-28 19:17:58 -0500 | [diff] [blame] | 564 | |
David Tolnay | 0a0d78c | 2018-01-05 15:24:01 -0800 | [diff] [blame] | 565 | #[cfg(any(feature = "full", feature = "derive"))] |
David Tolnay | f60f426 | 2017-12-28 19:17:58 -0500 | [diff] [blame] | 566 | #[path = "../gen_helper.rs"] |
| 567 | mod helper; |
Nika Layzell | a6f46c4 | 2017-10-26 15:26:16 -0400 | [diff] [blame] | 568 | } |
| 569 | pub use gen::*; |
gnzlbg | 9ae88d8 | 2017-01-26 20:45:17 +0100 | [diff] [blame] | 570 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 571 | //////////////////////////////////////////////////////////////////////////////// |
| 572 | |
David Tolnay | 5533772 | 2016-09-11 12:58:56 -0700 | [diff] [blame] | 573 | #[cfg(feature = "parsing")] |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 574 | use synom::{Parser, Synom}; |
Ted Driggs | 054abbb | 2017-05-01 12:20:52 -0700 | [diff] [blame] | 575 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 576 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 577 | mod error; |
| 578 | #[cfg(feature = "parsing")] |
David Tolnay | 203557a | 2017-12-27 23:59:33 -0500 | [diff] [blame] | 579 | use error::ParseError; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 580 | |
| 581 | // Not public API. |
David Tolnay | 1b752fb | 2017-12-26 21:41:39 -0500 | [diff] [blame] | 582 | #[cfg(feature = "parsing")] |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 583 | #[doc(hidden)] |
| 584 | pub use error::parse_error; |
Michael Layzell | 416724e | 2017-05-24 21:12:34 -0400 | [diff] [blame] | 585 | |
David Tolnay | ccab0be | 2018-01-06 22:24:47 -0800 | [diff] [blame] | 586 | /// Parse tokens of source code into the chosen syntax tree node. |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 587 | /// |
| 588 | /// This is preferred over parsing a string because tokens are able to preserve |
| 589 | /// information about where in the user's code they were originally written (the |
| 590 | /// "span" of the token), possibly allowing the compiler to produce better error |
| 591 | /// messages. |
| 592 | /// |
David Tolnay | ccab0be | 2018-01-06 22:24:47 -0800 | [diff] [blame] | 593 | /// This function parses a `proc_macro::TokenStream` which is the type used for |
| 594 | /// interop with the compiler in a procedural macro. To parse a |
| 595 | /// `proc_macro2::TokenStream`, use [`syn::parse2`] instead. |
| 596 | /// |
| 597 | /// [`syn::parse2`]: fn.parse2.html |
| 598 | /// |
hcpl | 4b72a38 | 2018-04-04 14:50:24 +0300 | [diff] [blame] | 599 | /// *This function is available if Syn is built with both the `"parsing"` and |
| 600 | /// `"proc-macro"` features.* |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 601 | /// |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 602 | /// # Examples |
| 603 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 604 | /// ```rust |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 605 | /// extern crate proc_macro; |
| 606 | /// use proc_macro::TokenStream; |
| 607 | /// |
| 608 | /// extern crate syn; |
| 609 | /// |
| 610 | /// #[macro_use] |
| 611 | /// extern crate quote; |
| 612 | /// |
| 613 | /// use syn::DeriveInput; |
| 614 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 615 | /// # const IGNORE_TOKENS: &str = stringify! { |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 616 | /// #[proc_macro_derive(MyMacro)] |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 617 | /// # }; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 618 | /// pub fn my_macro(input: TokenStream) -> TokenStream { |
| 619 | /// // Parse the tokens into a syntax tree |
| 620 | /// let ast: DeriveInput = syn::parse(input).unwrap(); |
| 621 | /// |
| 622 | /// // Build the output, possibly using quasi-quotation |
| 623 | /// let expanded = quote! { |
| 624 | /// /* ... */ |
| 625 | /// }; |
| 626 | /// |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 627 | /// // Convert into a token stream and return it |
| 628 | /// expanded.into() |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 629 | /// } |
David Tolnay | bcf2602 | 2017-12-25 22:10:52 -0500 | [diff] [blame] | 630 | /// # |
| 631 | /// # fn main() {} |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 632 | /// ``` |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 633 | #[cfg(all( |
| 634 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 635 | feature = "parsing", |
| 636 | feature = "proc-macro" |
| 637 | ))] |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 638 | pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 639 | where |
| 640 | T: Synom, |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 641 | { |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 642 | parse2(tokens.into()) |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 643 | } |
| 644 | |
David Tolnay | ccab0be | 2018-01-06 22:24:47 -0800 | [diff] [blame] | 645 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
| 646 | /// |
| 647 | /// This function parses a `proc_macro2::TokenStream` which is commonly useful |
| 648 | /// when the input comes from a node of the Syn syntax tree, for example the tts |
| 649 | /// of a [`Macro`] node. When in a procedural macro parsing the |
| 650 | /// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`] |
| 651 | /// instead. |
| 652 | /// |
| 653 | /// [`Macro`]: struct.Macro.html |
| 654 | /// [`syn::parse`]: fn.parse.html |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 655 | /// |
| 656 | /// *This function is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 657 | #[cfg(feature = "parsing")] |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 658 | pub fn parse2<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 659 | where |
| 660 | T: Synom, |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 661 | { |
David Tolnay | ca7cd97 | 2018-01-11 14:23:06 -0800 | [diff] [blame] | 662 | let parser = T::parse; |
David Tolnay | 94d2b79 | 2018-04-29 12:26:10 -0700 | [diff] [blame] | 663 | parser.parse2(tokens).map_err(|err| match T::description() { |
| 664 | Some(s) => ParseError::new(format!("failed to parse {}: {}", s, err)), |
| 665 | None => err, |
David Tolnay | ca7cd97 | 2018-01-11 14:23:06 -0800 | [diff] [blame] | 666 | }) |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 667 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 668 | |
David Tolnay | ccab0be | 2018-01-06 22:24:47 -0800 | [diff] [blame] | 669 | /// Parse a string of Rust code into the chosen syntax tree node. |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 670 | /// |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 671 | /// *This function is available if Syn is built with the `"parsing"` feature.* |
| 672 | /// |
David Tolnay | 3f5b06f | 2018-01-11 21:02:00 -0800 | [diff] [blame] | 673 | /// # Hygiene |
| 674 | /// |
| 675 | /// Every span in the resulting syntax tree will be set to resolve at the macro |
| 676 | /// call site. |
| 677 | /// |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 678 | /// # Examples |
| 679 | /// |
| 680 | /// ```rust |
| 681 | /// extern crate syn; |
| 682 | /// # |
David Tolnay | 9174b97 | 2017-11-09 22:27:50 -0800 | [diff] [blame] | 683 | /// # |
| 684 | /// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 685 | /// |
| 686 | /// use syn::Expr; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 687 | /// |
| 688 | /// fn run() -> Result<()> { |
| 689 | /// let code = "assert_eq!(u8::max_value(), 255)"; |
| 690 | /// let expr = syn::parse_str::<Expr>(code)?; |
| 691 | /// println!("{:#?}", expr); |
| 692 | /// Ok(()) |
| 693 | /// } |
| 694 | /// # |
| 695 | /// # fn main() { run().unwrap() } |
| 696 | /// ``` |
| 697 | #[cfg(feature = "parsing")] |
| 698 | pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> { |
David Tolnay | ffb1f4d | 2017-12-28 00:07:59 -0500 | [diff] [blame] | 699 | match s.parse() { |
David Tolnay | 04c5dca | 2018-01-05 20:12:21 -0800 | [diff] [blame] | 700 | Ok(tts) => parse2(tts), |
David Tolnay | ffb1f4d | 2017-12-28 00:07:59 -0500 | [diff] [blame] | 701 | Err(_) => Err(ParseError::new("error while lexing input string")), |
| 702 | } |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 703 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 704 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 705 | // FIXME the name parse_file makes it sound like you might pass in a path to a |
| 706 | // file, rather than the content. |
| 707 | /// Parse the content of a file of Rust code. |
| 708 | /// |
| 709 | /// This is different from `syn::parse_str::<File>(content)` in two ways: |
| 710 | /// |
| 711 | /// - It discards a leading byte order mark `\u{FEFF}` if the file has one. |
| 712 | /// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. |
| 713 | /// |
| 714 | /// If present, either of these would be an error using `from_str`. |
| 715 | /// |
Christopher Serr | 9727ef2 | 2018-02-03 16:42:12 +0100 | [diff] [blame] | 716 | /// *This function is available if Syn is built with the `"parsing"` and `"full"` features.* |
David Tolnay | 461d98e | 2018-01-07 11:07:19 -0800 | [diff] [blame] | 717 | /// |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 718 | /// # Examples |
| 719 | /// |
| 720 | /// ```rust,no_run |
| 721 | /// extern crate syn; |
| 722 | /// # |
David Tolnay | 9174b97 | 2017-11-09 22:27:50 -0800 | [diff] [blame] | 723 | /// # |
| 724 | /// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 725 | /// |
| 726 | /// use std::fs::File; |
| 727 | /// use std::io::Read; |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 728 | /// |
| 729 | /// fn run() -> Result<()> { |
| 730 | /// let mut file = File::open("path/to/code.rs")?; |
| 731 | /// let mut content = String::new(); |
| 732 | /// file.read_to_string(&mut content)?; |
| 733 | /// |
| 734 | /// let ast = syn::parse_file(&content)?; |
| 735 | /// if let Some(shebang) = ast.shebang { |
| 736 | /// println!("{}", shebang); |
| 737 | /// } |
| 738 | /// println!("{} items", ast.items.len()); |
| 739 | /// |
| 740 | /// Ok(()) |
| 741 | /// } |
| 742 | /// # |
| 743 | /// # fn main() { run().unwrap() } |
| 744 | /// ``` |
| 745 | #[cfg(all(feature = "parsing", feature = "full"))] |
| 746 | pub fn parse_file(mut content: &str) -> Result<File, ParseError> { |
| 747 | // Strip the BOM if it is present |
| 748 | const BOM: &'static str = "\u{feff}"; |
| 749 | if content.starts_with(BOM) { |
| 750 | content = &content[BOM.len()..]; |
David Tolnay | 35161ff | 2016-09-03 11:33:15 -0700 | [diff] [blame] | 751 | } |
Michael Layzell | 5e107ff | 2017-01-24 19:58:39 -0500 | [diff] [blame] | 752 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 753 | let mut shebang = None; |
| 754 | if content.starts_with("#!") && !content.starts_with("#![") { |
| 755 | if let Some(idx) = content.find('\n') { |
| 756 | shebang = Some(content[..idx].to_string()); |
| 757 | content = &content[idx..]; |
| 758 | } else { |
| 759 | shebang = Some(content.to_string()); |
| 760 | content = ""; |
| 761 | } |
Alex Crichton | 954046c | 2017-05-30 21:49:42 -0700 | [diff] [blame] | 762 | } |
David Tolnay | 0a8972b | 2017-02-27 02:10:01 -0800 | [diff] [blame] | 763 | |
David Tolnay | c7a5d3d | 2017-06-04 12:11:05 -0700 | [diff] [blame] | 764 | let mut file: File = parse_str(content)?; |
| 765 | file.shebang = shebang; |
| 766 | Ok(file) |
Michael Layzell | 5e107ff | 2017-01-24 19:58:39 -0500 | [diff] [blame] | 767 | } |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 768 | |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 769 | #[cfg(all( |
| 770 | any(feature = "full", feature = "derive"), |
| 771 | feature = "printing" |
| 772 | ))] |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 773 | struct TokensOrDefault<'a, T: 'a>(&'a Option<T>); |
| 774 | |
David Tolnay | 278f9e3 | 2018-08-14 22:41:11 -0700 | [diff] [blame] | 775 | #[cfg(all( |
| 776 | any(feature = "full", feature = "derive"), |
| 777 | feature = "printing" |
| 778 | ))] |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 779 | impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T> |
David Tolnay | 5138205 | 2017-12-27 13:46:21 -0500 | [diff] [blame] | 780 | where |
| 781 | T: quote::ToTokens + Default, |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 782 | { |
Alex Crichton | a74a1c8 | 2018-05-16 10:20:44 -0700 | [diff] [blame] | 783 | fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { |
Alex Crichton | 259ee53 | 2017-07-14 06:51:02 -0700 | [diff] [blame] | 784 | match *self.0 { |
| 785 | Some(ref t) => t.to_tokens(tokens), |
| 786 | None => T::default().to_tokens(tokens), |
| 787 | } |
| 788 | } |
| 789 | } |