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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use crate::lexer::EOI;
use crate::parser::ScannerIndex;
use crate::{LexerError, LocationBuilder, TerminalIndex, Token, TokenIter, TokenNumber};
use log::trace;
use scnr2::ScannerImpl;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use super::TokenBuffer;
///
/// The TokenStream<'t> type is the interface the parser actually uses.
/// It provides the lookahead functionality by maintaining a lookahead buffer.
///
/// The lifetime parameter `'t` refers to the lifetime of the scanned text.
///
pub struct TokenStream<'t, F>
where
F: Fn(char) -> Option<usize> + 'static + Clone,
{
/// The number of available lookahead tokens
pub k: usize,
/// The input text
pub(crate) input: &'t str,
/// The name of the input file
pub file_name: Arc<PathBuf>,
/// The actual token iterator.
/// It is replaced by a new one in case of scanner state switch.
token_iter: TokenIter<'t, F>,
/// Lookahead token buffer, maximum size is k
pub tokens: TokenBuffer<'t>,
/// Flag to indicate if the parser is in error recovery mode
pub(crate) recovering: bool,
}
impl<'t, F> TokenStream<'t, F>
where
F: Fn(char) -> Option<usize> + 'static + Clone,
{
///
/// Creates a new TokenStream object from an augmented terminals list and
/// an input string.
/// The k determines the number of lookahead tokens the stream supports.
///
/// Currently this never return LexerError but it could be changed in the future.
///
pub fn new<T>(
input: &'t str,
file_name: T,
scanner_impl: Rc<RefCell<ScannerImpl>>,
match_function: &'static F,
k: usize,
) -> Result<Self, LexerError>
where
T: AsRef<Path>,
{
let file_name = Arc::new(file_name.as_ref().to_owned());
// To output the compiled automata as dot files uncomment the following two lines
// const TARGET_FOLDER: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target");
// let _ = scanner.generate_compiled_automata_as_dot("Parol", Path::new(TARGET_FOLDER));
let token_iter = TokenIter::new(
ScannerImpl::find_matches_with_position(scanner_impl, input, 0, match_function),
input,
file_name.clone(),
k,
);
// issue #54 "Lookahead exceeds token buffer length" with simple grammar:
// Ensure that k is at least 1 and at most MAX_K
let k = std::cmp::max(1, k);
let mut token_stream = Self {
k,
input,
file_name,
token_iter,
tokens: TokenBuffer::new(),
recovering: false,
};
token_stream.read_tokens(k)?;
Ok(token_stream)
}
///
/// Provides at maximum k tokens lookahead relative to the current read
/// position.
/// If successful it returns a cloned token from buffer position self.pos + n
///
pub fn lookahead(&mut self, n: usize) -> Result<Token<'t>, LexerError> {
if n >= self.k {
Err(LexerError::LookaheadExceedsMaximum)
} else {
// Fill buffer to lookahead size k relative to pos
self.ensure_buffer()?;
if n >= self.tokens.len() {
if self.tokens.is_empty() && self.recovering {
trace!("lookahead LA({n}): EOI for recovery");
Ok(Token::eoi(TokenNumber::MAX))
} else {
trace!("{} in {}", n, self.tokens);
Err(LexerError::LookaheadExceedsTokenBufferLength)
}
} else {
trace!("LA({}): {}", n, self.tokens.non_skip_token_at(n).unwrap());
Ok(self.tokens.non_skip_token_at(n).unwrap().clone())
}
}
}
///
/// Provides at maximum k tokens lookahead relative to the current read
/// position.
/// If successful it returns the type (index) of the token at buffer
/// position n.
///
pub fn lookahead_token_type(&mut self, n: usize) -> Result<TerminalIndex, LexerError> {
if n >= self.k {
Err(LexerError::LookaheadExceedsMaximum)
} else {
// Fill buffer to lookahead size k relative to pos
self.ensure_buffer()?;
if n >= self.tokens.len() {
if self.tokens.is_empty() && self.recovering {
trace!("lookahead_token_type LA({n}): EOI for recovery");
Ok(EOI)
} else {
trace!("{} in {}", n, self.tokens);
Err(LexerError::LookaheadExceedsTokenBufferLength)
}
} else {
trace!(
"Type(LA({})): {}",
n,
self.tokens.non_skip_token_at(n).unwrap()
);
Ok(self.tokens.non_skip_token_at(n).unwrap().token_type)
}
}
}
/// Returns all skip tokens at the beginning of the token buffer.
/// The tokens are removed from the buffer and the line and column numbers are updated.
#[inline]
pub fn take_skip_tokens(&mut self) -> Vec<Token<'t>> {
self.tokens.take_skip_tokens()
}
///
/// Consumes one token.
/// If necessary more input is read via the token_iter into the tokens buffer.
///
/// The token's positions are captured to support scanner switching.
///
pub fn consume(&mut self) -> Result<Token<'t>, LexerError> {
self.ensure_buffer()?;
let token;
if self.tokens.is_empty() {
return Err(LexerError::InternalError(
"Consume on empty buffer is impossible".into(),
));
} else {
// We consume token LA(1) with buffer index 0.
trace!("Consuming {}", &self.tokens.non_skip_token_at(0).unwrap());
token = self.tokens.consume()?;
self.ensure_buffer()?;
}
Ok(token)
}
///
/// Test if all input was processed by the parser
///
pub fn all_input_consumed(&self) -> bool {
// The unwrap is safe because the token buffer is not empty here.
self.tokens.is_buffer_empty()
|| self.tokens.non_skip_token_at(0).unwrap().token_type == super::EOI
}
///
/// Returns the last valid token from token buffer if there is one
///
pub fn last_token(&self) -> Result<&Token<'_>, LexerError> {
self.tokens
.non_skip_tokens_rev()
.find(|t| t.token_type != super::EOI)
.ok_or(LexerError::TokenBufferEmptyError)
}
///
/// Returns the name of the currently active scanner state.
/// Used for diagnostics.
///
#[inline]
pub fn current_scanner(&self) -> &str {
self.token_iter
.scanner_mode_name(self.token_iter.current_mode())
.unwrap_or("unknown")
}
/// Returns the index of the currently active scanner state.
pub fn current_scanner_index(&self) -> ScannerIndex {
self.token_iter.current_mode()
}
///
/// Reads at most n tokens from the input stream and stores them in the token buffer.
/// It returns the number of tokens read.
/// The function is used by ensure_buffer and switch_scanner.
/// The idea is to fill the lookahead buffer with tokens and to switch scanner states as early
/// as possible.
///
fn read_tokens(&mut self, n: usize) -> Result<usize, LexerError> {
let mut tokens_read = 0usize;
for token in &mut self.token_iter {
trace!("Read {}: {}", self.tokens.len(), token);
if !token.is_skip_token() {
tokens_read += 1;
}
self.tokens.add(token, self.input);
if tokens_read >= n {
break;
}
}
while tokens_read < n {
trace!("read_tokens: Filling with EOI at end of input");
self.tokens.add(Token::eoi(TokenNumber::MAX), self.input);
tokens_read += 1;
}
Ok(tokens_read)
}
///
/// The function fills the lookahead buffer (self.tokens) with k tokens.
/// It returns the number of tokens read.
///
pub(crate) fn ensure_buffer(&mut self) -> Result<usize, LexerError> {
let fill_len = self.tokens.len();
if fill_len < self.k {
// Fill buffer to lookahead size k
self.read_tokens(self.k - fill_len)
} else {
Ok(0)
}
}
/// Returns the token types of the tokens in the lookahead buffer.
/// It only considers non-skip-tokens.
pub(crate) fn token_types(&self) -> Vec<TerminalIndex> {
self.tokens.non_skip_token_types()
}
pub(crate) fn diagnostic_message(&self) -> String {
format!(
"Lookahead buffer:\n[\n {}\n]\n",
self.tokens
.non_skip_tokens()
.enumerate()
.map(|(i, t)| format!("LA[{i}]: ({t})"))
.collect::<Vec<String>>()
.join(",\n ")
)
}
pub(crate) fn replace_token_type_at(
&mut self,
index: usize,
token_type: TerminalIndex,
) -> Result<(), LexerError> {
if self.tokens.len() > index {
trace!(
"replacing token {} at index {} by {}",
self.tokens.non_skip_token_at(index).unwrap(),
index,
token_type
);
if (self.tokens.non_skip_token_at(index).unwrap().token_type) == EOI {
Err(LexerError::RecoveryError("Can't replace EOI".to_owned()))
} else {
self.tokens.non_skip_token_at_mut(index).unwrap().token_type = token_type;
Ok(())
}
} else {
Err(LexerError::RecoveryError(
"Can't replace beyond token buffer".to_owned(),
))
}
}
/// Removes a token from the token buffer.
/// It is used in recovery mode to remove tokens that are not needed.
pub(crate) fn remove_token_at(&mut self, index: usize) -> Result<(), LexerError> {
if self.tokens.len() > index {
trace!("removing token at index {index}");
self.tokens.remove(index);
Ok(())
} else {
Err(LexerError::RecoveryError(
"Can't remove from token buffer".to_owned(),
))
}
}
/// Used in recovery mode to insert a token at a specific index in the token buffer.
pub(crate) fn insert_token_at(
&mut self,
index: usize,
token_type: TerminalIndex,
) -> Result<(), LexerError> {
if self.tokens.len() >= index {
trace!("inserting token {token_type} at index {index}");
let location = if self.tokens.len() > index {
self.tokens
.non_skip_token_at(index)
.unwrap()
.location
.clone()
} else {
LocationBuilder::default()
.file_name(self.file_name.clone())
.build()
.unwrap()
};
self.tokens.insert(
index,
Token::default()
.with_type(token_type)
.with_location(location),
);
Ok(())
} else {
Err(LexerError::RecoveryError(format!(
"Can't insert in token buffer at position {index}"
)))
}
}
// /// Returns the name of the scanner mode with the given index.
// #[inline]
// fn scanner_mode_name(&self, index: usize) -> &str {
// self.token_iter
// .scanner_mode_name(index)
// .unwrap_or("unknown")
// }
/// Sets the token stream in error recovery mode.
/// In this mode the parser can try to read more tokens even if the end of input is reached.
/// The token stream will return EOI tokens if the token buffer is empty.
pub(crate) fn enter_recovery_mode(&mut self) {
self.recovering = true;
}
}