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 | //! ``` |
| 81 | //! # #[macro_use] |
| 82 | //! # extern crate syn; |
| 83 | //! # |
| 84 | //! # extern crate proc_macro2; |
| 85 | //! # use proc_macro2::TokenStream; |
| 86 | //! # |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 87 | //! use syn::parse::Parser; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 88 | //! use syn::punctuated::Punctuated; |
| 89 | //! use syn::{PathSegment, Expr, Attribute}; |
| 90 | //! |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 91 | //! # fn run_parsers() -> Result<(), syn::parse::Error> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 92 | //! # let tokens = TokenStream::new().into(); |
| 93 | //! // Parse a nonempty sequence of path segments separated by `::` punctuation |
| 94 | //! // with no trailing punctuation. |
| 95 | //! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; |
| 96 | //! let path = parser.parse(tokens)?; |
| 97 | //! |
| 98 | //! # let tokens = TokenStream::new().into(); |
| 99 | //! // Parse a possibly empty sequence of expressions terminated by commas with |
| 100 | //! // an optional trailing punctuation. |
| 101 | //! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; |
| 102 | //! let args = parser.parse(tokens)?; |
| 103 | //! |
| 104 | //! # let tokens = TokenStream::new().into(); |
| 105 | //! // Parse zero or more outer attributes but not inner attributes. |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 106 | //! let parser = Attribute::parse_outer; |
| 107 | //! let attrs = parser.parse(tokens)?; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 108 | //! # |
| 109 | //! # Ok(()) |
| 110 | //! # } |
| 111 | //! # |
| 112 | //! # fn main() {} |
| 113 | //! ``` |
| 114 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 115 | //! --- |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 116 | //! |
| 117 | //! *This module is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 118 | |
| 119 | use std::cell::Cell; |
| 120 | use std::fmt::Display; |
| 121 | use std::marker::PhantomData; |
| 122 | use std::mem; |
| 123 | use std::ops::Deref; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 124 | use std::rc::Rc; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 125 | use std::str::FromStr; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 126 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 127 | #[cfg(all( |
| 128 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 129 | feature = "proc-macro" |
| 130 | ))] |
| 131 | use proc_macro; |
| 132 | use proc_macro2::{self, Delimiter, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 133 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 134 | use buffer::{Cursor, TokenBuffer}; |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 135 | use error; |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 136 | use lookahead; |
| 137 | use private; |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 138 | use punctuated::Punctuated; |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 139 | use token::Token; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 140 | |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 141 | pub use error::{Error, Result}; |
| 142 | pub use lookahead::{Lookahead1, Peek}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 143 | |
| 144 | /// Parsing interface implemented by all types that can be parsed in a default |
| 145 | /// way from a token stream. |
| 146 | pub trait Parse: Sized { |
| 147 | fn parse(input: ParseStream) -> Result<Self>; |
| 148 | } |
| 149 | |
| 150 | /// Input to a Syn parser function. |
David Tolnay | a0daa48 | 2018-09-01 02:09:40 -0700 | [diff] [blame] | 151 | /// |
| 152 | /// See the methods of this type under the documentation of [`ParseBuffer`]. For |
| 153 | /// an overview of parsing in Syn, refer to the [module documentation]. |
| 154 | /// |
| 155 | /// [module documentation]: index.html |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 156 | pub type ParseStream<'a> = &'a ParseBuffer<'a>; |
| 157 | |
| 158 | /// Cursor position within a buffered token stream. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 159 | pub struct ParseBuffer<'a> { |
| 160 | scope: Span, |
| 161 | cell: Cell<Cursor<'static>>, |
| 162 | marker: PhantomData<Cursor<'a>>, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 163 | unexpected: Rc<Cell<Option<Span>>>, |
| 164 | } |
| 165 | |
| 166 | impl<'a> Drop for ParseBuffer<'a> { |
| 167 | fn drop(&mut self) { |
| 168 | if !self.is_empty() && self.unexpected.get().is_none() { |
| 169 | self.unexpected.set(Some(self.cursor().span())); |
| 170 | } |
| 171 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 172 | } |
| 173 | |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 174 | #[derive(Copy, Clone)] |
| 175 | pub struct StepCursor<'c, 'a> { |
| 176 | scope: Span, |
| 177 | cursor: Cursor<'c>, |
| 178 | marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>, |
| 179 | } |
| 180 | |
| 181 | impl<'c, 'a> Deref for StepCursor<'c, 'a> { |
| 182 | type Target = Cursor<'c>; |
| 183 | |
| 184 | fn deref(&self) -> &Self::Target { |
| 185 | &self.cursor |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl<'c, 'a> StepCursor<'c, 'a> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 190 | pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> { |
| 191 | unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) } |
| 192 | } |
| 193 | |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 194 | pub fn error<T: Display>(self, message: T) -> Error { |
| 195 | error::new_at(self.scope, self.cursor, message) |
| 196 | } |
| 197 | } |
| 198 | |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 199 | fn skip(input: ParseStream) -> bool { |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 200 | input |
| 201 | .step(|cursor| { |
| 202 | if let Some((_lifetime, rest)) = cursor.lifetime() { |
| 203 | Ok((true, rest)) |
| 204 | } else if let Some((_token, rest)) = cursor.token_tree() { |
| 205 | Ok((true, rest)) |
| 206 | } else { |
| 207 | Ok((false, *cursor)) |
| 208 | } |
| 209 | }).unwrap() |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 210 | } |
| 211 | |
David Tolnay | 10951d5 | 2018-08-31 10:27:39 -0700 | [diff] [blame] | 212 | impl private { |
David Tolnay | 70f30e9 | 2018-09-01 02:04:17 -0700 | [diff] [blame] | 213 | pub fn new_parse_buffer( |
| 214 | scope: Span, |
| 215 | cursor: Cursor, |
| 216 | unexpected: Rc<Cell<Option<Span>>>, |
| 217 | ) -> ParseBuffer { |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 218 | let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 219 | ParseBuffer { |
| 220 | scope: scope, |
| 221 | cell: Cell::new(extend), |
| 222 | marker: PhantomData, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 223 | unexpected: unexpected, |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 224 | } |
| 225 | } |
| 226 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 227 | pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { |
| 228 | buffer.unexpected.clone() |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | impl<'a> ParseBuffer<'a> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 233 | pub fn parse<T: Parse>(&self) -> Result<T> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 234 | self.check_unexpected()?; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 235 | T::parse(self) |
| 236 | } |
| 237 | |
David Tolnay | 3a515a0 | 2018-08-25 21:08:27 -0400 | [diff] [blame] | 238 | pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> { |
| 239 | function(self) |
| 240 | } |
| 241 | |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 242 | pub fn peek<T: Peek>(&self, token: T) -> bool { |
| 243 | self.lookahead1().peek(token) |
| 244 | } |
| 245 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 246 | pub fn peek2<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 247 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 248 | skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 249 | } |
| 250 | |
| 251 | pub fn peek3<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 252 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 253 | skip(&ahead) && skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 254 | } |
| 255 | |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 256 | pub fn parse_terminated<T, P: Parse>( |
| 257 | &self, |
| 258 | parser: fn(ParseStream) -> Result<T>, |
| 259 | ) -> Result<Punctuated<T, P>> { |
David Tolnay | d0f8021 | 2018-08-30 18:32:14 -0700 | [diff] [blame] | 260 | Punctuated::parse_terminated_with(self, parser) |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 261 | } |
| 262 | |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame^] | 263 | pub fn is_empty(&self) -> bool { |
| 264 | self.cursor().eof() |
| 265 | } |
| 266 | |
| 267 | pub fn lookahead1(&self) -> Lookahead1<'a> { |
| 268 | lookahead::new(self.scope, self.cursor()) |
| 269 | } |
| 270 | |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 271 | pub fn fork(&self) -> Self { |
David Tolnay | 6456a9d | 2018-08-26 08:11:18 -0400 | [diff] [blame] | 272 | ParseBuffer { |
| 273 | scope: self.scope, |
| 274 | cell: self.cell.clone(), |
| 275 | marker: PhantomData, |
| 276 | // Not the parent's unexpected. Nothing cares whether the clone |
| 277 | // parses all the way. |
| 278 | unexpected: Rc::new(Cell::new(None)), |
| 279 | } |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 280 | } |
| 281 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 282 | pub fn error<T: Display>(&self, message: T) -> Error { |
| 283 | error::new_at(self.scope, self.cursor(), message) |
| 284 | } |
| 285 | |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 286 | pub fn step<F, R>(&self, function: F) -> Result<R> |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 287 | where |
| 288 | F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>, |
| 289 | { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 290 | self.check_unexpected()?; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 291 | match function(StepCursor { |
| 292 | scope: self.scope, |
| 293 | cursor: self.cell.get(), |
| 294 | marker: PhantomData, |
| 295 | }) { |
| 296 | Ok((ret, cursor)) => { |
| 297 | self.cell.set(cursor); |
| 298 | Ok(ret) |
| 299 | } |
| 300 | Err(err) => Err(err), |
| 301 | } |
| 302 | } |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 303 | |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame^] | 304 | pub fn cursor(&self) -> Cursor<'a> { |
| 305 | self.cell.get() |
| 306 | } |
| 307 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 308 | fn check_unexpected(&self) -> Result<()> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 309 | match self.unexpected.get() { |
| 310 | Some(span) => Err(Error::new(span, "unexpected token")), |
| 311 | None => Ok(()), |
| 312 | } |
| 313 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 314 | } |
| 315 | |
| 316 | impl Parse for Ident { |
| 317 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 318 | input.step(|cursor| { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 319 | if let Some((ident, rest)) = cursor.ident() { |
David Tolnay | c4fdb1a | 2018-08-24 21:11:07 -0400 | [diff] [blame] | 320 | match ident.to_string().as_str() { |
| 321 | "_" |
| 322 | // Based on https://doc.rust-lang.org/grammar.html#keywords |
| 323 | // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md |
| 324 | | "abstract" | "as" | "become" | "box" | "break" | "const" |
| 325 | | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" |
| 326 | | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" |
| 327 | | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub" |
| 328 | | "ref" | "return" | "Self" | "self" | "static" | "struct" |
| 329 | | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" |
| 330 | | "virtual" | "where" | "while" | "yield" => {} |
| 331 | _ => return Ok((ident, rest)), |
| 332 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 333 | } |
David Tolnay | c4fdb1a | 2018-08-24 21:11:07 -0400 | [diff] [blame] | 334 | Err(cursor.error("expected identifier")) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 335 | }) |
| 336 | } |
| 337 | } |
| 338 | |
David Tolnay | a7d69fc | 2018-08-26 13:30:24 -0400 | [diff] [blame] | 339 | impl<T: Parse> Parse for Box<T> { |
| 340 | fn parse(input: ParseStream) -> Result<Self> { |
| 341 | input.parse().map(Box::new) |
| 342 | } |
| 343 | } |
| 344 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 345 | impl<T: Parse + Token> Parse for Option<T> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 346 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 347 | if T::peek(&input.lookahead1()) { |
| 348 | Ok(Some(input.parse()?)) |
| 349 | } else { |
| 350 | Ok(None) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 351 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 352 | } |
| 353 | } |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 354 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 355 | impl Parse for TokenStream { |
| 356 | fn parse(input: ParseStream) -> Result<Self> { |
| 357 | input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | impl Parse for TokenTree { |
| 362 | fn parse(input: ParseStream) -> Result<Self> { |
| 363 | input.step(|cursor| match cursor.token_tree() { |
| 364 | Some((tt, rest)) => Ok((tt, rest)), |
| 365 | None => Err(cursor.error("expected token tree")), |
| 366 | }) |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | impl Parse for Group { |
| 371 | fn parse(input: ParseStream) -> Result<Self> { |
| 372 | input.step(|cursor| { |
| 373 | for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] { |
| 374 | if let Some((inside, span, rest)) = cursor.group(*delim) { |
| 375 | let mut group = Group::new(*delim, inside.token_stream()); |
| 376 | group.set_span(span); |
| 377 | return Ok((group, rest)); |
| 378 | } |
| 379 | } |
| 380 | Err(cursor.error("expected group token")) |
| 381 | }) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | impl Parse for Punct { |
| 386 | fn parse(input: ParseStream) -> Result<Self> { |
| 387 | input.step(|cursor| match cursor.punct() { |
| 388 | Some((punct, rest)) => Ok((punct, rest)), |
| 389 | None => Err(cursor.error("expected punctuation token")), |
| 390 | }) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | impl Parse for Literal { |
| 395 | fn parse(input: ParseStream) -> Result<Self> { |
| 396 | input.step(|cursor| match cursor.literal() { |
| 397 | Some((literal, rest)) => Ok((literal, rest)), |
| 398 | None => Err(cursor.error("expected literal token")), |
| 399 | }) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// Parser that can parse Rust tokens into a particular syntax tree node. |
| 404 | /// |
| 405 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 406 | /// |
| 407 | /// [module documentation]: index.html |
| 408 | /// |
| 409 | /// *This trait is available if Syn is built with the `"parsing"` feature.* |
| 410 | pub trait Parser: Sized { |
| 411 | type Output; |
| 412 | |
| 413 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
| 414 | fn parse2(self, tokens: TokenStream) -> Result<Self::Output>; |
| 415 | |
| 416 | /// Parse tokens of source code into the chosen syntax tree node. |
| 417 | /// |
| 418 | /// *This method is available if Syn is built with both the `"parsing"` and |
| 419 | /// `"proc-macro"` features.* |
| 420 | #[cfg(all( |
| 421 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 422 | feature = "proc-macro" |
| 423 | ))] |
| 424 | fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> { |
| 425 | self.parse2(proc_macro2::TokenStream::from(tokens)) |
| 426 | } |
| 427 | |
| 428 | /// Parse a string of Rust code into the chosen syntax tree node. |
| 429 | /// |
| 430 | /// # Hygiene |
| 431 | /// |
| 432 | /// Every span in the resulting syntax tree will be set to resolve at the |
| 433 | /// macro call site. |
| 434 | fn parse_str(self, s: &str) -> Result<Self::Output> { |
| 435 | self.parse2(proc_macro2::TokenStream::from_str(s)?) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | impl<F, T> Parser for F |
| 440 | where |
| 441 | F: FnOnce(ParseStream) -> Result<T>, |
| 442 | { |
| 443 | type Output = T; |
| 444 | |
| 445 | fn parse2(self, tokens: TokenStream) -> Result<T> { |
| 446 | let buf = TokenBuffer::new2(tokens); |
| 447 | let unexpected = Rc::new(Cell::new(None)); |
David Tolnay | 10951d5 | 2018-08-31 10:27:39 -0700 | [diff] [blame] | 448 | let state = private::new_parse_buffer(Span::call_site(), buf.begin(), unexpected); |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 449 | let node = self(&state)?; |
| 450 | state.check_unexpected()?; |
| 451 | if state.is_empty() { |
| 452 | Ok(node) |
| 453 | } else { |
| 454 | Err(state.error("unexpected token")) |
| 455 | } |
| 456 | } |
| 457 | } |