1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use std::cell::Cell;
use std::fmt::Display;
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use proc_macro2::{Ident, Span};
use syn::buffer::Cursor;
use error;
pub use error::{Error, Result};
pub use lookahead::{Lookahead1, Peek};
pub trait Parse: Sized {
fn parse(input: ParseStream) -> Result<Self>;
}
pub type ParseStream<'a> = &'a ParseBuffer<'a>;
#[derive(Clone)]
pub struct ParseBuffer<'a> {
scope: Span,
cell: Cell<Cursor<'static>>,
marker: PhantomData<Cursor<'a>>,
}
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct StepCursor<'c, 'a> {
scope: Span,
cursor: Cursor<'c>,
marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
}
impl<'c, 'a> Deref for StepCursor<'c, 'a> {
type Target = Cursor<'c>;
fn deref(&self) -> &Self::Target {
&self.cursor
}
}
impl<'c, 'a> StepCursor<'c, 'a> {
#[doc(hidden)]
pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
}
#[doc(hidden)]
pub fn error<T: Display>(self, message: T) -> Error {
error::new_at(self.scope, self.cursor, message)
}
}
impl<'a> ParseBuffer<'a> {
#[doc(hidden)]
pub fn new(scope: Span, cursor: Cursor<'a>) -> Self {
let extend = unsafe { mem::transmute::<Cursor<'a>, Cursor<'static>>(cursor) };
ParseBuffer {
scope: scope,
cell: Cell::new(extend),
marker: PhantomData,
}
}
pub fn cursor(&self) -> Cursor<'a> {
self.cell.get()
}
pub fn is_empty(&self) -> bool {
self.cursor().eof()
}
pub fn lookahead1(&self) -> Lookahead1<'a> {
Lookahead1::new(self.scope, self.cursor())
}
pub fn parse<T: Parse>(&self) -> Result<T> {
T::parse(self)
}
#[doc(hidden)]
pub fn step_cursor<F, R>(&self, function: F) -> Result<R>
where
F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
{
match function(StepCursor {
scope: self.scope,
cursor: self.cell.get(),
marker: PhantomData,
}) {
Ok((ret, cursor)) => {
self.cell.set(cursor);
Ok(ret)
}
Err(err) => Err(err),
}
}
}
impl Parse for Ident {
fn parse(input: ParseStream) -> Result<Self> {
input.step_cursor(|cursor| {
if let Some((ident, rest)) = cursor.ident() {
Ok((ident, rest))
} else {
Err(cursor.error("expected identifier"))
}
})
}
}
impl<T: Parse> Parse for Vec<T> {
fn parse(input: ParseStream) -> Result<Self> {
let mut vec = Vec::new();
while !input.is_empty() {
let t = input.parse::<T>()?;
vec.push(t);
}
Ok(vec)
}
}