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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
//! Core scalar grammar — mirrors `js/src/scalars.ts`: dates, numbers/type
//! coercion, quoting/escaping, and the shared quoted-or-typed scalar parser.
//!
//! Generic over [`Builder`] (mirrors `js/src/builder.ts`'s `ValueBuilder<V, M>`)
//! so the plain `LimaValue` projection and the position-annotated
//! `PositionedValue` tree share one grammar without a second, hand-copied
//! parser. No `regex` dependency: every date/number shape below is checked
//! in hand-written scanners, matching the char-code fast paths the TS
//! source already prefers over its regexes for the same forms.

use crate::chars::is_trim_whitespace;
use crate::errors::{LimaDiagnosticCode as Code, LimaError};
use crate::unicode_key::is_valid_unquoted;
use crate::value::{days_from_civil, Builder, Instant, ReferenceSource};

pub const SCALAR_LENGTH_LIMIT: usize = 16_384;

pub fn check_string_limit(value: &str, line: u32) -> Result<(), LimaError> {
    // Rust strings are UTF-8; `.chars().count()` is already the code-point
    // length (no UTF-16 surrogate-pair subtlety like the TS source has).
    if value.chars().count() > SCALAR_LENGTH_LIMIT {
        return Err(LimaError::new(
            Code::ResourceLimit,
            line,
            format!("Lima: scalar exceeds maximum length of {SCALAR_LENGTH_LIMIT} code points at line {line}"),
        ));
    }
    Ok(())
}

// ─── Dates ──────────────────────────────────────────────────────────────────

const DAYS_IN_MONTH: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

fn is_leap_year(y: i64) -> bool {
    (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}

fn days_in_month(y: i64, m: u32) -> u32 {
    if m == 2 && is_leap_year(y) {
        29
    } else {
        DAYS_IN_MONTH[(m - 1) as usize]
    }
}

fn is_valid_ymd_hms(y: i64, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> bool {
    y >= 1
        && (1..=12).contains(&mo)
        && d >= 1
        && d <= days_in_month(y, mo)
        && h <= 23
        && mi <= 59
        && s <= 59
}

fn to_instant(y: i64, mo: u32, d: u32, h: u32, mi: u32, s: u32, offset_min: i64) -> Instant {
    let epoch_seconds =
        days_from_civil(y, mo, d) * 86_400 + h as i64 * 3600 + mi as i64 * 60 + s as i64
            - offset_min * 60;
    Instant { epoch_seconds }
}

struct DateInvalid;

/// `(year, month, day, hour, minute, second, utc_offset_minutes)`.
type DateParts = (i64, u32, u32, u32, u32, u32, i64);

/// ISO 8601 date or datetime, optionally with `Z`/`±HH:MM` offset:
/// `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)?`.
fn try_parse_iso(s: &str) -> Option<Result<DateParts, DateInvalid>> {
    let b = s.as_bytes();
    if b.len() < 10
        || !is_digit4(&b[0..4])
        || b[4] != b'-'
        || !is_digit2(&b[5..7])
        || b[7] != b'-'
        || !is_digit2(&b[8..10])
    {
        return None;
    }
    let y = digits(&b[0..4]);
    let mo = digits(&b[5..7]) as u32;
    let d = digits(&b[8..10]) as u32;
    if b.len() == 10 {
        return Some(Ok((y, mo, d, 0, 0, 0, 0)));
    }
    if b.len() < 16
        || b[10] != b'T'
        || !is_digit2(&b[11..13])
        || b[13] != b':'
        || !is_digit2(&b[14..16])
    {
        return None;
    }
    let h = digits(&b[11..13]) as u32;
    let mi = digits(&b[14..16]) as u32;
    let mut rest = &s[16..];
    let mut sec = 0u32;
    if let Some(r) = rest.strip_prefix(':') {
        if r.len() < 2 || !is_digit2(r.as_bytes()) {
            return None;
        }
        sec = digits(r.as_bytes()[0..2].try_into().unwrap()) as u32;
        rest = &r[2..];
    }
    if rest.is_empty() {
        return Some(Ok((y, mo, d, h, mi, sec, 0)));
    }
    if rest == "Z" {
        return Some(Ok((y, mo, d, h, mi, sec, 0)));
    }
    let rb = rest.as_bytes();
    if rb.len() == 6
        && (rb[0] == b'+' || rb[0] == b'-')
        && is_digit2(&rb[1..3])
        && rb[3] == b':'
        && is_digit2(&rb[4..6])
    {
        let sign: i64 = if rb[0] == b'-' { -1 } else { 1 };
        let oh = digits(&rb[1..3]);
        let om = digits(&rb[4..6]);
        if oh > 14 || om > 59 || (oh == 14 && om != 0) {
            return Some(Err(DateInvalid));
        }
        return Some(Ok((y, mo, d, h, mi, sec, sign * (oh * 60 + om))));
    }
    None
}

/// `DD.MM.YYYY` or `DD.MM.YYYY HH:MM(:SS)?` (German style).
fn try_parse_german(s: &str) -> Option<(i64, u32, u32, u32, u32, u32)> {
    let (date_part, time_part) = split_once_space(s);
    let mut parts = date_part.split('.');
    let d = parts.next()?;
    let mo = parts.next()?;
    let y = parts.next()?;
    if parts.next().is_some() {
        return None;
    }
    if !(1..=2).contains(&d.len()) || !d.bytes().all(|c| c.is_ascii_digit()) {
        return None;
    }
    if !(1..=2).contains(&mo.len()) || !mo.bytes().all(|c| c.is_ascii_digit()) {
        return None;
    }
    if y.len() != 4 || !y.bytes().all(|c| c.is_ascii_digit()) {
        return None;
    }
    let (h, mi, sec) = parse_optional_time(time_part)?;
    Some((
        y.parse().ok()?,
        mo.parse().ok()?,
        d.parse().ok()?,
        h,
        mi,
        sec,
    ))
}

/// `YYYY/MM/DD` or `YYYY/MM/DD HH:MM(:SS)?`.
fn try_parse_slash(s: &str) -> Option<(i64, u32, u32, u32, u32, u32)> {
    let (date_part, time_part) = split_once_space(s);
    let b = date_part.as_bytes();
    if b.len() != 10
        || !is_digit4(&b[0..4])
        || b[4] != b'/'
        || !is_digit2(&b[5..7])
        || b[7] != b'/'
        || !is_digit2(&b[8..10])
    {
        return None;
    }
    let (h, mi, sec) = parse_optional_time(time_part)?;
    Some((
        digits(&b[0..4]),
        digits(&b[5..7]) as u32,
        digits(&b[8..10]) as u32,
        h,
        mi,
        sec,
    ))
}

fn split_once_space(s: &str) -> (&str, Option<&str>) {
    match s.split_once(' ') {
        Some((a, b)) => (a, Some(b)),
        None => (s, None),
    }
}

/// `None` time part -> midnight. `Some("HH:MM")` / `Some("HH:MM:SS")` -> that time. Anything else is invalid.
fn parse_optional_time(time_part: Option<&str>) -> Option<(u32, u32, u32)> {
    let Some(t) = time_part else {
        return Some((0, 0, 0));
    };
    let b = t.as_bytes();
    if b.len() != 5 && b.len() != 8 {
        return None;
    }
    if !is_digit2(&b[0..2]) || b[2] != b':' || !is_digit2(&b[3..5]) {
        return None;
    }
    let h = digits(&b[0..2]) as u32;
    let mi = digits(&b[3..5]) as u32;
    if b.len() == 5 {
        return Some((h, mi, 0));
    }
    if b[5] != b':' || !is_digit2(&b[6..8]) {
        return None;
    }
    Some((h, mi, digits(&b[6..8]) as u32))
}

fn is_digit4(b: &[u8]) -> bool {
    b.len() == 4 && b.iter().all(u8::is_ascii_digit)
}
fn is_digit2(b: &[u8]) -> bool {
    b.len() >= 2 && b[0].is_ascii_digit() && b[1].is_ascii_digit()
}
fn digits(b: &[u8]) -> i64 {
    b.iter().fold(0i64, |acc, c| acc * 10 + (c - b'0') as i64)
}

/// Parses one of the three Core §6.5.1 date shapes. `strict` throws
/// `INVALID_DATE` on a syntactically date-shaped but calendrically invalid
/// value (e.g. `2024-02-30`); non-strict returns `Ok(None)` so the caller
/// falls back to a plain string.
pub fn parse_date_utc(s: &str, strict: bool, line: u32) -> Result<Option<Instant>, LimaError> {
    let invalid = || -> Result<Option<Instant>, LimaError> {
        if strict {
            Err(LimaError::new(
                Code::InvalidDate,
                line,
                format!("Lima: invalid date \"{s}\" at line {line}"),
            ))
        } else {
            Ok(None)
        }
    };

    let parsed = if let Some(r) = try_parse_iso(s) {
        match r {
            Ok(v) => Some(v),
            Err(DateInvalid) => return invalid(),
        }
    } else if let Some((y, mo, d, h, mi, sec)) = try_parse_german(s) {
        Some((y, mo, d, h, mi, sec, 0))
    } else if let Some((y, mo, d, h, mi, sec)) = try_parse_slash(s) {
        Some((y, mo, d, h, mi, sec, 0))
    } else {
        None
    };

    let Some((y, mo, d, h, mi, sec, offset_min)) = parsed else {
        return Ok(None);
    };
    if !is_valid_ymd_hms(y, mo, d, h, mi, sec) {
        return invalid();
    }
    let instant = to_instant(y, mo, d, h, mi, sec, offset_min);
    let (result_year, _, _) =
        crate::value::civil_from_days(instant.epoch_seconds.div_euclid(86_400));
    if !(1..=9999).contains(&result_year) {
        return invalid();
    }
    Ok(Some(instant))
}

// ─── Numbers ────────────────────────────────────────────────────────────────

/// Core §6.4.1 number grammar: `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`
/// or `-?\.[0-9]+(...)?`. Never `str::parse` first — Rust's float parser
/// accepts strings (`inf`, `1_000`, leading `+`) Lima does not.
fn matches_number_grammar(s: &str) -> bool {
    let b = s.as_bytes();
    let mut i = 0;
    if i < b.len() && b[i] == b'-' {
        i += 1;
    }
    let int_start = i;
    if i < b.len() && b[i] == b'0' {
        i += 1;
    } else if i < b.len() && b[i].is_ascii_digit() {
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
    } else if i < b.len() && b[i] == b'.' {
        // leading-dot form: `.5` — no integer digits required
    } else {
        return false;
    }
    if i == int_start && (i >= b.len() || b[i] != b'.') {
        return false;
    }
    if i < b.len() && b[i] == b'.' {
        i += 1;
        let frac_start = i;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
        if i == frac_start {
            return false;
        }
    }
    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
        i += 1;
        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
            i += 1;
        }
        let exp_start = i;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
        if i == exp_start {
            return false;
        }
    }
    i == b.len() && !b.is_empty()
}

fn is_float_form(s: &str) -> bool {
    s.contains('.') || s.contains('e') || s.contains('E')
}

fn is_zero_literal(s: &str) -> bool {
    let s = s.strip_prefix('-').unwrap_or(s);
    let mantissa = s.split(['e', 'E']).next().unwrap_or(s);
    let (int_part, frac_part) = match mantissa.split_once('.') {
        Some((i, f)) => (i, f),
        None => (mantissa, ""),
    };
    !(int_part.is_empty() && frac_part.is_empty())
        && int_part.bytes().all(|c| c == b'0')
        && frac_part.bytes().all(|c| c == b'0')
}

/// A superset pre-check for whether `str` is worth running the (comparatively
/// expensive) date parsers over — must contain a digit and be at least 5
/// bytes of digits/date-ish punctuation. Mirrors `DATE_PRE_RE` in the TS
/// source; a cheap reject, not a grammar authority (`parse_date_utc` is).
fn looks_date_ish(s: &str) -> bool {
    let mut has_digit = false;
    let mut run = 0usize;
    for c in s.bytes() {
        let ok =
            c.is_ascii_digit() || matches!(c, b'-' | b':' | b'.' | b'/') || c.is_ascii_alphabetic();
        if c.is_ascii_digit() {
            has_digit = true;
        }
        if ok {
            run += 1;
            if has_digit && run >= 5 {
                return true;
            }
        } else {
            run = 0;
            has_digit = false;
        }
    }
    false
}

/// Classifies a raw token per Core §6.4.1's number grammar and §6.5.1's date
/// shapes, in that order, falling back to a plain string. Generic over
/// [`Builder`] — shared by `parse_core`'s plain result and
/// `references.rs`'s position-annotated tree, one grammar either way.
/// An unquoted string node. When `source` is given the node carries it so
/// `scan_tokens` can attribute each `${…}` / `$(…)` to a real physical
/// `(line, codepoint-offset)` in the source (§2.4). `PlainBuilder` discards
/// it.
fn build_string<B: Builder>(value: &str, line: u32, source: Option<ReferenceSource>) -> B::Value {
    match source {
        Some(s) => B::v_string_src(value.to_string(), line, s),
        None => B::v_string(value.to_string(), line, false),
    }
}

fn build_typed<B: Builder>(
    s: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<B::Value, LimaError> {
    if s.is_empty() || s == "null" || s == "~" {
        return Ok(B::v_null(line));
    }
    if s == "true" {
        return Ok(B::v_bool(true, line));
    }
    if s == "false" {
        return Ok(B::v_bool(false, line));
    }

    let first = s.as_bytes()[0];
    if !(first.is_ascii_digit() || first == b'-' || first == b'.') {
        check_string_limit(s, line)?;
        return Ok(build_string::<B>(s, line, source.clone()));
    }

    // Hex/octal/binary literals (0x, 0o, 0b) stay strings — YAML 1.2 compatible.
    if s.len() > 2 && s.as_bytes()[0] == b'0' {
        let c = s.as_bytes()[1] | 0x20; // lowercase
        if matches!(c, b'x' | b'o' | b'b') {
            check_string_limit(s, line)?;
            return Ok(build_string::<B>(s, line, source.clone()));
        }
    }

    if matches_number_grammar(s) {
        if is_float_form(s) {
            // Order matters and mirrors the TS source's if/else-if/else
            // exactly: overflow-to-infinity is checked first, then
            // underflow-to-zero, and only then the general finite case —
            // `0.0` is finite, so checking "is finite" before "is a genuine
            // zero literal" would wrongly accept underflowed values (an
            // earlier version of this port had exactly that bug: `1e-400`
            // parsed to `0.0`, which is finite, and returned `Float(0.0)`
            // before the underflow check ever ran).
            //
            // Non-strict overflow/underflow: TS's `Number()` still returns
            // `Infinity`/`0` respectively, but the TS `if` chain has no
            // `else` that returns a float for either case — execution falls
            // out of the whole `if (NUMBER_RE.test(str))` block and the
            // function ultimately falls back to a plain string. No `return`
            // here reproduces that.
            if let Ok(n) = s.parse::<f64>() {
                if !n.is_finite() {
                    if strict {
                        return Err(LimaError::new(
                            Code::InvalidNumber, line,
                            format!("Lima: float value overflows to a non-finite value at line {line}: \"{s}\""),
                        ));
                    }
                } else if n == 0.0 && !is_zero_literal(s) {
                    if strict {
                        return Err(LimaError::new(
                            Code::InvalidNumber, line,
                            format!("Lima: non-zero float value underflows to zero at line {line}: \"{s}\""),
                        ));
                    }
                } else {
                    return Ok(B::v_float(if n == 0.0 { 0.0 } else { n }, line));
                }
            }
        } else if let Ok(n) = s.parse::<i64>() {
            if n.unsigned_abs() <= 9_007_199_254_740_991 {
                // JS's MAX_SAFE_INTEGER
                return Ok(B::v_int(n, line));
            }
        }
    }

    if !s.contains('@') && looks_date_ish(s) {
        if let Some(instant) = parse_date_utc(s, strict, line)? {
            return Ok(B::v_instant(instant, line));
        }
    }

    check_string_limit(s, line)?;
    Ok(build_string::<B>(s, line, source.clone()))
}

// ─── Scalar / quoting ───────────────────────────────────────────────────────

const SINGLE_CHAR_ESCAPES: &[u8] = b"\"\\/bfnrt"; // deliberately excludes '0' — Appendix A: \0 is unknown.

fn is_valid_escape(escape: &str) -> bool {
    let b = escape.as_bytes();
    if b.len() == 1 {
        return SINGLE_CHAR_ESCAPES.contains(&b[0]);
    }
    if b[0] == b'u' && b.len() == 5 && b[1..].iter().all(u8::is_ascii_hexdigit) {
        let cp = u32::from_str_radix(&escape[1..], 16).unwrap_or(0xd800);
        return !(0xd800..=0xdfff).contains(&cp);
    }
    if b[0] == b'U' && b.len() == 9 && b[1..].iter().all(u8::is_ascii_hexdigit) {
        return u32::from_str_radix(&escape[1..], 16)
            .map(|cp| cp <= 0x10ffff)
            .unwrap_or(false);
    }
    if b[0] == b'x' && b.len() == 3 && b[1..].iter().all(u8::is_ascii_hexdigit) {
        return true;
    }
    false
}

/// Unescapes a double-quoted string body. `strict` validates every `\X`
/// sequence up front (`INVALID_ESCAPE` on the first bad one); non-strict
/// leaves unrecognised escapes untouched, byte-for-byte.
pub fn unescape_dq(s: &str, strict: bool, line: u32) -> Result<String, LimaError> {
    if !s.contains('\\') {
        return Ok(s.to_string());
    }

    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '\\' || i + 1 >= chars.len() {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        let (escape, consumed) = read_escape(&chars, i + 1);
        if !is_valid_escape(&escape) {
            if strict {
                return Err(LimaError::new(
                    Code::InvalidEscape,
                    line,
                    format!("Lima: unknown escape sequence \"\\{escape}\" at line {line}"),
                ));
            }
            out.push('\\');
            out.push_str(&escape);
            i += 1 + consumed;
            continue;
        }
        match escape.as_bytes()[0] {
            b'"' => out.push('"'),
            b'\\' => out.push('\\'),
            b'/' => out.push('/'),
            b'b' => out.push('\u{8}'),
            b'f' => out.push('\u{c}'),
            b'n' => out.push('\n'),
            b'r' => out.push('\r'),
            b't' => out.push('\t'),
            b'u' => out.push(
                char::from_u32(u32::from_str_radix(&escape[1..], 16).unwrap())
                    .unwrap_or('\u{fffd}'),
            ),
            b'U' => out.push(
                char::from_u32(u32::from_str_radix(&escape[1..], 16).unwrap())
                    .unwrap_or('\u{fffd}'),
            ),
            b'x' => out.push(
                char::from_u32(u32::from_str_radix(&escape[1..], 16).unwrap())
                    .unwrap_or('\u{fffd}'),
            ),
            _ => unreachable!(),
        }
        i += 1 + consumed;
    }
    Ok(out)
}

/// Index of the quote that closes a quoted scalar opening at `s[0]`, or
/// `None` if it is never closed. Escape-aware, so `"a\""` closes at its
/// last byte rather than the escaped inner `"`:
///   - double quotes: a backslash escapes the next byte (§6.1.2);
///   - single-quoted *values* (§6.1.3 "Backslash pairing"): scanning left
///     to right, `\\` (two literal backslashes) and `\'` (an escaped quote)
///     are each consumed as a two-character unit, so a lone `\` is literal
///     and a closing `'` after an even backslash run closes the string.
///     Pass `single_quote_escape = false` for single-quoted *keys*, which
///     are fully literal (§5.2), where the first `'` closes.
///
/// `s[0]` is assumed to be `'` or `"`. Byte-indexed: safe because `'`, `"`,
/// `\` are all single-byte ASCII and never a UTF-8 continuation byte.
pub fn closing_quote_index(s: &str, single_quote_escape: bool) -> Option<usize> {
    let b = s.as_bytes();
    let q = b[0];
    let mut i = 1;
    while i < b.len() {
        let c = b[i];
        if q == b'"' {
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == b'"' {
                return Some(i);
            }
        } else {
            if single_quote_escape && c == b'\\' {
                if let Some(&n) = b.get(i + 1) {
                    if n == b'\\' || n == b'\'' {
                        i += 2;
                        continue;
                    }
                }
            }
            if c == b'\'' {
                return Some(i);
            }
        }
        i += 1;
    }
    None
}

/// Whether `raw` (a key candidate as written, before quote stripping) is a
/// usable Lima key:
///   - a quoted string that is properly closed at its final byte, or
///   - an unquoted token matching the Core §5.1 grammar
///     `[a-zA-Z0-9_][a-zA-Z0-9_:\-]*`.
///
/// §5.1 is a closed pattern: a key with a space, a dot, a slash, a paren, or
/// any other byte outside `[a-zA-Z0-9_:\-]` (a surviving NBSP included) is
/// not an unquoted key. Per §4 such a line/item is unrecognised and skipped
/// in *both* modes — §10's strict list stays closed. The three mapping
/// contexts (top level, block-nested, flow) share this one check;
/// `docs/decisions/structural-indentation-unicode-whitespace.md` governs
/// only whether Unicode whitespace counts as *indentation*, not whether it
/// may appear in a key.
pub fn is_valid_key(raw: &str) -> bool {
    let b = raw.as_bytes();
    let Some(&first) = b.first() else {
        return false;
    };
    if first == b'"' || first == b'\'' {
        return closing_quote_index(raw, false) == Some(b.len() - 1);
    }
    let legacy_ascii_valid = (first.is_ascii_alphanumeric() || first == b'_')
        && b[1..]
            .iter()
            .all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b':' | b'-'));
    if legacy_ascii_valid {
        return true;
    }
    if raw.is_ascii() {
        return (first.is_ascii_alphanumeric() || first == b'_')
            && b[1..]
                .iter()
                .all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b':' | b'-' | b'*'));
    }
    is_valid_unquoted(raw, false)
}

/// Strips a key's surrounding quotes — unescaping a double-quoted key
/// (§6.1.2 escapes, strict-checked), taking a single-quoted key literally
/// (§5.2). Returns `s` unchanged when it is not a properly-closed quoted
/// string. Callers gate on `is_valid_key` first, so an unterminated or
/// trailing-content key never reaches here as a real key.
pub fn strip_key_quotes(s: &str, strict: bool, line: u32) -> Result<String, LimaError> {
    let b = s.as_bytes();
    if !b.is_empty()
        && (b[0] == b'\'' || b[0] == b'"')
        && closing_quote_index(s, false) == Some(b.len() - 1)
    {
        let inner = &s[1..s.len() - 1];
        return if b[0] == b'"' {
            unescape_dq(inner, strict, line)
        } else {
            Ok(inner.to_string())
        };
    }
    Ok(s.to_string())
}

/// Reads the escape token immediately after a `\` at `chars[start]` — one of
/// `"`,`\`,`/`,`b`,`f`,`n`,`r`,`t`, `u` + up to 4 hex, `U` + up to 8 hex,
/// `x` + up to 2 hex, or a single bare character. Returns the token text
/// (without the leading `\`) and how many chars it consumed.
fn read_escape(chars: &[char], start: usize) -> (String, usize) {
    if start >= chars.len() {
        return (String::new(), 0);
    }
    let kind = chars[start];
    let max_hex = match kind {
        'u' => 4,
        'U' => 8,
        'x' => 2,
        _ => return (kind.to_string(), 1),
    };
    let mut hex = String::new();
    let mut j = start + 1;
    while j < chars.len() && hex.len() < max_hex && chars[j].is_ascii_hexdigit() {
        hex.push(chars[j]);
        j += 1;
    }
    (format!("{kind}{hex}"), j - start)
}

/// Shared quoted-or-typed scalar parser — every value position (top-level
/// inline values, flow items, block-array/map scalar items) builds on this.
/// §10.1's two quoted-string strict checks — "unterminated quoted string"
/// and "non-whitespace content after closing quote in an inline value" —
/// apply in every one of those positions, so they are enforced here
/// unconditionally rather than gated to the top level.
pub fn parse_quoted_or_typed<B: Builder>(
    raw: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<B::Value, LimaError> {
    let bytes = raw.as_bytes();
    if !bytes.is_empty() && (bytes[0] == b'"' || bytes[0] == b'\'') {
        let quote = bytes[0];
        let close = closing_quote_index(raw, true);
        if close == Some(bytes.len() - 1) {
            let inner = &raw[1..raw.len() - 1];
            let value = if quote == b'"' {
                unescape_dq(inner, strict, line)?
            } else {
                inner.replace("\\'", "'")
            };
            check_string_limit(&value, line)?;
            // Core §2.3: text originating from closed quote syntax is
            // marked `quoted` — never a reference site for References.
            return Ok(B::v_string(value, line, true));
        }
        if strict {
            let message = if close.is_none() {
                format!("Lima: unterminated quoted string at line {line}{UNTERMINATED_HINT}")
            } else {
                // YAML doubles a quote inside a single-quoted value (Appendix E)
                let next = close.and_then(|c| bytes.get(c + 1));
                let hint = if quote == b'\'' && next == Some(&b'\'') {
                    DOUBLED_QUOTE_HINT
                } else {
                    ""
                };
                format!("Lima: non-whitespace content after closing quote at line {line}{hint}")
            };
            return Err(LimaError::new(Code::InvalidQuote, line, message));
        }
        // Non-strict: §6.1.2/§6.1.3 + §10.1 — the entire value falls back to
        // a literal string (opening quote included), handled below.
    } else if strict {
        check_yaml_value(raw, line)?;
    }

    if !raw.is_empty() && raw != "null" && raw != "~" && raw != "true" && raw != "false" {
        let first = raw.as_bytes()[0];
        if !(first.is_ascii_digit() || first == b'-' || first == b'.') {
            check_string_limit(raw, line)?;
            return Ok(build_string::<B>(raw, line, source));
        }
    }
    build_typed::<B>(raw, strict, line, source)
}

/// Core 1.3 §4 step 2: an unquoted, unescaped `#` begins a comment only as
/// the first character of the value or after whitespace (§1); any other `#`
/// is text. `chars` starts where the value starts. Mirrors
/// `js/src/scalars.ts`'s `isCommentHash`.
fn is_comment_hash(chars: &[char], i: usize) -> bool {
    i == 0 || is_trim_whitespace(chars[i - 1])
}

/// The byte index of the first colon in `s` that a space or a tab follows —
/// the key-value separator of an unquoted key (§5.1), whose other colons
/// belong to the key.
pub(crate) fn separator_index(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    (1..b.len())
        .find(|&i| b[i - 1] == b':' && matches!(b[i], b' ' | b'\t'))
        .map(|i| i - 1)
}

/// Core 1.3 §6.1.6 and Appendix D `yaml-header`: `>`, or `|` or `>`
/// followed by a chomping indicator (`-`, `+`) and an indentation digit
/// (`1`–`9`), one or both, in either order.
fn is_yaml_header(value: &str) -> bool {
    let b = value.as_bytes();
    let chomping = |c: u8| c == b'-' || c == b'+';
    let digit = |c: u8| (b'1'..=b'9').contains(&c);
    match b {
        [b'>'] => true,
        [b'>' | b'|', a] => chomping(*a) || digit(*a),
        [b'>' | b'|', a, c] => (chomping(*a) && digit(*c)) || (digit(*a) && chomping(*c)),
        _ => false,
    }
}

/// Core 1.3 §6.1.1, §6.1.6 and §10.1: in strict mode an unquoted value that
/// starts with `&`, `*` or `!`, or that is a YAML block scalar header other
/// than `|`, is an error; the message names what Lima writes instead
/// (§10.2, Appendix E). Mirrors `js/src/scalars.ts`'s `checkYamlValue`.
fn check_yaml_value(raw: &str, line: u32) -> Result<(), LimaError> {
    let property = match raw.as_bytes().first() {
        Some(b'&') => Some(('&', "an anchor")),
        Some(b'*') => Some(('*', "an alias")),
        Some(b'!') => Some(('!', "a tag")),
        _ => None,
    };
    if let Some((c, property)) = property {
        return Err(LimaError::new(
            Code::UnsupportedYaml,
            line,
            format!("Lima: unquoted value starting with \"{c}\" at line {line} (YAML reads it as {property}; Lima has no anchors, aliases or tags: quote the value)"),
        ));
    }
    if is_yaml_header(raw) {
        return Err(LimaError::new(
            Code::UnsupportedYaml,
            line,
            format!("Lima: YAML block scalar header \"{raw}\" at line {line} (Lima writes \"|\", and \"^^\" to join lines)"),
        ));
    }
    Ok(())
}

// Appendix E: what a message names in place of a YAML form.
const UNTERMINATED_HINT: &str =
    " (a quoted value ends on its line; write \"|\" for a value of several lines)";
const DOUBLED_QUOTE_HINT: &str = " (YAML doubles the quote; Lima writes 'It\\'s' or \"It's\")";
const UNCLOSED_SEQUENCE_HINT: &str =
    " (a flow sequence ends on its line; write a block sequence with \"- \")";
const UNCLOSED_MAPPING_HINT: &str = " (a flow mapping ends on its line; write a block mapping)";

/// The value text with a trailing `#` comment removed, but with `\#`
/// escapes left as written — the *physical* form a References 2.0 token's
/// column is measured against (§2.4). The comment is not part of the value
/// (so its `${…}`-shaped text must not be scanned as a token), but a `\#`
/// before a token still occupies its two source columns. Mirrors
/// `js/src/scalars.ts`'s `stripCommentKeepEscapes`.
pub fn strip_comment_keep_escapes(val: &str) -> String {
    let chars: Vec<char> = val.chars().collect();
    let mut quote: Option<char> = None;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if let Some(q) = quote {
            if c == '\\' {
                i += 1;
            } else if c == q {
                quote = None;
            }
        } else if c == '"' || c == '\'' {
            quote = Some(c);
        } else if c == '\\' && chars.get(i + 1) == Some(&'#') {
            i += 1;
        } else if c == '#' && is_comment_hash(&chars, i) {
            let cut: String = chars[..i].iter().collect();
            // Project whitespace set, not Rust's `char::is_whitespace` — the
            // latter trims U+0085 (NEL) and keeps U+FEFF, both wrong here.
            return cut.trim_end_matches(is_trim_whitespace).to_string();
        }
        i += 1;
    }
    val.to_string()
}

/// Strips a trailing `#` comment and collapses each `\#` *outside* a quoted
/// string to `#` (Core §6.1.4 — the escaped-hash rule is for unquoted values
/// only). Inside `"..."` / `'...'` the backslash is left intact: `\#` there
/// is an unknown double-quoted escape (§6.1.2) or a literal backslash in a
/// single-quoted string (§6.1.3). Finds the same comment boundary as
/// `strip_comment_keep_escapes`, and trims the end of what remains whether a
/// comment was removed or not (§4). Mirrors `js/src/scalars.ts`'s
/// `stripComment`.
pub fn strip_comment(val: &str) -> String {
    let chars: Vec<char> = val.chars().collect();
    let mut quote: Option<char> = None;
    let mut out = String::new();
    let mut seg = 0usize;
    let mut i = 0usize;
    while i < chars.len() {
        let c = chars[i];
        if let Some(q) = quote {
            if c == '\\' {
                i += 1;
            } else if c == q {
                quote = None;
            }
        } else if c == '"' || c == '\'' {
            quote = Some(c);
        } else if c == '\\' && chars.get(i + 1) == Some(&'#') {
            out.extend(&chars[seg..i]);
            out.push('#');
            i += 1;
            seg = i + 1;
        } else if c == '#' && is_comment_hash(&chars, i) {
            out.extend(&chars[seg..i]);
            return out.trim_end_matches(is_trim_whitespace).to_string();
        }
        i += 1;
    }
    out.extend(&chars[seg..]);
    // §4 step 3: the value is trimmed whether a comment was removed or not —
    // a `#` that begins none, as in `[#x]`, keeps no whitespace after it in
    // the value. `truncate` copies nothing.
    let end = out.trim_end_matches(is_trim_whitespace).len();
    out.truncate(end);
    out
}

/// The physical `raw` form for a References 2.0 token's column: a trailing
/// comment removed, `\#` kept. Mirrors `js/src/block.ts`'s `physicalRaw`.
pub fn physical_raw(s: &str) -> String {
    if s.contains('#') {
        strip_comment_keep_escapes(s)
    } else {
        s.to_string()
    }
}

/// Top-level entry: rejects an unclosed `[`/`{` in strict mode (References'
/// flow-syntax territory; Core has no flow grammar of its own to recover
/// with), otherwise delegates to [`parse_quoted_or_typed`].
pub fn parse_scalar_value<B: Builder>(
    raw: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<B::Value, LimaError> {
    if strict {
        if let Some(&first) = raw.as_bytes().first() {
            if first == b'[' || first == b'{' {
                let (kind, hint) = if first == b'[' {
                    ("sequence", UNCLOSED_SEQUENCE_HINT)
                } else {
                    ("mapping", UNCLOSED_MAPPING_HINT)
                };
                return Err(LimaError::new(
                    Code::InvalidFlowSyntax,
                    line,
                    format!("Lima: unclosed flow {kind} at line {line}{hint}"),
                ));
            }
        }
    }
    parse_quoted_or_typed::<B>(raw, strict, line, source)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::{LimaValue, PlainBuilder};

    fn v(raw: &str) -> LimaValue {
        parse_scalar_value::<PlainBuilder>(raw, false, 1, None).unwrap()
    }
    fn v_strict(raw: &str) -> Result<LimaValue, LimaError> {
        parse_scalar_value::<PlainBuilder>(raw, true, 1, None)
    }

    #[test]
    fn null_and_bool_literals() {
        assert_eq!(v(""), LimaValue::Null);
        assert_eq!(v("null"), LimaValue::Null);
        assert_eq!(v("~"), LimaValue::Null);
        assert_eq!(v("true"), LimaValue::Bool(true));
        assert_eq!(v("false"), LimaValue::Bool(false));
    }

    #[test]
    fn integers() {
        assert_eq!(v("0"), LimaValue::Int(0));
        assert_eq!(v("42"), LimaValue::Int(42));
        assert_eq!(v("-42"), LimaValue::Int(-42));
        // Leading zero is not a number (Core §6.4.1) -> string.
        assert_eq!(v("007"), LimaValue::String("007".into()));
    }

    #[test]
    fn floats() {
        assert_eq!(v("1.5"), LimaValue::Float(1.5));
        assert_eq!(v("-0.5"), LimaValue::Float(-0.5));
        assert_eq!(v("1e10"), LimaValue::Float(1e10));
        assert_eq!(v(".5"), LimaValue::Float(0.5));
    }

    #[test]
    fn norway_problem_does_not_apply() {
        // YAML 1.1's broader implicit-boolean set turns `NO`/`yes`/etc. into
        // booleans; Lima recognises only the literal tokens true/false.
        assert_eq!(v("NO"), LimaValue::String("NO".into()));
        assert_eq!(v("yes"), LimaValue::String("yes".into()));
        assert_eq!(v("off"), LimaValue::String("off".into()));
    }

    #[test]
    fn hex_octal_binary_stay_strings() {
        assert_eq!(v("0x1A"), LimaValue::String("0x1A".into()));
        assert_eq!(v("0o17"), LimaValue::String("0o17".into()));
        assert_eq!(v("0b101"), LimaValue::String("0b101".into()));
    }

    #[test]
    fn iso_dates() {
        let LimaValue::Instant(i) = v("2024-03-01") else {
            panic!("expected instant")
        };
        assert_eq!(i.to_iso_string(), "2024-03-01T00:00:00Z");
        let LimaValue::Instant(i) = v("2024-03-01T09:00:00+02:00") else {
            panic!("expected instant")
        };
        assert_eq!(i.to_iso_string(), "2024-03-01T07:00:00Z");
        let LimaValue::Instant(i) = v("2024-03-01T09:00:00Z") else {
            panic!("expected instant")
        };
        assert_eq!(i.to_iso_string(), "2024-03-01T09:00:00Z");
    }

    #[test]
    fn leap_year_and_month_lengths() {
        assert!(matches!(v("2024-02-29"), LimaValue::Instant(_))); // divisible by 4, not 100
        assert!(matches!(v("2000-02-29"), LimaValue::Instant(_))); // divisible by 400
        assert!(v_strict("1900-02-29").is_err()); // divisible by 100, not 400
        assert_eq!(v("2024-02-30"), LimaValue::String("2024-02-30".into())); // non-strict falls back
    }

    #[test]
    fn year_zero_is_out_of_range() {
        assert_eq!(v("0000-01-01"), LimaValue::String("0000-01-01".into()));
        assert!(v_strict("0000-01-01").is_err());
    }

    #[test]
    fn german_and_slash_dates() {
        let LimaValue::Instant(i) = v("1.3.2024") else {
            panic!("expected instant")
        };
        assert_eq!(i.to_iso_string(), "2024-03-01T00:00:00Z");
        let LimaValue::Instant(i) = v("2024/03/01") else {
            panic!("expected instant")
        };
        assert_eq!(i.to_iso_string(), "2024-03-01T00:00:00Z");
    }

    #[test]
    fn double_quoted_escapes() {
        assert_eq!(v("\"a\\nb\""), LimaValue::String("a\nb".into()));
        assert_eq!(v("\"caf\\u00e9\""), LimaValue::String("café".into()));
        assert!(v_strict("\"\\q\"").is_err());
        // Non-strict leaves an unknown escape untouched.
        assert_eq!(v("\"\\q\""), LimaValue::String("\\q".into()));
    }

    #[test]
    fn single_quoted_has_only_apostrophe_escape() {
        assert_eq!(v("'a\\'b'"), LimaValue::String("a'b".into()));
        assert_eq!(v("'a\\nb'"), LimaValue::String("a\\nb".into())); // no \n handling in single-quoted
    }

    #[test]
    fn plain_strings_and_urls() {
        assert_eq!(v("hello world"), LimaValue::String("hello world".into()));
        assert_eq!(
            v("https://example.com"),
            LimaValue::String("https://example.com".into())
        );
    }

    #[test]
    fn scalar_length_limit() {
        let long = "a".repeat(SCALAR_LENGTH_LIMIT + 1);
        assert!(v_strict(&long).is_err());
        let ok = "a".repeat(SCALAR_LENGTH_LIMIT);
        assert_eq!(v(&ok), LimaValue::String(ok));
    }

    #[test]
    fn strip_comment_is_quote_aware() {
        assert_eq!(strip_comment("value # comment"), "value");
        assert_eq!(strip_comment("\"a # b\" # real comment"), "\"a # b\"");
        assert_eq!(strip_comment("escaped \\# hash"), "escaped # hash");
        assert_eq!(strip_comment("no comment here"), "no comment here");
        // §4 step 3: trimmed when the `#` begins no comment, too
        assert_eq!(strip_comment("[#x]\t"), "[#x]");
        assert_eq!(strip_comment("x#y\u{a0}"), "x#y");
        assert_eq!(strip_comment("x\\#y\t"), "x#y");
        // FR-5: `\#` inside a quoted string keeps its backslash (§6.1.2/§6.1.3)
        assert_eq!(strip_comment("\"a\\#b\""), "\"a\\#b\"");
        assert_eq!(strip_comment("'a\\#b'"), "'a\\#b'");
        assert_eq!(strip_comment("\"a\\#b\" # real"), "\"a\\#b\"");
    }
}