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
758
759
760
761
762
763
764
//! Core §7 block collections (sequences and mappings). Mirrors
//! `js/src/block.ts`, with the same performance-motivated ASCII fast paths
//! deliberately dropped (see `scalars.rs`'s module doc) — `trim_slice` and
//! `strip_key_quotes` are called uniformly instead of branching on whether
//! a fast path applies. Generic over [`Builder`] — see `scalars.rs`'s
//! module doc.

use crate::block_cursor::BlockCursor;
use crate::block_scalar::build_block_scalar;
use crate::chars::is_trim_whitespace;
use crate::core::tab_adjust_slice;
use crate::errors::{LimaDiagnosticCode as Code, LimaError, MULTILINE_VALUE_HINT};
use crate::flow::{parse_flow_or_scalar_value_checked, parse_flow_sequence_checked};
use crate::key_hints::{specific_key_hint, KEY_GRAMMAR_HINT};
use crate::normalize::{check_duplicate_key, check_key_length, NESTING_DEPTH_LIMIT};
use crate::scalars::{
    closing_quote_index, is_valid_key, parse_quoted_or_typed, physical_raw, separator_index,
    strip_comment, strip_key_quotes,
};
use crate::value::{Builder, ReferenceSource};

/// A key's inline value text. If it is exactly `|`, consume the following
/// physical lines belonging to the Core §6.1.5 block scalar introduced by a
/// key at `key_indent` and return the scalar; the cursor is left on the
/// first line past it. Otherwise parse `raw` as an ordinary inline value
/// and advance one line. `value_col` is the physical codepoint column of
/// `raw`'s first character (References §2.4). §6.1.5 places no top-level
/// restriction on block scalars, so this is the same primitive `core.rs`
/// uses at the top level.
/// Core 1.1 §10.1: a line in a block whose key the key grammar (§5.1) rejects, in strict mode.
fn unrecognized_key_line(line: u32, trimmed: &str) -> LimaError {
    LimaError::new(
        Code::UnrecognizedLine,
        line,
        format!(
            "Lima: unrecognised line at line {line}: \"{trimmed}\"{}",
            specific_key_hint(trimmed)
                .as_deref()
                .unwrap_or(KEY_GRAMMAR_HINT)
        ),
    )
}

/// An inline value, or a `|` block scalar when `marker`: the value is `|`
/// alone (§6.1.5; `| # c` is the string `|`).
#[allow(clippy::too_many_arguments)]
fn inline_or_block_scalar<'a, B: Builder, const CHECK_DUPLICATES: bool>(
    raw: &str,
    marker: bool,
    key_indent: usize,
    key_line: u32,
    value_col: usize,
    raw_undecoded: &str,
    cursor: &mut BlockCursor<'a>,
    strict: bool,
) -> Result<B::Value, LimaError> {
    if !marker {
        let source = B::POSITIONED.then(|| ReferenceSource {
            raw: Some(physical_raw(raw_undecoded)),
            line: key_line,
            col: value_col,
            tab_adjust: tab_adjust_slice(key_line, 1),
        });
        let value = parse_flow_or_scalar_value_checked::<B, CHECK_DUPLICATES>(
            raw, strict, key_line, source,
        )?;
        cursor.next();
        return Ok(value);
    }
    cursor.next(); // past the `key: |` line
    let mut body_lines: Vec<&'a str> = Vec::new();
    while cursor.valid {
        // the scalar's own extent (§6.1.5, `build_block_scalar`): a line of
        // spaces only is empty, any other ends it at the key's column or less
        // — a line of other whitespace too, which is content here
        if cursor.line_end - cursor.line_start > cursor.ascii_indent
            && cursor.ascii_indent <= key_indent
        {
            break;
        }
        body_lines.push(&cursor.source[cursor.line_start..cursor.line_end]);
        cursor.next();
    }
    let (joined, raw_body, consumed) = build_block_scalar(&body_lines, key_indent, key_line)?;
    Ok(B::v_string_src(
        joined,
        key_line + 1,
        ReferenceSource {
            raw: Some(raw_body),
            line: key_line + 1,
            col: 0,
            tab_adjust: tab_adjust_slice(key_line + 1, consumed),
        },
    ))
}

/// Finds the key/value separator: the first unquoted colon followed by a
/// space or a tab (§5.1), or (for a quoted key) such a colon immediately
/// after the matching closing quote. §5.1: the separator must sit outside
/// the quoted key, so this scans past its (escape-aware) closing quote
/// first. Double-quoted keys honour `\"`; a single-quoted key is literal
/// (§5.2), so its first `'` closes.
fn find_key_sep(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    let first = *b.first()?;
    if first == b'\'' || first == b'"' {
        let close = closing_quote_index(s, false)?;
        let separated = matches!(b.get(close + 2), Some(b' ' | b'\t'));
        if b.get(close + 1) == Some(&b':') && separated {
            return Some(close + 1);
        }
        return None;
    }
    separator_index(s)
}

/// An item's text after `- ` with its comment removed and its end trimmed
/// (Core 1.3 §4). A quoted key is read by the key rules (§5.2), in which a
/// single-quoted key has no escape, so the comment is looked for after its
/// separator only: in `'a\': # c` the key is `a\` and its value is only a
/// comment, which leaves the key bare. Mirrors `js/src/block.ts`'s
/// `uncommentItem`.
fn uncomment_item(text: &str) -> String {
    if !text.contains('#') {
        return text.trim_end_matches(is_trim_whitespace).to_string();
    }
    let value_start = match text.as_bytes()[0] {
        b'\'' | b'"' => find_key_sep(text).map_or(0, |colon| colon + 1),
        _ => 0,
    };
    if value_start == 0 {
        return strip_comment(text);
    }
    text[..value_start].to_string() + &strip_comment(&text[value_start..])
}

fn trim_slice(source: &str, start: usize, end: usize) -> &str {
    source[start..end].trim_matches(is_trim_whitespace)
}

/// A key, or a line's content, keeps the whitespace it starts with, which
/// makes it no key (Core 1.1 §7.1: other whitespace before content is no
/// indentation).
fn trim_end_slice(source: &str, start: usize, end: usize) -> &str {
    source[start..end].trim_end_matches(is_trim_whitespace)
}

fn cursor_content<'a>(cursor: &BlockCursor<'a>) -> &'a str {
    &cursor.source[cursor.content_start..cursor.line_end]
}

/// Core §4 rule 7 / §6.1.3: comment lines (first non-whitespace character
/// `#`) do not affect base indentation and are skipped — including in the
/// lookahead that decides whether a bare key (`key:` with no inline value)
/// has any nested block at all. Advancing past a comment here, not only a
/// blank line, keeps that pre-check consistent with the same skip already
/// applied once inside an established block (`parse_cursor_block`'s own
/// `cursor.empty() || cursor.first_byte() == b'#'` check at the top of its
/// loop).
fn skip_empty_and_comment_lines(cursor: &mut BlockCursor) {
    while cursor.valid && (cursor.empty() || cursor.first_byte() == b'#') {
        cursor.next();
    }
}

/// The text after `- ` (dash + whitespace). If the character right after
/// the dash is *not* whitespace, the whole line (dash included) is treated
/// as an ordinary scalar starting with a literal `-` — not a sequence item.
/// The column of the first key after `- ` on the cursor's current line —
/// the base indentation for the item's sibling keys (§7.2). Codepoints, so
/// a multi-byte space after the dash counts as one column (matching the
/// TypeScript reference).
fn dash_key_column(cursor: &BlockCursor) -> usize {
    let end = cursor.line_end;
    let mut pos = cursor.content_start + 1;
    while pos < end {
        let ch = cursor.source[pos..end].chars().next().unwrap();
        if !is_trim_whitespace(ch) {
            break;
        }
        pos += ch.len_utf8();
    }
    cursor.source[cursor.line_start..pos].chars().count()
}

/// Codepoints of leading whitespace on `s` — for a value's column in its line.
fn leading_ws_len(s: &str) -> usize {
    s.chars().take_while(|c| is_trim_whitespace(*c)).count()
}

/// Length (codepoints) of the `- ` (dash + whitespace) prefix on the current line.
fn dash_prefix_len(cursor: &BlockCursor) -> usize {
    let end = cursor.line_end;
    let mut pos = cursor.content_start + 1;
    while pos < end {
        let ch = cursor.source[pos..end].chars().next().unwrap();
        if !is_trim_whitespace(ch) {
            break;
        }
        pos += ch.len_utf8();
    }
    cursor.source[cursor.content_start..pos].chars().count()
}

fn cursor_after_dash<'a>(cursor: &BlockCursor<'a>) -> &'a str {
    let start = cursor.content_start;
    let end = cursor.line_end;
    if start + 1 == end {
        return "";
    }
    let content = start + 1;
    let first_ch = cursor.source[content..end].chars().next().unwrap();
    if !is_trim_whitespace(first_ch) {
        return &cursor.source[start..end];
    }
    let mut content = content;
    while content < end {
        let ch = cursor.source[content..end].chars().next().unwrap();
        if !is_trim_whitespace(ch) {
            break;
        }
        content += ch.len_utf8();
    }
    &cursor.source[content..end]
}

fn is_dash_only_or_prefixed(s: &str) -> bool {
    if s == "-" {
        return true;
    }
    let Some(rest) = s.strip_prefix('-') else {
        return false;
    };
    rest.starts_with(is_trim_whitespace) && !rest.is_empty()
}

/// §7.2: a sequence item is a line of `-` alone or `-` followed by
/// whitespace; `---` or `-x` is none (Core 1.1). The cursor is on a line
/// with content.
fn is_sequence_item(cursor: &BlockCursor) -> bool {
    if cursor.first_byte() != b'-' {
        return false;
    }
    let next = cursor.content_start + 1;
    next == cursor.line_end
        || cursor.source[next..cursor.line_end]
            .chars()
            .next()
            .is_some_and(is_trim_whitespace)
}

/// Core 1.1 §7.2: the block of a bare key at `key_column` — deeper than the
/// key (§7.1 rule 3), or a sequence that starts at the key's own column,
/// which compact parsing ends at that column's first line that is no item.
/// None without either. The cursor is on the first content line after the
/// key.
fn block_of_bare_key<B: Builder, const CHECK_DUPLICATES: bool>(
    cursor: &mut BlockCursor,
    key_column: usize,
    strict: bool,
    base_line: u32,
) -> Result<Option<B::Value>, LimaError> {
    if !cursor.valid {
        return Ok(None);
    }
    if cursor.indent > key_column {
        let indent = cursor.indent;
        return parse_cursor_block::<B, CHECK_DUPLICATES>(cursor, indent, strict, base_line, false);
    }
    if cursor.indent == key_column && is_sequence_item(cursor) {
        return parse_cursor_block::<B, CHECK_DUPLICATES>(
            cursor, key_column, strict, base_line, true,
        );
    }
    Ok(None)
}

/// The value of an entry on the cursor's line whose content is `content`,
/// its key at `key_column` and its separator's colon at `colon` (`None` for
/// a `key:` that ends the line). An inline value that is empty after comment
/// removal and trimming makes a bare key, whose block may follow (Core 1.3
/// §4, §7.1); `|` alone is a block scalar (§6.1.5). Leaves the cursor on the
/// next unread line. `js/src/block.ts` reads it in each entry branch of
/// `parseCursorBlock`.
fn entry_value<B: Builder, const CHECK_DUPLICATES: bool>(
    cursor: &mut BlockCursor,
    content: &str,
    colon: Option<usize>,
    key_column: usize,
    line: u32,
    strict: bool,
    base_line: u32,
) -> Result<B::Value, LimaError> {
    let (colon, raw_undecoded) = match colon {
        Some(colon) => (colon, trim_slice(content, colon + 2, content.len())),
        None => (0, ""),
    };
    // Core 1.3 §4: a value that is empty after comment removal and trimming,
    // none or a comment, leaves the key bare, and its block follows
    if raw_undecoded.is_empty() || raw_undecoded.starts_with('#') {
        cursor.next();
        skip_empty_and_comment_lines(cursor);
        let block =
            block_of_bare_key::<B, CHECK_DUPLICATES>(cursor, key_column, strict, base_line)?;
        return Ok(block.unwrap_or(B::v_null(line)));
    }
    let raw = if raw_undecoded != "|" && raw_undecoded.contains('#') {
        strip_comment(raw_undecoded)
    } else {
        raw_undecoded.to_string()
    };
    let value_col = if B::POSITIONED {
        cursor.ascii_indent + colon + 2 + leading_ws_len(&content[colon + 2..])
    } else {
        0
    };
    inline_or_block_scalar::<B, CHECK_DUPLICATES>(
        &raw,
        raw_undecoded == "|",
        key_column,
        line,
        value_col,
        raw_undecoded,
        cursor,
        strict,
    )
}

/// Shared block grammar consuming one mutable physical-line cursor; a
/// `compact` sequence (Core 1.1 §7.2) ends at its column's first line that is
/// no item.
fn parse_cursor_block<B: Builder, const CHECK_DUPLICATES: bool>(
    cursor: &mut BlockCursor,
    base_indent: usize,
    strict: bool,
    base_line: u32,
    compact: bool,
) -> Result<Option<B::Value>, LimaError> {
    let mut items: Option<Vec<B::Value>> = None;
    let mut entries: Option<B::Mapping> = None;
    let mut pending_item: Option<B::Mapping> = None;
    // the column of the pending object item's keys: its first key's, after
    // `- ` (§7.2)
    let mut pending_column = 0;
    let start_line = cursor.line_index;

    while cursor.valid {
        let line = (base_line as i64 + cursor.line_index) as u32;
        if cursor.empty() || cursor.first_byte() == b'#' {
            cursor.next();
            continue;
        }
        let indent = cursor.indent;
        if indent < base_indent {
            break;
        }

        if indent > base_indent {
            let trimmed = cursor_content(cursor);
            // §7.2: an object item's keys stand at its first key's column. A
            // line less indented ends the item (§7.1 rule 4); a deeper one,
            // which no nested block took, is inconsistently indented (rule 5)
            // and the item goes on
            if indent < pending_column {
                if let Some(item) = pending_item.take() {
                    items.as_mut().unwrap().push(B::v_mapping(item, line));
                }
            }
            if pending_item.is_some() && indent > pending_column {
                if strict {
                    return Err(LimaError::new(
                        Code::InvalidIndentation,
                        line,
                        format!("Lima: unexpected indentation at line {line}: \"{trimmed}\"{MULTILINE_VALUE_HINT}"),
                    ));
                }
                cursor.next();
                continue;
            }
            if let (true, Some(pending)) = (items.is_some(), pending_item.as_mut()) {
                let colon_pos = find_key_sep(trimmed);
                let key_raw = match colon_pos {
                    Some(c) => trim_end_slice(trimmed, 0, c),
                    None => match trimmed.strip_suffix(':') {
                        Some(_) => trim_end_slice(trimmed, 0, trimmed.len() - 1),
                        None => "",
                    },
                };
                if !key_raw.is_empty() && !is_valid_key(key_raw) {
                    // §5.1: not a usable key — an unrecognised line, skipped in non-strict mode and an
                    // error in strict mode, as at the top level (Core 1.1 §10.1)
                    if strict {
                        return Err(unrecognized_key_line(line, trimmed));
                    }
                    cursor.next();
                } else if colon_pos.is_some() || trimmed.ends_with(':') {
                    let key = strip_key_quotes(key_raw, strict, line)?;
                    check_key_length(&key, line)?;
                    let value = entry_value::<B, CHECK_DUPLICATES>(
                        cursor, trimmed, colon_pos, indent, line, strict, base_line,
                    )?;
                    B::m_set(pending, key, value);
                } else {
                    if strict {
                        return Err(LimaError::new(
                            Code::InvalidIndentation, line,
                            format!("Lima: unexpected syntax in array item continuation at line {line}: \"{trimmed}\""),
                        ));
                    }
                    cursor.next();
                }
            } else {
                if strict {
                    return Err(LimaError::new(
                        Code::InvalidIndentation,
                        line,
                        format!("Lima: unexpected indentation at line {line}: \"{trimmed}\"{MULTILINE_VALUE_HINT}"),
                    ));
                }
                cursor.next();
            }
            continue;
        }

        // a sequence at its key's column ends at that column's first line
        // that is no item (Core 1.1 §7.2)
        if compact && !is_sequence_item(cursor) {
            break;
        }
        if is_sequence_item(cursor) {
            if let Some(p) = pending_item.take() {
                items
                    .get_or_insert_with(Vec::new)
                    .push(B::v_mapping(p, line));
            }
            // a block is a mapping or a sequence, as its first line decides;
            // in non-strict mode a line of the other kind is skipped, and what
            // the block holds stays (Core 1.1 §7.1)
            if entries.is_some() {
                if strict {
                    return Err(LimaError::new(
                        Code::InvalidIndentation,
                        line,
                        format!(
                            "Lima: mixed array and map entries for the same key at line {line}"
                        ),
                    ));
                }
                cursor.next();
                continue;
            }
            let items = items.get_or_insert_with(Vec::new);

            let after_dash_raw = cursor_after_dash(cursor);
            let after_dash = uncomment_item(after_dash_raw);
            let dash_src = |col: usize| {
                B::POSITIONED.then(|| ReferenceSource {
                    raw: Some(physical_raw(after_dash_raw)),
                    line,
                    col,
                    tab_adjust: tab_adjust_slice(line, 1),
                })
            };
            let first = after_dash.as_bytes().first().copied();
            // an item's value is an inline value (§15.3): a flow mapping, or
            // what an unclosed one falls back to (§7.5); a flow sequence there
            // is a sequence in a sequence (§7.2)
            if first == Some(b'{') {
                items.push(parse_flow_or_scalar_value_checked::<B, CHECK_DUPLICATES>(
                    &after_dash,
                    strict,
                    line,
                    dash_src(cursor.indent + dash_prefix_len(cursor)),
                )?);
                cursor.next();
                continue;
            }
            if first == Some(b'[') {
                let src = dash_src(cursor.indent + dash_prefix_len(cursor));
                match parse_flow_sequence_checked::<B, CHECK_DUPLICATES>(
                    &after_dash,
                    strict,
                    line,
                    src.clone(),
                )? {
                    None => items.push(parse_flow_or_scalar_value_checked::<B, CHECK_DUPLICATES>(
                        &after_dash,
                        strict,
                        line,
                        src,
                    )?),
                    Some(_) if strict => {
                        let content = cursor_content(cursor).to_string();
                        return Err(LimaError::new(
                            Code::InvalidFlowSyntax,
                            line,
                            format!("Lima: nested sequence at line {line}: \"{content}\""),
                        ));
                    }
                    Some(_) => items.push(B::v_null(line)),
                }
                cursor.next();
                continue;
            }
            let colon_pos = find_key_sep(&after_dash);
            if !matches!(first, Some(b'"') | Some(b'\'') | Some(b'-'))
                && colon_pos.is_none()
                && !after_dash.ends_with(':')
            {
                items.push(parse_quoted_or_typed::<B>(
                    &after_dash,
                    strict,
                    line,
                    dash_src(cursor.indent + dash_prefix_len(cursor)),
                )?);
                cursor.next();
                continue;
            }

            if is_dash_only_or_prefixed(&after_dash) {
                if strict {
                    let content = cursor_content(cursor).to_string();
                    return Err(LimaError::new(
                        Code::InvalidIndentation,
                        line,
                        format!("Lima: nested block sequence at line {line}: \"{content}\""),
                    ));
                }
                items.push(B::v_null(line));
                cursor.next();
                while cursor.valid {
                    if cursor.empty() || cursor.first_byte() == b'#' {
                        cursor.next();
                        continue;
                    }
                    if cursor.indent <= base_indent {
                        break;
                    }
                    cursor.next();
                }
            } else if colon_pos.is_some_and(|c| is_valid_key(trim_slice(&after_dash, 0, c))) {
                let colon_pos = colon_pos.unwrap();
                let key = strip_key_quotes(trim_slice(&after_dash, 0, colon_pos), strict, line)?;
                check_key_length(&key, line)?;
                let value_start = colon_pos + 2;
                let raw = trim_slice(&after_dash, value_start, after_dash.len());
                // The key sits after `- `, so the value column is dash prefix + `key: `.
                let value_col = if B::POSITIONED {
                    cursor.indent
                        + dash_prefix_len(cursor)
                        + value_start
                        + leading_ws_len(&after_dash[value_start..])
                } else {
                    0
                };
                let item_key_column = cursor.indent + dash_prefix_len(cursor);
                let marker = after_dash_raw
                    .get(value_start..)
                    .is_some_and(|v| v.trim_matches(is_trim_whitespace) == "|");
                let value = inline_or_block_scalar::<B, CHECK_DUPLICATES>(
                    raw,
                    marker,
                    item_key_column,
                    line,
                    value_col,
                    after_dash_raw
                        .get(value_start..)
                        .map_or(raw, |value| value.trim_matches(is_trim_whitespace)),
                    cursor,
                    strict,
                )?;
                let mut item = B::m_create_with(key, value);
                pending_column = item_key_column;
                // the item's later keys at its key column; any other line is
                // the block loop's (§7.2)
                while cursor.valid && cursor.indent == pending_column {
                    let continuation_line = (base_line as i64 + cursor.line_index) as u32;
                    let ckey_indent = cursor.ascii_indent;
                    // a last line of whitespace only has no first byte
                    if cursor.source.as_bytes().get(cursor.content_start) == Some(&b'#') {
                        break;
                    }
                    let cont_line =
                        trim_end_slice(cursor.source, cursor.content_start, cursor.line_end);
                    let Some(csep) = find_key_sep(cont_line) else {
                        break;
                    };
                    let ckey_raw = trim_end_slice(cont_line, 0, csep);
                    if !is_valid_key(ckey_raw) {
                        break;
                    }
                    let ckey = strip_key_quotes(ckey_raw, strict, continuation_line)?;
                    if ckey.is_empty() {
                        break;
                    }
                    check_key_length(&ckey, continuation_line)?;
                    let cvalue = entry_value::<B, CHECK_DUPLICATES>(
                        cursor,
                        cont_line,
                        Some(csep),
                        ckey_indent,
                        continuation_line,
                        strict,
                        base_line,
                    )?;
                    B::m_set(&mut item, ckey, cvalue);
                }
                pending_item = Some(item);
            } else if colon_pos.is_none() && after_dash.strip_suffix(':').is_some_and(is_valid_key)
            {
                let key_part = after_dash.strip_suffix(':').unwrap();
                let key =
                    strip_key_quotes(trim_end_slice(key_part, 0, key_part.len()), strict, line)?;
                check_key_length(&key, line)?;
                // §7.1 rule 3 / §7.2: a nested block must be indented deeper
                // than the first key's column (after `- `), not merely deeper
                // than the item's dash. A line at the key's own column is the
                // next sibling key, so the bare key is null.
                let key_column = dash_key_column(cursor);
                cursor.next();
                skip_empty_and_comment_lines(cursor);
                let value = block_of_bare_key::<B, CHECK_DUPLICATES>(
                    cursor, key_column, strict, base_line,
                )?
                .unwrap_or(B::v_null(line));
                pending_column = key_column;
                pending_item = Some(B::m_create_with(key, value));
            } else {
                // A quoted-or-typed scalar item — parse_quoted_or_typed enforces
                // §10.1's unterminated / trailing-content strict checks.
                items.push(parse_quoted_or_typed::<B>(
                    &after_dash,
                    strict,
                    line,
                    dash_src(cursor.indent + dash_prefix_len(cursor)),
                )?);
                cursor.next();
            }
        } else {
            let trimmed = cursor_content(cursor).to_string();
            if items.is_some() {
                if strict {
                    return Err(LimaError::new(
                        Code::InvalidIndentation,
                        line,
                        format!(
                            "Lima: mixed map and array entries for the same key at line {line}"
                        ),
                    ));
                }
                cursor.next();
                continue;
            }
            let colon_pos = find_key_sep(&trimmed);
            let key_attempt: Option<&str> = colon_pos
                .map(|c| trim_end_slice(&trimmed, 0, c))
                .or_else(|| trimmed.strip_suffix(':').filter(|k| !k.is_empty()));
            if key_attempt.is_some_and(|k| !is_valid_key(k)) {
                // §5.1: not a usable key — an unrecognised line, skipped in
                // non-strict mode and an error in strict mode, as at the top
                // level (Core 1.1 §10.1)
                if strict {
                    return Err(unrecognized_key_line(line, &trimmed));
                }
                cursor.next();
            } else if colon_pos.is_some() || trimmed.ends_with(':') {
                let entries = entries.get_or_insert_with(B::m_create);
                let key_end = colon_pos.unwrap_or(trimmed.len() - 1);
                let key = strip_key_quotes(trim_end_slice(&trimmed, 0, key_end), strict, line)?;
                check_key_length(&key, line)?;
                if CHECK_DUPLICATES {
                    check_duplicate_key(B::m_has_key(entries, &key), &key, line, strict)?;
                }
                let value = entry_value::<B, CHECK_DUPLICATES>(
                    cursor,
                    &trimmed,
                    colon_pos,
                    base_indent,
                    line,
                    strict,
                    base_line,
                )?;
                B::m_set(entries, key, value);
            } else {
                if strict {
                    return Err(LimaError::new(
                        Code::InvalidIndentation, line,
                        format!("Lima: indented freetext without a block scalar marker at line {line}: \"{trimmed}\""),
                    ));
                }
                cursor.next();
            }
        }
    }

    let result_line = (base_line as i64 + start_line) as u32;
    if let Some(p) = pending_item {
        items
            .get_or_insert_with(Vec::new)
            .push(B::v_mapping(p, result_line));
    }
    Ok(if let Some(items) = items {
        Some(B::v_array(items, result_line))
    } else {
        entries.map(|e| B::v_mapping(e, result_line))
    })
}

/// Complete block grammar over one UTF-8 source range (byte offsets).
/// `depth_risk`, if set to `true`, signals that recursive block containers
/// may have exceeded `NESTING_DEPTH_LIMIT` — Core §9's nesting-depth check
/// (this port doesn't yet enforce it as a hard error, only surfaces the
/// risk flag, matching how deep the TS source's own conservative bound is
/// meant to be used by its caller).
pub fn parse_block_range<B: Builder>(
    source: &str,
    start: usize,
    end: usize,
    strict: bool,
    check_duplicates: bool,
    base_line: u32,
    depth_risk: &mut bool,
) -> Result<Option<B::Value>, LimaError> {
    if check_duplicates {
        parse_block_range_checked::<B, true>(source, start, end, strict, base_line, depth_risk)
    } else {
        parse_block_range_checked::<B, false>(source, start, end, strict, base_line, depth_risk)
    }
}

pub(crate) fn parse_block_range_checked<B: Builder, const CHECK_DUPLICATES: bool>(
    source: &str,
    start: usize,
    end: usize,
    strict: bool,
    base_line: u32,
    depth_risk: &mut bool,
) -> Result<Option<B::Value>, LimaError> {
    let mut cursor = BlockCursor::new(source, start, end);
    if !cursor.next() {
        return Ok(None);
    }
    skip_empty_and_comment_lines(&mut cursor);
    if !cursor.valid {
        return Ok(None);
    }
    let base_indent = cursor.ascii_indent;
    // Core 1.1 §7.2: at the top level's own column 0 only a sequence is the
    // key's block; any other first line is not
    if base_indent == 0 && !is_sequence_item(&cursor) {
        return Ok(None);
    }
    let value = parse_cursor_block::<B, CHECK_DUPLICATES>(
        &mut cursor,
        base_indent,
        strict,
        base_line,
        base_indent == 0,
    )?;
    if cursor.max_indent.saturating_sub(base_indent) + 4 > NESTING_DEPTH_LIMIT {
        *depth_risk = true;
    }
    Ok(value)
}