char_lex/
traits.rs

1use super::utils::Context;
2
3/// The main trait for `Tokens`,
4/// it is the automatically implemented by the `token` attribute macro.
5pub trait TokenTrait
6where
7    Self: Sized + PartialEq,
8{
9    /// Returns the enum element that matches the given `char`.
10    fn match_char(c: char) -> Option<Self>;
11}
12
13/// Trait for anything that wants to automatically wrap a `Token`.
14pub trait TokenWrapper<T>
15where
16    Self: Sized,
17    T: TokenTrait,
18{
19    /// Function that wraps the `Token` and the `Context` and returns itself.
20    fn wrap(token: T, context: Context) -> Self;
21}
22
23impl<T> TokenWrapper<T> for T
24where
25    T: TokenTrait,
26{
27    fn wrap(token: T, _: Context) -> Self {
28        token
29    }
30}
31
32/// Trait for anything that wants to match a single `Token`.
33pub trait TokenMatch<T>
34where
35    T: TokenTrait,
36{
37    /// Function that matches a single `Token`.
38    fn matches_token(&self, t: &T) -> bool;
39}
40
41impl<T> TokenMatch<T> for T
42where
43    T: TokenTrait,
44{
45    fn matches_token(&self, t: &T) -> bool {
46        self == t
47    }
48}
49
50impl<T> TokenMatch<T> for Vec<T>
51where
52    T: TokenTrait,
53{
54    fn matches_token(&self, t: &T) -> bool {
55        for token in self {
56            if token == t {
57                return true;
58            }
59        }
60        false
61    }
62}