scnr2 0.5.2

Scanner/Lexer with regex patterns and multiple modes
Documentation
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! FindMatches struct and its implementation

use std::{cell::RefCell, rc::Rc};

use crate::{
    Dfa, Lookahead, ScannerImpl,
    internals::{
        char_iter::item::CharItem,
        char_iter::iter::CharIter,
        char_iter::iter_with_position::CharIterWithPosition,
        match_types::{Match, MatchEnd, MatchStart},
        position::{Position, Positions},
    },
};

/// A trait that defines the behavior of finding matches in a string slice using a DFA (Deterministic
/// Finite Automaton).
pub trait FindMatchesTrait {
    /// Returns the current DFA.
    fn current_dfa(&self) -> &'static Dfa;

    /// Handles the transition to a new mode based on the token type.
    fn handle_mode_transition(&self, token_type: usize);

    /// Returns the next character without advancing the iterator.
    fn peek(&mut self) -> Option<CharItem>;

    /// Returns the character class for the given character.
    fn get_disjoint_class(&self, ch: char) -> Option<usize>;

    /// Advances the character iterator to the next character.
    /// This method is used to move the iterator forward in the input string slice.
    /// It should return `true` if the iterator was advanced successfully, or `false` if it has
    /// reached the end of the input string slice.
    fn advance_char_iter(&mut self) -> bool;

    /// Saves the current character iterator state.
    fn save_char_iter(&mut self);

    /// Restores the saved character iterator state.
    fn restore_saved_char_iter(&mut self);
}

/// A structure that represents an iterator over character matches in a string slice.
/**

 * Iterator over token matches in the input text.
 *
 * # Example
 * ```rust
 * use scnr2::{scanner, Match};
 * scanner! {
 *     SimpleScanner {
 *         mode INITIAL {
 *             token r"\d+" => 1;
 *         }
 *     }
 * }
 * let input = "123 456";
 * let scanner = simple_scanner::SimpleScanner::new();
 * let matches: Vec<Match> = scanner.find_matches(input, 0).collect();
 * assert_eq!(matches.len(), 2);
 * ```
 */
pub struct FindMatches<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// An iterator over characters in the input string slice, starting from the given offset.
    char_iter: CharIter<'a>,
    /// The creating scanner implementation, wrapped in an `Rc<RefCell>` for thread safety.
    scanner_impl: Rc<RefCell<ScannerImpl>>,
    /// A reference to the match function that returns the character class for a given character.
    match_function: &'static F,
}

impl<'a, F> Clone for FindMatches<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    fn clone(&self) -> Self {
        Self {
            char_iter: self.char_iter.clone(),
            scanner_impl: self.scanner_impl.clone(),
            match_function: self.match_function,
        }
    }
}

impl<'a, F> FindMatches<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// Creates a new `FindMatches` from the given string slice and start position.
    pub(crate) fn new(
        input: &'a str,
        offset: usize,
        scanner_impl: Rc<RefCell<ScannerImpl>>,
        match_function: &'static F,
    ) -> Self {
        FindMatches {
            char_iter: CharIter::new(input, offset),
            scanner_impl,
            match_function,
        }
    }

    /// Returns the name of the current mode.
    #[inline]
    pub fn current_mode_name(&self) -> &'static str {
        let scanner_impl = self.scanner_impl.borrow();
        scanner_impl.current_mode_name()
    }

    /// Returns the name of the given mode.
    #[inline]
    pub fn mode_name(&self, index: usize) -> Option<&'static str> {
        self.scanner_impl.borrow().mode_name(index)
    }

    /// Returns the current mode index.
    #[inline]
    pub fn current_mode_index(&self) -> usize {
        self.scanner_impl.borrow().current_mode_index()
    }
}

impl<F> Iterator for FindMatches<'_, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    type Item = Match;

    fn next(&mut self) -> Option<Match> {
        next_match(self)
    }
}

impl<F> FindMatchesTrait for FindMatches<'_, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// Returns the current DFA.
    /// This method returns a reference to the DFA that is currently being used for matching.
    #[inline(always)]
    fn current_dfa(&self) -> &'static Dfa {
        let scanner_impl = self.scanner_impl.borrow();
        &scanner_impl.modes()[scanner_impl.current_mode_index()].dfa
    }

    /// Handles the transition to a new mode based on the token type.
    #[inline(always)]
    fn handle_mode_transition(&self, token_type: usize) {
        let scanner_impl = self.scanner_impl.borrow();
        scanner_impl.handle_mode_transition(token_type);
    }

    /// Returns the next character without advancing the iterator.
    #[inline(always)]
    fn peek(&mut self) -> Option<CharItem> {
        self.char_iter.peek()
    }

    /// Advances the character iterator to the next character.
    /// This method is used to move the iterator forward in the input string slice.
    /// It should return `true` if the iterator was advanced successfully, or `false` if it has
    /// reached the end of the input string slice.
    #[inline(always)]
    fn advance_char_iter(&mut self) -> bool {
        self.char_iter.next().is_some()
    }

    /// Returns the character class for the given character.
    #[inline(always)]
    fn get_disjoint_class(&self, ch: char) -> Option<usize> {
        (self.match_function)(ch)
    }

    /// Saves the current character iterator state.
    fn save_char_iter(&mut self) {
        self.char_iter.save_state();
    }

    /// Restores the saved character iterator state.
    fn restore_saved_char_iter(&mut self) {
        self.char_iter.restore_state();
    }
}

/// A structure that represents an iterator over character matches with positions in a string slice.
/// It uses the `FindMatches` struct for implementation, but includes additional position
/// information for each match.
/**

 * Iterator over token matches with position information (line/column).
 *
 * # Example
 * ```rust
 * use scnr2::{scanner, Match};
 * scanner! {
 *     SimpleScanner {
 *         mode INITIAL {
 *             token r"\d+" => 1;
 *         }
 *     }
 * }
 * let input = "123\n456";
 * let scanner = simple_scanner::SimpleScanner::new();
 * let matches: Vec<Match> = scanner.find_matches_with_position(input, 0).collect();
 * assert_eq!(matches[0].positions.is_some(), true);
 * ```
 */
pub struct FindMatchesWithPosition<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// An iterator over characters in the input string slice, starting from the given offset.
    char_iter: CharIterWithPosition<'a>,
    /// The creating scanner implementation, wrapped in an `Rc<RefCell>` for thread safety.
    scanner_impl: Rc<RefCell<ScannerImpl>>,
    /// A reference to the match function that returns the character class for a given character.
    match_function: &'static F,
}

impl<'a, F> Clone for FindMatchesWithPosition<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    fn clone(&self) -> Self {
        Self {
            char_iter: self.char_iter.clone(),
            scanner_impl: self.scanner_impl.clone(),
            match_function: self.match_function,
        }
    }
}

impl<'a, F> FindMatchesWithPosition<'a, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// Creates a new `FindMatchesWithPosition` from the given string slice and start position.
    pub(crate) fn new(
        input: &'a str,
        offset: usize,
        scanner_impl: Rc<RefCell<ScannerImpl>>,
        match_function: &'static F,
    ) -> Self {
        FindMatchesWithPosition {
            char_iter: CharIterWithPosition::new(input, offset),
            scanner_impl,
            match_function,
        }
    }

    /// Returns the name of the current mode.
    #[inline]
    pub fn current_mode_name(&self) -> Option<&'static str> {
        let scanner_impl = self.scanner_impl.borrow();
        let current_mode_index = scanner_impl.current_mode_index();
        scanner_impl.mode_name(current_mode_index)
    }

    /// Returns the name of the given mode.
    #[inline]
    pub fn mode_name(&self, index: usize) -> Option<&'static str> {
        self.scanner_impl.borrow().mode_name(index)
    }

    /// Returns the current mode index.
    #[inline]
    pub fn current_mode(&self) -> usize {
        self.scanner_impl.borrow().current_mode_index()
    }
}

impl<F> Iterator for FindMatchesWithPosition<'_, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    type Item = Match;

    fn next(&mut self) -> Option<Match> {
        next_match(self)
    }
}

impl<F> FindMatchesTrait for FindMatchesWithPosition<'_, F>
where
    F: Fn(char) -> Option<usize> + 'static + ?Sized,
{
    /// Returns the current DFA.
    /// This method returns a reference to the DFA that is currently being used for matching.
    #[inline(always)]
    fn current_dfa(&self) -> &'static Dfa {
        let scanner_impl = self.scanner_impl.borrow();
        &scanner_impl.modes()[scanner_impl.current_mode_index()].dfa
    }

    /// Handles the transition to a new mode based on the token type.
    #[inline(always)]
    fn handle_mode_transition(&self, token_type: usize) {
        let scanner_impl = self.scanner_impl.borrow();
        scanner_impl.handle_mode_transition(token_type);
    }

    /// Returns the next character without advancing the iterator.
    #[inline(always)]
    fn peek(&mut self) -> Option<CharItem> {
        self.char_iter.peek()
    }

    /// Advances the character iterator to the next character.
    /// This method is used to move the iterator forward in the input string slice.
    /// It should return `true` if the iterator was advanced successfully, or `false` if it has
    /// reached the end of the input string slice.
    #[inline(always)]
    fn advance_char_iter(&mut self) -> bool {
        self.char_iter.next().is_some()
    }

    /// Returns the character class for the given character.
    #[inline(always)]
    fn get_disjoint_class(&self, ch: char) -> Option<usize> {
        (self.match_function)(ch)
    }

    /// Saves the current character iterator state.
    fn save_char_iter(&mut self) {
        self.char_iter.save_state();
    }

    /// Restores the saved character iterator state.
    fn restore_saved_char_iter(&mut self) {
        self.char_iter.restore_state();
    }
}

/// Evaluates the lookahead condition for the current match.
/// This method checks if the lookahead condition is satisfied based on the
/// current match and the accept data.
/// It returns a tuple containing a boolean indicating whether the lookahead is satisfied
/// and the length of the lookahead match.
fn evaluate_lookahead<F: FindMatchesTrait + Clone>(
    mut find_matches: F,
    accept_data: &crate::AcceptData,
) -> (bool, usize) {
    match &accept_data.lookahead {
        crate::Lookahead::None => {
            unreachable!("Lookahead::None should not be evaluated here")
        }
        crate::Lookahead::Positive(dfa) => {
            // Handle positive lookahead logic here
            if let Some(ma) = find_next(&mut find_matches, dfa) {
                (true, ma.span.len())
            } else {
                (false, 0)
            }
        }
        crate::Lookahead::Negative(dfa) => {
            // Handle negative lookahead logic here
            if find_next(&mut find_matches, dfa).is_some() {
                (false, 0)
            } else {
                (true, 0)
            }
        }
    }
}

/// Returns the next match in the input, if available.
/// This method is responsible for finding the next match based on the current state of the
/// scanner implementation and the current position in the input.
/// It is used in the `next` method of the `Iterator` trait implementation.
#[inline(always)]
pub(crate) fn next_match<F: FindMatchesTrait + Clone>(find_matches: &mut F) -> Option<Match> {
    // Logic to find the next match in the input using the scanner implementation
    // and the current position in the char_iter.
    let dfa: &Dfa = find_matches.current_dfa();
    loop {
        if let Some(ma) = find_next(find_matches, dfa) {
            // If a match is found and there exists a transition to the next mode,
            // update the current mode in the scanner implementation.
            find_matches.handle_mode_transition(ma.token_type);
            return Some(ma);
        }
        // If no match, advance the iterator until a match is found
        // or the end of the input is reached.
        if !find_matches.advance_char_iter() {
            return None; // End of input reached
        }
    }
}

/// Simulates the DFA on the given input.
/// Returns a match starting at the current position. No try on next character is done.
/// The caller must do that.
///
/// If no match is found, None is returned.
#[inline(always)]
fn find_next<F: FindMatchesTrait + Clone>(find_matches: &mut F, dfa: &Dfa) -> Option<Match> {
    let mut state = 0; // Initial state of the DFA
    let mut match_start = MatchStart::default();
    let mut match_end = MatchEnd::default();
    let mut start_set = false;
    let mut end_set = false;

    find_matches.save_char_iter(); // Save the current state of the iterator

    // Iterate over characters in the input using char_iter
    while let Some(char_item) = find_matches.peek() {
        let character_class = find_matches.get_disjoint_class(char_item.ch);

        let Some(class_idx) = character_class else {
            break;
        };

        let state_data = &dfa.states[state];
        if let Some(Some(next_state)) = state_data.transitions.get(class_idx) {
            state = next_state.to;
        } else {
            break;
        };
        let state_data = &dfa.states[state];

        // Only now advance the iterator
        find_matches.advance_char_iter();

        if !start_set {
            match_start = MatchStart::new(char_item.byte_index).with_position(char_item.position);
            start_set = true;
        }

        for accept_data in state_data.accept_data {
            let (lookahead_satisfied, _lookahead_len) =
                if !matches!(accept_data.lookahead, Lookahead::None) {
                    evaluate_lookahead(find_matches.clone(), accept_data)
                } else {
                    (true, 0)
                };
            if lookahead_satisfied {
                let new_byte_index = char_item.byte_index + char_item.ch.len_utf8();
                let new_len = new_byte_index - match_start.byte_index;
                let update = !end_set || {
                    let old_len = match_end.byte_index - match_start.byte_index;
                    new_len > old_len
                        || (new_len == old_len && accept_data.priority < match_end.priority)
                };
                if update {
                    match_end =
                        MatchEnd::new(new_byte_index, accept_data.token_type, accept_data.priority)
                            .with_position(char_item.position.map(|p| {
                                if char_item.ch == '\n' {
                                    Position::new(p.line + 1, 1)
                                } else {
                                    Position::new(p.line, p.column + 1)
                                }
                            }));
                    end_set = true;
                    find_matches.save_char_iter();
                }
                // We found a satisfied lookahead for this state.
                // Since the accept_data is sorted by priority, we can stop here for this munch.
                break;
            }
        }
    }

    if end_set {
        let span: crate::Span = match_start.byte_index..match_end.byte_index;
        find_matches.restore_saved_char_iter();
        Some(
            Match::new(span, match_end.token_type).with_positions(
                match_start
                    .position
                    .zip(match_end.position)
                    .map(|(start, end)| Positions::new(start, end)),
            ),
        )
    } else {
        find_matches.restore_saved_char_iter();
        None
    }
}