blob: c833bb79a8adea42adb6b67265cc928120a5c4e0 [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
David Tolnaya8e29032018-08-25 17:14:31 -040046impl<'a> Clone for ParseBuffer<'a> {
47 fn clone(&self) -> Self {
48 ParseBuffer {
49 scope: self.scope,
50 cell: self.cell.clone(),
51 marker: PhantomData,
52 // Not the parent's unexpected. Nothing cares whether the clone
53 // parses all the way.
54 unexpected: Rc::new(Cell::new(None)),
55 }
56 }
57}
58
David Tolnay18c754c2018-08-21 23:26:58 -040059// Not public API.
60#[doc(hidden)]
61#[derive(Copy, Clone)]
62pub struct StepCursor<'c, 'a> {
63 scope: Span,
64 cursor: Cursor<'c>,
65 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
66}
67
68impl<'c, 'a> Deref for StepCursor<'c, 'a> {
69 type Target = Cursor<'c>;
70
71 fn deref(&self) -> &Self::Target {
72 &self.cursor
73 }
74}
75
76impl<'c, 'a> StepCursor<'c, 'a> {
77 // Not public API.
78 #[doc(hidden)]
79 pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
80 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
81 }
82
David Tolnay18c754c2018-08-21 23:26:58 -040083 pub fn error<T: Display>(self, message: T) -> Error {
84 error::new_at(self.scope, self.cursor, message)
85 }
86}
87
88impl<'a> ParseBuffer<'a> {
89 // Not public API.
90 #[doc(hidden)]
David Tolnayeafc8052018-08-25 16:33:53 -040091 pub fn new(scope: Span, cursor: Cursor<'a>, unexpected: Rc<Cell<Option<Span>>>) -> Self {
David Tolnay18c754c2018-08-21 23:26:58 -040092 let extend = unsafe { mem::transmute::<Cursor<'a>, Cursor<'static>>(cursor) };
93 ParseBuffer {
94 scope: scope,
95 cell: Cell::new(extend),
96 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -040097 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -040098 }
99 }
100
101 pub fn cursor(&self) -> Cursor<'a> {
102 self.cell.get()
103 }
104
105 pub fn is_empty(&self) -> bool {
106 self.cursor().eof()
107 }
108
109 pub fn lookahead1(&self) -> Lookahead1<'a> {
110 Lookahead1::new(self.scope, self.cursor())
111 }
112
113 pub fn parse<T: Parse>(&self) -> Result<T> {
David Tolnayeafc8052018-08-25 16:33:53 -0400114 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400115 T::parse(self)
116 }
117
David Tolnay3a515a02018-08-25 21:08:27 -0400118 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
119 function(self)
120 }
121
David Tolnayb77c8b62018-08-25 16:39:41 -0400122 pub fn peek<T: Peek>(&self, token: T) -> bool {
123 self.lookahead1().peek(token)
124 }
125
David Tolnay4fb71232018-08-25 23:14:50 -0400126 pub fn peek2<T: Peek>(&self, token: T) -> bool {
127 if self.is_empty() {
128 return false;
129 }
130 let ahead = self.fork();
131 ahead.step_cursor(|cursor| Ok(cursor.token_tree().unwrap())).unwrap();
132 ahead.peek(token)
133 }
134
135 pub fn peek3<T: Peek>(&self, token: T) -> bool {
136 if self.is_empty() {
137 return false;
138 }
139 let ahead = self.fork();
140 ahead.step_cursor(|cursor| Ok(cursor.token_tree().unwrap())).unwrap();
141 ahead.step_cursor(|cursor| Ok(cursor.token_tree().unwrap())).unwrap();
142 ahead.peek(token)
143 }
144
David Tolnay577d0332018-08-25 21:45:24 -0400145 pub fn parse_terminated<T, P: Parse>(
146 &self,
147 parser: fn(ParseStream) -> Result<T>,
148 ) -> Result<Punctuated<T, P>> {
149 Punctuated::parse_terminated2(self, parser)
150 }
151
David Tolnayb77c8b62018-08-25 16:39:41 -0400152 pub fn fork(&self) -> Self {
153 self.clone()
154 }
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 Tolnay4fb71232018-08-25 23:14:50 -0400225impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400226 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4fb71232018-08-25 23:14:50 -0400227 if T::peek(&input.lookahead1()) {
228 Ok(Some(input.parse()?))
229 } else {
230 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400231 }
David Tolnay18c754c2018-08-21 23:26:58 -0400232 }
233}