blob: 47b2a10cb78184258202b15fce55dabb63ff16d7 [file] [log] [blame]
David Tolnay18c754c2018-08-21 23:26:58 -04001//! Parsing interface for parsing a token stream into a syntax tree node.
2
3use std::cell::Cell;
4use std::fmt::Display;
5use std::marker::PhantomData;
6use std::mem;
7use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -04008use std::rc::Rc;
9
10use proc_macro2::{Ident, Span};
David Tolnay18c754c2018-08-21 23:26:58 -040011
David Tolnay6d67c742018-08-24 20:42:39 -040012use buffer::Cursor;
David Tolnayb6254182018-08-25 08:44:54 -040013use error;
David Tolnay577d0332018-08-25 21:45:24 -040014use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -040015use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -040016
David Tolnayb6254182018-08-25 08:44:54 -040017pub use error::{Error, Result};
18pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -040019
20/// Parsing interface implemented by all types that can be parsed in a default
21/// way from a token stream.
22pub trait Parse: Sized {
23 fn parse(input: ParseStream) -> Result<Self>;
24}
25
26/// Input to a Syn parser function.
27pub type ParseStream<'a> = &'a ParseBuffer<'a>;
28
29/// Cursor position within a buffered token stream.
David Tolnay18c754c2018-08-21 23:26:58 -040030pub struct ParseBuffer<'a> {
31 scope: Span,
32 cell: Cell<Cursor<'static>>,
33 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -040034 unexpected: Rc<Cell<Option<Span>>>,
35}
36
37impl<'a> Drop for ParseBuffer<'a> {
38 fn drop(&mut self) {
39 if !self.is_empty() && self.unexpected.get().is_none() {
40 self.unexpected.set(Some(self.cursor().span()));
41 }
42 }
David Tolnay18c754c2018-08-21 23:26:58 -040043}
44
45// Not public API.
46#[doc(hidden)]
47#[derive(Copy, Clone)]
48pub struct StepCursor<'c, 'a> {
49 scope: Span,
50 cursor: Cursor<'c>,
51 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
52}
53
54impl<'c, 'a> Deref for StepCursor<'c, 'a> {
55 type Target = Cursor<'c>;
56
57 fn deref(&self) -> &Self::Target {
58 &self.cursor
59 }
60}
61
62impl<'c, 'a> StepCursor<'c, 'a> {
63 // Not public API.
64 #[doc(hidden)]
65 pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
66 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
67 }
68
David Tolnay18c754c2018-08-21 23:26:58 -040069 pub fn error<T: Display>(self, message: T) -> Error {
70 error::new_at(self.scope, self.cursor, message)
71 }
72}
73
74impl<'a> ParseBuffer<'a> {
75 // Not public API.
76 #[doc(hidden)]
David Tolnayeafc8052018-08-25 16:33:53 -040077 pub fn new(scope: Span, cursor: Cursor<'a>, unexpected: Rc<Cell<Option<Span>>>) -> Self {
David Tolnay18c754c2018-08-21 23:26:58 -040078 let extend = unsafe { mem::transmute::<Cursor<'a>, Cursor<'static>>(cursor) };
79 ParseBuffer {
80 scope: scope,
81 cell: Cell::new(extend),
82 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -040083 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -040084 }
85 }
86
87 pub fn cursor(&self) -> Cursor<'a> {
88 self.cell.get()
89 }
90
91 pub fn is_empty(&self) -> bool {
92 self.cursor().eof()
93 }
94
95 pub fn lookahead1(&self) -> Lookahead1<'a> {
96 Lookahead1::new(self.scope, self.cursor())
97 }
98
99 pub fn parse<T: Parse>(&self) -> Result<T> {
David Tolnayeafc8052018-08-25 16:33:53 -0400100 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400101 T::parse(self)
102 }
103
David Tolnay3a515a02018-08-25 21:08:27 -0400104 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
105 function(self)
106 }
107
David Tolnayb77c8b62018-08-25 16:39:41 -0400108 pub fn peek<T: Peek>(&self, token: T) -> bool {
109 self.lookahead1().peek(token)
110 }
111
David Tolnay4fb71232018-08-25 23:14:50 -0400112 pub fn peek2<T: Peek>(&self, token: T) -> bool {
113 if self.is_empty() {
114 return false;
115 }
116 let ahead = self.fork();
David Tolnaya7d69fc2018-08-26 13:30:24 -0400117 ahead
David Tolnayb50c65a2018-08-30 21:14:57 -0700118 .step(|cursor| Ok(cursor.token_tree().unwrap()))
David Tolnaya7d69fc2018-08-26 13:30:24 -0400119 .unwrap();
David Tolnay4fb71232018-08-25 23:14:50 -0400120 ahead.peek(token)
121 }
122
123 pub fn peek3<T: Peek>(&self, token: T) -> bool {
124 if self.is_empty() {
125 return false;
126 }
127 let ahead = self.fork();
David Tolnaya7d69fc2018-08-26 13:30:24 -0400128 ahead
David Tolnayb50c65a2018-08-30 21:14:57 -0700129 .step(|cursor| Ok(cursor.token_tree().unwrap()))
David Tolnaya7d69fc2018-08-26 13:30:24 -0400130 .unwrap();
131 ahead
David Tolnayb50c65a2018-08-30 21:14:57 -0700132 .step(|cursor| Ok(cursor.token_tree().unwrap()))
David Tolnaya7d69fc2018-08-26 13:30:24 -0400133 .unwrap();
David Tolnay4fb71232018-08-25 23:14:50 -0400134 ahead.peek(token)
135 }
136
David Tolnay577d0332018-08-25 21:45:24 -0400137 pub fn parse_terminated<T, P: Parse>(
138 &self,
139 parser: fn(ParseStream) -> Result<T>,
140 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700141 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400142 }
143
David Tolnayb77c8b62018-08-25 16:39:41 -0400144 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400145 ParseBuffer {
146 scope: self.scope,
147 cell: self.cell.clone(),
148 marker: PhantomData,
149 // Not the parent's unexpected. Nothing cares whether the clone
150 // parses all the way.
151 unexpected: Rc::new(Cell::new(None)),
152 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400153 }
154
David Tolnay4fb71232018-08-25 23:14:50 -0400155 pub fn error<T: Display>(&self, message: T) -> Error {
156 error::new_at(self.scope, self.cursor(), message)
157 }
158
David Tolnayb50c65a2018-08-30 21:14:57 -0700159 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400160 where
161 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
162 {
David Tolnayeafc8052018-08-25 16:33:53 -0400163 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400164 match function(StepCursor {
165 scope: self.scope,
166 cursor: self.cell.get(),
167 marker: PhantomData,
168 }) {
169 Ok((ret, cursor)) => {
170 self.cell.set(cursor);
171 Ok(ret)
172 }
173 Err(err) => Err(err),
174 }
175 }
David Tolnayeafc8052018-08-25 16:33:53 -0400176
177 // Not public API.
178 #[doc(hidden)]
179 pub fn get_unexpected(&self) -> Rc<Cell<Option<Span>>> {
180 self.unexpected.clone()
181 }
182
183 // Not public API.
184 #[doc(hidden)]
185 pub fn check_unexpected(&self) -> Result<()> {
186 match self.unexpected.get() {
187 Some(span) => Err(Error::new(span, "unexpected token")),
188 None => Ok(()),
189 }
190 }
David Tolnay18c754c2018-08-21 23:26:58 -0400191}
192
193impl Parse for Ident {
194 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700195 input.step(|cursor| {
David Tolnay18c754c2018-08-21 23:26:58 -0400196 if let Some((ident, rest)) = cursor.ident() {
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400197 match ident.to_string().as_str() {
198 "_"
199 // Based on https://doc.rust-lang.org/grammar.html#keywords
200 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
201 | "abstract" | "as" | "become" | "box" | "break" | "const"
202 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
203 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
204 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
205 | "ref" | "return" | "Self" | "self" | "static" | "struct"
206 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
207 | "virtual" | "where" | "while" | "yield" => {}
208 _ => return Ok((ident, rest)),
209 }
David Tolnay18c754c2018-08-21 23:26:58 -0400210 }
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400211 Err(cursor.error("expected identifier"))
David Tolnay18c754c2018-08-21 23:26:58 -0400212 })
213 }
214}
215
David Tolnaya7d69fc2018-08-26 13:30:24 -0400216impl<T: Parse> Parse for Box<T> {
217 fn parse(input: ParseStream) -> Result<Self> {
218 input.parse().map(Box::new)
219 }
220}
221
David Tolnay4fb71232018-08-25 23:14:50 -0400222impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400223 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4fb71232018-08-25 23:14:50 -0400224 if T::peek(&input.lookahead1()) {
225 Ok(Some(input.parse()?))
226 } else {
227 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400228 }
David Tolnay18c754c2018-08-21 23:26:58 -0400229 }
230}