1use std::{cmp, error::Error, fmt, hash::Hash, marker};
2
3use cfgrammar::Span;
4use lrpar::{Lexeme, LexerTypes};
5use num_traits::{AsPrimitive, PrimInt, Unsigned};
6
7use crate::LRLexError;
8
9#[derive(Debug)]
11pub struct DefaultLexerTypes<T = u32>
12where
13 T: 'static + fmt::Debug + Hash + PrimInt + Unsigned,
14 usize: AsPrimitive<T>,
15{
16 phantom: std::marker::PhantomData<T>,
17}
18
19impl<T> LexerTypes for DefaultLexerTypes<T>
20where
21 usize: AsPrimitive<T>,
22 T: 'static + fmt::Debug + Hash + PrimInt + Unsigned,
23{
24 type LexemeT = DefaultLexeme<T>;
25 type StorageT = T;
26 type LexErrorT = LRLexError;
27}
28
29#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
31pub struct DefaultLexeme<StorageT: fmt::Debug = u32> {
32 start: usize,
33 len: usize,
34 faulty: bool,
35 tok_id: StorageT,
36}
37
38impl<StorageT: Copy + fmt::Debug + Hash + cmp::Eq> Lexeme<StorageT> for DefaultLexeme<StorageT> {
39 fn new(tok_id: StorageT, start: usize, len: usize) -> Self {
40 DefaultLexeme {
41 start,
42 len,
43 faulty: false,
44 tok_id,
45 }
46 }
47
48 fn new_faulty(tok_id: StorageT, start: usize, len: usize) -> Self {
49 DefaultLexeme {
50 start,
51 len,
52 faulty: true,
53 tok_id,
54 }
55 }
56
57 fn tok_id(&self) -> StorageT {
58 self.tok_id
59 }
60
61 fn span(&self) -> Span {
62 Span::new(self.start, self.start + self.len)
63 }
64
65 fn faulty(&self) -> bool {
66 self.faulty
67 }
68}
69
70impl<StorageT: Copy + fmt::Debug + cmp::Eq + Hash + marker::Copy> fmt::Display
71 for DefaultLexeme<StorageT>
72{
73 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74 write!(
75 f,
76 "DefaultLexeme[{}..{}]",
77 self.span().start(),
78 self.span().end()
79 )
80 }
81}
82
83impl<StorageT: Copy + fmt::Debug + cmp::Eq + Hash + marker::Copy> Error
84 for DefaultLexeme<StorageT>
85{
86}