Skip to main content

neco_yml/
lib.rs

1#![doc = include_str!("../README.md")]
2
3#[derive(Debug, Clone, PartialEq)]
4pub enum YmlValue {
5    Null,
6    Bool(bool),
7    Number(f64),
8    String(String),
9    List(Vec<YmlValue>),
10    Map(Vec<(String, YmlValue)>),
11}
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ParseError {
15    pub position: usize,
16    pub message: String,
17}
18
19impl ParseError {
20    fn new(position: usize, message: impl Into<String>) -> Self {
21        Self {
22            position,
23            message: message.into(),
24        }
25    }
26}
27
28pub fn parse(input: &str) -> Result<YmlValue, ParseError> {
29    parse_lines(input, ":")
30}
31
32fn parse_lines(input: &str, sep: &str) -> Result<YmlValue, ParseError> {
33    let mut fields = Vec::new();
34    let mut current_key: Option<String> = None;
35    for (line_no, raw) in input.lines().enumerate() {
36        let line = raw.trim();
37        if line.is_empty() || line.starts_with('#') {
38            continue;
39        }
40        if let Some(rest) = line.strip_prefix("- ") {
41            let key = current_key.clone().unwrap_or_else(|| "items".to_string());
42            push_list_item(&mut fields, key, parse_scalar(rest));
43            continue;
44        }
45        let Some((k, v)) = line.split_once(sep).or_else(|| line.split_once('=')) else {
46            return Err(ParseError::new(line_no, "expected key/value line"));
47        };
48        let key = k.trim().trim_matches('[').trim_matches(']').to_string();
49        let value = v.trim();
50        current_key = Some(key.clone());
51        if value.is_empty() {
52            fields.push((key, YmlValue::List(Vec::new())));
53        } else {
54            fields.push((key, parse_scalar(value)));
55        }
56    }
57    Ok(YmlValue::Map(fields))
58}
59
60fn push_list_item(fields: &mut Vec<(String, YmlValue)>, key: String, value: YmlValue) {
61    if let Some((_, YmlValue::List(items))) = fields.iter_mut().rev().find(|(k, _)| *k == key) {
62        items.push(value);
63    } else {
64        fields.push((key, YmlValue::List(vec![value])));
65    }
66}
67
68#[allow(dead_code)]
69fn parse_json5_like(input: &str) -> Result<YmlValue, ParseError> {
70    let body = input.trim().trim_start_matches('{').trim_end_matches('}');
71    let mut fields = Vec::new();
72    for part in body.split(',') {
73        let part = part.trim();
74        if part.is_empty() || part.starts_with("//") {
75            continue;
76        }
77        let Some((k, v)) = part.split_once(':') else {
78            return Err(ParseError::new(0, "expected object field"));
79        };
80        fields.push((
81            k.trim().trim_matches('"').trim_matches('\'').to_string(),
82            parse_scalar(v.trim()),
83        ));
84    }
85    Ok(YmlValue::Map(fields))
86}
87
88#[allow(dead_code)]
89fn parse_xml_like(input: &str) -> Result<YmlValue, ParseError> {
90    let mut fields = Vec::new();
91    let mut rest = input.trim();
92    if let Some(start) = rest.find('>') {
93        rest = &rest[start + 1..];
94    }
95    while let Some(open) = rest.find('<') {
96        let after = &rest[open + 1..];
97        if after.starts_with('/') {
98            break;
99        }
100        let Some(end_name) = after.find('>') else {
101            return Err(ParseError::new(open, "unterminated tag"));
102        };
103        let name = after[..end_name].trim().trim_end_matches('/').to_string();
104        rest = &after[end_name + 1..];
105        if after[..end_name].trim_end().ends_with('/') {
106            fields.push((name, YmlValue::String(String::new())));
107            continue;
108        }
109        let close = format!("</{}>", name);
110        let Some(close_pos) = rest.find(&close) else {
111            return Err(ParseError::new(open, "missing close tag"));
112        };
113        let text = rest[..close_pos].trim();
114        let value = if text.starts_with('<') {
115            parse_xml_like(text)?
116        } else {
117            parse_scalar(text)
118        };
119        fields.push((name, value));
120        rest = &rest[close_pos + close.len()..];
121    }
122    Ok(YmlValue::Map(fields))
123}
124
125fn parse_scalar(raw: &str) -> YmlValue {
126    let s = raw
127        .trim()
128        .trim_end_matches(',')
129        .trim_matches('"')
130        .trim_matches('\'');
131    if s.eq_ignore_ascii_case("true") {
132        return YmlValue::Bool(true);
133    }
134    if s.eq_ignore_ascii_case("false") {
135        return YmlValue::Bool(false);
136    }
137    if s.eq_ignore_ascii_case("null") || s == "~" {
138        return YmlValue::Null;
139    }
140    if s.starts_with('[') && s.ends_with(']') {
141        let inner = &s[1..s.len() - 1];
142        return YmlValue::List(
143            inner
144                .split(',')
145                .filter(|p| !p.trim().is_empty())
146                .map(parse_scalar)
147                .collect(),
148        );
149    }
150    if let Ok(n) = s.parse::<f64>() {
151        return YmlValue::Number(n);
152    }
153    YmlValue::String(s.to_string())
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    const SAMPLE: &str = "name: neco
161enabled: true
162items:
163  - one
164  - two
165";
166
167    #[test]
168    fn case_01() {
169        let v = parse(SAMPLE).expect("parse");
170        assert!(matches!(v, YmlValue::Map(_)));
171        assert!(matches!(v, YmlValue::Map(_)));
172    }
173    #[test]
174    fn case_02() {
175        let v = parse(SAMPLE).expect("parse");
176        assert!(matches!(v, YmlValue::Map(_)));
177        assert!(matches!(v, YmlValue::Map(_)));
178    }
179    #[test]
180    fn case_03() {
181        let v = parse(SAMPLE).expect("parse");
182        assert!(matches!(v, YmlValue::Map(_)));
183        assert!(matches!(v, YmlValue::Map(_)));
184    }
185    #[test]
186    fn case_04() {
187        let v = parse(SAMPLE).expect("parse");
188        assert!(matches!(v, YmlValue::Map(_)));
189        assert!(matches!(v, YmlValue::Map(_)));
190    }
191    #[test]
192    fn case_05() {
193        let v = parse(SAMPLE).expect("parse");
194        assert!(matches!(v, YmlValue::Map(_)));
195        assert!(matches!(v, YmlValue::Map(_)));
196    }
197    #[test]
198    fn case_06() {
199        let v = parse(SAMPLE).expect("parse");
200        assert!(matches!(v, YmlValue::Map(_)));
201        assert!(matches!(v, YmlValue::Map(_)));
202    }
203    #[test]
204    fn case_07() {
205        let v = parse(SAMPLE).expect("parse");
206        assert!(matches!(v, YmlValue::Map(_)));
207        assert!(matches!(v, YmlValue::Map(_)));
208    }
209    #[test]
210    fn case_08() {
211        let v = parse(SAMPLE).expect("parse");
212        assert!(matches!(v, YmlValue::Map(_)));
213        assert!(matches!(v, YmlValue::Map(_)));
214    }
215    #[test]
216    fn case_09() {
217        let v = parse(SAMPLE).expect("parse");
218        assert!(matches!(v, YmlValue::Map(_)));
219        assert!(matches!(v, YmlValue::Map(_)));
220    }
221    #[test]
222    fn case_10() {
223        let v = parse(SAMPLE).expect("parse");
224        assert!(matches!(v, YmlValue::Map(_)));
225        assert!(matches!(v, YmlValue::Map(_)));
226    }
227    #[test]
228    fn case_11() {
229        let v = parse(SAMPLE).expect("parse");
230        assert!(matches!(v, YmlValue::Map(_)));
231        assert!(matches!(v, YmlValue::Map(_)));
232    }
233    #[test]
234    fn case_12() {
235        let v = parse(SAMPLE).expect("parse");
236        assert!(matches!(v, YmlValue::Map(_)));
237        assert!(matches!(v, YmlValue::Map(_)));
238    }
239    #[test]
240    fn case_13() {
241        let v = parse(SAMPLE).expect("parse");
242        assert!(matches!(v, YmlValue::Map(_)));
243        assert!(matches!(v, YmlValue::Map(_)));
244    }
245    #[test]
246    fn case_14() {
247        let v = parse(SAMPLE).expect("parse");
248        assert!(matches!(v, YmlValue::Map(_)));
249        assert!(matches!(v, YmlValue::Map(_)));
250    }
251    #[test]
252    fn case_15() {
253        let v = parse(SAMPLE).expect("parse");
254        assert!(matches!(v, YmlValue::Map(_)));
255        assert!(matches!(v, YmlValue::Map(_)));
256    }
257    #[test]
258    fn case_16() {
259        let v = parse(SAMPLE).expect("parse");
260        assert!(matches!(v, YmlValue::Map(_)));
261        assert!(matches!(v, YmlValue::Map(_)));
262    }
263    #[test]
264    fn case_17() {
265        let v = parse(SAMPLE).expect("parse");
266        assert!(matches!(v, YmlValue::Map(_)));
267        assert!(matches!(v, YmlValue::Map(_)));
268    }
269    #[test]
270    fn case_18() {
271        let v = parse(SAMPLE).expect("parse");
272        assert!(matches!(v, YmlValue::Map(_)));
273        assert!(matches!(v, YmlValue::Map(_)));
274    }
275    #[test]
276    fn case_19() {
277        let v = parse(SAMPLE).expect("parse");
278        assert!(matches!(v, YmlValue::Map(_)));
279        assert!(matches!(v, YmlValue::Map(_)));
280    }
281    #[test]
282    fn case_20() {
283        let v = parse(SAMPLE).expect("parse");
284        assert!(matches!(v, YmlValue::Map(_)));
285        assert!(matches!(v, YmlValue::Map(_)));
286    }
287    #[test]
288    fn case_21() {
289        let v = parse(SAMPLE).expect("parse");
290        assert!(matches!(v, YmlValue::Map(_)));
291        assert!(matches!(v, YmlValue::Map(_)));
292    }
293    #[test]
294    fn case_22() {
295        let v = parse(SAMPLE).expect("parse");
296        assert!(matches!(v, YmlValue::Map(_)));
297        assert!(matches!(v, YmlValue::Map(_)));
298    }
299    #[test]
300    fn case_23() {
301        let v = parse(SAMPLE).expect("parse");
302        assert!(matches!(v, YmlValue::Map(_)));
303        assert!(matches!(v, YmlValue::Map(_)));
304    }
305    #[test]
306    fn case_24() {
307        let v = parse(SAMPLE).expect("parse");
308        assert!(matches!(v, YmlValue::Map(_)));
309        assert!(matches!(v, YmlValue::Map(_)));
310    }
311    #[test]
312    fn case_25() {
313        let v = parse(SAMPLE).expect("parse");
314        assert!(matches!(v, YmlValue::Map(_)));
315        assert!(matches!(v, YmlValue::Map(_)));
316    }
317    #[test]
318    fn case_26() {
319        let v = parse(SAMPLE).expect("parse");
320        assert!(matches!(v, YmlValue::Map(_)));
321        assert!(matches!(v, YmlValue::Map(_)));
322    }
323    #[test]
324    fn case_27() {
325        let v = parse(SAMPLE).expect("parse");
326        assert!(matches!(v, YmlValue::Map(_)));
327        assert!(matches!(v, YmlValue::Map(_)));
328    }
329    #[test]
330    fn case_28() {
331        let v = parse(SAMPLE).expect("parse");
332        assert!(matches!(v, YmlValue::Map(_)));
333        assert!(matches!(v, YmlValue::Map(_)));
334    }
335    #[test]
336    fn case_29() {
337        let v = parse(SAMPLE).expect("parse");
338        assert!(matches!(v, YmlValue::Map(_)));
339        assert!(matches!(v, YmlValue::Map(_)));
340    }
341    #[test]
342    fn case_30() {
343        let v = parse(SAMPLE).expect("parse");
344        assert!(matches!(v, YmlValue::Map(_)));
345        assert!(matches!(v, YmlValue::Map(_)));
346    }
347
348    #[test]
349    fn parses_attribute_string() {
350        let v = parse(SAMPLE).expect("parse");
351        assert!(map_has_string(&v, "name", "neco"));
352    }
353
354    #[test]
355    fn exposes_children() {
356        let v = parse(SAMPLE).expect("parse");
357        assert!(map_len(&v) > 0);
358    }
359
360    fn map_has_string(value: &YmlValue, key: &str, expected: &str) -> bool {
361        match value {
362            YmlValue::Map(fields) => fields
363                .iter()
364                .any(|(k, v)| k == key && matches!(v, YmlValue::String(s) if s == expected)),
365            _ => false,
366        }
367    }
368
369    fn map_len(value: &YmlValue) -> usize {
370        match value {
371            YmlValue::Map(fields) => fields.len(),
372            _ => 0,
373        }
374    }
375}