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
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum YAMLKey<'a> {
Slice(&'a str),
Index(usize),
}
#[derive(Debug, PartialEq, Eq)]
pub enum RootYAMLValue<'a> {
String(&'a str),
MultilineString(MultilineString<'a>),
Number(&'a str),
True,
False,
// Null,
}
#[derive(Debug)]
pub enum YAMLParseErrorReason {
ExpectedColon,
ExpectedEndOfValue,
ExpectedBracket,
ExpectedTrueFalseNull,
ExpectedValue,
}
#[derive(Debug)]
pub struct YAMLParseError {
pub at: usize,
pub reason: YAMLParseErrorReason,
}
impl std::error::Error for YAMLParseError {}
impl std::fmt::Display for YAMLParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_fmt(format_args!(
"YAMLParseError: {:?} at {:?}",
self.reason, self.at
))
}
}
/// If you want to return early (not parse the whole input) use [`parse_with_exit_signal`]
///
/// # Errors
/// Returns an error if it tries to parse invalid YAML input
pub fn parse<'a>(
on: &'a str,
mut cb: impl for<'b> FnMut(&'b [YAMLKey<'a>], RootYAMLValue<'a>),
) -> Result<(), YAMLParseError> {
parse_with_exit_signal(
on,
|k, v| {
cb(k, v);
false
},
&ParseOptions::default(),
)
}
/// For `|` and `>` based values
#[derive(Debug, PartialEq, Eq)]
pub struct MultilineString<'a> {
on: &'a str,
/// replace new lines with spaces. Done using `>`
collapse: bool,
/// with `|+` etc
preserve_leading_whitespace: bool,
}
pub struct ParseOptions {
pub indent_size: usize,
}
impl Default for ParseOptions {
fn default() -> Self {
Self { indent_size: 2 }
}
}
/// # Errors
/// Returns an error if it tries to parse invalid YAML input
#[allow(clippy::too_many_lines)]
pub fn parse_with_exit_signal<'a>(
on: &'a str,
mut cb: impl for<'b> FnMut(&'b [YAMLKey<'a>], RootYAMLValue<'a>) -> bool,
options: &ParseOptions,
) -> Result<(), YAMLParseError> {
enum State {
Value,
Identifier,
ListItem,
Multiline {
collapse: bool,
preserve_leading_whitespace: bool,
indent: usize,
},
Skip,
}
let chars = on.char_indices();
let mut key_chain = Vec::new();
let mut state = State::Identifier;
let mut list_idx: usize = 0;
let mut indent = 0;
let mut start = 0;
for (idx, chr) in chars {
match state {
State::Value => {
let rest_of_line = on[start..idx].trim();
if let (true, '-') = (rest_of_line.is_empty(), chr) {
state = State::ListItem;
start = idx + '-'.len_utf8();
} else if let '\n' = chr {
if rest_of_line.is_empty() {
// ready for identifier
state = State::Skip;
} else {
let modifier = match rest_of_line {
"|" => Some((true, false)),
">" => Some((false, false)),
_ => None,
};
if let Some((collapse, preserve_leading_whitespace)) = modifier {
state = State::Multiline {
collapse,
preserve_leading_whitespace,
indent,
};
start = idx;
} else {
let value = on[start..idx].trim();
let value = match value {
"true" => RootYAMLValue::True,
"false" => RootYAMLValue::False,
value => RootYAMLValue::String(value),
};
cb(&key_chain, value);
key_chain.pop();
state = State::Skip;
}
}
indent = 0;
}
}
State::Multiline {
collapse,
preserve_leading_whitespace,
indent: current_indent,
} => {
if let '\n' = chr {
let upcoming_line = &on[(idx + '\n'.len_utf8())..];
let mut upcoming_indent = 0;
let mut is_empty = false;
for chr in upcoming_line.chars() {
if let '\n' = chr {
is_empty = true;
break;
}
if let '\t' | ' ' = chr {
upcoming_indent += 1;
} else {
break;
}
}
if !is_empty && upcoming_indent <= current_indent {
let multiline_string = MultilineString {
on: &on[start..idx],
collapse,
preserve_leading_whitespace,
};
cb(&key_chain, RootYAMLValue::MultilineString(multiline_string));
key_chain.pop();
state = State::Skip;
indent = 0;
}
}
}
State::Identifier => {
if let ':' = chr {
let key = YAMLKey::Slice(on[start..idx].trim());
let current_level = indent / options.indent_size;
let keys = key_chain
.iter()
.filter(|key| matches!(key, YAMLKey::Slice(_)))
.count();
if current_level < keys {
drop(key_chain.drain(current_level..));
match key_chain.last() {
Some(YAMLKey::Index(idx)) => {
list_idx = *idx;
}
_ => {
list_idx = 0;
}
}
}
key_chain.push(key);
state = State::Value;
start = idx + ':'.len_utf8();
}
// TODO whitespace warning etc...?
}
State::ListItem => {
if let ':' = chr {
let current_level = indent / options.indent_size;
if current_level < key_chain.len() {
drop(key_chain.drain((current_level + 1)..));
}
key_chain.push(YAMLKey::Index(list_idx));
key_chain.push(YAMLKey::Slice(on[start..idx].trim()));
state = State::Value;
start = idx + ':'.len_utf8();
list_idx += 1;
}
if let '\n' = chr {
key_chain.push(YAMLKey::Index(list_idx));
let value = on[start..idx].trim();
let value = match value {
"true" => RootYAMLValue::True,
"false" => RootYAMLValue::False,
value => RootYAMLValue::String(value),
};
cb(&key_chain, value);
key_chain.pop();
list_idx += 1;
state = State::Skip;
indent = 0;
}
}
State::Skip => {
if let '-' = chr {
state = State::ListItem;
start = idx + '-'.len_utf8();
} else if let '\t' = chr {
indent += options.indent_size;
} else if let ' ' = chr {
indent += 1;
} else if !chr.is_whitespace() {
state = State::Identifier;
start = idx;
}
}
}
}
// TODO left over stuff here
Ok(())
}