blob: efd77269b683c947811dbbe6bc254b0f244c227b [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 Tolnay18c754c2018-08-21 23:26:58 -040014
David Tolnayb6254182018-08-25 08:44:54 -040015pub use error::{Error, Result};
16pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -040017
18/// Parsing interface implemented by all types that can be parsed in a default
19/// way from a token stream.
20pub trait Parse: Sized {
21 fn parse(input: ParseStream) -> Result<Self>;
22}
23
24/// Input to a Syn parser function.
25pub type ParseStream<'a> = &'a ParseBuffer<'a>;
26
27/// Cursor position within a buffered token stream.
28#[derive(Clone)]
29pub struct ParseBuffer<'a> {
30 scope: Span,
31 cell: Cell<Cursor<'static>>,
32 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -040033 unexpected: Rc<Cell<Option<Span>>>,
34}
35
36impl<'a> Drop for ParseBuffer<'a> {
37 fn drop(&mut self) {
38 if !self.is_empty() && self.unexpected.get().is_none() {
39 self.unexpected.set(Some(self.cursor().span()));
40 }
41 }
David Tolnay18c754c2018-08-21 23:26:58 -040042}
43
44// Not public API.
45#[doc(hidden)]
46#[derive(Copy, Clone)]
47pub struct StepCursor<'c, 'a> {
48 scope: Span,
49 cursor: Cursor<'c>,
50 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
51}
52
53impl<'c, 'a> Deref for StepCursor<'c, 'a> {
54 type Target = Cursor<'c>;
55
56 fn deref(&self) -> &Self::Target {
57 &self.cursor
58 }
59}
60
61impl<'c, 'a> StepCursor<'c, 'a> {
62 // Not public API.
63 #[doc(hidden)]
64 pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
65 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
66 }
67
68 // Not public API.
69 #[doc(hidden)]
70 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
105 // Not public API.
106 #[doc(hidden)]
107 pub fn step_cursor<F, R>(&self, function: F) -> Result<R>
108 where
109 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
110 {
David Tolnayeafc8052018-08-25 16:33:53 -0400111 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400112 match function(StepCursor {
113 scope: self.scope,
114 cursor: self.cell.get(),
115 marker: PhantomData,
116 }) {
117 Ok((ret, cursor)) => {
118 self.cell.set(cursor);
119 Ok(ret)
120 }
121 Err(err) => Err(err),
122 }
123 }
David Tolnayeafc8052018-08-25 16:33:53 -0400124
125 // Not public API.
126 #[doc(hidden)]
127 pub fn get_unexpected(&self) -> Rc<Cell<Option<Span>>> {
128 self.unexpected.clone()
129 }
130
131 // Not public API.
132 #[doc(hidden)]
133 pub fn check_unexpected(&self) -> Result<()> {
134 match self.unexpected.get() {
135 Some(span) => Err(Error::new(span, "unexpected token")),
136 None => Ok(()),
137 }
138 }
David Tolnay18c754c2018-08-21 23:26:58 -0400139}
140
141impl Parse for Ident {
142 fn parse(input: ParseStream) -> Result<Self> {
143 input.step_cursor(|cursor| {
144 if let Some((ident, rest)) = cursor.ident() {
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400145 match ident.to_string().as_str() {
146 "_"
147 // Based on https://doc.rust-lang.org/grammar.html#keywords
148 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
149 | "abstract" | "as" | "become" | "box" | "break" | "const"
150 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
151 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
152 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
153 | "ref" | "return" | "Self" | "self" | "static" | "struct"
154 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
155 | "virtual" | "where" | "while" | "yield" => {}
156 _ => return Ok((ident, rest)),
157 }
David Tolnay18c754c2018-08-21 23:26:58 -0400158 }
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400159 Err(cursor.error("expected identifier"))
David Tolnay18c754c2018-08-21 23:26:58 -0400160 })
161 }
162}
163
164// In reality the impl would be for Punctuated.
165impl<T: Parse> Parse for Vec<T> {
166 fn parse(input: ParseStream) -> Result<Self> {
167 let mut vec = Vec::new();
168 while !input.is_empty() {
169 let t = input.parse::<T>()?;
170 vec.push(t);
171 }
172 Ok(vec)
173 }
174}