iron-shell 14.0.3

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
//! A YAML subset parser and emitter with an explicit, enforced boundary.
//!
//! # Why this exists
//!
//! `from-yaml` previously split each line on the first `:` and collected the
//! results into one flat record. That silently mis-parsed almost every real
//! YAML document: nesting collapsed, sequences vanished (a `- item` line has no
//! colon, so it was dropped), `#` comments were kept as part of the value, and
//! `---` document markers became a `{"---": ""}` entry. `to-yaml` emitted
//! values unquoted, so any string containing `: ` produced output that would
//! not read back.
//!
//! For a shell whose entire pitch is *deterministic typed output*, silently
//! returning wrong data is the worst available behavior — an agent cannot
//! detect it and will act on the corruption.
//!
//! # The contract
//!
//! This module implements the commonly-used subset of YAML and **fails loudly**
//! on everything else, naming the construct it cannot handle. Callers get
//! either correct data or an error — never quiet corruption.
//!
//! Supported:
//! - Nested block mappings (indentation-based) and block sequences (`- `)
//! - Scalars: null/`~`, booleans, integers, floats, strings
//! - Single-quoted scalars (`''` is the one escape) and double-quoted scalars,
//!   which decode every YAML 1.2 escape: `\0 \a \b \e \f \v \n \r \t \" \/ \\`,
//!   `\xhh`, `\uhhhh` and `\Uhhhhhhhh`
//! - `#` comments, blank lines, leading `---` and trailing `...`
//! - Flow collections that are valid JSON (`[1, 2]`, `{"a": 1}`)
//!
//! Rejected with a clear error (rather than mis-parsed):
//! - Anchors and aliases (`&anchor`, `*alias`), merge keys (`<<`)
//! - Block scalars (`|`, `>`)
//! - Explicit tags (`!!str`, `!Custom`)
//! - Multiple documents in one string
//!
//! # Example
//!
//! ```
//! use iron_shell::yaml;
//! use iron_shell::value::Value;
//!
//! let v = yaml::parse("name: ae\nports:\n  - 80\n  - 443\n").unwrap();
//! let Value::Record(r) = &v else { panic!("expected a record") };
//! assert_eq!(r.get("name"), Some(&Value::Str("ae".into())));
//! assert_eq!(
//!     r.get("ports"),
//!     Some(&Value::Array(vec![Value::Int(80), Value::Int(443)]))
//! );
//! ```

use crate::value::Value;
use anyhow::{anyhow, Result};
use std::collections::BTreeMap;

/// One significant line: its indentation depth and its content.
#[derive(Debug, Clone)]
struct Line {
    indent: usize,
    content: String,
    /// 1-based source line number, for error messages.
    number: usize,
}

/// Parse a YAML document into a [`Value`].
///
/// Returns an error naming the unsupported construct rather than guessing —
/// see the module docs for the supported subset.
pub fn parse(src: &str) -> Result<Value> {
    let lines = significant_lines(src)?;
    if lines.is_empty() {
        return Ok(Value::Null);
    }
    let mut pos = 0usize;
    let base = lines[0].indent;
    let value = parse_block(&lines, &mut pos, base)?;
    if pos < lines.len() {
        return Err(anyhow!(
            "line {}: unexpected content at indentation {} (expected {})",
            lines[pos].number,
            lines[pos].indent,
            base
        ));
    }
    Ok(value)
}

/// Strip blanks, comments and document markers; reject unsupported constructs.
fn significant_lines(src: &str) -> Result<Vec<Line>> {
    let mut out = Vec::new();
    let mut seen_doc_start = false;

    for (i, raw) in src.lines().enumerate() {
        let number = i + 1;
        let indent = raw.len() - raw.trim_start().len();
        let trimmed = raw.trim();

        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if trimmed == "..." {
            break; // explicit end of document
        }
        if trimmed == "---" {
            if seen_doc_start || !out.is_empty() {
                return Err(anyhow!(
                    "line {number}: multiple YAML documents are not supported; \
                     split them and parse each separately"
                ));
            }
            seen_doc_start = true;
            continue;
        }

        reject_unsupported(trimmed, number)?;

        out.push(Line {
            indent,
            content: trimmed.to_string(),
            number,
        });
    }
    Ok(out)
}

/// Reject YAML features this parser does not implement, by name.
fn reject_unsupported(line: &str, number: usize) -> Result<()> {
    // Look at the value side of `key:` when there is one, else the whole line.
    let value_part: String = match split_key(line) {
        Some((_, rest)) => rest.trim().to_string(),
        None => line.trim_start_matches("- ").trim().to_string(),
    };
    let value_part = value_part.as_str();

    let unsupported = [
        ("&", "anchors (&name)"),
        ("*", "aliases (*name)"),
        ("!", "explicit tags (!!type)"),
        ("|", "block scalars (|)"),
        (">", "folded block scalars (>)"),
    ];
    for (marker, name) in unsupported {
        if value_part.starts_with(marker) {
            return Err(anyhow!(
                "line {number}: {name} are not supported by IronShell's YAML \
                 subset. Convert the document to JSON, or simplify it."
            ));
        }
    }
    if line.starts_with("<<") {
        return Err(anyhow!(
            "line {number}: merge keys (<<) are not supported by IronShell's \
             YAML subset."
        ));
    }
    Ok(())
}

/// Parse a block (mapping or sequence) at the given indentation.
fn parse_block(lines: &[Line], pos: &mut usize, indent: usize) -> Result<Value> {
    if *pos >= lines.len() {
        return Ok(Value::Null);
    }
    let content = lines[*pos].content.as_str();
    if content.starts_with("- ") || content == "-" {
        parse_sequence(lines, pos, indent)
    } else if content.starts_with(['{', '['])
        && serde_json::from_str::<serde_json::Value>(content).is_ok()
    {
        // A whole JSON-style flow collection on its own line: the `{}` or `[]`
        // that `to-yaml` writes for an empty top-level value.
        let number = lines[*pos].number;
        *pos += 1;
        parse_scalar(content, number)
    } else {
        parse_mapping(lines, pos, indent)
    }
}

fn parse_sequence(lines: &[Line], pos: &mut usize, indent: usize) -> Result<Value> {
    let mut items = Vec::new();
    while *pos < lines.len() && lines[*pos].indent == indent {
        let line = &lines[*pos];
        if !(line.content.starts_with("- ") || line.content == "-") {
            break;
        }
        let rest = line.content[1..].trim().to_string();
        *pos += 1;

        if rest.is_empty() {
            // `-` alone: the item is the nested block beneath it.
            items.push(parse_nested(lines, pos, indent)?);
        } else if let Some((key, value)) = split_key(&rest) {
            // `- key: value` — a mapping that starts on the dash line. Its
            // logical indent is where the key text begins.
            let inner_indent = indent + (line.content.len() - rest.len());
            let mut map = BTreeMap::new();
            insert_entry(&mut map, key, value, lines, pos, inner_indent, line.number)?;
            while *pos < lines.len() && lines[*pos].indent == inner_indent {
                let l = &lines[*pos];
                let Some((k, v)) = split_key(&l.content) else {
                    break;
                };
                let n = l.number;
                *pos += 1;
                insert_entry(&mut map, k, v, lines, pos, inner_indent, n)?;
            }
            items.push(Value::Record(map));
        } else {
            items.push(parse_scalar(&rest, line.number)?);
        }
    }
    Ok(Value::Array(items))
}

fn parse_mapping(lines: &[Line], pos: &mut usize, indent: usize) -> Result<Value> {
    let mut map = BTreeMap::new();
    while *pos < lines.len() && lines[*pos].indent == indent {
        let line = lines[*pos].clone();
        let Some((key, value)) = split_key(&line.content) else {
            return Err(anyhow!(
                "line {}: expected `key: value`, found {:?}",
                line.number,
                line.content
            ));
        };
        *pos += 1;
        insert_entry(&mut map, key, value, lines, pos, indent, line.number)?;
    }
    Ok(Value::Record(map))
}

/// Insert one `key: value` entry, descending into a nested block when the
/// value is empty.
fn insert_entry(
    map: &mut BTreeMap<String, Value>,
    key: String,
    value: String,
    lines: &[Line],
    pos: &mut usize,
    indent: usize,
    number: usize,
) -> Result<()> {
    let key = key_name(&key, number)?;
    let parsed = if value.trim().is_empty() {
        parse_nested(lines, pos, indent)?
    } else {
        parse_scalar(value.trim(), number)?
    };
    if map.insert(key.clone(), parsed).is_some() {
        // Duplicate keys are a YAML error, and silently keeping the last one
        // is precisely the sort of quiet data loss this module exists to stop.
        return Err(anyhow!("line {number}: duplicate key {key:?}"));
    }
    Ok(())
}

/// Parse the block nested beneath the current line, if any.
fn parse_nested(lines: &[Line], pos: &mut usize, indent: usize) -> Result<Value> {
    if *pos < lines.len() && lines[*pos].indent > indent {
        let deeper = lines[*pos].indent;
        parse_block(lines, pos, deeper)
    } else {
        // `key:` with nothing under it is an explicit null, as in YAML.
        Ok(Value::Null)
    }
}

/// Split `key: value`, respecting quotes so `"a: b": 1` works.
///
/// Returns `None` when the line has no top-level `:` separator.
fn split_key(line: &str) -> Option<(String, String)> {
    let bytes: Vec<char> = line.chars().collect();
    let mut quote: Option<char> = None;
    let mut i = 0usize;
    while i < bytes.len() {
        let c = bytes[i];
        match quote {
            Some(q) => {
                if c == '\\' {
                    i += 1;
                } else if c == q {
                    quote = None;
                }
            }
            None => {
                if c == '"' || c == '\'' {
                    quote = Some(c);
                } else if c == ':' {
                    // A `:` only separates when followed by space or EOL —
                    // otherwise it is part of a scalar such as `12:30` or a URL.
                    let next = bytes.get(i + 1);
                    if next.is_none() || next == Some(&' ') {
                        let key = line[..byte_index(line, i)].trim();
                        let value = line[byte_index(line, i + 1)..].trim();
                        return Some((key.to_string(), value.to_string()));
                    }
                }
            }
        }
        i += 1;
    }
    None
}

/// Byte offset of the `n`th character.
fn byte_index(s: &str, n: usize) -> usize {
    s.char_indices().nth(n).map(|(b, _)| b).unwrap_or(s.len())
}

/// The name of a mapping key: quotes are stripped, and a double-quoted key
/// decodes its escapes the same way a double-quoted value does.
fn key_name(raw: &str, number: usize) -> Result<String> {
    let t = raw.trim();
    if t.len() >= 2 && t.starts_with('"') && t.ends_with('"') {
        unescape_double(&t[1..t.len() - 1], number)
    } else if t.len() >= 2 && t.starts_with('\'') && t.ends_with('\'') {
        Ok(t[1..t.len() - 1].replace("''", "'"))
    } else {
        Ok(t.to_string())
    }
}

/// Parse a scalar: quoted string, JSON flow collection, or plain scalar.
/// The quoted scalar at the start of `s` when only a ` #` comment follows it:
/// `"x" # note` gives `"x"`. `None` when `s` is not quoted or something other
/// than a comment follows the closing quote.
fn quoted_before_comment(s: &str) -> Option<&str> {
    let quote = s.chars().next().filter(|c| *c == '"' || *c == '\'')?;
    let bytes = s.as_bytes();
    let mut i = 1;
    let end = loop {
        let b = *bytes.get(i)?;
        if quote == '"' && b == b'\\' {
            i += 2;
            continue;
        }
        if b == quote as u8 {
            // In single quotes, '' is an escaped quote, not the end.
            if quote == '\'' && bytes.get(i + 1) == Some(&b'\'') {
                i += 2;
                continue;
            }
            break i;
        }
        i += 1;
    };
    let rest = &s[end + 1..];
    let trimmed = rest.trim_start();
    if trimmed.is_empty() {
        return None;
    }
    (trimmed.starts_with('#') && rest.len() > trimmed.len()).then(|| &s[..=end])
}

fn parse_scalar(raw: &str, number: usize) -> Result<Value> {
    let s = raw.trim();
    // A quoted scalar followed by a comment, `"x" # note`: the comment goes,
    // and the quoted scalar is read as one, quotes and all.
    let s = quoted_before_comment(s).unwrap_or(s);

    // Quoted strings keep everything inside verbatim (after escapes), so a `#`
    // or `:` inside quotes is data, not syntax.
    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        return Ok(Value::Str(unescape_double(&s[1..s.len() - 1], number)?));
    }
    if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
        // Single quotes: only '' is an escape, for a literal quote.
        return Ok(Value::Str(s[1..s.len() - 1].replace("''", "'")));
    }

    // Flow collections: JSON is a subset of YAML flow style, so anything that
    // parses as JSON is correct here. Anything else in flow style is rejected
    // rather than guessed at.
    if s.starts_with('[') || s.starts_with('{') {
        return match serde_json::from_str::<serde_json::Value>(s) {
            Ok(j) => match crate::builtins::wide_integer_refusal("from_yaml", s) {
                Some(refusal) => Err(refusal),
                None => Ok(json_to_value(j)),
            },
            Err(e) => Err(anyhow!(
                "line {number}: flow collection {s:?} is not valid JSON ({e}); \
                 IronShell's YAML subset supports JSON-compatible flow style only"
            )),
        };
    }

    // Plain scalar: an unquoted ` #` starts a comment.
    let s = match s.find(" #") {
        Some(i) => s[..i].trim(),
        None => s,
    };

    // An integer past the 64-bit range would read as a Float and lose its digits.
    // A 0o or 0x integer past it is refused the same way.
    let overflow = || {
        crate::safety::value_not_representable(
            "from_yaml",
            format!("from_yaml: line {number}: integer overflow at {s}: it does not fit in a 64-bit Int"),
            &format!("quote it as a string to keep the digits, such as \"{s}\""),
        )
    };
    if let Some((radix, digits)) = radix_integer(s) {
        return i64::from_str_radix(digits, radix)
            .map(Value::Int)
            .map_err(|_| overflow());
    }
    if crate::builtins::is_wide_integer(s) {
        return Err(overflow());
    }
    // IronShell numbers are finite (`float("inf")` is refused), so the YAML
    // spellings of infinity and not-a-number are refused here, not read as Floats.
    if matches!(
        s,
        ".inf"
            | ".Inf"
            | ".INF"
            | "+.inf"
            | "+.Inf"
            | "+.INF"
            | "-.inf"
            | "-.Inf"
            | "-.INF"
            | ".nan"
            | ".NaN"
            | ".NAN"
    ) {
        return Err(crate::safety::value_not_representable(
            "from_yaml",
            format!("from_yaml: line {number}: {s} is not a finite number; IronShell numbers are finite"),
            &format!("quote it as a string to keep the text, such as \"{s}\""),
        ));
    }
    Ok(plain_scalar(s))
}

/// The digits and radix of a YAML 1.2 core octal (`0o17`) or hex (`0x1F`)
/// integer: no sign, a lowercase prefix, and at least one digit.
fn radix_integer(s: &str) -> Option<(u32, &str)> {
    if let Some(digits) = s.strip_prefix("0o") {
        return (!digits.is_empty() && digits.bytes().all(|b| (b'0'..=b'7').contains(&b)))
            .then_some((8, digits));
    }
    let digits = s.strip_prefix("0x")?;
    (!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_hexdigit())).then_some((16, digits))
}

/// Type a plain (unquoted) scalar the way YAML 1.2 core schema does.
fn plain_scalar(s: &str) -> Value {
    match s {
        "" | "~" | "null" | "Null" | "NULL" => Value::Null,
        "true" | "True" | "TRUE" => Value::Bool(true),
        "false" | "False" | "FALSE" => Value::Bool(false),
        // The YAML 1.2 core spellings of the special floats.
        ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => Value::Float(f64::INFINITY),
        "-.inf" | "-.Inf" | "-.INF" => Value::Float(f64::NEG_INFINITY),
        ".nan" | ".NaN" | ".NAN" => Value::Float(f64::NAN),
        _ => {
            if let Ok(i) = s.parse::<i64>() {
                Value::Int(i)
            } else if let Ok(f) = s.parse::<f64>() {
                // Reject things Rust parses but YAML does not treat as numbers,
                // e.g. "inf" alone; YAML spells it `.inf`.
                if s.chars().any(|c| c.is_ascii_digit()) {
                    Value::Float(f)
                } else {
                    Value::Str(s.to_string())
                }
            } else {
                Value::Str(s.to_string())
            }
        }
    }
}

/// Decode the escapes of a double-quoted scalar, per YAML 1.2. An unknown
/// escape, a short hex escape, or a value that is not a Unicode code point is
/// an error naming the line, not a guess.
fn unescape_double(s: &str, number: usize) -> Result<String> {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        let Some(e) = chars.next() else {
            return Err(anyhow!(
                "line {number}: a double-quoted string ends in a lone backslash"
            ));
        };
        match e {
            '0' => out.push('\0'),
            'a' => out.push('\u{7}'),
            'b' => out.push('\u{8}'),
            'e' => out.push('\u{1b}'),
            'f' => out.push('\u{c}'),
            'v' => out.push('\u{b}'),
            'n' => out.push('\n'),
            'r' => out.push('\r'),
            't' => out.push('\t'),
            '"' => out.push('"'),
            '/' => out.push('/'),
            '\\' => out.push('\\'),
            'x' => out.push(hex_escape(&mut chars, 'x', 2, number)?),
            'u' => out.push(hex_escape(&mut chars, 'u', 4, number)?),
            'U' => out.push(hex_escape(&mut chars, 'U', 8, number)?),
            other => {
                return Err(anyhow!(
                    "line {number}: unknown escape \\{other} in a double-quoted string"
                ))
            }
        }
    }
    Ok(out)
}

/// The character named by the `digits` hex digits that follow `\x`, `\u` or `\U`.
fn hex_escape(
    chars: &mut std::str::Chars<'_>,
    kind: char,
    digits: usize,
    number: usize,
) -> Result<char> {
    let hex: String = chars.by_ref().take(digits).collect();
    if hex.len() != digits || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(anyhow!(
            "line {number}: \\{kind} needs {digits} hex digits, found {hex:?}"
        ));
    }
    u32::from_str_radix(&hex, 16)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| anyhow!("line {number}: \\{kind}{hex} is not a Unicode code point"))
}

fn json_to_value(j: serde_json::Value) -> Value {
    match j {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => n
            .as_i64()
            .map(Value::Int)
            .or_else(|| n.as_f64().map(Value::Float))
            .unwrap_or(Value::Null),
        serde_json::Value::String(s) => Value::Str(s),
        serde_json::Value::Array(a) => Value::Array(a.into_iter().map(json_to_value).collect()),
        serde_json::Value::Object(o) => {
            Value::Record(o.into_iter().map(|(k, v)| (k, json_to_value(v))).collect())
        }
    }
}

// ============================================================================
// EMIT
// ============================================================================

/// Render a [`Value`] as YAML.
///
/// Output is quoted wherever quoting is required, so the result reads back
/// through [`parse`] as the same value — the property the previous emitter did
/// not have.
pub fn emit(value: &Value) -> String {
    let mut out = String::new();
    emit_into(value, 0, &mut out);
    if out.is_empty() {
        out.push_str("null\n");
    }
    out
}

fn emit_into(value: &Value, indent: usize, out: &mut String) {
    let pad = " ".repeat(indent);
    match value {
        Value::Record(map) if map.is_empty() => out.push_str("{}\n"),
        Value::Record(map) => {
            for (k, v) in map {
                out.push_str(&pad);
                out.push_str(&quote_key(k));
                match v {
                    Value::Record(inner) if !inner.is_empty() => {
                        out.push_str(":\n");
                        emit_into(v, indent + 2, out);
                    }
                    Value::Array(items) if !items.is_empty() => {
                        out.push_str(":\n");
                        emit_into(v, indent + 2, out);
                    }
                    Value::Record(_) => out.push_str(": {}\n"),
                    Value::Array(_) => out.push_str(": []\n"),
                    _ => {
                        out.push_str(": ");
                        out.push_str(&scalar_to_yaml(v));
                        out.push('\n');
                    }
                }
            }
        }
        Value::Array(items) if items.is_empty() => out.push_str("[]\n"),
        Value::Array(items) => {
            for item in items {
                out.push_str(&pad);
                match item {
                    Value::Record(m) if m.is_empty() => out.push_str("- {}\n"),
                    Value::Array(a) if a.is_empty() => out.push_str("- []\n"),
                    Value::Record(_) | Value::Array(_) => {
                        // Nested collections start on the following line so the
                        // dash does not disturb their indentation.
                        out.push_str("-\n");
                        emit_into(item, indent + 2, out);
                    }
                    _ => {
                        out.push_str("- ");
                        out.push_str(&scalar_to_yaml(item));
                        out.push('\n');
                    }
                }
            }
        }
        other => {
            out.push_str(&pad);
            out.push_str(&scalar_to_yaml(other));
            out.push('\n');
        }
    }
}

fn quote_key(k: &str) -> String {
    if needs_quoting(k) {
        format!("\"{}\"", escape_double(k))
    } else {
        k.to_string()
    }
}

fn scalar_to_yaml(v: &Value) -> String {
    match v {
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Int(i) => i.to_string(),
        Value::Float(f) => {
            if f.is_finite() {
                // Debug keeps the point on whole numbers (1.0, -0.0) so they read
                // back as Float; an exponent form such as 1e20 gets one too.
                let text = format!("{f:?}");
                match text.find('e') {
                    Some(i) if !text[..i].contains('.') => {
                        format!("{}.0{}", &text[..i], &text[i..])
                    }
                    _ => text,
                }
            } else if f.is_nan() {
                ".nan".to_string()
            } else if *f > 0.0 {
                ".inf".to_string()
            } else {
                "-.inf".to_string()
            }
        }
        Value::Str(s) | Value::Uri(s) => {
            if needs_quoting(s) {
                format!("\"{}\"", escape_double(s))
            } else {
                s.clone()
            }
        }
        // Anything else (lambdas, futures, tables) has no YAML representation;
        // render its display form as a quoted string rather than emitting
        // something that would not read back.
        other => format!("\"{}\"", escape_double(&other.to_display_string())),
    }
}

/// Whether a scalar must be quoted to survive a round trip.
fn needs_quoting(s: &str) -> bool {
    if s.is_empty() {
        return true;
    }
    // Anything that would re-parse as a different type, or that contains
    // structural characters, has to be quoted.
    if !matches!(plain_scalar(s), Value::Str(_)) {
        return true;
    }
    // YAML 1.1 readers (PyYAML and others) read these words as booleans. This
    // reader keeps them as strings, but the output must mean the same everywhere.
    if matches!(
        s,
        "y" | "Y"
            | "yes"
            | "Yes"
            | "YES"
            | "n"
            | "N"
            | "no"
            | "No"
            | "NO"
            | "on"
            | "On"
            | "ON"
            | "off"
            | "Off"
            | "OFF"
    ) {
        return true;
    }
    // A 0o or 0x integer reads back as an Int, so a String that looks like one is quoted.
    if radix_integer(s).is_some() || s.chars().any(needs_escape) {
        return true;
    }
    // A number or date to a YAML 1.1 reader, though this reader keeps it a String.
    if yaml11_non_string(s) {
        return true;
    }
    s.contains(':')
        || s.contains('#')
        || s.contains('\n')
        || s.contains('\t')
        || s.contains('"')
        || s.contains('\'')
        || s.starts_with([
            '-', '?', '&', '*', '!', '|', '>', '%', '@', '`', '[', '{', ',',
        ])
        || s.trim() != s
}

/// Whether a YAML 1.1 reader (PyYAML) reads `s` as a number or a date: digits
/// with underscores (`1_000`), an ISO date or datetime prefix (`2026-01-02`), a
/// binary integer (`0b101`), or a number with a leading `+` or `.` (`+12`, `.5`).
/// A sexagesimal `1:20` is already quoted by the colon rule.
fn yaml11_non_string(s: &str) -> bool {
    let b = s.as_bytes();
    let digits_with_underscores = s.contains('_')
        && b.first().is_some_and(u8::is_ascii_digit)
        && b.iter().all(|c| c.is_ascii_digit() || *c == b'_');
    let date = b.len() >= 10
        && b[..4].iter().all(u8::is_ascii_digit)
        && b[4] == b'-'
        && b[5..7].iter().all(u8::is_ascii_digit)
        && b[7] == b'-'
        && b[8..10].iter().all(u8::is_ascii_digit);
    let unsigned = s.strip_prefix(['+', '-']).unwrap_or(s);
    let binary = unsigned
        .strip_prefix("0b")
        .is_some_and(|d| !d.is_empty() && d.bytes().all(|c| c == b'0' || c == b'1'));
    let dotted = (s.starts_with('+') || s.starts_with('.'))
        && s[1..].starts_with(|c: char| c.is_ascii_digit());
    digits_with_underscores || date || binary || dotted
}

/// Whether `c` is written escaped in a double-quoted scalar: a C0 control, DEL,
/// or a character a reader may take for a line or paragraph break.
fn needs_escape(c: char) -> bool {
    c < ' ' || matches!(c, '\u{7f}' | '\u{85}' | '\u{2028}' | '\u{2029}')
}

fn escape_double(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\0' => out.push_str("\\0"),
            '\u{7}' => out.push_str("\\a"),
            '\u{8}' => out.push_str("\\b"),
            '\t' => out.push_str("\\t"),
            '\n' => out.push_str("\\n"),
            '\u{b}' => out.push_str("\\v"),
            '\u{c}' => out.push_str("\\f"),
            '\r' => out.push_str("\\r"),
            '\u{1b}' => out.push_str("\\e"),
            c if c < ' ' || c == '\u{7f}' => out.push_str(&format!("\\x{:02X}", c as u32)),
            c if needs_escape(c) => out.push_str(&format!("\\u{:04X}", c as u32)),
            other => out.push(other),
        }
    }
    out
}

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

    fn rec(pairs: &[(&str, Value)]) -> Value {
        Value::Record(
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.clone()))
                .collect(),
        )
    }

    // ---- the failures of the previous line-splitting implementation ----

    #[test]
    fn parses_nested_mappings() {
        // The old parser flattened this into one record, losing the structure.
        let v = parse("server:\n  host: localhost\n  port: 8080\n").unwrap();
        assert_eq!(
            v,
            rec(&[(
                "server",
                rec(&[
                    ("host", Value::Str("localhost".into())),
                    ("port", Value::Int(8080)),
                ])
            )])
        );
    }

    #[test]
    fn parses_sequences() {
        // The old parser dropped these entirely: a `- item` line has no colon.
        let v = parse("ports:\n  - 80\n  - 443\n").unwrap();
        assert_eq!(
            v,
            rec(&[("ports", Value::Array(vec![Value::Int(80), Value::Int(443)]))])
        );
    }

    #[test]
    fn parses_sequence_of_mappings() {
        let v = parse("users:\n  - name: ada\n    admin: true\n  - name: bob\n    admin: false\n")
            .unwrap();
        let Value::Record(r) = &v else { panic!() };
        let Some(Value::Array(items)) = r.get("users") else {
            panic!("expected array, got {r:?}")
        };
        assert_eq!(items.len(), 2);
        assert_eq!(
            items[0],
            rec(&[
                ("name", Value::Str("ada".into())),
                ("admin", Value::Bool(true))
            ])
        );
    }

    #[test]
    fn strips_comments() {
        // The old parser kept " # the port" as part of the value.
        let v = parse("# leading\nport: 8080 # the port\n").unwrap();
        assert_eq!(v, rec(&[("port", Value::Int(8080))]));
    }

    #[test]
    fn keeps_hash_inside_quotes() {
        let v = parse(r##"color: "#ff0000""##).unwrap();
        assert_eq!(v, rec(&[("color", Value::Str("#ff0000".into()))]));
    }

    #[test]
    fn ignores_document_start_marker() {
        // The old parser turned `---` into a {"---": ""} entry.
        let v = parse("---\nname: ae\n").unwrap();
        assert_eq!(v, rec(&[("name", Value::Str("ae".into()))]));
    }

    #[test]
    fn colon_inside_a_value_is_not_a_separator() {
        let v = parse("time: 12:30\nurl: https://example.com/x\n").unwrap();
        assert_eq!(
            v,
            rec(&[
                ("time", Value::Str("12:30".into())),
                ("url", Value::Str("https://example.com/x".into())),
            ])
        );
    }

    // ---- typing ----

    #[test]
    fn types_plain_scalars() {
        let v = parse("i: 42\nf: 1.5\nt: true\nf2: False\nn: null\ne: ~\ns: hello\n").unwrap();
        assert_eq!(
            v,
            rec(&[
                ("i", Value::Int(42)),
                ("f", Value::Float(1.5)),
                ("t", Value::Bool(true)),
                ("f2", Value::Bool(false)),
                ("n", Value::Null),
                ("e", Value::Null),
                ("s", Value::Str("hello".into())),
            ])
        );
    }

    #[test]
    fn quoted_numbers_stay_strings() {
        let v = parse("version: \"1.0\"\nzip: '01234'\n").unwrap();
        assert_eq!(
            v,
            rec(&[
                ("version", Value::Str("1.0".into())),
                ("zip", Value::Str("01234".into())),
            ])
        );
    }

    #[test]
    fn handles_escapes_in_double_quotes() {
        let v = parse(r#"msg: "line1\nline2\ttabbed""#).unwrap();
        assert_eq!(
            v,
            rec(&[("msg", Value::Str("line1\nline2\ttabbed".into()))])
        );
    }

    #[test]
    fn parses_json_flow_collections() {
        let v = parse("list: [1, 2, 3]\nmap: {\"a\": 1}\n").unwrap();
        assert_eq!(
            v,
            rec(&[
                (
                    "list",
                    Value::Array(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
                ),
                ("map", rec(&[("a", Value::Int(1))])),
            ])
        );
    }

    #[test]
    fn key_with_no_value_is_null() {
        let v = parse("empty:\n").unwrap();
        assert_eq!(v, rec(&[("empty", Value::Null)]));
    }

    // ---- loud failure instead of quiet corruption ----

    #[test]
    fn rejects_unsupported_constructs_by_name() {
        for (src, expect) in [
            ("a: &anchor 1\n", "anchors"),
            ("a: *alias\n", "aliases"),
            ("a: !!str 1\n", "tags"),
            ("a: |\n  block\n", "block scalars"),
            ("a: >\n  folded\n", "folded"),
            ("<<: base\n", "merge keys"),
            ("a: 1\n---\nb: 2\n", "multiple YAML documents"),
        ] {
            let err = parse(src).unwrap_err().to_string();
            assert!(
                err.contains(expect),
                "parsing {src:?} should name {expect:?}, said: {err}"
            );
        }
    }

    #[test]
    fn rejects_duplicate_keys() {
        // Silently keeping the last value is the class of bug this module exists
        // to eliminate.
        let err = parse("a: 1\na: 2\n").unwrap_err().to_string();
        assert!(err.contains("duplicate key"), "got {err}");
    }

    #[test]
    fn rejects_malformed_flow_collections() {
        let err = parse("a: [1, 2\n").unwrap_err().to_string();
        assert!(err.contains("not valid JSON"), "got {err}");
    }

    #[test]
    fn rejects_a_line_that_is_not_a_mapping_entry() {
        let err = parse("just a bare line\n").unwrap_err().to_string();
        assert!(err.contains("expected `key: value`"), "got {err}");
    }

    #[test]
    fn empty_input_is_null() {
        assert_eq!(parse("").unwrap(), Value::Null);
        assert_eq!(parse("# only a comment\n").unwrap(), Value::Null);
    }

    // ---- emit ----

    #[test]
    fn emits_nested_structures() {
        let v = rec(&[(
            "server",
            rec(&[
                ("host", Value::Str("localhost".into())),
                ("port", Value::Int(8080)),
            ]),
        )]);
        assert_eq!(emit(&v), "server:\n  host: localhost\n  port: 8080\n");
    }

    #[test]
    fn emits_sequences() {
        let v = rec(&[("ports", Value::Array(vec![Value::Int(80), Value::Int(443)]))]);
        assert_eq!(emit(&v), "ports:\n  - 80\n  - 443\n");
    }

    #[test]
    fn quotes_values_that_would_not_read_back() {
        // The old emitter wrote these bare, producing unreadable YAML.
        let v = rec(&[
            ("colon", Value::Str("a: b".into())),
            ("hash", Value::Str("#tag".into())),
            ("numeric", Value::Str("42".into())),
            ("empty", Value::Str(String::new())),
        ]);
        let out = emit(&v);
        assert!(out.contains(r#"colon: "a: b""#), "got {out}");
        assert!(out.contains(r##"hash: "#tag""##), "got {out}");
        assert!(out.contains(r#"numeric: "42""#), "got {out}");
        assert!(out.contains(r#"empty: """#), "got {out}");
    }

    #[test]
    fn round_trips() {
        // The property that matters: emit then parse yields the same value.
        let original = rec(&[
            ("name", Value::Str("ae".into())),
            ("version", Value::Str("1.6.0".into())),
            ("port", Value::Int(8080)),
            ("ratio", Value::Float(0.5)),
            ("debug", Value::Bool(false)),
            ("nothing", Value::Null),
            ("tricky", Value::Str("a: b # c".into())),
            (
                "nested",
                rec(&[("deep", Value::Array(vec![Value::Int(1), Value::Int(2)]))]),
            ),
            (
                "list",
                Value::Array(vec![Value::Str("x".into()), Value::Str("y".into())]),
            ),
        ]);
        let text = emit(&original);
        let reparsed = parse(&text).unwrap_or_else(|e| panic!("reparse failed: {e}\n---\n{text}"));
        assert_eq!(reparsed, original, "round trip changed the value:\n{text}");
    }

    #[test]
    fn round_trips_a_sequence_of_records() {
        let original = rec(&[(
            "users",
            Value::Array(vec![
                rec(&[("name", Value::Str("ada".into()))]),
                rec(&[("name", Value::Str("bob".into()))]),
            ]),
        )]);
        let text = emit(&original);
        assert_eq!(parse(&text).unwrap(), original, "\n{text}");
    }

    #[test]
    fn emits_empty_collections() {
        assert_eq!(emit(&Value::Record(BTreeMap::new())), "{}\n");
        assert_eq!(emit(&Value::Array(vec![])), "[]\n");
    }
}