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