blob: 64f972d6a73cce12927e0dd5bab1ed23bf92dce3 [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 Tolnayb77c8b62018-08-25 16:39:41 -040015use synom::PResult;
David Tolnay4fb71232018-08-25 23:14:50 -040016use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -040017
David Tolnayb6254182018-08-25 08:44:54 -040018pub use error::{Error, Result};
19pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -040020
21/// Parsing interface implemented by all types that can be parsed in a default
22/// way from a token stream.
23pub trait Parse: Sized {
24 fn parse(input: ParseStream) -> Result<Self>;
25}
26
27/// Input to a Syn parser function.
28pub type ParseStream<'a> = &'a ParseBuffer<'a>;
29
30/// Cursor position within a buffered token stream.
David Tolnay18c754c2018-08-21 23:26:58 -040031pub struct ParseBuffer<'a> {
32 scope: Span,
33 cell: Cell<Cursor<'static>>,
34 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -040035 unexpected: Rc<Cell<Option<Span>>>,
36}
37
38impl<'a> Drop for ParseBuffer<'a> {
39 fn drop(&mut self) {
40 if !self.is_empty() && self.unexpected.get().is_none() {
41 self.unexpected.set(Some(self.cursor().span()));
42 }
43 }
David Tolnay18c754c2018-08-21 23:26:58 -040044}
45
46// Not public API.
47#[doc(hidden)]
48#[derive(Copy, Clone)]
49pub struct StepCursor<'c, 'a> {
50 scope: Span,
51 cursor: Cursor<'c>,
52 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
53}
54
55impl<'c, 'a> Deref for StepCursor<'c, 'a> {
56 type Target = Cursor<'c>;
57
58 fn deref(&self) -> &Self::Target {
59 &self.cursor
60 }
61}
62
63impl<'c, 'a> StepCursor<'c, 'a> {
64 // Not public API.
65 #[doc(hidden)]
66 pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
67 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
68 }
69
David Tolnay18c754c2018-08-21 23:26:58 -040070 pub fn error<T: Display>(self, message: T) -> Error {
71 error::new_at(self.scope, self.cursor, message)
72 }
73}
74
75impl<'a> ParseBuffer<'a> {
76 // Not public API.
77 #[doc(hidden)]
David Tolnayeafc8052018-08-25 16:33:53 -040078 pub fn new(scope: Span, cursor: Cursor<'a>, unexpected: Rc<Cell<Option<Span>>>) -> Self {
David Tolnay18c754c2018-08-21 23:26:58 -040079 let extend = unsafe { mem::transmute::<Cursor<'a>, Cursor<'static>>(cursor) };
80 ParseBuffer {
81 scope: scope,
82 cell: Cell::new(extend),
83 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -040084 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -040085 }
86 }
87
88 pub fn cursor(&self) -> Cursor<'a> {
89 self.cell.get()
90 }
91
92 pub fn is_empty(&self) -> bool {
93 self.cursor().eof()
94 }
95
96 pub fn lookahead1(&self) -> Lookahead1<'a> {
97 Lookahead1::new(self.scope, self.cursor())
98 }
99
100 pub fn parse<T: Parse>(&self) -> Result<T> {
David Tolnayeafc8052018-08-25 16:33:53 -0400101 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400102 T::parse(self)
103 }
104
David Tolnay3a515a02018-08-25 21:08:27 -0400105 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
106 function(self)
107 }
108
David Tolnayb77c8b62018-08-25 16:39:41 -0400109 pub fn peek<T: Peek>(&self, token: T) -> bool {
110 self.lookahead1().peek(token)
111 }
112
David Tolnay4fb71232018-08-25 23:14:50 -0400113 pub fn peek2<T: Peek>(&self, token: T) -> bool {
114 if self.is_empty() {
115 return false;
116 }
117 let ahead = self.fork();
David Tolnaya7d69fc2018-08-26 13:30:24 -0400118 ahead
119 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
120 .unwrap();
David Tolnay4fb71232018-08-25 23:14:50 -0400121 ahead.peek(token)
122 }
123
124 pub fn peek3<T: Peek>(&self, token: T) -> bool {
125 if self.is_empty() {
126 return false;
127 }
128 let ahead = self.fork();
David Tolnaya7d69fc2018-08-26 13:30:24 -0400129 ahead
130 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
131 .unwrap();
132 ahead
133 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
134 .unwrap();
David Tolnay4fb71232018-08-25 23:14:50 -0400135 ahead.peek(token)
136 }
137
David Tolnay577d0332018-08-25 21:45:24 -0400138 pub fn parse_terminated<T, P: Parse>(
139 &self,
140 parser: fn(ParseStream) -> Result<T>,
141 ) -> Result<Punctuated<T, P>> {
142 Punctuated::parse_terminated2(self, parser)
143 }
144
David Tolnayb77c8b62018-08-25 16:39:41 -0400145 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400146 ParseBuffer {
147 scope: self.scope,
148 cell: self.cell.clone(),
149 marker: PhantomData,
150 // Not the parent's unexpected. Nothing cares whether the clone
151 // parses all the way.
152 unexpected: Rc::new(Cell::new(None)),
153 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400154 }
155
David Tolnay4fb71232018-08-25 23:14:50 -0400156 pub fn error<T: Display>(&self, message: T) -> Error {
157 error::new_at(self.scope, self.cursor(), message)
158 }
159
David Tolnay18c754c2018-08-21 23:26:58 -0400160 // Not public API.
161 #[doc(hidden)]
162 pub fn step_cursor<F, R>(&self, function: F) -> Result<R>
163 where
164 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
165 {
David Tolnayeafc8052018-08-25 16:33:53 -0400166 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400167 match function(StepCursor {
168 scope: self.scope,
169 cursor: self.cell.get(),
170 marker: PhantomData,
171 }) {
172 Ok((ret, cursor)) => {
173 self.cell.set(cursor);
174 Ok(ret)
175 }
176 Err(err) => Err(err),
177 }
178 }
David Tolnayeafc8052018-08-25 16:33:53 -0400179
180 // Not public API.
181 #[doc(hidden)]
David Tolnayb77c8b62018-08-25 16:39:41 -0400182 pub fn parse_synom<T>(&self, parse: fn(Cursor) -> PResult<T>) -> Result<T> {
183 self.step_cursor(|step| parse(step.cursor))
184 }
185
186 // Not public API.
187 #[doc(hidden)]
David Tolnayeafc8052018-08-25 16:33:53 -0400188 pub fn get_unexpected(&self) -> Rc<Cell<Option<Span>>> {
189 self.unexpected.clone()
190 }
191
192 // Not public API.
193 #[doc(hidden)]
194 pub fn check_unexpected(&self) -> Result<()> {
195 match self.unexpected.get() {
196 Some(span) => Err(Error::new(span, "unexpected token")),
197 None => Ok(()),
198 }
199 }
David Tolnay18c754c2018-08-21 23:26:58 -0400200}
201
202impl Parse for Ident {
203 fn parse(input: ParseStream) -> Result<Self> {
204 input.step_cursor(|cursor| {
205 if let Some((ident, rest)) = cursor.ident() {
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400206 match ident.to_string().as_str() {
207 "_"
208 // Based on https://doc.rust-lang.org/grammar.html#keywords
209 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
210 | "abstract" | "as" | "become" | "box" | "break" | "const"
211 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
212 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
213 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
214 | "ref" | "return" | "Self" | "self" | "static" | "struct"
215 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
216 | "virtual" | "where" | "while" | "yield" => {}
217 _ => return Ok((ident, rest)),
218 }
David Tolnay18c754c2018-08-21 23:26:58 -0400219 }
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400220 Err(cursor.error("expected identifier"))
David Tolnay18c754c2018-08-21 23:26:58 -0400221 })
222 }
223}
224
David Tolnaya7d69fc2018-08-26 13:30:24 -0400225impl<T: Parse> Parse for Box<T> {
226 fn parse(input: ParseStream) -> Result<Self> {
227 input.parse().map(Box::new)
228 }
229}
230
David Tolnay4fb71232018-08-25 23:14:50 -0400231impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400232 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4fb71232018-08-25 23:14:50 -0400233 if T::peek(&input.lookahead1()) {
234 Ok(Some(input.parse()?))
235 } else {
236 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400237 }
David Tolnay18c754c2018-08-21 23:26:58 -0400238 }
239}