blob: 0570e2d6278ad109e17223eaea9a0350b39081de [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
118 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
119 .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
129 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
130 .unwrap();
131 ahead
132 .step_cursor(|cursor| Ok(cursor.token_tree().unwrap()))
133 .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 Tolnay18c754c2018-08-21 23:26:58 -0400159 // Not public API.
160 #[doc(hidden)]
161 pub fn step_cursor<F, R>(&self, function: F) -> Result<R>
162 where
163 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
164 {
David Tolnayeafc8052018-08-25 16:33:53 -0400165 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400166 match function(StepCursor {
167 scope: self.scope,
168 cursor: self.cell.get(),
169 marker: PhantomData,
170 }) {
171 Ok((ret, cursor)) => {
172 self.cell.set(cursor);
173 Ok(ret)
174 }
175 Err(err) => Err(err),
176 }
177 }
David Tolnayeafc8052018-08-25 16:33:53 -0400178
179 // Not public API.
180 #[doc(hidden)]
181 pub fn get_unexpected(&self) -> Rc<Cell<Option<Span>>> {
182 self.unexpected.clone()
183 }
184
185 // Not public API.
186 #[doc(hidden)]
187 pub fn check_unexpected(&self) -> Result<()> {
188 match self.unexpected.get() {
189 Some(span) => Err(Error::new(span, "unexpected token")),
190 None => Ok(()),
191 }
192 }
David Tolnay18c754c2018-08-21 23:26:58 -0400193}
194
195impl Parse for Ident {
196 fn parse(input: ParseStream) -> Result<Self> {
197 input.step_cursor(|cursor| {
198 if let Some((ident, rest)) = cursor.ident() {
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400199 match ident.to_string().as_str() {
200 "_"
201 // Based on https://doc.rust-lang.org/grammar.html#keywords
202 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
203 | "abstract" | "as" | "become" | "box" | "break" | "const"
204 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
205 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
206 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
207 | "ref" | "return" | "Self" | "self" | "static" | "struct"
208 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
209 | "virtual" | "where" | "while" | "yield" => {}
210 _ => return Ok((ident, rest)),
211 }
David Tolnay18c754c2018-08-21 23:26:58 -0400212 }
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400213 Err(cursor.error("expected identifier"))
David Tolnay18c754c2018-08-21 23:26:58 -0400214 })
215 }
216}
217
David Tolnaya7d69fc2018-08-26 13:30:24 -0400218impl<T: Parse> Parse for Box<T> {
219 fn parse(input: ParseStream) -> Result<Self> {
220 input.parse().map(Box::new)
221 }
222}
223
David Tolnay4fb71232018-08-25 23:14:50 -0400224impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400225 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4fb71232018-08-25 23:14:50 -0400226 if T::peek(&input.lookahead1()) {
227 Ok(Some(input.parse()?))
228 } else {
229 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400230 }
David Tolnay18c754c2018-08-21 23:26:58 -0400231 }
232}