David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1 | //! Parsing interface for parsing a token stream into a syntax tree node. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 2 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 3 | //! Parsing in Syn is built on parser functions that take in a [`ParseStream`] |
| 4 | //! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying |
| 5 | //! these parser functions is a lower level mechanism built around the |
| 6 | //! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of |
| 7 | //! tokens in a token stream. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 8 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 9 | //! [`ParseStream`]: type.ParseStream.html |
| 10 | //! [`Result<T>`]: type.Result.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 11 | //! [`Cursor`]: ../buffer/index.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 12 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 13 | //! # Example |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 14 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 15 | //! Here is a snippet of parsing code to get a feel for the style of the |
| 16 | //! library. We define data structures for a subset of Rust syntax including |
| 17 | //! enums (not shown) and structs, then provide implementations of the [`Parse`] |
| 18 | //! trait to parse these syntax tree data structures from a token stream. |
| 19 | //! |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 20 | //! Once `Parse` impls have been defined, they can be called conveniently from a |
David Tolnay | 8e6096a | 2018-09-06 02:14:47 -0700 | [diff] [blame] | 21 | //! procedural macro through [`parse_macro_input!`] as shown at the bottom of |
| 22 | //! the snippet. If the caller provides syntactically invalid input to the |
| 23 | //! procedural macro, they will receive a helpful compiler error message |
| 24 | //! pointing out the exact token that triggered the failure to parse. |
| 25 | //! |
| 26 | //! [`parse_macro_input!`]: ../macro.parse_macro_input.html |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 27 | //! |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 28 | //! ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 29 | //! extern crate proc_macro; |
| 30 | //! |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 31 | //! use proc_macro::TokenStream; |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 32 | //! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 33 | //! use syn::parse::{Parse, ParseStream}; |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 34 | //! use syn::punctuated::Punctuated; |
| 35 | //! |
| 36 | //! enum Item { |
| 37 | //! Struct(ItemStruct), |
| 38 | //! Enum(ItemEnum), |
| 39 | //! } |
| 40 | //! |
| 41 | //! struct ItemStruct { |
| 42 | //! struct_token: Token![struct], |
| 43 | //! ident: Ident, |
| 44 | //! brace_token: token::Brace, |
| 45 | //! fields: Punctuated<Field, Token![,]>, |
| 46 | //! } |
| 47 | //! # |
| 48 | //! # enum ItemEnum {} |
| 49 | //! |
| 50 | //! impl Parse for Item { |
| 51 | //! fn parse(input: ParseStream) -> Result<Self> { |
| 52 | //! let lookahead = input.lookahead1(); |
| 53 | //! if lookahead.peek(Token![struct]) { |
| 54 | //! input.parse().map(Item::Struct) |
| 55 | //! } else if lookahead.peek(Token![enum]) { |
| 56 | //! input.parse().map(Item::Enum) |
| 57 | //! } else { |
| 58 | //! Err(lookahead.error()) |
| 59 | //! } |
| 60 | //! } |
| 61 | //! } |
| 62 | //! |
| 63 | //! impl Parse for ItemStruct { |
| 64 | //! fn parse(input: ParseStream) -> Result<Self> { |
| 65 | //! let content; |
| 66 | //! Ok(ItemStruct { |
| 67 | //! struct_token: input.parse()?, |
| 68 | //! ident: input.parse()?, |
| 69 | //! brace_token: braced!(content in input), |
| 70 | //! fields: content.parse_terminated(Field::parse_named)?, |
| 71 | //! }) |
| 72 | //! } |
| 73 | //! } |
| 74 | //! # |
| 75 | //! # impl Parse for ItemEnum { |
| 76 | //! # fn parse(input: ParseStream) -> Result<Self> { |
| 77 | //! # unimplemented!() |
| 78 | //! # } |
| 79 | //! # } |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 80 | //! |
| 81 | //! # const IGNORE: &str = stringify! { |
| 82 | //! #[proc_macro] |
| 83 | //! # }; |
| 84 | //! pub fn my_macro(tokens: TokenStream) -> TokenStream { |
| 85 | //! let input = parse_macro_input!(tokens as Item); |
| 86 | //! |
| 87 | //! /* ... */ |
| 88 | //! # "".parse().unwrap() |
| 89 | //! } |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 90 | //! ``` |
| 91 | //! |
| 92 | //! # The `syn::parse*` functions |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 93 | //! |
| 94 | //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve |
| 95 | //! as an entry point for parsing syntax tree nodes that can be parsed in an |
| 96 | //! obvious default way. These functions can return any syntax tree node that |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 97 | //! implements the [`Parse`] trait, which includes most types in Syn. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 98 | //! |
| 99 | //! [`syn::parse`]: ../fn.parse.html |
| 100 | //! [`syn::parse2`]: ../fn.parse2.html |
| 101 | //! [`syn::parse_str`]: ../fn.parse_str.html |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 102 | //! [`Parse`]: trait.Parse.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 103 | //! |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 104 | //! ``` |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 105 | //! use syn::Type; |
| 106 | //! |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 107 | //! # fn run_parser() -> syn::Result<()> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 108 | //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?; |
| 109 | //! # Ok(()) |
| 110 | //! # } |
| 111 | //! # |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 112 | //! # run_parser().unwrap(); |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 113 | //! ``` |
| 114 | //! |
| 115 | //! The [`parse_quote!`] macro also uses this approach. |
| 116 | //! |
| 117 | //! [`parse_quote!`]: ../macro.parse_quote.html |
| 118 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 119 | //! # The `Parser` trait |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 120 | //! |
| 121 | //! Some types can be parsed in several ways depending on context. For example |
| 122 | //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like |
| 123 | //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`] |
| 124 | //! may or may not allow trailing punctuation, and parsing it the wrong way |
| 125 | //! would either reject valid input or accept invalid input. |
| 126 | //! |
| 127 | //! [`Attribute`]: ../struct.Attribute.html |
| 128 | //! [`Punctuated`]: ../punctuated/index.html |
| 129 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 130 | //! The `Parse` trait is not implemented in these cases because there is no good |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 131 | //! behavior to consider the default. |
| 132 | //! |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 133 | //! ```compile_fail |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 134 | //! # extern crate proc_macro; |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 135 | //! # |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 136 | //! # use syn::punctuated::Punctuated; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 137 | //! # use syn::{PathSegment, Result, Token}; |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 138 | //! # |
| 139 | //! # fn f(tokens: proc_macro::TokenStream) -> Result<()> { |
| 140 | //! # |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 141 | //! // Can't parse `Punctuated` without knowing whether trailing punctuation |
| 142 | //! // should be allowed in this context. |
| 143 | //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?; |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 144 | //! # |
| 145 | //! # Ok(()) |
| 146 | //! # } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 147 | //! ``` |
| 148 | //! |
| 149 | //! In these cases the types provide a choice of parser functions rather than a |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 150 | //! single `Parse` implementation, and those parser functions can be invoked |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 151 | //! through the [`Parser`] trait. |
| 152 | //! |
| 153 | //! [`Parser`]: trait.Parser.html |
| 154 | //! |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 155 | //! ``` |
David Tolnay | 66a2360 | 2018-12-31 17:59:21 -0500 | [diff] [blame] | 156 | //! extern crate proc_macro; |
| 157 | //! |
| 158 | //! use proc_macro::TokenStream; |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 159 | //! use syn::parse::Parser; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 160 | //! use syn::punctuated::Punctuated; |
David Tolnay | 66a2360 | 2018-12-31 17:59:21 -0500 | [diff] [blame] | 161 | //! use syn::{Attribute, Expr, PathSegment, Result, Token}; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 162 | //! |
David Tolnay | 66a2360 | 2018-12-31 17:59:21 -0500 | [diff] [blame] | 163 | //! fn call_some_parser_methods(input: TokenStream) -> Result<()> { |
| 164 | //! // Parse a nonempty sequence of path segments separated by `::` punctuation |
| 165 | //! // with no trailing punctuation. |
| 166 | //! let tokens = input.clone(); |
| 167 | //! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; |
| 168 | //! let _path = parser.parse(tokens)?; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 169 | //! |
David Tolnay | 66a2360 | 2018-12-31 17:59:21 -0500 | [diff] [blame] | 170 | //! // Parse a possibly empty sequence of expressions terminated by commas with |
| 171 | //! // an optional trailing punctuation. |
| 172 | //! let tokens = input.clone(); |
| 173 | //! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; |
| 174 | //! let _args = parser.parse(tokens)?; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 175 | //! |
David Tolnay | 66a2360 | 2018-12-31 17:59:21 -0500 | [diff] [blame] | 176 | //! // Parse zero or more outer attributes but not inner attributes. |
| 177 | //! let tokens = input.clone(); |
| 178 | //! let parser = Attribute::parse_outer; |
| 179 | //! let _attrs = parser.parse(tokens)?; |
| 180 | //! |
| 181 | //! Ok(()) |
| 182 | //! } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 183 | //! ``` |
| 184 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 185 | //! --- |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 186 | //! |
| 187 | //! *This module is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 188 | |
David Tolnay | b9e2303 | 2019-01-23 21:43:36 -0800 | [diff] [blame] | 189 | #[path = "discouraged.rs"] |
cad97 | 89bb945 | 2019-01-20 18:33:48 -0500 | [diff] [blame] | 190 | pub mod discouraged; |
| 191 | |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 192 | use std::cell::Cell; |
Diggory Hardy | 1c522e1 | 2018-11-02 10:10:02 +0000 | [diff] [blame] | 193 | use std::fmt::{self, Debug, Display}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 194 | use std::marker::PhantomData; |
| 195 | use std::mem; |
| 196 | use std::ops::Deref; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 197 | use std::rc::Rc; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 198 | use std::str::FromStr; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 199 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 200 | #[cfg(all( |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 201 | not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 202 | feature = "proc-macro" |
| 203 | ))] |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 204 | use crate::proc_macro; |
David Tolnay | f07b334 | 2018-09-01 11:58:11 -0700 | [diff] [blame] | 205 | use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 206 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 207 | use crate::buffer::{Cursor, TokenBuffer}; |
| 208 | use crate::error; |
| 209 | use crate::lookahead; |
| 210 | use crate::punctuated::Punctuated; |
| 211 | use crate::token::Token; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 212 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 213 | pub use crate::error::{Error, Result}; |
| 214 | pub use crate::lookahead::{Lookahead1, Peek}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 215 | |
| 216 | /// Parsing interface implemented by all types that can be parsed in a default |
| 217 | /// way from a token stream. |
| 218 | pub trait Parse: Sized { |
| 219 | fn parse(input: ParseStream) -> Result<Self>; |
| 220 | } |
| 221 | |
| 222 | /// Input to a Syn parser function. |
David Tolnay | a0daa48 | 2018-09-01 02:09:40 -0700 | [diff] [blame] | 223 | /// |
| 224 | /// See the methods of this type under the documentation of [`ParseBuffer`]. For |
| 225 | /// an overview of parsing in Syn, refer to the [module documentation]. |
| 226 | /// |
David Tolnay | b8dec88 | 2019-07-20 09:46:14 -0700 | [diff] [blame] | 227 | /// [module documentation]: self |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 228 | pub type ParseStream<'a> = &'a ParseBuffer<'a>; |
| 229 | |
| 230 | /// Cursor position within a buffered token stream. |
David Tolnay | 20d29a1 | 2018-09-01 15:15:33 -0700 | [diff] [blame] | 231 | /// |
| 232 | /// This type is more commonly used through the type alias [`ParseStream`] which |
| 233 | /// is an alias for `&ParseBuffer`. |
| 234 | /// |
| 235 | /// `ParseStream` is the input type for all parser functions in Syn. They have |
| 236 | /// the signature `fn(ParseStream) -> Result<T>`. |
David Tolnay | 028a7d7 | 2018-12-31 17:11:02 -0500 | [diff] [blame] | 237 | /// |
| 238 | /// ## Calling a parser function |
| 239 | /// |
| 240 | /// There is no public way to construct a `ParseBuffer`. Instead, if you are |
| 241 | /// looking to invoke a parser function that requires `ParseStream` as input, |
| 242 | /// you will need to go through one of the public parsing entry points. |
| 243 | /// |
| 244 | /// - The [`parse_macro_input!`] macro if parsing input of a procedural macro; |
| 245 | /// - One of [the `syn::parse*` functions][syn-parse]; or |
| 246 | /// - A method of the [`Parser`] trait. |
| 247 | /// |
David Tolnay | 028a7d7 | 2018-12-31 17:11:02 -0500 | [diff] [blame] | 248 | /// [syn-parse]: index.html#the-synparse-functions |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 249 | pub struct ParseBuffer<'a> { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame] | 250 | scope: Span, |
David Tolnay | 5d7f225 | 2018-09-02 08:21:40 -0700 | [diff] [blame] | 251 | // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a. |
| 252 | // The rest of the code in this module needs to be careful that only a |
| 253 | // cursor derived from this `cell` is ever assigned to this `cell`. |
| 254 | // |
| 255 | // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a |
| 256 | // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter |
| 257 | // than 'a, and then assign a Cursor<'short> into the Cell. |
| 258 | // |
| 259 | // By extension, it would not be safe to expose an API that accepts a |
| 260 | // Cursor<'a> and trusts that it lives as long as the cursor currently in |
| 261 | // the cell. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 262 | cell: Cell<Cursor<'static>>, |
| 263 | marker: PhantomData<Cursor<'a>>, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 264 | unexpected: Rc<Cell<Option<Span>>>, |
| 265 | } |
| 266 | |
| 267 | impl<'a> Drop for ParseBuffer<'a> { |
| 268 | fn drop(&mut self) { |
| 269 | if !self.is_empty() && self.unexpected.get().is_none() { |
| 270 | self.unexpected.set(Some(self.cursor().span())); |
| 271 | } |
| 272 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 273 | } |
| 274 | |
Diggory Hardy | 1c522e1 | 2018-11-02 10:10:02 +0000 | [diff] [blame] | 275 | impl<'a> Display for ParseBuffer<'a> { |
| 276 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 277 | Display::fmt(&self.cursor().token_stream(), f) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | impl<'a> Debug for ParseBuffer<'a> { |
| 282 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 283 | Debug::fmt(&self.cursor().token_stream(), f) |
| 284 | } |
| 285 | } |
| 286 | |
David Tolnay | 642832f | 2018-09-01 13:08:10 -0700 | [diff] [blame] | 287 | /// Cursor state associated with speculative parsing. |
| 288 | /// |
| 289 | /// This type is the input of the closure provided to [`ParseStream::step`]. |
| 290 | /// |
David Tolnay | b8dec88 | 2019-07-20 09:46:14 -0700 | [diff] [blame] | 291 | /// [`ParseStream::step`]: ParseBuffer::step |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 292 | /// |
| 293 | /// # Example |
| 294 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 295 | /// ``` |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 296 | /// use proc_macro2::TokenTree; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 297 | /// use syn::Result; |
| 298 | /// use syn::parse::ParseStream; |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 299 | /// |
| 300 | /// // This function advances the stream past the next occurrence of `@`. If |
| 301 | /// // no `@` is present in the stream, the stream position is unchanged and |
| 302 | /// // an error is returned. |
| 303 | /// fn skip_past_next_at(input: ParseStream) -> Result<()> { |
| 304 | /// input.step(|cursor| { |
| 305 | /// let mut rest = *cursor; |
Sharad Chand | e1df40a | 2018-09-08 15:25:52 +0545 | [diff] [blame] | 306 | /// while let Some((tt, next)) = rest.token_tree() { |
David Tolnay | 6533607 | 2019-04-22 23:10:52 -0700 | [diff] [blame] | 307 | /// match &tt { |
| 308 | /// TokenTree::Punct(punct) if punct.as_char() == '@' => { |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 309 | /// return Ok(((), next)); |
| 310 | /// } |
| 311 | /// _ => rest = next, |
| 312 | /// } |
| 313 | /// } |
| 314 | /// Err(cursor.error("no `@` was found after this point")) |
| 315 | /// }) |
| 316 | /// } |
| 317 | /// # |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 318 | /// # fn remainder_after_skipping_past_next_at( |
| 319 | /// # input: ParseStream, |
| 320 | /// # ) -> Result<proc_macro2::TokenStream> { |
| 321 | /// # skip_past_next_at(input)?; |
| 322 | /// # input.parse() |
| 323 | /// # } |
| 324 | /// # |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 325 | /// # use syn::parse::Parser; |
| 326 | /// # let remainder = remainder_after_skipping_past_next_at |
| 327 | /// # .parse_str("a @ b c") |
| 328 | /// # .unwrap(); |
| 329 | /// # assert_eq!(remainder.to_string(), "b c"); |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 330 | /// ``` |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 331 | #[derive(Copy, Clone)] |
| 332 | pub struct StepCursor<'c, 'a> { |
| 333 | scope: Span, |
David Tolnay | 56924f4 | 2018-09-02 08:24:58 -0700 | [diff] [blame] | 334 | // This field is covariant in 'c. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 335 | cursor: Cursor<'c>, |
David Tolnay | 56924f4 | 2018-09-02 08:24:58 -0700 | [diff] [blame] | 336 | // This field is contravariant in 'c. Together these make StepCursor |
| 337 | // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a |
| 338 | // different lifetime but can upcast into a StepCursor with a shorter |
| 339 | // lifetime 'a. |
| 340 | // |
| 341 | // As long as we only ever construct a StepCursor for which 'c outlives 'a, |
| 342 | // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c |
| 343 | // outlives 'a. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 344 | marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>, |
| 345 | } |
| 346 | |
| 347 | impl<'c, 'a> Deref for StepCursor<'c, 'a> { |
| 348 | type Target = Cursor<'c>; |
| 349 | |
| 350 | fn deref(&self) -> &Self::Target { |
| 351 | &self.cursor |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | impl<'c, 'a> StepCursor<'c, 'a> { |
David Tolnay | 642832f | 2018-09-01 13:08:10 -0700 | [diff] [blame] | 356 | /// Triggers an error at the current position of the parse stream. |
| 357 | /// |
| 358 | /// The `ParseStream::step` invocation will return this same error without |
| 359 | /// advancing the stream state. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 360 | pub fn error<T: Display>(self, message: T) -> Error { |
| 361 | error::new_at(self.scope, self.cursor, message) |
| 362 | } |
| 363 | } |
| 364 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 365 | pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> { |
| 366 | // Refer to the comments within the StepCursor definition. We use the |
| 367 | // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a. |
| 368 | // Cursor is covariant in its lifetime parameter so we can cast a |
| 369 | // Cursor<'c> to one with the shorter lifetime Cursor<'a>. |
| 370 | let _ = proof; |
| 371 | unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) } |
David Tolnay | 6ea3fdc | 2018-09-01 13:30:53 -0700 | [diff] [blame] | 372 | } |
| 373 | |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 374 | fn skip(input: ParseStream) -> bool { |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 375 | input |
| 376 | .step(|cursor| { |
| 377 | if let Some((_lifetime, rest)) = cursor.lifetime() { |
| 378 | Ok((true, rest)) |
| 379 | } else if let Some((_token, rest)) = cursor.token_tree() { |
| 380 | Ok((true, rest)) |
| 381 | } else { |
| 382 | Ok((false, *cursor)) |
| 383 | } |
David Tolnay | fb84fc0 | 2018-10-02 21:01:30 -0700 | [diff] [blame] | 384 | }) |
| 385 | .unwrap() |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 386 | } |
| 387 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 388 | pub(crate) fn new_parse_buffer( |
| 389 | scope: Span, |
| 390 | cursor: Cursor, |
| 391 | unexpected: Rc<Cell<Option<Span>>>, |
| 392 | ) -> ParseBuffer { |
| 393 | ParseBuffer { |
| 394 | scope, |
| 395 | // See comment on `cell` in the struct definition. |
| 396 | cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }), |
| 397 | marker: PhantomData, |
| 398 | unexpected, |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 399 | } |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 400 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 401 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 402 | pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { |
| 403 | buffer.unexpected.clone() |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 404 | } |
| 405 | |
| 406 | impl<'a> ParseBuffer<'a> { |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 407 | /// Parses a syntax tree node of type `T`, advancing the position of our |
| 408 | /// parse stream past it. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 409 | pub fn parse<T: Parse>(&self) -> Result<T> { |
| 410 | T::parse(self) |
| 411 | } |
| 412 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 413 | /// Calls the given parser function to parse a syntax tree node of type `T` |
| 414 | /// from this stream. |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 415 | /// |
| 416 | /// # Example |
| 417 | /// |
| 418 | /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of |
| 419 | /// zero or more outer attributes. |
| 420 | /// |
David Tolnay | b8dec88 | 2019-07-20 09:46:14 -0700 | [diff] [blame] | 421 | /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 422 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 423 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 424 | /// use syn::{Attribute, Ident, Result, Token}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 425 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 426 | /// |
| 427 | /// // Parses a unit struct with attributes. |
| 428 | /// // |
| 429 | /// // #[path = "s.tmpl"] |
| 430 | /// // struct S; |
| 431 | /// struct UnitStruct { |
| 432 | /// attrs: Vec<Attribute>, |
| 433 | /// struct_token: Token![struct], |
| 434 | /// name: Ident, |
| 435 | /// semi_token: Token![;], |
| 436 | /// } |
| 437 | /// |
| 438 | /// impl Parse for UnitStruct { |
| 439 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 440 | /// Ok(UnitStruct { |
| 441 | /// attrs: input.call(Attribute::parse_outer)?, |
| 442 | /// struct_token: input.parse()?, |
| 443 | /// name: input.parse()?, |
| 444 | /// semi_token: input.parse()?, |
| 445 | /// }) |
| 446 | /// } |
| 447 | /// } |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 448 | /// ``` |
David Tolnay | 3a515a0 | 2018-08-25 21:08:27 -0400 | [diff] [blame] | 449 | pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> { |
| 450 | function(self) |
| 451 | } |
| 452 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 453 | /// Looks at the next token in the parse stream to determine whether it |
| 454 | /// matches the requested type of token. |
| 455 | /// |
| 456 | /// Does not advance the position of the parse stream. |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 457 | /// |
David Tolnay | 7d229e8 | 2018-09-01 16:42:34 -0700 | [diff] [blame] | 458 | /// # Syntax |
| 459 | /// |
| 460 | /// Note that this method does not use turbofish syntax. Pass the peek type |
| 461 | /// inside of parentheses. |
| 462 | /// |
| 463 | /// - `input.peek(Token![struct])` |
| 464 | /// - `input.peek(Token![==])` |
David Tolnay | b8a68e4 | 2019-04-22 14:01:56 -0700 | [diff] [blame] | 465 | /// - `input.peek(Ident)` *(does not accept keywords)* |
| 466 | /// - `input.peek(Ident::peek_any)` |
David Tolnay | 7d229e8 | 2018-09-01 16:42:34 -0700 | [diff] [blame] | 467 | /// - `input.peek(Lifetime)` |
| 468 | /// - `input.peek(token::Brace)` |
| 469 | /// |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 470 | /// # Example |
| 471 | /// |
| 472 | /// In this example we finish parsing the list of supertraits when the next |
| 473 | /// token in the input is either `where` or an opening curly brace. |
| 474 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 475 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 476 | /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 477 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 478 | /// use syn::punctuated::Punctuated; |
| 479 | /// |
| 480 | /// // Parses a trait definition containing no associated items. |
| 481 | /// // |
| 482 | /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {} |
| 483 | /// struct MarkerTrait { |
| 484 | /// trait_token: Token![trait], |
| 485 | /// ident: Ident, |
| 486 | /// generics: Generics, |
| 487 | /// colon_token: Option<Token![:]>, |
| 488 | /// supertraits: Punctuated<TypeParamBound, Token![+]>, |
| 489 | /// brace_token: token::Brace, |
| 490 | /// } |
| 491 | /// |
| 492 | /// impl Parse for MarkerTrait { |
| 493 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 494 | /// let trait_token: Token![trait] = input.parse()?; |
| 495 | /// let ident: Ident = input.parse()?; |
| 496 | /// let mut generics: Generics = input.parse()?; |
| 497 | /// let colon_token: Option<Token![:]> = input.parse()?; |
| 498 | /// |
| 499 | /// let mut supertraits = Punctuated::new(); |
| 500 | /// if colon_token.is_some() { |
| 501 | /// loop { |
| 502 | /// supertraits.push_value(input.parse()?); |
| 503 | /// if input.peek(Token![where]) || input.peek(token::Brace) { |
| 504 | /// break; |
| 505 | /// } |
| 506 | /// supertraits.push_punct(input.parse()?); |
| 507 | /// } |
| 508 | /// } |
| 509 | /// |
| 510 | /// generics.where_clause = input.parse()?; |
| 511 | /// let content; |
| 512 | /// let empty_brace_token = braced!(content in input); |
| 513 | /// |
| 514 | /// Ok(MarkerTrait { |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 515 | /// trait_token, |
| 516 | /// ident, |
| 517 | /// generics, |
| 518 | /// colon_token, |
| 519 | /// supertraits, |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 520 | /// brace_token: empty_brace_token, |
| 521 | /// }) |
| 522 | /// } |
| 523 | /// } |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 524 | /// ``` |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 525 | pub fn peek<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 576779a | 2018-09-01 11:54:12 -0700 | [diff] [blame] | 526 | let _ = token; |
| 527 | T::Token::peek(self.cursor()) |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 528 | } |
| 529 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 530 | /// Looks at the second-next token in the parse stream. |
David Tolnay | e334b87 | 2018-09-01 16:38:10 -0700 | [diff] [blame] | 531 | /// |
| 532 | /// This is commonly useful as a way to implement contextual keywords. |
| 533 | /// |
| 534 | /// # Example |
| 535 | /// |
| 536 | /// This example needs to use `peek2` because the symbol `union` is not a |
| 537 | /// keyword in Rust. We can't use just `peek` and decide to parse a union if |
| 538 | /// the very next token is `union`, because someone is free to write a `mod |
| 539 | /// union` and a macro invocation that looks like `union::some_macro! { ... |
| 540 | /// }`. In other words `union` is a contextual keyword. |
| 541 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 542 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 543 | /// use syn::{Ident, ItemUnion, Macro, Result, Token}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 544 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | e334b87 | 2018-09-01 16:38:10 -0700 | [diff] [blame] | 545 | /// |
| 546 | /// // Parses either a union or a macro invocation. |
| 547 | /// enum UnionOrMacro { |
| 548 | /// // union MaybeUninit<T> { uninit: (), value: T } |
| 549 | /// Union(ItemUnion), |
| 550 | /// // lazy_static! { ... } |
| 551 | /// Macro(Macro), |
| 552 | /// } |
| 553 | /// |
| 554 | /// impl Parse for UnionOrMacro { |
| 555 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 556 | /// if input.peek(Token![union]) && input.peek2(Ident) { |
| 557 | /// input.parse().map(UnionOrMacro::Union) |
| 558 | /// } else { |
| 559 | /// input.parse().map(UnionOrMacro::Macro) |
| 560 | /// } |
| 561 | /// } |
| 562 | /// } |
David Tolnay | e334b87 | 2018-09-01 16:38:10 -0700 | [diff] [blame] | 563 | /// ``` |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 564 | pub fn peek2<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 565 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 566 | skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 567 | } |
| 568 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 569 | /// Looks at the third-next token in the parse stream. |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 570 | pub fn peek3<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 571 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 572 | skip(&ahead) && skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 573 | } |
| 574 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 575 | /// Parses zero or more occurrences of `T` separated by punctuation of type |
| 576 | /// `P`, with optional trailing punctuation. |
| 577 | /// |
| 578 | /// Parsing continues until the end of this parse stream. The entire content |
| 579 | /// of this parse stream must consist of `T` and `P`. |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 580 | /// |
| 581 | /// # Example |
| 582 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 583 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 584 | /// # use quote::quote; |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 585 | /// # |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 586 | /// use syn::{parenthesized, token, Ident, Result, Token, Type}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 587 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 588 | /// use syn::punctuated::Punctuated; |
| 589 | /// |
| 590 | /// // Parse a simplified tuple struct syntax like: |
| 591 | /// // |
| 592 | /// // struct S(A, B); |
| 593 | /// struct TupleStruct { |
| 594 | /// struct_token: Token![struct], |
| 595 | /// ident: Ident, |
| 596 | /// paren_token: token::Paren, |
| 597 | /// fields: Punctuated<Type, Token![,]>, |
| 598 | /// semi_token: Token![;], |
| 599 | /// } |
| 600 | /// |
| 601 | /// impl Parse for TupleStruct { |
| 602 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 603 | /// let content; |
| 604 | /// Ok(TupleStruct { |
| 605 | /// struct_token: input.parse()?, |
| 606 | /// ident: input.parse()?, |
| 607 | /// paren_token: parenthesized!(content in input), |
| 608 | /// fields: content.parse_terminated(Type::parse)?, |
| 609 | /// semi_token: input.parse()?, |
| 610 | /// }) |
| 611 | /// } |
| 612 | /// } |
| 613 | /// # |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 614 | /// # let input = quote! { |
| 615 | /// # struct S(A, B); |
| 616 | /// # }; |
| 617 | /// # syn::parse2::<TupleStruct>(input).unwrap(); |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 618 | /// ``` |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 619 | pub fn parse_terminated<T, P: Parse>( |
| 620 | &self, |
| 621 | parser: fn(ParseStream) -> Result<T>, |
| 622 | ) -> Result<Punctuated<T, P>> { |
David Tolnay | d0f8021 | 2018-08-30 18:32:14 -0700 | [diff] [blame] | 623 | Punctuated::parse_terminated_with(self, parser) |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 624 | } |
| 625 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 626 | /// Returns whether there are tokens remaining in this stream. |
| 627 | /// |
| 628 | /// This method returns true at the end of the content of a set of |
| 629 | /// delimiters, as well as at the very end of the complete macro input. |
David Tolnay | cce6b5f | 2018-09-01 14:24:46 -0700 | [diff] [blame] | 630 | /// |
| 631 | /// # Example |
| 632 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 633 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 634 | /// use syn::{braced, token, Ident, Item, Result, Token}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 635 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | cce6b5f | 2018-09-01 14:24:46 -0700 | [diff] [blame] | 636 | /// |
| 637 | /// // Parses a Rust `mod m { ... }` containing zero or more items. |
| 638 | /// struct Mod { |
| 639 | /// mod_token: Token![mod], |
| 640 | /// name: Ident, |
| 641 | /// brace_token: token::Brace, |
| 642 | /// items: Vec<Item>, |
| 643 | /// } |
| 644 | /// |
| 645 | /// impl Parse for Mod { |
| 646 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 647 | /// let content; |
| 648 | /// Ok(Mod { |
| 649 | /// mod_token: input.parse()?, |
| 650 | /// name: input.parse()?, |
| 651 | /// brace_token: braced!(content in input), |
| 652 | /// items: { |
| 653 | /// let mut items = Vec::new(); |
| 654 | /// while !content.is_empty() { |
| 655 | /// items.push(content.parse()?); |
| 656 | /// } |
| 657 | /// items |
| 658 | /// }, |
| 659 | /// }) |
| 660 | /// } |
| 661 | /// } |
David Tolnay | f2b7860 | 2018-11-06 20:42:37 -0800 | [diff] [blame] | 662 | /// ``` |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 663 | pub fn is_empty(&self) -> bool { |
| 664 | self.cursor().eof() |
| 665 | } |
| 666 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 667 | /// Constructs a helper for peeking at the next token in this stream and |
| 668 | /// building an error message if it is not one of a set of expected tokens. |
David Tolnay | 2c77e77 | 2018-09-01 14:18:46 -0700 | [diff] [blame] | 669 | /// |
| 670 | /// # Example |
| 671 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 672 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 673 | /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 674 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 2c77e77 | 2018-09-01 14:18:46 -0700 | [diff] [blame] | 675 | /// |
| 676 | /// // A generic parameter, a single one of the comma-separated elements inside |
| 677 | /// // angle brackets in: |
| 678 | /// // |
| 679 | /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... } |
| 680 | /// // |
| 681 | /// // On invalid input, lookahead gives us a reasonable error message. |
| 682 | /// // |
| 683 | /// // error: expected one of: identifier, lifetime, `const` |
| 684 | /// // | |
| 685 | /// // 5 | fn f<!Sized>() {} |
| 686 | /// // | ^ |
| 687 | /// enum GenericParam { |
| 688 | /// Type(TypeParam), |
| 689 | /// Lifetime(LifetimeDef), |
| 690 | /// Const(ConstParam), |
| 691 | /// } |
| 692 | /// |
| 693 | /// impl Parse for GenericParam { |
| 694 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 695 | /// let lookahead = input.lookahead1(); |
| 696 | /// if lookahead.peek(Ident) { |
| 697 | /// input.parse().map(GenericParam::Type) |
| 698 | /// } else if lookahead.peek(Lifetime) { |
| 699 | /// input.parse().map(GenericParam::Lifetime) |
| 700 | /// } else if lookahead.peek(Token![const]) { |
| 701 | /// input.parse().map(GenericParam::Const) |
| 702 | /// } else { |
| 703 | /// Err(lookahead.error()) |
| 704 | /// } |
| 705 | /// } |
| 706 | /// } |
David Tolnay | 2c77e77 | 2018-09-01 14:18:46 -0700 | [diff] [blame] | 707 | /// ``` |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 708 | pub fn lookahead1(&self) -> Lookahead1<'a> { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame] | 709 | lookahead::new(self.scope, self.cursor()) |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 710 | } |
| 711 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 712 | /// Forks a parse stream so that parsing tokens out of either the original |
| 713 | /// or the fork does not advance the position of the other. |
| 714 | /// |
| 715 | /// # Performance |
| 716 | /// |
| 717 | /// Forking a parse stream is a cheap fixed amount of work and does not |
| 718 | /// involve copying token buffers. Where you might hit performance problems |
| 719 | /// is if your macro ends up parsing a large amount of content more than |
| 720 | /// once. |
| 721 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 722 | /// ``` |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 723 | /// # use syn::{Expr, Result}; |
| 724 | /// # use syn::parse::ParseStream; |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 725 | /// # |
| 726 | /// # fn bad(input: ParseStream) -> Result<Expr> { |
| 727 | /// // Do not do this. |
| 728 | /// if input.fork().parse::<Expr>().is_ok() { |
| 729 | /// return input.parse::<Expr>(); |
| 730 | /// } |
| 731 | /// # unimplemented!() |
| 732 | /// # } |
| 733 | /// ``` |
| 734 | /// |
| 735 | /// As a rule, avoid parsing an unbounded amount of tokens out of a forked |
| 736 | /// parse stream. Only use a fork when the amount of work performed against |
| 737 | /// the fork is small and bounded. |
| 738 | /// |
David Tolnay | 34506d9 | 2019-06-23 14:13:54 -0700 | [diff] [blame] | 739 | /// When complex speculative parsing against the forked stream is |
| 740 | /// unavoidable, use [`parse::discouraged::Speculative`] to advance the |
| 741 | /// original stream once the fork's parse is determined to have been |
| 742 | /// successful. |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 743 | /// |
David Tolnay | 34506d9 | 2019-06-23 14:13:54 -0700 | [diff] [blame] | 744 | /// For a lower level way to perform speculative parsing at the token level, |
| 745 | /// consider using [`ParseStream::step`] instead. |
| 746 | /// |
David Tolnay | b8dec88 | 2019-07-20 09:46:14 -0700 | [diff] [blame] | 747 | /// [`parse::discouraged::Speculative`]: discouraged::Speculative |
| 748 | /// [`ParseStream::step`]: ParseBuffer::step |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 749 | /// |
| 750 | /// # Example |
| 751 | /// |
| 752 | /// The parse implementation shown here parses possibly restricted `pub` |
| 753 | /// visibilities. |
| 754 | /// |
| 755 | /// - `pub` |
| 756 | /// - `pub(crate)` |
| 757 | /// - `pub(self)` |
| 758 | /// - `pub(super)` |
| 759 | /// - `pub(in some::path)` |
| 760 | /// |
| 761 | /// To handle the case of visibilities inside of tuple structs, the parser |
| 762 | /// needs to distinguish parentheses that specify visibility restrictions |
| 763 | /// from parentheses that form part of a tuple type. |
| 764 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 765 | /// ``` |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 766 | /// # struct A; |
| 767 | /// # struct B; |
| 768 | /// # struct C; |
| 769 | /// # |
| 770 | /// struct S(pub(crate) A, pub (B, C)); |
| 771 | /// ``` |
| 772 | /// |
| 773 | /// In this example input the first tuple struct element of `S` has |
| 774 | /// `pub(crate)` visibility while the second tuple struct element has `pub` |
| 775 | /// visibility; the parentheses around `(B, C)` are part of the type rather |
| 776 | /// than part of a visibility restriction. |
| 777 | /// |
| 778 | /// The parser uses a forked parse stream to check the first token inside of |
| 779 | /// parentheses after the `pub` keyword. This is a small bounded amount of |
| 780 | /// work performed against the forked parse stream. |
| 781 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 782 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 783 | /// use syn::{parenthesized, token, Ident, Path, Result, Token}; |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 784 | /// use syn::ext::IdentExt; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 785 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 786 | /// |
| 787 | /// struct PubVisibility { |
| 788 | /// pub_token: Token![pub], |
| 789 | /// restricted: Option<Restricted>, |
| 790 | /// } |
| 791 | /// |
| 792 | /// struct Restricted { |
| 793 | /// paren_token: token::Paren, |
| 794 | /// in_token: Option<Token![in]>, |
| 795 | /// path: Path, |
| 796 | /// } |
| 797 | /// |
| 798 | /// impl Parse for PubVisibility { |
| 799 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 800 | /// let pub_token: Token![pub] = input.parse()?; |
| 801 | /// |
| 802 | /// if input.peek(token::Paren) { |
| 803 | /// let ahead = input.fork(); |
| 804 | /// let mut content; |
| 805 | /// parenthesized!(content in ahead); |
| 806 | /// |
| 807 | /// if content.peek(Token![crate]) |
| 808 | /// || content.peek(Token![self]) |
| 809 | /// || content.peek(Token![super]) |
| 810 | /// { |
| 811 | /// return Ok(PubVisibility { |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 812 | /// pub_token, |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 813 | /// restricted: Some(Restricted { |
| 814 | /// paren_token: parenthesized!(content in input), |
| 815 | /// in_token: None, |
| 816 | /// path: Path::from(content.call(Ident::parse_any)?), |
| 817 | /// }), |
| 818 | /// }); |
| 819 | /// } else if content.peek(Token![in]) { |
| 820 | /// return Ok(PubVisibility { |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 821 | /// pub_token, |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 822 | /// restricted: Some(Restricted { |
| 823 | /// paren_token: parenthesized!(content in input), |
| 824 | /// in_token: Some(content.parse()?), |
| 825 | /// path: content.call(Path::parse_mod_style)?, |
| 826 | /// }), |
| 827 | /// }); |
| 828 | /// } |
| 829 | /// } |
| 830 | /// |
| 831 | /// Ok(PubVisibility { |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 832 | /// pub_token, |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 833 | /// restricted: None, |
| 834 | /// }) |
| 835 | /// } |
| 836 | /// } |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 837 | /// ``` |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 838 | pub fn fork(&self) -> Self { |
David Tolnay | 6456a9d | 2018-08-26 08:11:18 -0400 | [diff] [blame] | 839 | ParseBuffer { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame] | 840 | scope: self.scope, |
David Tolnay | 6456a9d | 2018-08-26 08:11:18 -0400 | [diff] [blame] | 841 | cell: self.cell.clone(), |
| 842 | marker: PhantomData, |
| 843 | // Not the parent's unexpected. Nothing cares whether the clone |
| 844 | // parses all the way. |
| 845 | unexpected: Rc::new(Cell::new(None)), |
| 846 | } |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 847 | } |
| 848 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 849 | /// Triggers an error at the current position of the parse stream. |
David Tolnay | 23fce0b | 2018-09-01 13:50:31 -0700 | [diff] [blame] | 850 | /// |
| 851 | /// # Example |
| 852 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 853 | /// ``` |
David Tolnay | fd5b117 | 2018-12-31 17:54:36 -0500 | [diff] [blame] | 854 | /// use syn::{Expr, Result, Token}; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 855 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 23fce0b | 2018-09-01 13:50:31 -0700 | [diff] [blame] | 856 | /// |
| 857 | /// // Some kind of loop: `while` or `for` or `loop`. |
| 858 | /// struct Loop { |
| 859 | /// expr: Expr, |
| 860 | /// } |
| 861 | /// |
| 862 | /// impl Parse for Loop { |
| 863 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 864 | /// if input.peek(Token![while]) |
| 865 | /// || input.peek(Token![for]) |
| 866 | /// || input.peek(Token![loop]) |
| 867 | /// { |
| 868 | /// Ok(Loop { |
| 869 | /// expr: input.parse()?, |
| 870 | /// }) |
| 871 | /// } else { |
| 872 | /// Err(input.error("expected some kind of loop")) |
| 873 | /// } |
| 874 | /// } |
| 875 | /// } |
| 876 | /// ``` |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 877 | pub fn error<T: Display>(&self, message: T) -> Error { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame] | 878 | error::new_at(self.scope, self.cursor(), message) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 879 | } |
| 880 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 881 | /// Speculatively parses tokens from this parse stream, advancing the |
| 882 | /// position of this stream only if parsing succeeds. |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 883 | /// |
David Tolnay | ad1d1d2 | 2018-09-01 13:34:43 -0700 | [diff] [blame] | 884 | /// This is a powerful low-level API used for defining the `Parse` impls of |
| 885 | /// the basic built-in token types. It is not something that will be used |
| 886 | /// widely outside of the Syn codebase. |
| 887 | /// |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 888 | /// # Example |
| 889 | /// |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 890 | /// ``` |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 891 | /// use proc_macro2::TokenTree; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame] | 892 | /// use syn::Result; |
| 893 | /// use syn::parse::ParseStream; |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 894 | /// |
| 895 | /// // This function advances the stream past the next occurrence of `@`. If |
| 896 | /// // no `@` is present in the stream, the stream position is unchanged and |
| 897 | /// // an error is returned. |
| 898 | /// fn skip_past_next_at(input: ParseStream) -> Result<()> { |
| 899 | /// input.step(|cursor| { |
| 900 | /// let mut rest = *cursor; |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 901 | /// while let Some((tt, next)) = rest.token_tree() { |
David Tolnay | 6533607 | 2019-04-22 23:10:52 -0700 | [diff] [blame] | 902 | /// match &tt { |
| 903 | /// TokenTree::Punct(punct) if punct.as_char() == '@' => { |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 904 | /// return Ok(((), next)); |
| 905 | /// } |
| 906 | /// _ => rest = next, |
| 907 | /// } |
| 908 | /// } |
| 909 | /// Err(cursor.error("no `@` was found after this point")) |
| 910 | /// }) |
| 911 | /// } |
| 912 | /// # |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 913 | /// # fn remainder_after_skipping_past_next_at( |
| 914 | /// # input: ParseStream, |
| 915 | /// # ) -> Result<proc_macro2::TokenStream> { |
| 916 | /// # skip_past_next_at(input)?; |
| 917 | /// # input.parse() |
| 918 | /// # } |
| 919 | /// # |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 920 | /// # use syn::parse::Parser; |
| 921 | /// # let remainder = remainder_after_skipping_past_next_at |
| 922 | /// # .parse_str("a @ b c") |
| 923 | /// # .unwrap(); |
| 924 | /// # assert_eq!(remainder.to_string(), "b c"); |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 925 | /// ``` |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 926 | pub fn step<F, R>(&self, function: F) -> Result<R> |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 927 | where |
| 928 | F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>, |
| 929 | { |
David Tolnay | c142b09 | 2018-09-02 08:52:52 -0700 | [diff] [blame] | 930 | // Since the user's function is required to work for any 'c, we know |
| 931 | // that the Cursor<'c> they return is either derived from the input |
| 932 | // StepCursor<'c, 'a> or from a Cursor<'static>. |
| 933 | // |
| 934 | // It would not be legal to write this function without the invariant |
| 935 | // lifetime 'c in StepCursor<'c, 'a>. If this function were written only |
| 936 | // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to |
| 937 | // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke |
| 938 | // `step` on their ParseBuffer<'short> with a closure that returns |
| 939 | // Cursor<'short>, and we would wrongly write that Cursor<'short> into |
| 940 | // the Cell intended to hold Cursor<'a>. |
| 941 | // |
| 942 | // In some cases it may be necessary for R to contain a Cursor<'a>. |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 943 | // Within Syn we solve this using `advance_step_cursor` which uses the |
| 944 | // existence of a StepCursor<'c, 'a> as proof that it is safe to cast |
| 945 | // from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it would be |
| 946 | // safe to expose that API as a method on StepCursor. |
David Tolnay | 6b65f85 | 2018-09-01 11:56:25 -0700 | [diff] [blame] | 947 | let (node, rest) = function(StepCursor { |
David Tolnay | 6db0f2a | 2019-06-23 13:37:39 -0700 | [diff] [blame] | 948 | scope: self.scope, |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 949 | cursor: self.cell.get(), |
| 950 | marker: PhantomData, |
David Tolnay | 6b65f85 | 2018-09-01 11:56:25 -0700 | [diff] [blame] | 951 | })?; |
| 952 | self.cell.set(rest); |
| 953 | Ok(node) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 954 | } |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 955 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 956 | /// Provides low-level access to the token representation underlying this |
| 957 | /// parse stream. |
| 958 | /// |
| 959 | /// Cursors are immutable so no operations you perform against the cursor |
| 960 | /// will affect the state of this parse stream. |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 961 | pub fn cursor(&self) -> Cursor<'a> { |
| 962 | self.cell.get() |
| 963 | } |
| 964 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 965 | fn check_unexpected(&self) -> Result<()> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 966 | match self.unexpected.get() { |
| 967 | Some(span) => Err(Error::new(span, "unexpected token")), |
| 968 | None => Ok(()), |
| 969 | } |
| 970 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 971 | } |
| 972 | |
David Tolnay | a7d69fc | 2018-08-26 13:30:24 -0400 | [diff] [blame] | 973 | impl<T: Parse> Parse for Box<T> { |
| 974 | fn parse(input: ParseStream) -> Result<Self> { |
| 975 | input.parse().map(Box::new) |
| 976 | } |
| 977 | } |
| 978 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 979 | impl<T: Parse + Token> Parse for Option<T> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 980 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | 00f81fd | 2018-09-01 10:50:12 -0700 | [diff] [blame] | 981 | if T::peek(input.cursor()) { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 982 | Ok(Some(input.parse()?)) |
| 983 | } else { |
| 984 | Ok(None) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 985 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 986 | } |
| 987 | } |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 988 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 989 | impl Parse for TokenStream { |
| 990 | fn parse(input: ParseStream) -> Result<Self> { |
| 991 | input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | impl Parse for TokenTree { |
| 996 | fn parse(input: ParseStream) -> Result<Self> { |
| 997 | input.step(|cursor| match cursor.token_tree() { |
| 998 | Some((tt, rest)) => Ok((tt, rest)), |
| 999 | None => Err(cursor.error("expected token tree")), |
| 1000 | }) |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | impl Parse for Group { |
| 1005 | fn parse(input: ParseStream) -> Result<Self> { |
| 1006 | input.step(|cursor| { |
| 1007 | for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] { |
| 1008 | if let Some((inside, span, rest)) = cursor.group(*delim) { |
| 1009 | let mut group = Group::new(*delim, inside.token_stream()); |
| 1010 | group.set_span(span); |
| 1011 | return Ok((group, rest)); |
| 1012 | } |
| 1013 | } |
| 1014 | Err(cursor.error("expected group token")) |
| 1015 | }) |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | impl Parse for Punct { |
| 1020 | fn parse(input: ParseStream) -> Result<Self> { |
| 1021 | input.step(|cursor| match cursor.punct() { |
| 1022 | Some((punct, rest)) => Ok((punct, rest)), |
| 1023 | None => Err(cursor.error("expected punctuation token")), |
| 1024 | }) |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | impl Parse for Literal { |
| 1029 | fn parse(input: ParseStream) -> Result<Self> { |
| 1030 | input.step(|cursor| match cursor.literal() { |
| 1031 | Some((literal, rest)) => Ok((literal, rest)), |
| 1032 | None => Err(cursor.error("expected literal token")), |
| 1033 | }) |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | /// Parser that can parse Rust tokens into a particular syntax tree node. |
| 1038 | /// |
| 1039 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 1040 | /// |
David Tolnay | b8dec88 | 2019-07-20 09:46:14 -0700 | [diff] [blame] | 1041 | /// [module documentation]: self |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1042 | /// |
| 1043 | /// *This trait is available if Syn is built with the `"parsing"` feature.* |
| 1044 | pub trait Parser: Sized { |
| 1045 | type Output; |
| 1046 | |
| 1047 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
Jethro Beekman | 33c2233 | 2018-12-31 11:16:25 +0530 | [diff] [blame] | 1048 | /// |
| 1049 | /// This function will check that the input is fully parsed. If there are |
| 1050 | /// any unparsed tokens at the end of the stream, an error is returned. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1051 | fn parse2(self, tokens: TokenStream) -> Result<Self::Output>; |
| 1052 | |
| 1053 | /// Parse tokens of source code into the chosen syntax tree node. |
| 1054 | /// |
Jethro Beekman | 33c2233 | 2018-12-31 11:16:25 +0530 | [diff] [blame] | 1055 | /// This function will check that the input is fully parsed. If there are |
| 1056 | /// any unparsed tokens at the end of the stream, an error is returned. |
| 1057 | /// |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1058 | /// *This method is available if Syn is built with both the `"parsing"` and |
| 1059 | /// `"proc-macro"` features.* |
| 1060 | #[cfg(all( |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1061 | not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1062 | feature = "proc-macro" |
| 1063 | ))] |
| 1064 | fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> { |
| 1065 | self.parse2(proc_macro2::TokenStream::from(tokens)) |
| 1066 | } |
| 1067 | |
| 1068 | /// Parse a string of Rust code into the chosen syntax tree node. |
| 1069 | /// |
Jethro Beekman | 33c2233 | 2018-12-31 11:16:25 +0530 | [diff] [blame] | 1070 | /// This function will check that the input is fully parsed. If there are |
| 1071 | /// any unparsed tokens at the end of the string, an error is returned. |
| 1072 | /// |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1073 | /// # Hygiene |
| 1074 | /// |
| 1075 | /// Every span in the resulting syntax tree will be set to resolve at the |
| 1076 | /// macro call site. |
| 1077 | fn parse_str(self, s: &str) -> Result<Self::Output> { |
| 1078 | self.parse2(proc_macro2::TokenStream::from_str(s)?) |
| 1079 | } |
David Tolnay | d639f61 | 2019-06-09 03:36:01 -0700 | [diff] [blame] | 1080 | |
| 1081 | // Not public API. |
| 1082 | #[doc(hidden)] |
| 1083 | fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { |
| 1084 | let _ = scope; |
| 1085 | self.parse2(tokens) |
| 1086 | } |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1087 | |
| 1088 | // Not public API. |
| 1089 | #[doc(hidden)] |
| 1090 | fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> { |
| 1091 | input.parse().and_then(|tokens| self.parse2(tokens)) |
| 1092 | } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1093 | } |
| 1094 | |
David Tolnay | 7b07aa1 | 2018-09-01 11:41:12 -0700 | [diff] [blame] | 1095 | fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer { |
| 1096 | let scope = Span::call_site(); |
| 1097 | let cursor = tokens.begin(); |
| 1098 | let unexpected = Rc::new(Cell::new(None)); |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1099 | new_parse_buffer(scope, cursor, unexpected) |
David Tolnay | 7b07aa1 | 2018-09-01 11:41:12 -0700 | [diff] [blame] | 1100 | } |
| 1101 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1102 | impl<F, T> Parser for F |
| 1103 | where |
| 1104 | F: FnOnce(ParseStream) -> Result<T>, |
| 1105 | { |
| 1106 | type Output = T; |
| 1107 | |
| 1108 | fn parse2(self, tokens: TokenStream) -> Result<T> { |
| 1109 | let buf = TokenBuffer::new2(tokens); |
David Tolnay | 7b07aa1 | 2018-09-01 11:41:12 -0700 | [diff] [blame] | 1110 | let state = tokens_to_parse_buffer(&buf); |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1111 | let node = self(&state)?; |
| 1112 | state.check_unexpected()?; |
| 1113 | if state.is_empty() { |
| 1114 | Ok(node) |
| 1115 | } else { |
| 1116 | Err(state.error("unexpected token")) |
| 1117 | } |
| 1118 | } |
David Tolnay | d639f61 | 2019-06-09 03:36:01 -0700 | [diff] [blame] | 1119 | |
| 1120 | #[doc(hidden)] |
| 1121 | fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> { |
| 1122 | let buf = TokenBuffer::new2(tokens); |
| 1123 | let cursor = buf.begin(); |
| 1124 | let unexpected = Rc::new(Cell::new(None)); |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1125 | let state = new_parse_buffer(scope, cursor, unexpected); |
David Tolnay | d639f61 | 2019-06-09 03:36:01 -0700 | [diff] [blame] | 1126 | let node = self(&state)?; |
| 1127 | state.check_unexpected()?; |
| 1128 | if state.is_empty() { |
| 1129 | Ok(node) |
| 1130 | } else { |
| 1131 | Err(state.error("unexpected token")) |
| 1132 | } |
| 1133 | } |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1134 | |
| 1135 | #[doc(hidden)] |
| 1136 | fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> { |
| 1137 | self(input) |
| 1138 | } |
David Tolnay | d639f61 | 2019-06-09 03:36:01 -0700 | [diff] [blame] | 1139 | } |
| 1140 | |
Chih-Hung Hsieh | 467ea21 | 2019-10-31 17:36:47 -0700 | [diff] [blame] | 1141 | pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> { |
| 1142 | f.__parse_scoped(scope, tokens) |
| 1143 | } |
| 1144 | |
| 1145 | pub(crate) fn parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Output> { |
| 1146 | f.__parse_stream(input) |
| 1147 | } |
| 1148 | |
| 1149 | /// An empty syntax tree node that consumes no tokens when parsed. |
| 1150 | /// |
| 1151 | /// This is useful for attribute macros that want to ensure they are not |
| 1152 | /// provided any attribute args. |
| 1153 | /// |
| 1154 | /// ``` |
| 1155 | /// extern crate proc_macro; |
| 1156 | /// |
| 1157 | /// use proc_macro::TokenStream; |
| 1158 | /// use syn::parse_macro_input; |
| 1159 | /// use syn::parse::Nothing; |
| 1160 | /// |
| 1161 | /// # const IGNORE: &str = stringify! { |
| 1162 | /// #[proc_macro_attribute] |
| 1163 | /// # }; |
| 1164 | /// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream { |
| 1165 | /// parse_macro_input!(args as Nothing); |
| 1166 | /// |
| 1167 | /// /* ... */ |
| 1168 | /// # "".parse().unwrap() |
| 1169 | /// } |
| 1170 | /// ``` |
| 1171 | /// |
| 1172 | /// ```text |
| 1173 | /// error: unexpected token |
| 1174 | /// --> src/main.rs:3:19 |
| 1175 | /// | |
| 1176 | /// 3 | #[my_attr(asdf)] |
| 1177 | /// | ^^^^ |
| 1178 | /// ``` |
| 1179 | pub struct Nothing; |
| 1180 | |
| 1181 | impl Parse for Nothing { |
| 1182 | fn parse(_input: ParseStream) -> Result<Self> { |
| 1183 | Ok(Nothing) |
David Tolnay | d639f61 | 2019-06-09 03:36:01 -0700 | [diff] [blame] | 1184 | } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1185 | } |