This repository was archived by the owner on Sep 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparse.rs
More file actions
275 lines (244 loc) · 6.64 KB
/
parse.rs
File metadata and controls
275 lines (244 loc) · 6.64 KB
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use std::collections::HashSet;
use std::str::{Chars, FromStr};
use strum::*;
use strum_macros::*;
use thiserror::Error;
#[derive(Debug, Clone, Default)]
pub struct SyntaxTree {
pub constructs: Vec<Construct>,
}
#[derive(Debug, Clone)]
pub enum Construct {
Keyword(Keyword),
Identifier(String),
Block(SyntaxTree),
Parenthesized(SyntaxTree),
Literal(Literal),
Token(Token),
}
impl Construct {
pub fn as_keyword(&self) -> Option<&Keyword> {
match self {
Construct::Keyword(x) => Some(x),
_ => None,
}
}
pub fn as_identifier(&self) -> Option<String> {
match self {
Construct::Identifier(x) => Some(x.clone()),
Construct::Keyword(k) => Some(k.to_string().to_lowercase()),
_ => None,
}
}
pub fn as_block(&self) -> Option<&SyntaxTree> {
match self {
Construct::Block(x) => Some(x),
_ => None,
}
}
pub fn as_parenthesized(&self) -> Option<&SyntaxTree> {
match self {
Construct::Parenthesized(x) => Some(x),
_ => None,
}
}
pub fn as_literal(&self) -> Option<&Literal> {
match self {
Construct::Literal(x) => Some(x),
_ => None,
}
}
pub fn as_token(&self) -> Option<&Token> {
match self {
Construct::Token(x) => Some(x),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub enum Literal {
Integer(i64),
String(String),
}
impl Literal {
pub fn as_integer(&self) -> Option<i64> {
match self {
Literal::Integer(x) => Some(*x),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match self {
Literal::String(s) => Some(s.as_str()),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Token {
Semicolon, // ;
Comma, // ,
Equals, // =
Yields, // =>
Array, // []
Annotation, // @
}
impl Token {
fn from_str(x: &str) -> Option<Self> {
match x {
";" => Some(Token::Semicolon),
"," => Some(Token::Comma),
"=" => Some(Token::Equals),
"=>" => Some(Token::Yields),
"[]" => Some(Token::Array),
"@" => Some(Token::Annotation),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumString, Display, AsRefStr, EnumIter)]
pub enum Keyword {
Clientbound,
Serverbound,
Byte,
Short,
Int,
Long,
Ubyte,
Ushort,
Uint,
Ulong,
Struct,
Enum,
Block,
Item,
Identifier,
Chat,
Boolean,
Position,
Slot,
Node,
Nbt,
Varint,
Uuid,
Float,
Angle,
Double,
String,
#[strum(serialize = "Opt_chat")]
OptChat,
}
pub fn parse_str(input: &str) -> anyhow::Result<SyntaxTree> {
let mut tree = SyntaxTree::default();
let mut input = input.chars();
parse(&mut input, &mut tree, None)?;
Ok(tree)
}
#[derive(Debug, Error)]
pub enum Error {
#[error("unexpected end of input")]
UnexpectedEof,
}
/// Trash parser function. Messy algorithm; don't see this as
/// clean—but it works.
fn parse(input: &mut Chars, tree: &mut SyntaxTree, until: Option<char>) -> Result<(), Error> {
let mut current = String::new();
loop {
if let Some(char) = input.next() {
if until.map_or(false, |until| until == char) {
if !current.is_empty() {
tree.constructs.push(construct(¤t)?);
}
current.clear();
break;
}
if char == '{' {
let mut block = SyntaxTree::default();
parse(input, &mut block, Some('}'))?;
if !current.is_empty() {
tree.constructs.push(construct(¤t)?);
}
current.clear();
tree.constructs.push(Construct::Block(block));
current.clear();
continue;
} else if char == '(' {
let mut parenthesized = SyntaxTree::default();
parse(input, &mut parenthesized, Some(')'))?;
if !current.is_empty() {
tree.constructs.push(construct(¤t)?);
}
current.clear();
tree.constructs
.push(Construct::Parenthesized(parenthesized));
continue;
} else if char == '"' {
tree.constructs
.push(Construct::Literal(parse_string_literal(input)?));
current.clear();
continue;
} else if let Some(token) = Token::from_str(&char.to_string()) {
if !current.is_empty() {
tree.constructs.push(construct(¤t)?);
}
current.clear();
tree.constructs.push(Construct::Token(token));
continue;
}
if char.is_whitespace() {
if !current.is_empty() {
tree.constructs.push(construct(¤t)?);
}
current.clear();
} else {
current.push(char);
}
} else {
if until.is_some() {
return Err(Error::UnexpectedEof);
} else {
break;
}
}
}
Ok(())
}
fn parse_string_literal(input: &mut Chars) -> Result<Literal, Error> {
let mut s = String::new();
loop {
let char = input.next().ok_or(Error::UnexpectedEof)?;
if char == '"' {
return Ok(Literal::String(s));
} else {
s.push(char);
}
}
}
fn construct(from: &str) -> Result<Construct, Error> {
let keywords: HashSet<String> = Keyword::iter()
.map(|keyword| keyword.to_string().to_lowercase())
.collect();
let construct = if keywords.contains(from) {
Construct::Keyword(keyword_from_str(from))
} else if let Ok(x) = i64::from_str(from) {
Construct::Literal(Literal::Integer(x))
} else if let Some(token) = Token::from_str(from) {
Construct::Token(token)
} else {
Construct::Identifier(from.to_string())
};
Ok(construct)
}
fn keyword_from_str(x: &str) -> Keyword {
Keyword::from_str(&capitalize_first(x)).unwrap()
}
fn capitalize_first(s: &str) -> String {
let mut chars = s.chars();
chars
.next()
.map(|first_letter| first_letter.to_uppercase())
.into_iter()
.flatten()
.chain(chars)
.collect()
}