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