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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//! Module implementing the lexer cursor. This is used for managing the input byte stream.
use crate::{profiler::BoaProfiler, syntax::ast::Position};
use std::io::{self, Bytes, Error, ErrorKind, Read};
/// Cursor over the source code.
#[derive(Debug)]
pub(super) struct Cursor<R> {
iter: InnerIter<R>,
peeked: Option<Option<char>>,
pos: Position,
}
impl<R> Cursor<R> {
/// Gets the current position of the cursor in the source code.
#[inline]
pub(super) fn pos(&self) -> Position {
self.pos
}
/// Advances the position to the next column.
#[inline]
pub(super) fn next_column(&mut self) {
let current_line = self.pos.line_number();
let next_column = self.pos.column_number() + 1;
self.pos = Position::new(current_line, next_column);
}
/// Advances the position to the next line.
#[inline]
fn next_line(&mut self) {
let next_line = self.pos.line_number() + 1;
self.pos = Position::new(next_line, 1);
}
/// Performs a carriage return to modify the position in the source.
#[inline]
fn carriage_return(&mut self) {
let current_line = self.pos.line_number();
self.pos = Position::new(current_line, 1);
}
}
impl<R> Cursor<R>
where
R: Read,
{
/// Creates a new Lexer cursor.
#[inline]
pub(super) fn new(inner: R) -> Self {
Self {
iter: InnerIter::new(inner.bytes()),
peeked: None,
pos: Position::new(1, 1),
}
}
/// Peeks the next character.
#[inline]
pub(super) fn peek(&mut self) -> Result<Option<char>, Error> {
let _timer = BoaProfiler::global().start_event("cursor::peek()", "Lexing");
let iter = &mut self.iter;
if let Some(v) = self.peeked {
Ok(v)
} else {
let val = iter.next_char()?;
self.peeked = Some(val);
Ok(val)
}
}
/// Compares the character passed in to the next character, if they match true is returned and the buffer is incremented
#[inline]
pub(super) fn next_is(&mut self, peek: char) -> io::Result<bool> {
let _timer = BoaProfiler::global().start_event("cursor::next_is()", "Lexing");
Ok(match self.peek()? {
Some(next) if next == peek => {
let _ = self.peeked.take();
true
}
_ => false,
})
}
/// Applies the predicate to the next character and returns the result.
/// Returns false if there is no next character.
///
/// The buffer is not incremented.
#[inline]
pub(super) fn next_is_pred<F>(&mut self, pred: &F) -> io::Result<bool>
where
F: Fn(char) -> bool,
{
let _timer = BoaProfiler::global().start_event("cursor::next_is_pred()", "Lexing");
Ok(if let Some(peek) = self.peek()? {
pred(peek)
} else {
false
})
}
/// Fills the buffer with all characters until the stop character is found.
///
/// Note: It will not add the stop character to the buffer.
pub(super) fn take_until(&mut self, stop: char, buf: &mut String) -> io::Result<()> {
let _timer = BoaProfiler::global().start_event("cursor::take_until()", "Lexing");
loop {
if self.next_is(stop)? {
return Ok(());
} else if let Some(ch) = self.next_char()? {
buf.push(ch);
} else {
return Err(io::Error::new(
ErrorKind::UnexpectedEof,
format!("Unexpected end of file when looking for character {}", stop),
));
}
}
}
/// Fills the buffer with characters until the first character (x) for which the predicate (pred) is false
/// (or the next character is none).
///
/// Note that all characters up until x are added to the buffer including the character right before.
pub(super) fn take_while_pred<F>(&mut self, buf: &mut String, pred: &F) -> io::Result<()>
where
F: Fn(char) -> bool,
{
let _timer = BoaProfiler::global().start_event("cursor::take_while_pred()", "Lexing");
loop {
if !self.next_is_pred(pred)? {
return Ok(());
} else if let Some(ch) = self.next_char()? {
buf.push(ch);
} else {
// next_is_pred will return false if the next value is None so the None case should already be handled.
unreachable!();
}
}
}
/// It will fill the buffer with checked ASCII bytes.
///
/// This expects for the buffer to be fully filled. If it's not, it will fail with an
/// `UnexpectedEof` I/O error.
#[inline]
pub(super) fn fill_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
let _timer = BoaProfiler::global().start_event("cursor::fill_bytes()", "Lexing");
self.iter.fill_bytes(buf)
}
/// Retrieves the next UTF-8 character.
#[inline]
pub(crate) fn next_char(&mut self) -> Result<Option<char>, Error> {
let _timer = BoaProfiler::global().start_event("cursor::next_char()", "Lexing");
let chr = match self.peeked.take() {
Some(v) => v,
None => self.iter.next_char()?,
};
match chr {
Some('\r') => self.carriage_return(),
Some('\n') | Some('\u{2028}') | Some('\u{2029}') => self.next_line(),
Some(_) => self.next_column(),
None => {}
}
Ok(chr)
}
}
/// Inner iterator for a cursor.
#[derive(Debug)]
struct InnerIter<R> {
iter: Bytes<R>,
}
impl<R> InnerIter<R> {
/// Creates a new inner iterator.
#[inline]
fn new(iter: Bytes<R>) -> Self {
Self { iter }
}
}
impl<R> InnerIter<R>
where
R: Read,
{
/// It will fill the buffer with checked ASCII bytes.
///
/// This expects for the buffer to be fully filled. If it's not, it will fail with an
/// `UnexpectedEof` I/O error.
#[inline]
fn fill_bytes(&mut self, buf: &mut [u8]) -> io::Result<()> {
for byte in buf.iter_mut() {
*byte = self.next_ascii()?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"unexpected EOF when filling buffer",
)
})?;
}
Ok(())
}
/// Retrieves the next UTF-8 checked character.
fn next_char(&mut self) -> io::Result<Option<char>> {
let first_byte = match self.iter.next().transpose()? {
Some(b) => b,
None => return Ok(None),
};
let chr: char = if first_byte < 0x80 {
// 0b0xxx_xxxx
first_byte.into()
} else {
let mut buf = [first_byte, 0u8, 0u8, 0u8];
let num_bytes = if first_byte < 0xE0 {
// 0b110x_xxxx
2
} else if first_byte < 0xF0 {
// 0b1110_xxxx
3
} else {
// 0b1111_0xxx
4
};
for b in buf.iter_mut().take(num_bytes).skip(1) {
let next = match self.iter.next() {
Some(Ok(b)) => b,
Some(Err(e)) => return Err(e),
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
))
}
};
*b = next;
}
if let Ok(s) = std::str::from_utf8(&buf) {
if let Some(chr) = s.chars().next() {
chr
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
));
}
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
));
}
};
Ok(Some(chr))
}
/// Retrieves the next ASCII checked character.
#[inline]
fn next_ascii(&mut self) -> io::Result<Option<u8>> {
let next_byte = self.iter.next().transpose()?;
match next_byte {
Some(next) if next <= 0x7F => Ok(Some(next)),
None => Ok(None),
_ => Err(io::Error::new(
io::ErrorKind::InvalidData,
"non-ASCII byte found",
)),
}
}
}