Debian Codegraph @

src/parser.rs

raw symbols SCIP
1 use crate::lexer::{lex, LexItem};
2
3 const OPEN_PAREN: char = '{';
4 const CLOSED_PAREN: char = '}';
5
6 #[derive(Debug, Clone)]
7 pub enum ParseError {
8 UnexpectedEndOfInput,
9 UnexpectedInput {
10 found: String,
11 expected: Vec<String>,
12 },
13 }
14
15 #[derive(Debug, Clone, Eq, PartialEq)]
16 pub(crate) enum GrammarItem {
17 Notation {
18 meta: Vec<String>,
19 params: Vec<String>,
20 tag: String,
21 },
22 Text(String),
23 GroupStart,
24 GroupEnd,
25 }
26
27 pub(crate) fn parse(input: String) -> Result<Vec<GrammarItem>, ParseError> {
28 let mut lexed = lex(input);
29 lexed.push(LexItem::Space);
30 lexed.push(LexItem::Space);
31 lexed.push(LexItem::Space);
32 parse_items(lexed)
33 }
34
35 fn parse_items(input: Vec<LexItem>) -> Result<Vec<GrammarItem>, ParseError> {
36 let mut grammar_items = vec![];
37 let mut param_iter_skip_count = 0;
38
39 for item in input.windows(4) {
40 let current = item.get(0).unwrap();
41 let next = item.get(1);
42
43 match current {
44 LexItem::At(_) => {
45 if let Some(next) = next {
46 match next {
47 LexItem::Paren(v) => match *v {
48 OPEN_PAREN => grammar_items.push(GrammarItem::GroupStart),
49 CLOSED_PAREN => grammar_items.push(GrammarItem::GroupEnd),
50 _ => {
51 return Err(ParseError::UnexpectedInput {
52 found: v.to_string(),
53 expected: vec![OPEN_PAREN.into(), CLOSED_PAREN.into()],
54 })
55 }
56 },
57 LexItem::Word(v) => {
58 let mut meta = vec![];
59 let params;
60 let content;
61
62 if v.starts_with("param") {
63 let value = v.split('[').collect::<Vec<_>>();
64 match value.get(1) {
65 Some(&"in]") => meta.push("in".into()),
66 Some(&"out]") => meta.push("out".into()),
67 Some(&"in,out]") | Some(&"out,in]") => {
68 meta.push("in".into());
69 meta.push("out".into());
70 }
71 _ => match value.get(1) {
72 None => {}
73 Some(v) => {
74 return Err(ParseError::UnexpectedInput {
75 found: v.to_string(),
76 expected: vec!["in]".into(), "out]".into()],
77 })
78 }
79 },
80 }
81
82 params = match item.get(3) {
83 None => vec![],
84 Some(LexItem::Word(v)) => vec![v.into()],
85 Some(_) => vec![],
86 };
87
88 content = "param"
89 } else {
90 content = v;
91
92 params = match v.as_str() {
93 "a" | "b" | "c" | "p" | "emoji" | "e" | "em" | "def"
94 | "class" | "category" | "concept" | "enum" | "example"
95 | "extends" | "file" | "sa" | "see" | "retval"
96 | "exception" | "throw" | "throws" => match item.get(3) {
97 None => vec![],
98 Some(LexItem::Word(v)) => vec![v.into()],
99 Some(_) => vec![],
100 },
101 _ => vec![],
102 };
103 }
104
105 if params.is_empty() {
106 param_iter_skip_count = 1;
107 } else {
108 param_iter_skip_count = 2;
109 }
110
111 grammar_items.push(GrammarItem::Notation {
112 meta,
113 params,
114 tag: content.into(),
115 });
116 }
117 _ => {}
118 }
119 }
120 }
121 LexItem::Word(v) => {
122 if param_iter_skip_count > 0 {
123 param_iter_skip_count -= 1;
124 continue;
125 }
126
127 if let Some(prev) = grammar_items.last_mut() {
128 match prev {
129 GrammarItem::Text(text) => *text += v,
130 _ => grammar_items.push(GrammarItem::Text(v.into())),
131 }
132 } else {
133 grammar_items.push(GrammarItem::Text(v.into()));
134 }
135 }
136 LexItem::Space => {
137 if let Some(prev) = grammar_items.last_mut() {
138 match prev {
139 GrammarItem::Text(text) => *text += " ",
140 _ => grammar_items.push(GrammarItem::Text("".into())),
141 }
142 } else {
143 grammar_items.push(GrammarItem::Text(" ".into()))
144 }
145 }
146 LexItem::NewLine => {
147 if let Some(GrammarItem::Text(text)) = grammar_items.last_mut() {
148 *text += "\n"
149 }
150 }
151 LexItem::Paren(v) => {
152 if let Some(GrammarItem::Text(text)) = grammar_items.last_mut() {
153 *text += &v.to_string()
154 }
155 }
156 }
157 }
158
159 Ok(grammar_items)
160 }
161
162 #[cfg(test)]
163 mod test {
164 use super::*;
165
166 #[test]
167 pub fn simple_notation() {
168 let result = parse("@name Memory Management".into()).unwrap();
169 assert_eq!(
170 result,
171 vec![
172 GrammarItem::Notation {
173 meta: vec![],
174 params: vec![],
175 tag: "name".into(),
176 },
177 GrammarItem::Text("Memory Management".into())
178 ]
179 );
180 }
181
182 #[test]
183 pub fn paren_in_notation() {
184 let result = parse("@note hoge_t = {a, b, c}".into()).unwrap();
185 assert_eq!(
186 result,
187 vec![
188 GrammarItem::Notation {
189 meta: vec![],
190 params: vec![],
191 tag: "note".into(),
192 },
193 GrammarItem::Text("hoge_t = {a, b, c}".into())
194 ]
195 );
196 }
197
198 #[test]
199 pub fn param() {
200 let result =
201 parse("@param[in] random This is, without a doubt, a random argument.".into()).unwrap();
202 assert_eq!(
203 result,
204 vec![
205 GrammarItem::Notation {
206 meta: vec!["in".into()],
207 params: vec!["random".into()],
208 tag: "param".into(),
209 },
210 GrammarItem::Text(" This is, without a doubt, a random argument.".into())
211 ]
212 );
213 }
214
215 #[test]
216 pub fn groups() {
217 let result = parse("@{\n* @name Memory Management\n@}".into()).unwrap();
218 assert_eq!(
219 result,
220 vec![
221 GrammarItem::GroupStart,
222 GrammarItem::Text("* ".into()),
223 GrammarItem::Notation {
224 meta: vec![],
225 params: vec![],
226 tag: "name".into(),
227 },
228 GrammarItem::Text("Memory Management\n".into()),
229 GrammarItem::GroupEnd
230 ]
231 );
232 }
233
234 #[test]
235 pub fn trims_param_texts() {
236 let result = parse("@param[in] var Example description".into()).unwrap();
237 assert_eq!(
238 result,
239 vec![
240 GrammarItem::Notation {
241 meta: vec!["in".into()],
242 params: vec!["var".into()],
243 tag: "param".into(),
244 },
245 GrammarItem::Text(" Example description".into())
246 ]
247 )
248 }
249 }