okf 0.2.0

A pure-Rust, zero-dependency implementation of the Open Knowledge Format (OKF) v0.2: parser, model, validator, provenance/trust/attestation families, link graph, and index/log tooling.
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Recursive parser for the OKF YAML subset. See the [module docs](super) for
//! the supported grammar and intentional limitations.

use super::{Mapping, Value};
use std::fmt;

/// An error produced while parsing YAML frontmatter.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct YamlError {
    /// 1-based source line where the problem was detected (0 if not known).
    pub line: usize,
    /// Human-readable description.
    pub message: String,
}

impl fmt::Display for YamlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.line > 0 {
            write!(f, "YAML error at line {}: {}", self.line, self.message)
        } else {
            write!(f, "YAML error: {}", self.message)
        }
    }
}

impl std::error::Error for YamlError {}

/// Parses a YAML document (the OKF subset) into a [`Value`].
///
/// Empty or comment/whitespace-only input parses to [`Value::Null`], mirroring
/// PyYAML's `safe_load("") is None`.
pub fn parse(text: &str) -> Result<Value, YamlError> {
    let lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
    let mut p = Parser { lines, pos: 0 };
    p.skip_blank_and_comments();
    if p.pos >= p.lines.len() {
        return Ok(Value::Null);
    }
    let base = p.current_indent()?;
    let value = p.parse_node(base)?;
    p.skip_blank_and_comments();
    if p.pos < p.lines.len() {
        return Err(p.err("unexpected trailing content"));
    }
    Ok(value)
}

struct Parser {
    lines: Vec<String>,
    pos: usize,
}

impl Parser {
    fn err(&self, msg: impl Into<String>) -> YamlError {
        YamlError {
            line: self.pos + 1,
            message: msg.into(),
        }
    }

    fn is_blank_or_comment(line: &str) -> bool {
        let t = line.trim_start();
        t.is_empty() || t.starts_with('#')
    }

    fn skip_blank_and_comments(&mut self) {
        while self.pos < self.lines.len() && Self::is_blank_or_comment(&self.lines[self.pos]) {
            self.pos += 1;
        }
    }

    /// Indentation (count of leading spaces) of the current line. Errors if the
    /// leading whitespace contains a tab (YAML forbids tab indentation).
    fn current_indent(&self) -> Result<usize, YamlError> {
        indent_of(&self.lines[self.pos]).ok_or_else(|| self.err("tab character in indentation"))
    }

    /// Parses a node whose block items begin at column `indent`.
    fn parse_node(&mut self, indent: usize) -> Result<Value, YamlError> {
        let line = &self.lines[self.pos];
        let content = &line[indent.min(line.len())..];
        let trimmed = content.trim_start();

        if trimmed == "-" || trimmed.starts_with("- ") {
            self.parse_sequence(indent)
        } else if split_key_value(trimmed).is_some() {
            self.parse_mapping(indent)
        } else {
            // A bare scalar or flow collection. A plain scalar may continue on
            // the following lines at this same indent.
            let first = trimmed.to_string();
            let entry_line = self.pos;
            self.pos += 1;
            self.read_scalar(&first, indent, entry_line)
        }
    }

    fn parse_mapping(&mut self, indent: usize) -> Result<Value, YamlError> {
        let mut map = Mapping::new();
        loop {
            self.skip_blank_and_comments();
            if self.pos >= self.lines.len() {
                break;
            }
            let ind = self.current_indent()?;
            if ind < indent {
                break;
            }
            if ind > indent {
                return Err(self.err("unexpected indentation in mapping"));
            }
            let line = self.lines[self.pos].clone();
            let content = line[indent..].to_string();
            let trimmed = content.trim_start();
            if trimmed == "-" || trimmed.starts_with("- ") {
                break; // sequence at the same level: not part of this mapping
            }
            let (key_str, rest) = split_key_value(trimmed)
                .ok_or_else(|| self.err("expected 'key: value' mapping entry"))?;
            let key = parse_scalar(&key_str, self.pos)?;
            let entry_line = self.pos;
            self.pos += 1;

            let value = match rest {
                Some(r) if r.starts_with('|') || r.starts_with('>') => {
                    self.parse_block_scalar(indent, &r)?
                }
                Some(r) => self.read_scalar(&r, indent + 1, entry_line)?,
                None => {
                    // Nested block on the following more-indented lines, else null.
                    self.parse_nested(indent)?
                }
            };
            map.push_raw(key, value);
        }
        Ok(Value::Mapping(map))
    }

    fn parse_sequence(&mut self, indent: usize) -> Result<Value, YamlError> {
        let mut seq = Vec::new();
        loop {
            self.skip_blank_and_comments();
            if self.pos >= self.lines.len() {
                break;
            }
            let ind = self.current_indent()?;
            if ind < indent {
                break;
            }
            if ind > indent {
                return Err(self.err("unexpected indentation in sequence"));
            }
            let line = self.lines[self.pos].clone();
            let content = &line[indent..];
            if !(content == "-" || content.starts_with("- ")) {
                break;
            }
            // Column at which the item payload starts.
            let dash_rest = &content[1..]; // after '-'
            let item_offset = indent + 1 + (dash_rest.len() - dash_rest.trim_start().len());
            let item_text = content[1..].trim_start().to_string();
            let entry_line = self.pos;

            if item_text.is_empty() {
                // Nested block belonging to this item.
                self.pos += 1;
                let v = self.parse_nested(indent)?;
                seq.push(v);
            } else if item_text.starts_with('|') || item_text.starts_with('>') {
                self.pos += 1;
                let v = self.parse_block_scalar(indent, &item_text)?;
                seq.push(v);
            } else if split_key_value(&item_text).is_some() {
                // Inline-started mapping element ("- key: value"). Rewrite the
                // dash to whitespace so the payload aligns at `item_offset`,
                // then parse a mapping at that deeper indent.
                let mut rewritten = " ".repeat(item_offset);
                rewritten.push_str(&item_text);
                self.lines[entry_line] = rewritten;
                let v = self.parse_mapping(item_offset)?;
                seq.push(v);
            } else {
                self.pos += 1;
                let v = self.read_scalar(&item_text, indent + 1, entry_line)?;
                seq.push(v);
            }
        }
        Ok(Value::Sequence(seq))
    }

    /// Reads a scalar that starts as `first` and may continue on the following
    /// lines, folding each line break into a single space.
    ///
    /// YAML lets both plain and quoted scalars span lines (§6.5 line folding),
    /// and PyYAML's `safe_dump` leans on it: any value longer than its 80-column
    /// line width comes out wrapped. The reference implementation dumps with
    /// `safe_dump`, so its own published bundles carry wrapped `description` and
    /// `title` values, and a parser that rejects them cannot read
    /// reference-produced OKF at all.
    ///
    /// A following line continues the scalar when it reaches `min_indent` and,
    /// outside an open quote, does not itself open a mapping entry, a sequence
    /// item, or a comment. Inside an unclosed quote every line belongs to the
    /// scalar until the closing quote, since a wrapped quoted value may contain
    /// anything, `key: value` shapes included. Flow collections are returned as
    /// they stand: nothing emits one across lines.
    fn read_scalar(
        &mut self,
        first: &str,
        min_indent: usize,
        line: usize,
    ) -> Result<Value, YamlError> {
        if first.starts_with('[') || first.starts_with('{') {
            return parse_inline_value(first, line);
        }

        let mut text = first.to_string();
        let mut open_quote = unclosed_quote(first);
        while self.pos < self.lines.len() {
            let raw = &self.lines[self.pos];
            if raw.trim().is_empty() {
                break;
            }
            let ind = indent_of(raw).ok_or_else(|| self.err("tab character in indentation"))?;
            if ind < min_indent {
                break;
            }
            let content = raw.trim();
            if open_quote.is_none() && starts_a_new_node(content) {
                break;
            }
            text.push(' ');
            text.push_str(content);
            if let Some(quote) = open_quote {
                if closes_quote(content, quote, 0) {
                    open_quote = None;
                }
            }
            self.pos += 1;
        }

        parse_scalar(&text, line)
    }

    /// Parses a nested block following a `key:` with no inline value.
    ///
    /// A nested *mapping* must be indented deeper than `parent_indent`. A nested
    /// block *sequence*, however, is also permitted at exactly `parent_indent`
    /// which is YAML's standard "indentation-relaxed" block sequence, and it is
    /// what PyYAML's `safe_dump` (used by the reference implementation) emits for
    /// list values such as `tags`. Returns [`Value::Null`] when no block
    /// follows.
    fn parse_nested(&mut self, parent_indent: usize) -> Result<Value, YamlError> {
        self.skip_blank_and_comments();
        if self.pos >= self.lines.len() {
            return Ok(Value::Null);
        }
        let ind = self.current_indent()?;
        if ind > parent_indent {
            self.parse_node(ind)
        } else if ind == parent_indent && self.line_is_sequence_item(ind) {
            self.parse_sequence(ind)
        } else {
            Ok(Value::Null)
        }
    }

    /// Whether the current line, taken from column `indent`, begins a block
    /// sequence item (`-` alone or `- …`).
    fn line_is_sequence_item(&self, indent: usize) -> bool {
        let line = &self.lines[self.pos];
        let content = &line[indent.min(line.len())..];
        content == "-" || content.starts_with("- ")
    }

    /// Parses a `|` (literal) or `>` (folded) block scalar. The header (`r`)
    /// is the text after the `key:` (e.g. `|`, `|-`, `>+`).
    fn parse_block_scalar(
        &mut self,
        parent_indent: usize,
        header: &str,
    ) -> Result<Value, YamlError> {
        let style = header.as_bytes()[0]; // b'|' or b'>'
        let chomp = header[1..].chars().find(|c| *c == '+' || *c == '-');

        // Collect body lines: blanks, or lines indented deeper than the parent.
        let mut body: Vec<String> = Vec::new();
        let mut block_indent: Option<usize> = None;
        while self.pos < self.lines.len() {
            let line = &self.lines[self.pos];
            if line.trim().is_empty() {
                body.push(String::new());
                self.pos += 1;
                continue;
            }
            let ind = indent_of(line).ok_or_else(|| self.err("tab in block scalar indentation"))?;
            if ind <= parent_indent {
                break;
            }
            if block_indent.is_none() {
                block_indent = Some(ind);
            }
            let bi = block_indent.unwrap();
            let stripped = if line.len() >= bi {
                line[bi..].to_string()
            } else {
                String::new()
            };
            body.push(stripped);
            self.pos += 1;
        }

        // Drop trailing blank lines for accounting, remember how many there were.
        let mut trailing_blanks = 0;
        while body.last().map(|l| l.is_empty()).unwrap_or(false) {
            body.pop();
            trailing_blanks += 1;
        }

        let mut text = if style == b'|' {
            body.join("\n")
        } else {
            fold_lines(&body)
        };

        match chomp {
            Some('-') => {} // strip: no trailing newline
            Some('+') => {
                // keep: restore all trailing blank lines + one newline for content
                text.push('\n');
                for _ in 0..trailing_blanks {
                    text.push('\n');
                }
            }
            _ => {
                // clip: exactly one trailing newline if there was any content
                if !text.is_empty() || trailing_blanks > 0 {
                    text.push('\n');
                }
            }
        }
        Ok(Value::String(text))
    }
}

/// Folds a literal block's lines per YAML's folded (`>`) rules: runs of
/// non-empty lines join with a single space; blank lines become newlines.
fn fold_lines(lines: &[String]) -> String {
    let mut out = String::new();
    let mut prev_nonempty = false;
    for line in lines {
        if line.is_empty() {
            out.push('\n');
            prev_nonempty = false;
        } else {
            if prev_nonempty {
                out.push(' ');
            }
            out.push_str(line);
            prev_nonempty = true;
        }
    }
    out
}

/// Whether a (trimmed) line opens a node of its own rather than continuing the
/// scalar above it: a comment, a sequence item, or a mapping entry.
fn starts_a_new_node(content: &str) -> bool {
    content.starts_with('#')
        || content == "-"
        || content.starts_with("- ")
        || split_key_value(content).is_some()
}

/// The quote character of a quoted scalar that `s` opens but does not close, or
/// `None` when `s` is plain or self-contained.
fn unclosed_quote(s: &str) -> Option<char> {
    let quote = match s.chars().next() {
        Some(c @ ('\'' | '"')) => c,
        _ => return None,
    };
    (!closes_quote(s, quote, 1)).then_some(quote)
}

/// Whether the closing `quote` of an already-open quoted scalar appears in `s`
/// at or after character index `from`, honouring `''` and `\"` escapes.
fn closes_quote(s: &str, quote: char, from: usize) -> bool {
    let chars: Vec<char> = s.chars().collect();
    let mut i = from;
    while i < chars.len() {
        let c = chars[i];
        if quote == '"' && c == '\\' {
            i += 2;
            continue;
        }
        if c == quote {
            if quote == '\'' && chars.get(i + 1) == Some(&'\'') {
                i += 2;
                continue;
            }
            return true;
        }
        i += 1;
    }
    false
}

/// Leading-space count, or `None` if the indentation contains a tab.
fn indent_of(line: &str) -> Option<usize> {
    let mut n = 0;
    for c in line.chars() {
        match c {
            ' ' => n += 1,
            '\t' => return None,
            _ => break,
        }
    }
    Some(n)
}

/// Splits a (left-trimmed) line into a `key` and optional rest at the first
/// top-level `:` that is followed by a space or end-of-line. Returns `None`
/// when the line is not a mapping entry.
fn split_key_value(s: &str) -> Option<(String, Option<String>)> {
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    let mut quote: Option<char> = None;
    let mut depth: i32 = 0;
    while i < chars.len() {
        let c = chars[i];
        if let Some(q) = quote {
            if q == '"' && c == '\\' {
                i += 2;
                continue;
            }
            if c == q {
                if q == '\'' && chars.get(i + 1) == Some(&'\'') {
                    i += 2;
                    continue;
                }
                quote = None;
            }
            i += 1;
            continue;
        }
        match c {
            '\'' | '"' => quote = Some(c),
            '[' | '{' => depth += 1,
            ']' | '}' => {
                if depth > 0 {
                    depth -= 1;
                }
            }
            '#' if depth == 0 && i > 0 && (chars[i - 1] == ' ' || chars[i - 1] == '\t') => {
                break; // comment region without a preceding separator
            }
            ':' if depth == 0 => {
                let next = chars.get(i + 1).copied();
                if next.is_none() || next == Some(' ') || next == Some('\t') {
                    let key: String = chars[..i].iter().collect();
                    let rest: String = chars[i + 1..].iter().collect();
                    let rest = rest.trim();
                    let rest_opt = if rest.is_empty() || rest.starts_with('#') {
                        None
                    } else {
                        Some(rest.to_string())
                    };
                    return Some((key.trim().to_string(), rest_opt));
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// Parses a single-line value: a flow collection or a scalar.
fn parse_inline_value(s: &str, line: usize) -> Result<Value, YamlError> {
    let t = s.trim();
    if t.starts_with('[') || t.starts_with('{') {
        let mut fp = FlowParser {
            chars: t.chars().collect(),
            pos: 0,
            line,
        };
        let v = fp.parse_value()?;
        fp.skip_ws();
        // Allow a trailing comment after the flow collection.
        if fp.pos < fp.chars.len() && fp.chars[fp.pos] != '#' {
            return Err(YamlError {
                line: line + 1,
                message: "unexpected content after flow collection".into(),
            });
        }
        Ok(v)
    } else {
        parse_scalar(t, line)
    }
}

/// Interprets a scalar token (possibly quoted) into a typed [`Value`].
fn parse_scalar(token: &str, line: usize) -> Result<Value, YamlError> {
    let t = token.trim();
    if t.is_empty() {
        return Ok(Value::Null);
    }
    if t.starts_with('"') {
        return parse_double_quoted(t, line).map(Value::String);
    }
    if t.starts_with('\'') {
        return parse_single_quoted(t, line).map(Value::String);
    }
    // Plain scalar: strip a trailing " #" comment.
    let plain = strip_trailing_comment(t);
    Ok(interpret_plain(plain))
}

/// Strips a trailing ` #...` comment from a plain scalar.
fn strip_trailing_comment(s: &str) -> &str {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'#' && i > 0 && (bytes[i - 1] == b' ' || bytes[i - 1] == b'\t') {
            return s[..i].trim_end();
        }
        i += 1;
    }
    s.trim_end()
}

/// Resolves a plain (unquoted) scalar to null/bool/int/float/string.
///
/// Number resolution is intentionally conservative to avoid silently coercing
/// identifier-like values: integers must have no redundant leading zero (so a
/// zero-padded code such as `007` stays a string), and floats must contain a
/// decimal point (so `1e3` stays a string). This matches the safe, predictable
/// end of YAML scalar resolution rather than PyYAML's legacy octal/sexagesimal
/// quirks. The special float tokens `.inf`, `-.inf`, and `.nan` are recognized
/// so non-finite floats produced by the emitter round-trip.
fn interpret_plain(s: &str) -> Value {
    match s {
        "" | "~" | "null" | "Null" | "NULL" => return Value::Null,
        "true" | "True" | "TRUE" => return Value::Bool(true),
        "false" | "False" | "FALSE" => return Value::Bool(false),
        ".inf" | ".Inf" | ".INF" | "+.inf" => return Value::Float(f64::INFINITY),
        "-.inf" | "-.Inf" | "-.INF" => return Value::Float(f64::NEG_INFINITY),
        ".nan" | ".NaN" | ".NAN" => return Value::Float(f64::NAN),
        _ => {}
    }
    if is_canonical_int(s) {
        if let Ok(i) = s.parse::<i64>() {
            return Value::Int(i);
        }
    }
    if is_canonical_float(s) {
        if let Ok(f) = s.parse::<f64>() {
            return Value::Float(f);
        }
    }
    Value::String(s.to_string())
}

/// `[-+]?(0|[1-9][0-9]*)`: a decimal integer with no redundant leading zero.
fn is_canonical_int(s: &str) -> bool {
    let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    digits == "0" || !digits.starts_with('0')
}

/// A float that contains a decimal point and a digit (optionally with an
/// exponent), e.g. `0.1`, `-3.5`, `1.0e9`. Bare-exponent forms like `1e3` are
/// deliberately treated as strings.
fn is_canonical_float(s: &str) -> bool {
    if !s.contains('.') || !s.bytes().any(|b| b.is_ascii_digit()) {
        return false;
    }
    s.parse::<f64>().is_ok()
}

fn parse_double_quoted(s: &str, line: usize) -> Result<String, YamlError> {
    let chars: Vec<char> = s.chars().collect();
    debug_assert_eq!(chars[0], '"');
    let mut out = String::new();
    let mut i = 1;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' {
            return Ok(out);
        }
        if c == '\\' {
            i += 1;
            let e = *chars.get(i).ok_or_else(|| YamlError {
                line: line + 1,
                message: "dangling escape in double-quoted string".into(),
            })?;
            match e {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                'r' => out.push('\r'),
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                '/' => out.push('/'),
                '0' => out.push('\0'),
                'b' => out.push('\u{0008}'),
                'f' => out.push('\u{000C}'),
                'u' => {
                    let hex: String = chars[i + 1..(i + 5).min(chars.len())].iter().collect();
                    if hex.len() == 4 {
                        if let Ok(cp) = u32::from_str_radix(&hex, 16) {
                            if let Some(ch) = char::from_u32(cp) {
                                out.push(ch);
                            }
                        }
                        i += 4;
                    }
                }
                other => out.push(other),
            }
            i += 1;
            continue;
        }
        out.push(c);
        i += 1;
    }
    Err(YamlError {
        line: line + 1,
        message: "unterminated double-quoted string".into(),
    })
}

fn parse_single_quoted(s: &str, line: usize) -> Result<String, YamlError> {
    let chars: Vec<char> = s.chars().collect();
    debug_assert_eq!(chars[0], '\'');
    let mut out = String::new();
    let mut i = 1;
    while i < chars.len() {
        let c = chars[i];
        if c == '\'' {
            if chars.get(i + 1) == Some(&'\'') {
                out.push('\'');
                i += 2;
                continue;
            }
            return Ok(out);
        }
        out.push(c);
        i += 1;
    }
    Err(YamlError {
        line: line + 1,
        message: "unterminated single-quoted string".into(),
    })
}

/// A recursive parser for flow collections (`[...]`, `{...}`).
struct FlowParser {
    chars: Vec<char>,
    pos: usize,
    line: usize,
}

impl FlowParser {
    fn skip_ws(&mut self) {
        while self.pos < self.chars.len() && self.chars[self.pos].is_whitespace() {
            self.pos += 1;
        }
    }

    fn err(&self, msg: impl Into<String>) -> YamlError {
        YamlError {
            line: self.line + 1,
            message: msg.into(),
        }
    }

    fn parse_value(&mut self) -> Result<Value, YamlError> {
        self.skip_ws();
        match self.chars.get(self.pos) {
            Some('[') => self.parse_seq(),
            Some('{') => self.parse_map(),
            Some(_) => self.parse_flow_scalar(),
            None => Ok(Value::Null),
        }
    }

    fn parse_seq(&mut self) -> Result<Value, YamlError> {
        self.pos += 1; // consume '['
        let mut seq = Vec::new();
        loop {
            self.skip_ws();
            match self.chars.get(self.pos) {
                Some(']') => {
                    self.pos += 1;
                    break;
                }
                None => return Err(self.err("unterminated flow sequence")),
                _ => {}
            }
            seq.push(self.parse_value()?);
            self.skip_ws();
            match self.chars.get(self.pos) {
                Some(',') => self.pos += 1,
                Some(']') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(self.err("expected ',' or ']' in flow sequence")),
            }
        }
        Ok(Value::Sequence(seq))
    }

    fn parse_map(&mut self) -> Result<Value, YamlError> {
        self.pos += 1; // consume '{'
        let mut map = Mapping::new();
        loop {
            self.skip_ws();
            match self.chars.get(self.pos) {
                Some('}') => {
                    self.pos += 1;
                    break;
                }
                None => return Err(self.err("unterminated flow mapping")),
                _ => {}
            }
            let key = self.parse_flow_scalar()?;
            self.skip_ws();
            // A key with no `: value` is a null-valued entry, as in YAML.
            let value = if self.chars.get(self.pos) == Some(&':') {
                self.pos += 1;
                self.parse_value()?
            } else {
                Value::Null
            };
            map.push_raw(key, value);
            self.skip_ws();
            match self.chars.get(self.pos) {
                Some(',') => self.pos += 1,
                Some('}') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(self.err("expected ',' or '}' in flow mapping")),
            }
        }
        Ok(Value::Mapping(map))
    }

    fn parse_flow_scalar(&mut self) -> Result<Value, YamlError> {
        self.skip_ws();
        let c = *self
            .chars
            .get(self.pos)
            .ok_or_else(|| self.err("expected scalar"))?;
        if c == '"' || c == '\'' {
            let start = self.pos;
            self.pos += 1;
            while self.pos < self.chars.len() {
                let cur = self.chars[self.pos];
                if c == '"' && cur == '\\' {
                    self.pos += 2;
                    continue;
                }
                if cur == c {
                    if c == '\'' && self.chars.get(self.pos + 1) == Some(&'\'') {
                        self.pos += 2;
                        continue;
                    }
                    self.pos += 1;
                    break;
                }
                self.pos += 1;
            }
            let raw: String = self.chars[start..self.pos].iter().collect();
            let s = if c == '"' {
                parse_double_quoted(&raw, self.line)?
            } else {
                parse_single_quoted(&raw, self.line)?
            };
            return Ok(Value::String(s));
        }
        // Plain flow scalar: read until `,`, `]`, `}`, or a `:` acting as a
        // key/value separator.
        let start = self.pos;
        while self.pos < self.chars.len() {
            match self.chars[self.pos] {
                ',' | ']' | '}' => break,
                ':' if is_separator_colon(&self.chars, self.pos) => break,
                _ => self.pos += 1,
            }
        }
        let raw: String = self.chars[start..self.pos].iter().collect();
        Ok(interpret_plain(raw.trim()))
    }
}

/// Whether the `:` at `i` separates a flow mapping's key from its value, rather
/// than being an ordinary character inside a plain scalar.
///
/// YAML only treats `:` as a separator in flow context when it is followed by
/// whitespace, a flow indicator, or the end of the collection. OKF v0.2 relies
/// on this: `{ by: human:ahormati, at: 2026-06-25T09:00:00Z }` is one mapping
/// of two entries, not a parse error: the colons in `human:ahormati` and
/// `09:00:00` are content (§5.2, §7).
fn is_separator_colon(chars: &[char], i: usize) -> bool {
    match chars.get(i + 1) {
        None => true,
        Some(c) => c.is_whitespace() || matches!(c, ',' | '[' | ']' | '{' | '}'),
    }
}