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
use std::{cmp, error::Error, fmt, hash::Hash, marker};

use cfgrammar::Span;
use lrpar::{Lexeme, LexerTypes};
use num_traits::{AsPrimitive, PrimInt, Unsigned};

use crate::LRLexError;

/// lrlex's standard [LexerTypes] `struct`, provided as a convenience.
#[derive(Debug)]
pub struct DefaultLexerTypes<T = u32>
where
    T: 'static + fmt::Debug + Hash + PrimInt + Unsigned,
    usize: AsPrimitive<T>,
{
    phantom: std::marker::PhantomData<T>,
}

impl<T> LexerTypes for DefaultLexerTypes<T>
where
    usize: AsPrimitive<T>,
    T: 'static + fmt::Debug + Hash + PrimInt + Unsigned,
{
    type LexemeT = DefaultLexeme<T>;
    type StorageT = T;
    type LexErrorT = LRLexError;
}

/// lrlex's standard lexeme struct, provided as a convenience.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct DefaultLexeme<StorageT: fmt::Debug = u32> {
    start: usize,
    len: usize,
    faulty: bool,
    tok_id: StorageT,
}

impl<StorageT: Copy + fmt::Debug + Hash + cmp::Eq> Lexeme<StorageT> for DefaultLexeme<StorageT> {
    fn new(tok_id: StorageT, start: usize, len: usize) -> Self {
        DefaultLexeme {
            start,
            len,
            faulty: false,
            tok_id,
        }
    }

    fn new_faulty(tok_id: StorageT, start: usize, len: usize) -> Self {
        DefaultLexeme {
            start,
            len,
            faulty: true,
            tok_id,
        }
    }

    fn tok_id(&self) -> StorageT {
        self.tok_id
    }

    fn span(&self) -> Span {
        Span::new(self.start, self.start + self.len)
    }

    fn faulty(&self) -> bool {
        self.faulty
    }
}

impl<StorageT: Copy + fmt::Debug + cmp::Eq + Hash + marker::Copy> fmt::Display
    for DefaultLexeme<StorageT>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "DefaultLexeme[{}..{}]",
            self.span().start(),
            self.span().end()
        )
    }
}

impl<StorageT: Copy + fmt::Debug + cmp::Eq + Hash + marker::Copy> Error
    for DefaultLexeme<StorageT>
{
}