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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use crate::coords::{Coords, Span};
use crate::errors::{ParserError, ParserErrorDetails, ParserErrorSource, ParserResult};
use crate::lexer_input_error;
use std::borrow::Cow;
/// Aggregate structure consisting of a character and it's position within the input stream
pub struct CharWithCoords {
pub ch: char,
pub coords: Coords,
}
/// A tuple consisting of a stringish thing, and associated span
pub struct StringWithSpan {
pub str: String,
pub span: Span,
}
/// Just clone a [CharWithCoords] structure
macro_rules! clone_char_with_coords {
($src : expr) => {
CharWithCoords {
ch: $src.ch,
coords: $src.coords.clone(),
}
};
}
/// Structure to manage input state information for the lexer. Allows for an absolute position as well as a sliding
/// buffer of (as of yet) unconsumed entries
#[derive()]
pub struct LexerInput<'a> {
/// Single lookahead character
lookahead: Option<char>,
/// The underlying source of characters
chars: &'a mut dyn Iterator<Item = char>,
/// The absolute [Coords]
position: Coords,
/// Input buffer
buffer: Vec<CharWithCoords>,
/// Pushback buffer
pushbacks: Vec<CharWithCoords>,
}
/// An input adapter used by the lexer. A [LexerInput] is responsible for managing input
/// state to to provide access to segments (or individual characters) from within the source input.
impl<'a> LexerInput<'a> {
/// Create a new state instance with all the defaults
pub fn new(chars: &'a mut dyn Iterator<Item = char>) -> Self {
LexerInput {
lookahead: None,
chars,
position: Coords::default(),
buffer: vec![],
pushbacks: vec![],
}
}
/// Reset the state without resetting the state of the underlying char iterator
pub fn clear(&mut self) {
self.buffer = vec![];
}
/// Push the last read character (and it's coords) onto the pushback buffer
pub fn pushback(&mut self) {
if !self.buffer.is_empty() {
let last = self.buffer.remove(self.buffer.len() - 1);
self.pushbacks.push(last);
}
}
/// Get the absolute position in the underlying input
pub fn position(&self) -> Coords {
self.position.clone()
}
/// Get the optional [char] at the front of the buffer
pub fn front(&self) -> Option<CharWithCoords> {
return if !self.buffer.is_empty() {
Some(clone_char_with_coords!(self.buffer.last().unwrap()))
} else {
None
};
}
/// Get the optional [char] at the back of the buffer
pub fn back(&self) -> Option<CharWithCoords> {
return if !self.buffer.is_empty() {
Some(clone_char_with_coords!(self.buffer.first().unwrap()))
} else {
None
};
}
/// Advance the input to the next available character, optionally skipping whitespace.
pub fn advance(&mut self, skip_whitespace: bool) -> ParserResult<()> {
// skip any whitespace, which may populate pushback or lookahead
if skip_whitespace {
self.skip_whitespace()?;
}
// check that we haven't pushed back during whitespace skipping
if !self.pushbacks.is_empty() {
self.buffer.push(self.pushbacks.pop().unwrap());
self.position = self.buffer.last().unwrap().coords;
return Ok(());
}
// otherwise, just grab the next available character from either the underlying input,
// or from the lookahead buffer
return match self.next_char() {
Some(next) => {
self.inc_position(false);
match next {
(ch, Some(coords)) => self.buffer.push(CharWithCoords { ch, coords }),
(ch, None) => self.buffer.push(CharWithCoords {
ch,
coords: self.position,
}),
}
Ok(())
}
None => lexer_input_error!(ParserErrorDetails::EndOfInput, self.position),
};
}
/// Look ahead one in the input stream
fn try_lookahead(&mut self) -> Option<char> {
self.lookahead = self.chars.next();
self.lookahead
}
/// Clear the lookahead
fn clear_lookahead(&mut self) {
self.lookahead = None;
}
/// Skip any whitespace within the input, making sure to update our overall position in the
/// input correctly. As we skip whitespace, we may "overrun" and so need to populate the
/// pushback buffer, or alternatively in the case of line endings, we may need to populate
/// the lookahead with a character. Populating the pushback buffer should update coordinate
/// information, populating the lookahead will not
fn skip_whitespace(&mut self) -> ParserResult<()> {
loop {
let next = self.next_char();
match next {
Some((ch, _)) => match ch.is_whitespace() {
true => match ch {
'\r' => {
self.inc_position(true);
match self.try_lookahead() {
Some(la) => match la {
'\n' => {
self.inc_position(false);
self.clear_lookahead();
}
_ => {
self.inc_position(false);
self.pushbacks.push(CharWithCoords {
ch: la,
coords: self.position,
})
}
},
None => {
return lexer_input_error!(
ParserErrorDetails::EndOfInput,
self.position
);
}
}
}
'\n' => self.inc_position(true),
_ => self.inc_position(false),
},
false => {
self.inc_position(false);
self.pushbacks.push(CharWithCoords {
ch,
coords: self.position,
});
return Ok(());
}
},
None => {
return lexer_input_error!(ParserErrorDetails::EndOfInput, self.position);
}
}
}
}
/// Grab the next available character, which might come from either the lookahead, or failing
/// that, from the underlying input. Return a tuple consisting of a character, and an optional
/// coordinate position, depending on where we managed to source the character from...
fn next_char(&mut self) -> Option<(char, Option<Coords>)> {
// check to see if we have anything in the pushback buffer
if !self.pushbacks.is_empty() {
let popped = self.pushbacks.pop().unwrap();
return Some((popped.ch, Some(popped.coords)));
}
// grab from the lookahead, or read from the underlying input
match self.lookahead {
Some(ch) => {
self.lookahead = None;
Some((ch, None))
}
None => self.chars.next().map(|ch| (ch, None)),
}
}
/// Advance the input over n available characters, returning a [ParserError] if it's not
/// possible to do so. After calling this method the input state should be read using the
/// other associated functions available for this type
pub fn advance_n(&mut self, n: usize, skip_whitespace: bool) -> ParserResult<()> {
for _ in 0..n {
self.advance(skip_whitespace)?;
}
Ok(())
}
/// Increment position, optionally resetting at the beginning of a new line
fn inc_position(&mut self, newline: bool) {
// check whether we're on the very first character
if self.position.line == 0 {
self.position.line = 1
}
// adjust absolute position
self.position.absolute += 1;
// adjust based on whether we've hit a newline
match newline {
true => {
self.position.column = 0;
self.position.line += 1;
}
false => {
self.position.column += 1;
}
}
}
/// Extract the current buffer as a [StringWithSpan]. Will return an empty string if there's
/// nothing in the buffer
pub fn buffer_as_string_with_span(&mut self) -> StringWithSpan {
return if !self.buffer.is_empty() {
let mut s = String::with_capacity(self.buffer.len());
self.buffer.iter().for_each(|cwc| s.push(cwc.ch));
StringWithSpan {
str: s,
span: Span {
start: self.back().unwrap().coords,
end: self.front().unwrap().coords,
},
}
} else {
StringWithSpan {
str: String::new(),
span: Span {
start: self.position,
end: self.position,
},
}
};
}
/// Extract the current buffer as a [char] slice
pub fn buffer_as_char_array(&mut self) -> Vec<char> {
return if !self.buffer.is_empty() {
let mut arr: Vec<char> = vec![];
self.buffer.iter().for_each(|cwc| arr.push(cwc.ch));
arr
} else {
vec![]
};
}
/// Extract the current buffer as a byte buffer. You just get an empty vec if the buffer is
/// currently empty
pub fn buffer_as_byte_array(&self) -> Vec<u8> {
return if !self.buffer.is_empty() {
self.buffer.iter().map(|cwc| cwc.ch as u8).collect()
} else {
vec![]
};
}
}
#[cfg(test)]
mod test {
use crate::lexer_input::LexerInput;
use crate::reader_from_bytes;
use chisel_decoders::utf8::Utf8Decoder;
use std::io::{BufRead, BufReader};
#[test]
fn should_create_new() {
let mut reader = reader_from_bytes!("{}[],:");
let mut decoder = Utf8Decoder::new(&mut reader);
let _ = LexerInput::new(&mut decoder);
}
#[test]
fn should_consume_single_lines_correctly() {
let mut reader = reader_from_bytes!("this is a test line");
let mut decoder = Utf8Decoder::new(&mut reader);
let mut input = LexerInput::new(&mut decoder);
let result = input.advance(true);
assert!(result.is_ok());
assert_eq!(input.front().unwrap().ch, 't');
for _ in 1..5 {
let result = input.advance(true);
assert!(result.is_ok());
}
assert_eq!(input.front().unwrap().ch, 'i');
assert_eq!(input.front().unwrap().coords.column, 6);
input.clear();
for _ in 1..5 {
let result = input.advance(false);
assert!(result.is_ok());
}
assert_eq!(input.front().unwrap().ch, ' ');
assert_eq!(input.front().unwrap().coords.column, 10)
}
}