yash_syntax/parser/lex/
keyword.rs1use std::fmt;
20use std::str::FromStr;
21use thiserror::Error;
22
23#[derive(Clone, Debug, Eq, Error, Hash, PartialEq)]
28pub struct ParseKeywordError;
29
30impl fmt::Display for ParseKeywordError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 f.write_str("not a keyword")
33 }
34}
35
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum Keyword {
39 Bang,
40 OpenBracketBracket,
42 Case,
43 Do,
44 Done,
45 Elif,
46 Else,
47 Esac,
48 Fi,
49 For,
50 Function,
51 If,
52 In,
53 Then,
54 Until,
55 While,
56 OpenBrace,
58 CloseBrace,
60}
61
62impl Keyword {
63 #[must_use]
65 pub const fn as_str(&self) -> &'static str {
66 use Keyword::*;
67 match self {
68 Bang => "!",
69 OpenBracketBracket => "[[",
70 Case => "case",
71 Do => "do",
72 Done => "done",
73 Elif => "elif",
74 Else => "else",
75 Esac => "esac",
76 Fi => "fi",
77 For => "for",
78 Function => "function",
79 If => "if",
80 In => "in",
81 Then => "then",
82 Until => "until",
83 While => "while",
84 OpenBrace => "{",
85 CloseBrace => "}",
86 }
87 }
88
89 #[must_use]
94 pub const fn is_clause_delimiter(self) -> bool {
95 use Keyword::*;
96 match self {
97 Do | Done | Elif | Else | Esac | Fi | Then | CloseBrace => true,
98 Bang | OpenBracketBracket | Case | For | Function | If | In | Until | While
99 | OpenBrace => false,
100 }
101 }
102}
103
104impl fmt::Display for Keyword {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.write_str(self.as_str())
107 }
108}
109
110impl FromStr for Keyword {
111 type Err = ParseKeywordError;
112 fn from_str(s: &str) -> Result<Keyword, ParseKeywordError> {
113 use Keyword::*;
114 match s {
115 "!" => Ok(Bang),
116 "[[" => Ok(OpenBracketBracket),
117 "case" => Ok(Case),
118 "do" => Ok(Do),
119 "done" => Ok(Done),
120 "elif" => Ok(Elif),
121 "else" => Ok(Else),
122 "esac" => Ok(Esac),
123 "fi" => Ok(Fi),
124 "for" => Ok(For),
125 "function" => Ok(Function),
126 "if" => Ok(If),
127 "in" => Ok(In),
128 "then" => Ok(Then),
129 "until" => Ok(Until),
130 "while" => Ok(While),
131 "{" => Ok(OpenBrace),
132 "}" => Ok(CloseBrace),
133 _ => Err(ParseKeywordError),
134 }
135 }
136}