jaml 0.2.0

A Rust library for parsing and formatting JAML (Just Another Markup Language)
Documentation
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Internal implementation details for JAML parsing.

#![allow(missing_docs)]

use std::{collections::BTreeMap, result::Result as StdResult};

use pest::{Parser, iterators::Pair};
use pest_derive::Parser;

use super::{Error, Result, indent};
use crate::{Binary, Value};

pub(super) type PestError = pest::error::Error<Rule>;

/// Parsing struct generated by pest from the grammar
#[derive(Parser)]
#[grammar = "parser/grammar.pest"]
pub(super) struct JamlParser;

#[derive(Debug, Clone)]
struct Line {
    indent: usize,
    content: LineContent,
    line_num: usize,
}

#[derive(Debug, Clone)]
enum LineContent {
    ListItem(Option<Value>),
    MapEntry(String, Option<Value>),
    Value(Value),
    Empty,
}

pub(super) fn parse_impl(input: &str) -> Result<Value> {
    let pairs = JamlParser::parse(Rule::jaml, input)?;

    // Parse all lines
    let lines = parse_lines(pairs)?;

    if lines.is_empty() {
        return Err(Error::EmptyDocument);
    }

    // Build value from lines
    let (value, _) = build_value(&lines, 0, 0)?;
    Ok(value)
}

fn parse_lines(pairs: pest::iterators::Pairs<Rule>) -> Result<Vec<Line>> {
    let mut lines = Vec::new();
    let mut line_num = 1;
    let mut indent_tracker = indent::Tracker::default();

    for pair in pairs {
        if pair.as_rule() == Rule::jaml {
            let document = pair.into_inner().next().unwrap();
            for line_pair in document.into_inner() {
                match line_pair.as_rule() {
                    Rule::non_empty_line => {
                        let mut inner = line_pair.into_inner();

                        // Get indent
                        let indent_pair = inner.next().unwrap();
                        let indent_str = indent_pair.as_str();

                        // Validate and get indent level using tracker
                        let indent = indent_tracker.validate(indent_str)?;

                        // Get content
                        let content_pair = inner.next().unwrap();
                        let content = parse_line_content(content_pair, line_num)?;

                        if !matches!(content, LineContent::Empty) {
                            lines.push(Line {
                                indent,
                                content,
                                line_num,
                            });
                        }

                        line_num += 1;
                    }
                    Rule::empty_line | Rule::NEWLINE => {
                        // Skip empty lines, just increment line number
                        line_num += 1;
                    }
                    _ => {}
                }
            }
        }
    }

    Ok(lines)
}

fn parse_line_content(pair: Pair<Rule>, _line_num: usize) -> Result<LineContent> {
    match pair.as_rule() {
        Rule::content => {
            let inner = pair.into_inner().next().unwrap();
            parse_line_content(inner, _line_num)
        }
        Rule::list_item => {
            let value = pair
                .into_inner()
                .find_map(|inner| {
                    match inner.as_rule() {
                        Rule::inline_value => Some(parse_inline_value(inner)),
                        _ => None, // Skip trailing_ws and comment
                    }
                })
                .transpose()?;
            Ok(LineContent::ListItem(value))
        }
        Rule::map_entry => {
            let mut inner = pair.into_inner();
            let key = parse_key(inner.next().unwrap())?;
            let value = inner
                .find_map(|pair| {
                    match pair.as_rule() {
                        Rule::inline_value => Some(parse_inline_value(pair)),
                        _ => None, // Skip trailing_ws and comment
                    }
                })
                .transpose()?;
            Ok(LineContent::MapEntry(key, value))
        }
        Rule::inline_value => {
            let value = parse_inline_value(pair)?;
            Ok(LineContent::Value(value))
        }
        Rule::comment => Ok(LineContent::Empty),
        _ => Ok(LineContent::Empty),
    }
}

fn build_value(lines: &[Line], start_idx: usize, expected_indent: usize) -> Result<(Value, usize)> {
    if start_idx >= lines.len() {
        return Err(Error::EmptyDocument);
    }

    let first = &lines[start_idx];

    if first.indent != expected_indent {
        return Err(Error::UnexpectedIndent(expected_indent, first.indent));
    }

    match &first.content {
        LineContent::Value(v) => Ok((v.clone(), start_idx + 1)),
        LineContent::ListItem(_) => build_list(lines, start_idx, expected_indent),
        LineContent::MapEntry(_, _) => build_map(lines, start_idx, expected_indent),
        LineContent::Empty => Err(Error::EmptyDocument),
    }
}

fn build_list(lines: &[Line], start_idx: usize, expected_indent: usize) -> Result<(Value, usize)> {
    let mut items = Vec::new();
    let mut idx = start_idx;

    while idx < lines.len() {
        let line = &lines[idx];

        if line.indent < expected_indent {
            break;
        }

        if line.indent > expected_indent {
            return Err(Error::UnexpectedIndent(expected_indent, line.indent));
        }

        match &line.content {
            LineContent::ListItem(maybe_val) => {
                if let Some(val) = maybe_val {
                    items.push(val.clone());
                    idx += 1;
                } else {
                    // Value on next line
                    idx += 1;
                    if idx < lines.len() {
                        let (nested_val, next_idx) = build_value(lines, idx, expected_indent + 1)?;
                        items.push(nested_val);
                        idx = next_idx;
                    } else {
                        return Err(Error::MissingValue(line.line_num));
                    }
                }
            }
            _ => break,
        }
    }

    Ok((Value::List(items), idx))
}

fn build_map(lines: &[Line], start_idx: usize, expected_indent: usize) -> Result<(Value, usize)> {
    let mut map = BTreeMap::new();
    let mut idx = start_idx;

    while idx < lines.len() {
        let line = &lines[idx];

        if line.indent < expected_indent {
            break;
        }

        if line.indent > expected_indent {
            return Err(Error::UnexpectedIndent(expected_indent, line.indent));
        }

        match &line.content {
            LineContent::MapEntry(key, maybe_val) => {
                if map.contains_key(key) {
                    return Err(Error::DuplicateKey(key.clone()));
                }

                if let Some(val) = maybe_val {
                    map.insert(key.clone(), val.clone());
                    idx += 1;
                } else {
                    // Value on next line
                    idx += 1;
                    if idx < lines.len() {
                        let (nested_val, next_idx) = build_value(lines, idx, expected_indent + 1)?;
                        map.insert(key.clone(), nested_val);
                        idx = next_idx;
                    } else {
                        return Err(Error::MissingValue(line.line_num));
                    }
                }
            }
            _ => break,
        }
    }

    Ok((Value::Map(map), idx))
}

fn parse_key(pair: Pair<Rule>) -> Result<String> {
    match pair.as_rule() {
        Rule::key => {
            let inner = pair.into_inner().next().unwrap();
            parse_key(inner)
        }
        Rule::identifier => Ok(pair.as_str().to_string()),
        Rule::string => {
            if let Value::String(s) = parse_string(pair)? {
                Ok(s)
            } else {
                unreachable!()
            }
        }
        _ => unreachable!("Unexpected key rule: {:?}", pair.as_rule()),
    }
}

fn parse_inline_value(pair: Pair<Rule>) -> Result<Value> {
    let rule = if pair.as_rule() == Rule::inline_value {
        pair.into_inner().next().unwrap()
    } else {
        pair
    };

    match rule.as_rule() {
        Rule::null => Ok(Value::Null),
        Rule::boolean => Ok(Value::Bool(rule.as_str() == "true")),
        Rule::integer => parse_int(rule),
        Rule::float => parse_float(rule),
        Rule::string => parse_string(rule),
        Rule::binary => parse_binary(rule),
        Rule::timestamp => parse_timestamp(rule),
        Rule::inline_list => parse_inline_list(rule),
        Rule::inline_map => parse_inline_map(rule),
        _ => unreachable!("Unexpected inline value rule: {:?}", rule.as_rule()),
    }
}

fn parse_inline_list(pair: Pair<Rule>) -> Result<Value> {
    let mut items = Vec::new();

    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::inline_value {
            items.push(parse_inline_value(inner)?);
        }
    }

    Ok(Value::List(items))
}

fn parse_inline_map(pair: Pair<Rule>) -> Result<Value> {
    let mut map = BTreeMap::new();

    for member in pair.into_inner() {
        if member.as_rule() == Rule::inline_member {
            let mut inner = member.into_inner();
            let key = parse_key(inner.next().unwrap())?;
            let value = parse_inline_value(inner.next().unwrap())?;

            if map.contains_key(&key) {
                return Err(Error::DuplicateKey(key));
            }

            map.insert(key, value);
        }
    }

    Ok(Value::Map(map))
}

// Number parsing (same as JASN)
fn parse_int(pair: Pair<Rule>) -> Result<Value> {
    let s = pair.as_str();

    let normalized = s.replace('_', "");
    let normalized = normalized.strip_prefix('+').unwrap_or(&normalized);

    let (is_negative, unsigned_str) = match normalized.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, normalized),
    };

    let uint = match unsigned_str {
        s if s.starts_with("0x") || s.starts_with("0X") => parse_int_radix(&s[2..], 16)?,
        s if s.starts_with("0b") || s.starts_with("0B") => parse_int_radix(&s[2..], 2)?,
        s if s.starts_with("0o") || s.starts_with("0O") => parse_int_radix(&s[2..], 8)?,
        _ => return Ok(Value::Int(normalized.parse::<i64>()?)),
    };

    let int = if is_negative { -uint } else { uint };

    Ok(Value::Int(int))
}

fn parse_int_radix(s: &str, radix: u32) -> Result<i64> {
    i64::from_str_radix(s, radix).map_err(Into::into)
}

fn parse_float(pair: Pair<Rule>) -> Result<Value> {
    let s = pair.as_str();

    let value = match s {
        "inf" | "+inf" => f64::INFINITY,
        "-inf" => f64::NEG_INFINITY,
        "nan" | "+nan" | "-nan" => f64::NAN,
        _ => s.parse::<f64>()?,
    };

    Ok(Value::Float(value))
}

fn parse_string(pair: Pair<Rule>) -> Result<Value> {
    let mut inner = pair.into_inner();
    let quoted = inner.next().unwrap();
    let content_pair = quoted.into_inner().next().unwrap();
    let content = content_pair.as_str();

    let mut result = String::with_capacity(content.len());
    let mut chars = content.chars();

    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.next() {
                Some('"') => result.push('"'),
                Some('\'') => result.push('\''),
                Some('\\') => result.push('\\'),
                Some('/') => result.push('/'),
                Some('b') => result.push('\u{0008}'),
                Some('f') => result.push('\u{000C}'),
                Some('n') => result.push('\n'),
                Some('r') => result.push('\r'),
                Some('t') => result.push('\t'),
                Some('u') => result.push(parse_unicode_escape(&mut chars)?),
                Some(c) => return Err(Error::InvalidEscapeChar(c)),
                None => return Err(Error::InvalidEscapeChar('\\')),
            }
        } else {
            result.push(ch);
        }
    }

    Ok(Value::String(result))
}

fn parse_unicode_escape(chars: &mut std::str::Chars) -> Result<char> {
    let hex: String = chars.take(4).collect();
    if hex.len() < 4 {
        return Err(Error::InvalidUnicodeEscape(hex));
    }
    let code =
        u32::from_str_radix(&hex, 16).map_err(|_| Error::InvalidUnicodeEscape(hex.clone()))?;

    if (0xD800..=0xDBFF).contains(&code) {
        let saved_chars = chars.clone();
        if chars.next() == Some('\\') && chars.next() == Some('u') {
            let low_hex: String = chars.take(4).collect();
            if low_hex.len() == 4
                && let Ok(low_code) = u32::from_str_radix(&low_hex, 16)
                && (0xDC00..=0xDFFF).contains(&low_code)
            {
                let codepoint = 0x10000 + ((code - 0xD800) << 10) + (low_code - 0xDC00);
                return char::from_u32(codepoint).ok_or(Error::InvalidUnicodeCodepoint(codepoint));
            }
        }
        *chars = saved_chars;
    }

    char::from_u32(code).ok_or(Error::InvalidUnicodeCodepoint(code))
}

fn parse_binary(pair: Pair<Rule>) -> Result<Value> {
    let rule = pair.into_inner().next().unwrap();

    match rule.as_rule() {
        Rule::base64_binary => {
            let content = rule.into_inner().next().unwrap().as_str();
            let bytes =
                base64::Engine::decode(&base64::engine::general_purpose::STANDARD, content)?;
            Ok(Value::Binary(Binary(bytes)))
        }
        Rule::hex_binary => {
            let content = rule.into_inner().next().unwrap().as_str();
            if !content.len().is_multiple_of(2) {
                return Err(Error::OddHexDigits);
            }
            let bytes = (0..content.len())
                .step_by(2)
                .map(|i| u8::from_str_radix(&content[i..i + 2], 16))
                .collect::<StdResult<Vec<u8>, _>>()?;
            Ok(Value::Binary(Binary(bytes)))
        }
        _ => unreachable!("Unexpected binary rule: {:?}", rule.as_rule()),
    }
}

fn parse_timestamp(pair: Pair<Rule>) -> Result<Value> {
    let content = pair.into_inner().next().unwrap().as_str();

    match time::OffsetDateTime::parse(content, &time::format_description::well_known::Rfc3339) {
        Ok(dt) => Ok(Value::Timestamp(dt)),
        Err(e) => Err(Error::InvalidTimestamp(content.to_string(), e.to_string())),
    }
}