luau_lexer/token/keyword.rs
1//! [`Keyword`] and [`PartialKeyword`] enums.
2
3/// A macro to generate an enum for keywords.
4macro_rules! generate_keyword_enum {
5 ($(#[$meta:meta])* $vis:vis enum $struct: ident {
6 $( $(#[$name_meta:meta])* $str: literal => $name: ident ),* $(,)?
7 }) => {
8 $(#[$meta])*
9 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
10 #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
11 $vis enum $struct {
12 $( $(#[$name_meta])* $name, )*
13 }
14
15 impl $struct {
16 /// Try creating this item from a string.
17 pub fn try_from_str(value: &str) -> Option<Self> {
18 match value {
19 $( $str => Some(Self::$name), )*
20 _ => None,
21 }
22 }
23 }
24
25 impl std::fmt::Display for $struct {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 f.write_str(match self {
28 $( Self::$name => $str, )*
29 })
30 }
31 }
32 };
33}
34
35generate_keyword_enum!(
36 /// Words that can only be used as be keywords. Check [`PartialKeyword`].
37 pub enum Keyword {
38 /// The `local` keyword.
39 "local" => Local,
40
41 /// The `function` keyword.
42 "function" => Function,
43
44 /// The `if` keyword.
45 "if" => If,
46
47 /// The `elseif` keyword.
48 "elseif" => Elseif,
49
50 /// The `then` keyword.
51 "then" => Then,
52
53 /// The `else` keyword.
54 "else" => Else,
55
56 /// The `while` keyword.
57 "while" => While,
58
59 /// The `for` keyword.
60 "for" => For,
61
62 /// The `in` keyword.
63 "in" => In,
64
65 /// The `do` keyword.
66 "do" => Do,
67
68 /// The `break` keyword.
69 "break" => Break,
70
71 /// The `return` keyword.
72 "return" => Return,
73
74 /// The `end` keyword.
75 "end" => End,
76
77 /// The `repeat` keyword.
78 "repeat" => Repeat,
79
80 /// The `until` keyword.
81 "until" => Until,
82
83 /// The `nil` keyword.
84 "nil" => Nil,
85 }
86);
87generate_keyword_enum!(
88 /// Words that can be keywords or identifiers, depending on the context.
89 /// Check [`Keyword`].
90 pub enum PartialKeyword {
91 /// The `type` keyword
92 "type" => Type,
93
94 /// The `continue` keyword
95 "continue" => Continue,
96
97 /// The `export` keyword
98 "export" => Export,
99
100 /// The `typeof` keyword
101 "typeof" => TypeOf,
102 }
103);