kamo 0.5.0

A library to assist in the creation of an interpreter or compiler and its associated runtime.
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#[cfg(feature = "regex")]
use regex::Regex;

use super::{Position, TARGET};

/// A parser input. It is a wrapper around a string slice that keeps track of
/// the current character and position.
/// 
/// The input is advanced by calling `advance` or one of the `advance_*`
/// functions. The current character can be accessed with `current` and the
/// current position with `position`. It keeps track of newlines and the current
/// position is updated accordingly. Input reads are UTF-8 safe and the current
/// character is always a valid UTF-8 character. Lines and columns are counted
/// in UTF-8 characters and not in bytes. The offset is always in bytes and
/// counts the number of bytes read from the input.
/// 
/// The underlying string slice can be accessed with `as_str`. The length of the
/// remaining input in bytes can be accessed with `len` and if the input is
/// empty with `is_empty`. If the end of input is reached `current` returns
/// `None` and `is_eof` returns `true`.
/// 
/// When advancing the slice is updated and the current character and position
/// are updated. The current character is always at offset 0 in the slice.
/// Therefore the offset returned by `position` is always the number of bytes
/// read from the begining to the current character.
#[derive(Clone, Copy, Debug)]
pub struct Input<'a> {
    input: &'a str,
    current: (Option<char>, Position, bool),
}

impl<'a> Input<'a> {
    pub fn new(input: &'a str) -> Self {
        let current = if let Some((_, ch)) = Self::decode(input) {
            (Some(ch), Position::new(0, 1, 1), ch == '\n')
        } else {
            (None, Position::new(0, 1, 1), false)
        };

        log::debug!(target: TARGET, "Input: new input {:#}: {:?}", current.1, input);
        Self { input, current }
    }

    /// Return the current character or `None` if end of input is reached.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.current(), Some('a'));
    /// assert_eq!(input.advance(), Some('b'));
    /// assert_eq!(input.current(), Some('b'));
    /// assert_eq!(input.advance(), Some('c'));
    /// assert_eq!(input.current(), Some('c'));
    /// assert_eq!(input.advance(), None);
    /// assert_eq!(input.current(), None);
    /// ```
    #[inline]
    pub const fn current(&self) -> Option<char> {
        self.current.0
    }

    /// Return the current position
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.position().offset(), 0);
    /// assert_eq!(input.advance(), Some('b'));
    /// assert_eq!(input.position().offset(), 1);
    /// assert_eq!(input.advance(), Some('c'));
    /// assert_eq!(input.position().offset(), 2);
    /// assert_eq!(input.advance(), None);
    /// assert_eq!(input.position().offset(), 3);
    /// assert_eq!(input.position().line(), 1);
    /// assert_eq!(input.position().column(), 4);
    /// ```
    #[inline]
    pub const fn position(&self) -> Position {
        self.current.1
    }

    /// Return if the current position marks a newline.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc\n123");
    /// 
    /// assert!(!input.newline());
    /// assert_eq!(input.advance(), Some('b'));
    /// assert_eq!(input.advance(), Some('c'));
    /// assert_eq!(input.advance(), Some('\n'));
    /// assert!(input.newline());
    /// assert_eq!(input.advance(), Some('1'));
    /// ```
    #[inline]
    pub const fn newline(&self) -> bool {
        self.current.2
    }

    /// Reads and returns the next charater. After the function returns the
    /// charater is the current. Returns `None` if end of input is reached.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.advance(), Some('b'));
    /// assert_eq!(input.advance(), Some('c'));
    /// assert_eq!(input.advance(), None);
    /// assert_eq!(input.advance(), None);
    /// ```
    #[inline]
    pub fn advance(&mut self) -> Option<char> {
        if let Some(curr_ch) = self.current.0 {
            let offset = curr_ch.len_utf8();

            self.input = &self.input[offset..];

            if let Some((_, next_ch)) = Self::decode(self.input) {
                let (curr_ch, pos, newline) = &mut self.current;

                if *newline {
                    pos.column = 1;
                    pos.line += 1;
                } else if *curr_ch != Some('\r') {
                    pos.column += 1;
                }
                *curr_ch = Some(next_ch);
                *newline = next_ch == '\n';
                pos.offset += offset as u32;
                log::trace!(target: TARGET, "input: {:#}: {:?}", pos, next_ch);
                return Some(next_ch);
            } else {
                let (ch, pos, _) = &mut self.current;

                if *ch != Some('\r') {
                    pos.column += 1;
                }
                *ch = None;
                pos.offset += offset as u32;
            }
        }
        log::debug!(target: TARGET, "Input: {:#}: reached end of input", self.current.1);
        None
    }

    /// Advances to the character following the tag. Returns `true` if the tag
    /// matched, `false` otherwise. Returns `None` if end of input is reached
    /// and the tag did not match.
    /// 
    /// On `None` and `Some(false)` the input is reset to the state before the
    /// function was called.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.advance_tag("abc"), Some(true));
    /// assert_eq!(input.current(), None);
    /// assert_eq!(input.position().offset(), 3);
    /// 
    /// let mut input = Input::new("ab");
    /// 
    /// assert_eq!(input.advance_tag("abc"), None);
    /// assert_eq!(input.position().offset(), 0);
    /// 
    /// let mut input = Input::new("abdef");
    /// 
    /// assert_eq!(input.advance_tag("abc"), Some(false));
    /// assert_eq!(input.position().offset(), 0);
    /// ```
    pub fn advance_tag(&mut self, tag: &str) -> Option<bool> {
        let state = *self;

        for chr in tag.chars() {
            if let Some(curr) = self.current() {
                if curr != chr {
                    *self = state;
                    return Some(false);
                }
                self.advance();
            } else {
                *self = state;
                return None;
            }
        }
        Some(true)
    }

    #[cfg(feature = "regex")]
    /// Advances to the character following the regular expression. Returns
    /// `Some(matched)` if the regular expression matched, `None` otherwise.
    /// 
    /// # Example
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// # use regex::Regex;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.advance_match(&Regex::new(r"^\w+").unwrap()), Some("abc"));
    /// assert_eq!(input.current(), None);
    /// assert_eq!(input.position().offset(), 3);
    /// 
    /// let mut input = Input::new("ab");
    /// 
    /// assert_eq!(input.advance_match(&Regex::new(r"^\d+").unwrap()), None);
    /// assert_eq!(input.position().offset(), 0);
    /// ```
    pub fn advance_match(&mut self, re: &Regex) -> Option<&'a str> {
        if let Some(mat) = re.find(self.input) {
            let matched = &self.input[..mat.end()];

            for _ in matched.chars() {
                self.advance();
            }
            Some(matched)
        } else {
            None
        }
    }

    /// Advances to the next character if the predicate returns `true` for the
    /// current character. Returns `true` if progress was made, `false`
    /// otherwise. Returns `None` if end of input is reached.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc");
    /// 
    /// assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
    /// assert_eq!(input.current(), Some('b'));
    /// assert_eq!(input.advance_if(|c| c.is_ascii_digit()), Some(false));
    /// assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
    /// assert_eq!(input.current(), Some('c'));
    /// assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
    /// assert_eq!(input.current(), None);
    /// assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), None);
    /// ```
    pub fn advance_if<F>(&mut self, f: F) -> Option<bool>
    where
        F: FnOnce(char) -> bool,
    {
        if let Some(chr) = self.current() {
            if f(chr) {
                self.advance();
                return Some(true);
            }
            return Some(false);
        }
        None
    }

    /// Advances to the next charater as long as the predicate returns `true`
    /// for the current character. Returns the slice that matched. It may be
    /// zero length.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("abc\n123");
    /// 
    /// assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "abc");
    /// assert_eq!(input.current(), Some('\n'));
    /// assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "");
    /// assert_eq!(input.advance(), Some('1'));
    /// assert_eq!(input.advance_while(|c| c.is_ascii_digit()), "123");
    /// assert_eq!(input.current(), None);
    /// assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "");
    /// ```
    pub fn advance_while<F>(&mut self, f: F) -> &'a str
    where
        F: Fn(char) -> bool,
    {
        let matched = self.input;
        let start = self.position().offset();

        while let Some(chr) = self.current() {
            if !f(chr) {
                break;
            }
            self.advance();
        }
        &matched[..(self.position().offset() - start)]
    }

    /// Advances to the next charater as long as the predicate returns `false`
    /// for the current character. Returns `None` if end of input is reached or
    /// `Some(matched)` if the predicate returned `true` for the current
    /// character. The matched slice may be zero length.
    /// 
    /// On `None` the input is reset to the state before the function was
    /// called.
    /// 
    /// ```rust
    /// # use kamo::parser::Input;
    /// let mut input = Input::new("123\nabc|");
    /// 
    /// assert_eq!(input.advance_until(|c| c == '\n'), Some("123"));
    /// assert_eq!(input.current(), Some('\n'));
    /// assert_eq!(input.advance_until(|c| c == '\n'), Some(""));
    /// assert_eq!(input.advance(), Some('a'));
    /// assert_eq!(input.advance_until(|c| c == '|'), Some("abc"));
    /// assert_eq!(input.current(), Some('|'));
    /// assert_eq!(input.advance_until(|c| c.is_ascii_alphabetic()), None);
    /// ```
    pub fn advance_until<F>(&mut self, f: F) -> Option<&'a str>
    where
        F: Fn(char) -> bool,
    {
        let state = *self;
        let matched = self.input;
        let start = self.position().offset();

        while let Some(chr) = self.current() {
            if f(chr) {
                return Some(&matched[..(self.position().offset() - start)]);
            }
            self.advance();
        }
        *self = state;
        None
    }

    /// Return the length of the input in bytes.
    #[inline]
    pub const fn len(&self) -> usize {
        self.input.len()
    }

    /// Return if the input is empty.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.input.is_empty()
    }

    /// Return if the input is at the end.
    #[inline]
    pub const fn is_eof(&self) -> bool {
        self.current.0.is_none()
    }

    /// Returns a reference to the underlying string.
    #[inline]
    pub const fn as_str(&self) -> &'a str {
        self.input
    }

    #[inline]
    fn decode(input: &str) -> Option<(usize, char)> {
        if let Some(ch) = input.chars().next() {
            let offset = ch.len_utf8();
            Some((offset, ch))
        } else {
            None
        }
    }
}

impl PartialEq for Input<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.input == other.input
    }
}

impl<'a> From<&'a str> for Input<'a> {
    fn from(input: &'a str) -> Self {
        Self::new(input)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn input_advance() {
        let mut input = Input::new("abc\n123");

        assert_eq!(input.current(), Some('a'));
        assert_eq!(input.position(), Position::new(0, 1, 1));
        assert!(!input.newline());

        assert_eq!(input.advance(), Some('b'));
        assert_eq!(input.current(), Some('b'));
        assert_eq!(input.position(), Position::new(1, 1, 2));
        assert!(!input.newline());

        assert_eq!(input.advance(), Some('c'));
        assert_eq!(input.current(), Some('c'));
        assert_eq!(input.position(), Position::new(2, 1, 3));
        assert!(!input.newline());

        assert_eq!(input.advance(), Some('\n'));
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance(), Some('1'));
        assert_eq!(input.current(), Some('1'));
        assert_eq!(input.position(), Position::new(4, 2, 1));
        assert!(!input.newline());

        assert_eq!(input.advance(), Some('2'));
        assert_eq!(input.current(), Some('2'));
        assert_eq!(input.position(), Position::new(5, 2, 2));
        assert!(!input.newline());

        assert_eq!(input.advance(), Some('3'));
        assert_eq!(input.current(), Some('3'));
        assert_eq!(input.position(), Position::new(6, 2, 3));
        assert!(!input.newline());

        assert_eq!(input.advance(), None);
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());

        assert_eq!(input.advance(), None);
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());
    }

    #[test]
    fn input_advance_if() {
        let mut input = Input::new("abc\n123");

        assert_eq!(input.current(), Some('a'));
        assert_eq!(input.position(), Position::new(0, 1, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
        assert_eq!(input.current(), Some('b'));
        assert_eq!(input.position(), Position::new(1, 1, 2));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
        assert_eq!(input.current(), Some('c'));
        assert_eq!(input.position(), Position::new(2, 1, 3));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(true));
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_alphabetic()), Some(false));
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance(), Some('1'));
        assert_eq!(input.current(), Some('1'));
        assert_eq!(input.position(), Position::new(4, 2, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_digit()), Some(true));
        assert_eq!(input.current(), Some('2'));
        assert_eq!(input.position(), Position::new(5, 2, 2));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_digit()), Some(true));
        assert_eq!(input.current(), Some('3'));
        assert_eq!(input.position(), Position::new(6, 2, 3));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_digit()), Some(true));
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());

        assert_eq!(input.advance_if(|c| c.is_ascii_digit()), None);
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());
    }

    #[test]
    fn input_advance_while() {
        let mut input = Input::new("abc\n123");

        assert_eq!(input.current(), Some('a'));
        assert_eq!(input.position(), Position::new(0, 1, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "abc");
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "");
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance(), Some('1'));
        assert_eq!(input.current(), Some('1'));
        assert_eq!(input.position(), Position::new(4, 2, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_while(|c| c.is_ascii_digit()), "123");
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());

        assert_eq!(input.advance_while(|c| c.is_ascii_alphabetic()), "");
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());
    }

    #[cfg(feature = "regex")]
    #[test]
    fn input_advance_match() {
        let mut input = Input::new("abc\n123");

        assert_eq!(input.current(), Some('a'));
        assert_eq!(input.position(), Position::new(0, 1, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_match(&Regex::new(r"^\w+").unwrap()), Some("abc"));
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance_match(&Regex::new(r"^\w+").unwrap()), None);
        assert_eq!(input.current(), Some('\n'));
        assert_eq!(input.position(), Position::new(3, 1, 4));
        assert!(input.newline());

        assert_eq!(input.advance(), Some('1'));
        assert_eq!(input.current(), Some('1'));
        assert_eq!(input.position(), Position::new(4, 2, 1));
        assert!(!input.newline());

        assert_eq!(input.advance_match(&Regex::new(r"^\d+").unwrap()), Some("123"));
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());

        assert_eq!(input.advance_match(&Regex::new(r"^\w+").unwrap()), None);
        assert_eq!(input.current(), None);
        assert_eq!(input.position(), Position::new(7, 2, 4));
        assert!(!input.newline());
    }
}