lima 0.9.0

Lima frontmatter parser — LIMA Is Metadata Annotation
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
//! Public entry point — orchestrates `block`/`flow`/`scalars` into a full
//! document parse. Mirrors `js/src/core.ts`'s top-level scan (find `key:`/
//! `key: value` lines at column 0; everything else — including a strict-mode
//! non-key line — is silently skipped, per Core §10.1's closed strict-error
//! list) plus its `|` literal block-scalar merging. `block::parse_block_range`
//! is used only for a bare `key:`'s nested content, exactly as in the TS
//! source, not for the top level itself.
//!
//! Scoped down from `js/src/core.ts` for this pass:
//! - No `scanner.ts`/`KeyCursor` fast path — pure performance optimization,
//!   no behavioral difference from the linear scan below.
//!
//! `NESTING_DEPTH_LIMIT` *is* enforced here as a hard error (§9), gated by
//! `block.rs`'s cheap conservative "may exceed" risk flag so the common
//! case never pays for a full tree walk just to find depth 0.

use crate::block::parse_block_range_checked;
use crate::block_scalar::build_block_scalar;
use crate::chars::is_trim_whitespace;
use crate::errors::{Diagnostic, LimaDiagnosticCode as Code, LimaError};
use crate::flow::parse_flow_or_scalar_value_checked;
use crate::normalize::{
    begin_warning_collection, check_duplicate_key, check_key_length, finish_warning_collection,
    DOCUMENT_SIZE_LIMIT, NESTING_DEPTH_LIMIT, TOP_LEVEL_KEY_LIMIT,
};
use crate::scalars::{
    is_valid_key, physical_raw, separator_index, strip_comment, strip_key_quotes,
};
use crate::structure::{check_range_lines, RangeOwner};
use crate::value::{
    Builder, LimaValue, PlainBuilder, PositionedBuilder, PositionedValue, ReferenceSource,
};

/// One discovered top-level `key:`/`key: value` line.
struct TopKey {
    line: u32,
    /// Byte offset of this key's own line start — the previous entry's span
    /// ends here (exclusive).
    key_start: usize,
    /// Byte offset where the value text begins: right after `": "` for an
    /// inline value, or right after this line's own newline for a bare
    /// `key:` (`is_block`).
    value_start: usize,
    is_block: bool,
    key: String,
}

/// Unlike `block.rs`'s `find_key_sep` (matched against block.ts's own
/// naive, non-escape-aware `findKeySep`, used only for nested content),
/// the top-level key scan needs to recognize an escaped quote inside a
/// double-quoted key (`"say \"hi\"": value`) — real Lima delegates this to
/// `scanner.ts`'s escape-aware key scanner, not `findKeySep`. Single-quoted
/// keys stay non-escape-aware, matching `SPACE_BEFORE_COLON_RE`'s own
/// asymmetric `[^']*` vs `(?:[^"\\]|\\.)*` treatment of the two quote kinds.
fn find_key_sep(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    let first = *b.first()?;
    let separated = |i: usize| matches!(b.get(i), Some(b' ' | b'\t'));
    if first == b'\'' {
        let mut i = 1;
        while i < b.len() && b[i] != first {
            i += 1;
        }
        if b.get(i + 1) == Some(&b':') && separated(i + 2) {
            return Some(i + 1);
        }
        return None;
    }
    if first == b'"' {
        let mut i = 1;
        while i < b.len() && b[i] != b'"' {
            i += if b[i] == b'\\' && i + 1 < b.len() {
                2
            } else {
                1
            };
        }
        if b.get(i + 1) == Some(&b':') && separated(i + 2) {
            return Some(i + 1);
        }
        return None;
    }
    separator_index(s)
}

/// Finds every `key:`/`key: value` line starting at column 0 (no leading
/// whitespace). Any other line — blank, comment, indented, matching no key
/// pattern, or an unquoted key candidate with interior whitespace (§5.2) —
/// is simply never visited here, which is *why* it's tolerated even in
/// strict mode (Core §10.1's closed list has nothing to say about text the
/// top-level scan never looks at).
fn scan_top_keys(source: &str, strict: bool) -> Result<Vec<TopKey>, LimaError> {
    let mut result = Vec::new();
    let bytes = source.as_bytes();
    let mut pos = 0usize;
    let mut line_no = 1u32;
    while pos <= bytes.len() {
        let line_end = source[pos..]
            .find('\n')
            .map(|p| pos + p)
            .unwrap_or(bytes.len());
        let line = &source[pos..line_end];
        if !line.is_empty() && !line.starts_with([' ', '\t', '#']) {
            if let Some(colon_pos) = find_key_sep(line) {
                let key_raw = &line[..colon_pos];
                if is_valid_key(key_raw) {
                    let key = strip_key_quotes(key_raw, strict, line_no)?;
                    result.push(TopKey {
                        line: line_no,
                        key_start: pos,
                        value_start: pos + colon_pos + 2,
                        is_block: false,
                        key,
                    });
                }
            } else if let Some(key_part) = line.strip_suffix(':') {
                if !key_part.is_empty() && is_valid_key(key_part) {
                    let key = strip_key_quotes(key_part, strict, line_no)?;
                    let value_start = if line_end < bytes.len() {
                        line_end + 1
                    } else {
                        line_end
                    };
                    result.push(TopKey {
                        line: line_no,
                        key_start: pos,
                        value_start,
                        is_block: true,
                        key,
                    });
                }
            }
        }
        if line_end >= bytes.len() {
            break;
        }
        pos = line_end + 1;
        line_no += 1;
    }
    Ok(result)
}

/// Core §6.1.6: does this quoted-key line have whitespace between the
/// closing quote and the colon? (`"key" : value` — invalid in strict mode.)
/// Mirrors `SPACE_BEFORE_COLON_RE`. Not escape-aware for single quotes
/// (matches the TS regex's own `[^']*`); double-quoted strings do skip
/// `\X` pairs so an escaped `"` doesn't end the string early.
fn has_space_before_colon(line: &str) -> bool {
    let b = line.as_bytes();
    let Some(&quote) = b.first() else {
        return false;
    };
    if quote != b'\'' && quote != b'"' {
        return false;
    }
    let mut i = 1;
    if quote == b'\'' {
        while i < b.len() && b[i] != b'\'' {
            i += 1;
        }
    } else {
        while i < b.len() && b[i] != b'"' {
            i += if b[i] == b'\\' && i + 1 < b.len() {
                2
            } else {
                1
            };
        }
    }
    if i >= b.len() {
        return false;
    } // unterminated quote
    i += 1; // past the closing quote
    let ws_start = i;
    while i < b.len() && (b[i] == b' ' || b[i] == b'\t') {
        i += 1;
    }
    i > ws_start && b.get(i) == Some(&b':')
}

/// §4 step 3: the byte offset where an inline value begins, after the
/// whitespace (§1) that follows its separator at `start`, however much there
/// is, and at most `end`. The newline that ends the line is not skipped.
fn inline_value_start(source: &str, start: usize, end: usize) -> usize {
    source[start..end]
        .char_indices()
        .find(|&(_, c)| c == '\n' || !is_trim_whitespace(c))
        .map_or(end, |(i, _)| start + i)
}

/// Core 1.3 §4: where the block of a top-level entry starts when its inline
/// value, from `value_start` (see [`inline_value_start`]) up to the next key
/// at `end`, is empty after comment removal and trimming, which makes the
/// entry a bare key; `None` for any other value. Reads only the comment of a
/// bare key.
fn bare_key_block_start(source: &str, value_start: usize, end: usize) -> Option<usize> {
    let rest = &source[value_start..end];
    if !(rest.is_empty() || rest.starts_with(['\n', '#'])) {
        return None;
    }
    let line_end = rest.find('\n').map_or(end, |p| value_start + p);
    Some((line_end + 1).min(end))
}

fn line_at(source: &str, byte_pos: usize) -> u32 {
    1 + source[..byte_pos].bytes().filter(|&c| c == b'\n').count() as u32
}

thread_local! {
    /// Per-line (0-based) count of columns added by leading-tab expansion,
    /// for reporting a References 2.0 token at its *original* column (§2.4).
    /// `None` when the document had no tabs.
    static TAB_ADJUST: std::cell::RefCell<Option<Vec<usize>>> = const { std::cell::RefCell::new(None) };
}

pub(crate) fn tab_adjust_slice(from_line: u32, count: usize) -> Option<Vec<usize>> {
    TAB_ADJUST.with(|t| {
        t.borrow().as_ref().map(|v| {
            let start = from_line.saturating_sub(1) as usize;
            (0..count)
                .map(|i| v.get(start + i).copied().unwrap_or(0))
                .collect()
        })
    })
}

/// Expands tabs to two spaces, but only within each line's *leading*
/// whitespace run — a tab anywhere else in the line is left alone. Records
/// the per-line column growth in `TAB_ADJUST` when any tab is present.
fn expand_leading_tabs(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut adjust: Vec<usize> = Vec::new();
    for (i, line) in s.split('\n').enumerate() {
        if i > 0 {
            out.push('\n');
        }
        let leading_end = line
            .find(|c: char| c != ' ' && c != '\t')
            .unwrap_or(line.len());
        let (leading, rest) = line.split_at(leading_end);
        let tabs = leading.chars().filter(|&c| c == '\t').count();
        adjust.push(tabs); // each tab: 2 expanded cols - 1 original col = +1
        if tabs > 0 {
            for c in leading.chars() {
                if c == '\t' {
                    out.push_str("  ");
                } else {
                    out.push(c);
                }
            }
        } else {
            out.push_str(leading);
        }
        out.push_str(rest);
    }
    TAB_ADJUST.with(|t| *t.borrow_mut() = Some(adjust));
    out
}

/// Strips trailing ASCII spaces from every line.
fn strip_trailing_spaces(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for (i, line) in s.split('\n').enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(line.trim_end_matches(' '));
    }
    out
}

/// Shared top-level scan, generic over [`Builder`] — mirrors
/// `js/src/core.ts`'s `parseCoreGeneric`. Returns the root mapping type
/// directly (`B::Mapping`), not wrapped in a `B::Value` — `parse_core`'s
/// `LimaValue` and `parse_core_with_positions`'s lookup table are both
/// "a set of top-level key/value pairs", not a value in their own right.
fn parse_core_generic<B: Builder, const CHECK_DUPLICATES: bool>(
    front_matter: &str,
    strict: bool,
) -> Result<B::Mapping, LimaError> {
    if front_matter.len() > DOCUMENT_SIZE_LIMIT {
        return Err(LimaError::new(
            Code::ResourceLimit,
            1,
            format!("Lima: document exceeds maximum size of {DOCUMENT_SIZE_LIMIT} bytes at line 1"),
        ));
    }
    TAB_ADJUST.with(|t| *t.borrow_mut() = None);
    let mut owned = front_matter.to_string();
    if owned.contains('\r') {
        owned = owned.replace("\r\n", "\n").replace('\r', "\n");
    }
    if owned.contains('\t') {
        owned = expand_leading_tabs(&owned);
    }
    if owned.contains(" \n") || owned.ends_with(' ') {
        owned = strip_trailing_spaces(&owned);
    }
    let front_matter: &str = &owned;
    if front_matter.is_empty() {
        return Ok(B::m_create());
    }

    if strict {
        let mut search_from = 0usize;
        loop {
            let line_end = front_matter[search_from..]
                .find('\n')
                .map(|p| search_from + p);
            let line = &front_matter[search_from..line_end.unwrap_or(front_matter.len())];
            if has_space_before_colon(line) {
                let l = line_at(front_matter, search_from);
                return Err(LimaError::new(
                    Code::InvalidQuote,
                    l,
                    format!("Lima: space between closing quote and colon at line {l}"),
                ));
            }
            match line_end {
                Some(e) => search_from = e + 1,
                None => break,
            }
        }
    }

    let top_keys = scan_top_keys(front_matter, strict)?;
    if top_keys.len() > TOP_LEVEL_KEY_LIMIT {
        return Err(LimaError::new(
            Code::ResourceLimit,
            1,
            format!("Lima: too many top-level key entries (max {TOP_LEVEL_KEY_LIMIT}) at line 1"),
        ));
    }

    // Core 1.1: before the first key no line belongs to any structure (structure.rs)
    if strict {
        let first = top_keys
            .first()
            .map_or(front_matter.len(), |tk| tk.key_start);
        check_range_lines(front_matter, 0, first, 1, RangeOwner::None)?;
    }

    let mut root: B::Mapping = B::m_create();
    let mut depth_risk = false;
    let mut top_keys = top_keys.into_iter().peekable();
    while let Some(tk) = top_keys.next() {
        let next_start = top_keys
            .peek()
            .map(|n| n.key_start)
            .unwrap_or(front_matter.len());
        check_key_length(&tk.key, tk.line)?;
        if CHECK_DUPLICATES {
            check_duplicate_key(B::m_has_key(&root, &tk.key), &tk.key, tk.line, strict)?;
        }

        // §4 step 3: an inline value begins after the whitespace that follows
        // `: `, as in a block mapping, so that the bare-key test and the scalar
        // paths below, and the source column, see the value itself. Core 1.3
        // §4: an inline value that is empty after comment removal and
        // trimming makes a bare key, whose block starts on the next line
        let span_end = next_start.min(front_matter.len());
        let (value_start, block_start) = if tk.is_block {
            (tk.value_start, Some(tk.value_start))
        } else {
            let value_start = inline_value_start(front_matter, tk.value_start, span_end);
            (
                value_start,
                bare_key_block_start(front_matter, value_start, span_end),
            )
        };
        // an inline value's line end and whether it is a `|` marker, for the
        // strict check below
        let mut inline_line: Option<(usize, bool)> = None;
        let value = if let Some(block_start) = block_start {
            parse_block_range_checked::<B, CHECK_DUPLICATES>(
                front_matter,
                block_start,
                next_start,
                strict,
                tk.line + 1,
                &mut depth_risk,
            )?
            .unwrap_or(B::v_null(tk.line))
        } else {
            let first_newline = front_matter[value_start..span_end]
                .find('\n')
                .map(|p| p + value_start);
            // Physical codepoint column of the value's first char (References
            // §2.4) — only the positioned builder keeps it; `parse_core` would
            // pay a backward `rfind('\n')` scan plus a codepoint count per
            // value for nothing (mirrors the TS `wantSource` guard).
            let value_col = if B::POSITIONED {
                let value_line_start = front_matter[..value_start].rfind('\n').map_or(0, |p| p + 1);
                front_matter[value_line_start..value_start].chars().count()
            } else {
                0
            };
            // `raw` keeps `\#` (so it does not shift a token's reported
            // column) but drops a trailing comment (whose `${…}`-shaped text
            // is not part of the value and must not be scanned) — §2.4.
            let inline_src = |raw: &str| {
                B::POSITIONED.then(|| ReferenceSource {
                    raw: Some(physical_raw(raw)),
                    line: tk.line,
                    col: value_col,
                    tab_adjust: tab_adjust_slice(tk.line, 1),
                })
            };
            // §6.1.5: `|` alone is a literal block scalar marker, with a body
            // or without one (then its value is empty). The introducing key is
            // at column 0; the range runs to the next top-level key, so
            // `build_block_scalar` finds the scalar's own extent within it — a
            // dedented comment or freetext before that key ends the scalar
            // instead of being absorbed.
            let first_line = &front_matter[value_start..first_newline.unwrap_or(span_end)];
            let marker = first_line.trim_matches(is_trim_whitespace) == "|";
            inline_line = first_newline.map(|nl| (nl, marker));
            if marker {
                let body: Vec<&str> = match first_newline {
                    Some(nl) => front_matter[nl + 1..span_end].split('\n').collect(),
                    None => Vec::new(),
                };
                let (joined, raw_body, consumed) = build_block_scalar(&body, 0, tk.line)?;
                B::v_string_src(
                    joined,
                    tk.line + 1,
                    ReferenceSource {
                        raw: Some(raw_body),
                        line: tk.line + 1,
                        col: 0,
                        tab_adjust: tab_adjust_slice(tk.line + 1, consumed),
                    },
                )
            } else if first_line.contains('#') {
                let stripped = strip_comment(first_line);
                parse_flow_or_scalar_value_checked::<B, CHECK_DUPLICATES>(
                    &stripped,
                    strict,
                    tk.line,
                    inline_src(first_line),
                )?
            } else {
                parse_flow_or_scalar_value_checked::<B, CHECK_DUPLICATES>(
                    first_line.trim_end_matches(is_trim_whitespace),
                    strict,
                    tk.line,
                    inline_src(first_line),
                )?
            }
        };
        // Core 1.1: the lines after the key's own line, up to the next key,
        // belong to its block or to nothing
        if strict {
            if let Some(block_start) = block_start {
                check_range_lines(
                    front_matter,
                    block_start,
                    next_start,
                    tk.line + 1,
                    RangeOwner::Mapping,
                )?;
            } else if let Some((line_end, marker)) =
                inline_line.filter(|&(nl, _)| nl + 1 < next_start)
            {
                // lines follow the key's own line
                let owner = if marker {
                    RangeOwner::Scalar
                } else {
                    RangeOwner::Inline
                };
                check_range_lines(front_matter, line_end + 1, next_start, tk.line + 1, owner)?;
            }
        }
        B::m_set(&mut root, tk.key, value);
    }

    // Core §9 nesting depth, over Core's own reference-inert tree. When
    // References is layered on top, it re-checks depth on the final,
    // post-substitution tree separately — substituted values can add depth
    // this check cannot see yet. `depth_risk` is a cheap conservative
    // pre-filter (block.rs's own bound on how deep it recursed) so the
    // common case never pays for a full tree walk just to find depth 0.
    if depth_risk && B::m_max_depth(&root) > NESTING_DEPTH_LIMIT as u32 {
        return Err(LimaError::new(
            Code::ResourceLimit,
            1,
            format!("Lima: nesting depth exceeds maximum of {NESTING_DEPTH_LIMIT} at line 1"),
        ));
    }

    Ok(root)
}

/// Parses Lima Core 1.1 syntax. `($key)`/`(%key)`-shaped text is never
/// recognised here — Core is reference-unaware by construction; that's
/// exclusively the References extension's concern.
#[derive(Default)]
pub struct CoreOptions {
    pub strict: bool,
    pub on_warning: Option<Box<dyn FnMut(Diagnostic)>>,
}

impl From<bool> for CoreOptions {
    fn from(strict: bool) -> Self {
        Self {
            strict,
            on_warning: None,
        }
    }
}

pub fn parse_core(
    front_matter: &str,
    options: impl Into<CoreOptions>,
) -> Result<LimaValue, LimaError> {
    let mut options = options.into();
    if options.on_warning.is_none() {
        return if options.strict {
            parse_core_generic::<PlainBuilder, true>(front_matter, true)
        } else {
            parse_core_generic::<PlainBuilder, false>(front_matter, false)
        }
        .map(LimaValue::Mapping);
    }
    begin_warning_collection(true);
    let result = parse_core_generic::<PlainBuilder, true>(front_matter, options.strict)
        .map(LimaValue::Mapping);
    let warnings = finish_warning_collection();
    if let Some(callback) = options.on_warning.as_mut() {
        for warning in warnings {
            callback(warning);
        }
    }
    result
}

/// Parses Lima Core 1.1 syntax into the internal annotated value tree —
/// every node carrying its source line, string leaves additionally
/// carrying whether they came from quoted syntax. `($key)`/`(%key)` text
/// is left exactly as written; nothing here ever inspects or resolves it.
/// The primitive `references.rs` builds on.
pub fn parse_core_with_positions(
    front_matter: &str,
    strict: bool,
) -> Result<Vec<(String, PositionedValue)>, LimaError> {
    if strict {
        parse_core_generic::<PositionedBuilder, true>(front_matter, true)
    } else {
        parse_core_generic::<PositionedBuilder, false>(front_matter, false)
    }
}

pub(crate) fn parse_core_with_positions_options(
    front_matter: &str,
    strict: bool,
    collect_warnings: bool,
) -> Result<Vec<(String, PositionedValue)>, LimaError> {
    if strict || collect_warnings {
        parse_core_generic::<PositionedBuilder, true>(front_matter, strict)
    } else {
        parse_core_generic::<PositionedBuilder, false>(front_matter, false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn get<'a>(v: &'a LimaValue, key: &str) -> &'a LimaValue {
        let LimaValue::Mapping(entries) = v else {
            panic!("expected mapping")
        };
        &entries
            .iter()
            .find(|(k, _)| k == key)
            .unwrap_or_else(|| panic!("missing key {key:?} in {entries:?}"))
            .1
    }

    #[test]
    fn flat_document() {
        let v = parse_core("title: Hello\ncount: 3\n", false).unwrap();
        assert_eq!(get(&v, "title"), &LimaValue::String("Hello".into()));
        assert_eq!(get(&v, "count"), &LimaValue::Int(3));
    }

    #[test]
    fn nested_mapping() {
        let v = parse_core("address:\n  street: Main St\n  city: Springfield\n", false).unwrap();
        let addr = get(&v, "address");
        assert_eq!(get(addr, "street"), &LimaValue::String("Main St".into()));
        assert_eq!(get(addr, "city"), &LimaValue::String("Springfield".into()));
    }

    #[test]
    fn block_sequence() {
        let v = parse_core("tags:\n  - a\n  - b\n  - c\n", false).unwrap();
        let LimaValue::Array(items) = get(&v, "tags") else {
            panic!("expected array")
        };
        assert_eq!(
            items,
            &[
                LimaValue::String("a".into()),
                LimaValue::String("b".into()),
                LimaValue::String("c".into()),
            ]
        );
    }

    #[test]
    fn sequence_of_mappings() {
        let v = parse_core(
            "items:\n  - name: a\n    qty: 1\n  - name: b\n    qty: 2\n",
            false,
        )
        .unwrap();
        let LimaValue::Array(items) = get(&v, "items") else {
            panic!("expected array")
        };
        assert_eq!(get(&items[0], "name"), &LimaValue::String("a".into()));
        assert_eq!(get(&items[0], "qty"), &LimaValue::Int(1));
        assert_eq!(get(&items[1], "name"), &LimaValue::String("b".into()));
    }

    #[test]
    fn flow_sequence_and_mapping() {
        let v = parse_core("tags: [a, b, c]\nauthor: {name: Alice, age: 30}\n", false).unwrap();
        let LimaValue::Array(tags) = get(&v, "tags") else {
            panic!("expected array")
        };
        assert_eq!(tags.len(), 3);
        let author = get(&v, "author");
        assert_eq!(get(author, "name"), &LimaValue::String("Alice".into()));
        assert_eq!(get(author, "age"), &LimaValue::Int(30));
    }

    #[test]
    fn duplicate_key_strict_throws() {
        assert!(parse_core("title: First\ntitle: Second", true).is_err());
    }

    #[test]
    fn duplicate_key_non_strict_last_wins() {
        let v = parse_core("title: First\ntitle: Second", false).unwrap();
        assert_eq!(get(&v, "title"), &LimaValue::String("Second".into()));
    }

    #[test]
    fn comments_are_stripped() {
        let v = parse_core(
            "title: Hello # a comment\n# full line comment\ncount: 3\n",
            false,
        )
        .unwrap();
        assert_eq!(get(&v, "title"), &LimaValue::String("Hello".into()));
        assert_eq!(get(&v, "count"), &LimaValue::Int(3));
    }

    #[test]
    fn unrecognized_top_level_lines_are_skipped_non_strict_and_throw_strict() {
        // Core 1.1 §10.1: until Core 1.1 strict mode skipped the line too.
        let input = "title: Hello\nthis is not a key line at all\ncount: 42";
        let v = parse_core(input, false).unwrap();
        assert_eq!(get(&v, "title"), &LimaValue::String("Hello".into()));
        assert_eq!(get(&v, "count"), &LimaValue::Int(42));
        let error = parse_core(input, true).unwrap_err();
        assert_eq!(error.code, Code::UnrecognizedLine);
        assert_eq!(error.line, Some(2));
    }

    #[test]
    fn indented_line_is_not_a_top_level_key() {
        let v = parse_core("  bogus: value\nreal: Hello", false).unwrap();
        let LimaValue::Mapping(entries) = &v else {
            panic!()
        };
        assert_eq!(entries.len(), 1);
        assert_eq!(get(&v, "real"), &LimaValue::String("Hello".into()));
    }

    #[test]
    fn block_scalar_basic() {
        let v = parse_core("description: |\n  Line one.\n  Line two.\n", false).unwrap();
        assert_eq!(
            get(&v, "description"),
            &LimaValue::String("Line one.\nLine two.".into())
        );
    }

    #[test]
    fn block_scalar_continuation() {
        let v = parse_core(
            "description: |\n  This is long\n  ^^and continues.\n",
            false,
        )
        .unwrap();
        assert_eq!(
            get(&v, "description"),
            &LimaValue::String("This is long and continues.".into())
        );
    }

    #[test]
    fn block_scalar_trailing_blank_lines_stripped() {
        let v = parse_core("description: |\n  Line one.\n\n\nnext: value\n", false).unwrap();
        assert_eq!(
            get(&v, "description"),
            &LimaValue::String("Line one.".into())
        );
        assert_eq!(get(&v, "next"), &LimaValue::String("value".into()));
    }

    #[test]
    fn quoted_key_with_escaped_quote() {
        let v = parse_core(r#""say \"hi\"": value"#, false).unwrap();
        assert_eq!(get(&v, "say \"hi\""), &LimaValue::String("value".into()));
    }

    #[test]
    fn space_before_colon_strict_error() {
        assert!(parse_core("\"first name\" : Alice", true).is_err());
    }

    #[test]
    fn core_12_unicode_keys_and_message_hints() {
        let v = parse_core("größe: one\n𠀀: two\nautor*in: three\n", false).unwrap();
        assert_eq!(get(&v, "größe"), &LimaValue::String("one".into()));
        assert_eq!(get(&v, "𠀀"), &LimaValue::String("two".into()));
        assert_eq!(get(&v, "autor*in"), &LimaValue::String("three".into()));

        let whitespace = parse_core("\u{a0}key: value\n", true).unwrap_err();
        assert!(whitespace
            .message
            .contains("U+00A0 before the key; Lima indents by spaces only"));
        let colon = parse_core("title: value\n", true).unwrap_err();
        assert!(colon.message.contains(
            "the key-value separator is \": \" (U+003A and a space), not U+FF1A FULLWIDTH COLON"
        ));
    }

    #[test]
    fn spaced_key_with_separator_names_the_quoted_key_at_every_level() {
        // Core 1.3 Appendix E
        for input in ["x y: 2\n", "outer:\n  x y: 2\n"] {
            let error = parse_core(input, true).unwrap_err();
            assert!(error
                .message
                .contains("(quote a key that holds spaces: 'x y':)"));
            assert!(!error.message.contains("a key needs \": \" after it"));
        }
        let error = parse_core("x/y: 2\n", true).unwrap_err();
        assert!(error
            .message
            .contains("an unquoted key starts with a Unicode letter or number"));
    }
}