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
//! Declares macros to help implementing parsers.

/// Macro for declaring a keyword enumeration to help parse a document.
///
/// A keyword enumber implements the Keyword trait.
///
/// These enums are a bit different from those made by `caret`, in a
/// few ways.  Notably, they are optimized for parsing, they are
/// required to be compact, and they allow multiple strings to be mapped to
/// a single index.
///
/// ```ignore
/// decl_keyword! {
///    Location {
//         "start" => START,
///        "middle" | "center" => MID,
///        "end" => END
///    }
/// }
///
/// assert_eq!(Location::from_str("start"), Location::START);
/// assert_eq!(Location::from_str("stfff"), Location::UNRECOGNIZED);
/// ```
macro_rules! decl_keyword {
    { $(#[$meta:meta])* $v:vis
      $name:ident { $( $($anno:ident)? $($s:literal)|+ => $i:ident),* $(,)? } } => {
        #[derive(Copy,Clone,Eq,PartialEq,Debug,std::hash::Hash)]
        #[allow(non_camel_case_types)]
        $(#[$meta])*
        #[allow(unknown_lints)]
        #[allow(clippy::unknown_clippy_lints)]
        #[allow(clippy::upper_case_acronyms)]
        $v enum $name {
            $( $i , )*
            UNRECOGNIZED,
            ANN_UNRECOGNIZED
        }
        impl $crate::parse::keyword::Keyword for $name {
            fn idx(self) -> usize { self as usize }
            fn n_vals() -> usize { ($name::ANN_UNRECOGNIZED as usize) + 1 }
            fn unrecognized() -> Self { $name::UNRECOGNIZED }
            fn ann_unrecognized() -> Self { $name::ANN_UNRECOGNIZED }
            fn from_str(s : &str) -> Self {
                // Note usage of phf crate to create a perfect hash over
                // the possible keywords.  It will be even better if someday
                // the phf crate can find hash functions that are better
                // than siphash.
                const KEYWORD: phf::Map<&'static str, $name> = phf::phf_map! {
                    $( $( $s => $name::$i , )+ )*
                };
                match KEYWORD.get(s) {
                    Some(k) => *k,
                    None => if s.starts_with('@') {
                        $name::ANN_UNRECOGNIZED
                    } else {
                        $name::UNRECOGNIZED
                    }
                }
            }
            fn from_idx(i : usize) -> Option<Self> {
                // Note looking up the value in a vec.  This may or may
                // not be faster than a case statement would be.
                static VALS: once_cell::sync::Lazy<Vec<$name>> =
                    once_cell::sync::Lazy::new(
                        || vec![ $($name::$i , )*
                              $name::UNRECOGNIZED,
                                 $name::ANN_UNRECOGNIZED ]);
                VALS.get(i).copied()
            }
            fn to_str(self) -> &'static str {
                use $name::*;
                match self {
                    $( $i => decl_keyword![@impl join $($s),+], )*
                    UNRECOGNIZED => "<unrecognized>",
                    ANN_UNRECOGNIZED => "<unrecognized annotation>"
                }
            }
            fn is_annotation(self) -> bool {
                use $name::*;
                match self {
                    $( $i => decl_keyword![@impl is_anno $($anno)? ], )*
                    UNRECOGNIZED => false,
                    ANN_UNRECOGNIZED => true,
                }
            }
        }
    };
    [ @impl is_anno annotation ] => ( true );
    [ @impl is_anno $x:ident ] => ( compile_error!("unrecognized keyword; not annotation") );
    [ @impl is_anno ] => ( false );
    [ @impl join $s:literal ] => ( $s );
    [ @impl join $s:literal , $($ss:literal),+ ] => (
        concat! { $s, "/", decl_keyword![@impl join $($ss),*] }
    );
}

#[cfg(test)]
pub(crate) mod test {

    decl_keyword! {
        pub(crate) Fruit {
            "apple" => APPLE,
            "orange" => ORANGE,
            "lemon" => LEMON,
            "guava" => GUAVA,
            "cherry" | "plum" => STONEFRUIT,
            annotation "@tasty" => ANN_TASTY,
        }
    }

    #[test]
    fn kwd() {
        use crate::parse::keyword::Keyword;
        use Fruit::*;
        assert_eq!(Fruit::from_str("lemon"), LEMON);
        assert_eq!(Fruit::from_str("cherry"), STONEFRUIT);
        assert_eq!(Fruit::from_str("plum"), STONEFRUIT);
        assert_eq!(Fruit::from_str("pear"), UNRECOGNIZED);
        assert_eq!(Fruit::from_str("@tasty"), ANN_TASTY);
        assert_eq!(Fruit::from_str("@tastier"), ANN_UNRECOGNIZED);

        assert_eq!(APPLE.idx(), 0);
        assert_eq!(ORANGE.idx(), 1);
        assert_eq!(ANN_UNRECOGNIZED.idx(), 7);
        assert_eq!(Fruit::n_vals(), 8);

        assert_eq!(Fruit::from_idx(0), Some(APPLE));
        assert_eq!(Fruit::from_idx(7), Some(ANN_UNRECOGNIZED));
        assert_eq!(Fruit::from_idx(8), None);

        assert_eq!(Fruit::idx_to_str(3), "guava");
        assert_eq!(Fruit::idx_to_str(999), "<out of range>");

        assert_eq!(APPLE.to_str(), "apple");
        assert_eq!(GUAVA.to_str(), "guava");
        assert_eq!(ANN_TASTY.to_str(), "@tasty");
        assert_eq!(STONEFRUIT.to_str(), "cherry/plum");
        assert_eq!(UNRECOGNIZED.to_str(), "<unrecognized>");
        assert_eq!(ANN_UNRECOGNIZED.to_str(), "<unrecognized annotation>");

        assert!(!GUAVA.is_annotation());
        assert!(!STONEFRUIT.is_annotation());
        assert!(!UNRECOGNIZED.is_annotation());
        assert!(ANN_TASTY.is_annotation());
        assert!(ANN_UNRECOGNIZED.is_annotation());
    }
}