rlsp-yaml 0.5.0

A fast, lightweight YAML language server
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
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
// SPDX-License-Identifier: MIT

use rlsp_fmt::{Doc, FormatOptions, concat, format as fmt_format, hard_line, indent, join, text};
use saphyr::{LoadableYamlNode, ScalarOwned, ScalarStyle, YamlOwned};

/// Classification of a YAML comment.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CommentKind {
    /// On the same line as code: `key: value  # comment`
    Trailing,
    /// On a line by itself (possibly with leading whitespace): `# comment`
    Leading,
}

/// A comment extracted from raw YAML text.
#[derive(Debug, Clone)]
struct Comment {
    /// 0-based line number in the original text.
    line: usize,
    /// The comment text including `#` (e.g. `# this is a comment`).
    text: String,
    /// Classification.
    kind: CommentKind,
}

/// Scan raw YAML text and extract all comments with their positions.
///
/// A `#` starts a comment if it is not inside a quoted string and is either:
/// - the first non-whitespace character on the line (Leading), or
/// - preceded by at least one whitespace character (Trailing).
fn extract_comments(text: &str) -> Vec<Comment> {
    let mut comments = Vec::new();
    for (line_idx, line) in text.lines().enumerate() {
        if let Some((byte_pos, comment_text)) = find_comment_on_line(line) {
            let before = &line[..byte_pos];
            let kind = if before.trim().is_empty() {
                CommentKind::Leading
            } else {
                CommentKind::Trailing
            };
            comments.push(Comment {
                line: line_idx,
                text: comment_text,
                kind,
            });
        }
    }
    comments
}

/// Find the comment portion of a single line, respecting quoted strings.
///
/// Returns `(byte_offset_of_hash, comment_text)` or `None` if the line has no comment.
fn find_comment_on_line(line: &str) -> Option<(usize, String)> {
    let mut in_single = false;
    let mut in_double = false;
    let mut chars = line.char_indices();
    while let Some((byte_pos, c)) = chars.next() {
        match c {
            '\'' if !in_double => {
                in_single = !in_single;
            }
            '"' if !in_single => {
                in_double = !in_double;
            }
            '\\' if in_double => {
                // Skip the next character (escape sequence).
                chars.next();
            }
            '#' if !in_single && !in_double => {
                // Must be preceded by whitespace or be the first non-whitespace char.
                let before = &line[..byte_pos];
                if before.trim_end().is_empty() || before.ends_with(|c: char| c.is_whitespace()) {
                    return Some((byte_pos, line[byte_pos..].to_string()));
                }
            }
            _ => {}
        }
    }
    None
}

/// Extract the content signature from a line: the trimmed non-comment portion.
fn content_signature(line: &str) -> String {
    if let Some((byte_pos, _)) = find_comment_on_line(line) {
        line[..byte_pos].trim().to_string()
    } else {
        line.trim().to_string()
    }
}

/// A content line from the original text, with its associated comments.
struct ContentEntry {
    signature: String,
    /// Leading comment lines that precede this content line.
    leading: Vec<String>,
    /// Trailing comment on this content line (if any).
    trailing: Option<String>,
}

/// Attach extracted comments back to formatted YAML output.
///
/// Strategy:
/// - Build a list of content entries from the original (one per non-blank, non-leading-comment line).
/// - For each entry, record leading comments that preceded it and any trailing comment on the line.
/// - Walk the formatted output; when a line's signature matches the next entry, emit leading
///   comments (indented to match the content line) before it, and append any trailing comment.
/// - Any unmatched leading comments (e.g. at end of file) are appended at the end.
fn attach_comments(original: &str, formatted: &str, comments: &[Comment]) -> String {
    if comments.is_empty() {
        return formatted.to_string();
    }

    // Build a quick lookup: line index -> comment.
    let line_to_comment: std::collections::HashMap<usize, &Comment> =
        comments.iter().map(|c| (c.line, c)).collect();

    let mut entries: Vec<ContentEntry> = Vec::new();
    let mut pending_leading: Vec<String> = Vec::new();
    let mut pending_blanks: usize = 0;

    for (idx, line) in original.lines().enumerate() {
        if let Some(comment) = line_to_comment.get(&idx) {
            match comment.kind {
                CommentKind::Leading => {
                    // Insert a blank separator if there was a gap before this comment group.
                    if pending_blanks > 0 && !pending_leading.is_empty() {
                        pending_leading.push(String::new());
                    }
                    pending_blanks = 0;
                    pending_leading.push(comment.text.clone());
                }
                CommentKind::Trailing => {
                    entries.push(ContentEntry {
                        signature: content_signature(line),
                        leading: std::mem::take(&mut pending_leading),
                        trailing: Some(comment.text.clone()),
                    });
                    pending_blanks = 0;
                }
            }
        } else if line.trim().is_empty() {
            pending_blanks += 1;
        } else {
            entries.push(ContentEntry {
                signature: content_signature(line),
                leading: std::mem::take(&mut pending_leading),
                trailing: None,
            });
            pending_blanks = 0;
        }
    }

    // Any remaining leading comments (after all content) go at the end.
    let trailing_leading = pending_leading;

    let mut result_lines: Vec<String> = Vec::new();
    let mut entry_iter = entries.iter();
    let mut next_entry = entry_iter.next();

    for fmt_line in formatted.lines() {
        let fmt_sig = content_signature(fmt_line);

        // Match this formatted line to the next entry by signature.
        if !fmt_sig.is_empty() {
            if let Some(entry) = next_entry {
                if entry.signature == fmt_sig {
                    let indent_len = fmt_line.len() - fmt_line.trim_start().len();
                    let indent_str = " ".repeat(indent_len);

                    for lc in &entry.leading {
                        if lc.is_empty() {
                            result_lines.push(String::new());
                        } else {
                            result_lines.push(format!("{indent_str}{lc}"));
                        }
                    }

                    if let Some(tc) = &entry.trailing {
                        result_lines.push(format!("{fmt_line}  {tc}"));
                    } else {
                        result_lines.push(fmt_line.to_string());
                    }

                    next_entry = entry_iter.next();
                    continue;
                }
            }
        }

        result_lines.push(fmt_line.to_string());
    }

    // Append trailing leading comments (e.g. at end of file after all content).
    for lc in &trailing_leading {
        if lc.is_empty() {
            result_lines.push(String::new());
        } else {
            result_lines.push(lc.clone());
        }
    }

    let mut out = result_lines.join("\n");
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// YAML-specific formatting options.
#[derive(Debug, Clone)]
pub struct YamlFormatOptions {
    /// Maximum line width. Default: 80.
    pub print_width: usize,
    /// Spaces per indent level. Default: 2.
    pub tab_width: usize,
    /// Use tabs instead of spaces. Default: false.
    pub use_tabs: bool,
    /// Prefer single-quoted strings. Default: false (double quotes).
    pub single_quote: bool,
    /// Add spaces inside flow braces: `{ a: 1 }` vs `{a: 1}`. Default: true.
    pub bracket_spacing: bool,
}

impl Default for YamlFormatOptions {
    fn default() -> Self {
        Self {
            print_width: 80,
            tab_width: 2,
            use_tabs: false,
            single_quote: false,
            bracket_spacing: true,
        }
    }
}

/// Format a YAML document string.
///
/// Returns the formatted text. If the input fails to parse, returns the
/// original text unchanged so the caller never loses content.
/// Comments are extracted from the input and reattached to the formatted output.
#[must_use]
pub fn format_yaml(text_input: &str, options: &YamlFormatOptions) -> String {
    let Ok(documents) = YamlOwned::load_from_str(text_input) else {
        return text_input.to_string();
    };

    if documents.is_empty() {
        return String::new();
    }

    // Extract comments before formatting (saphyr discards them during parse).
    let comments = extract_comments(text_input);

    let fmt_options = FormatOptions {
        print_width: options.print_width,
        tab_width: options.tab_width,
        use_tabs: options.use_tabs,
    };

    // Join multiple documents with `---` separators.
    let sep = text("---");
    let mut parts: Vec<Doc> = Vec::new();
    let mut iter = documents.iter().map(|doc| node_to_doc(doc, options));
    if let Some(first) = iter.next() {
        parts.push(first);
    }
    for doc in iter {
        parts.push(hard_line());
        parts.push(sep.clone());
        parts.push(hard_line());
        parts.push(doc);
    }
    let joined = concat(parts);

    let mut result = fmt_format(&joined, &fmt_options);

    // Ensure output ends with a single newline.
    if !result.ends_with('\n') {
        result.push('\n');
    }

    // Reattach comments to the formatted output.
    if !comments.is_empty() {
        result = attach_comments(text_input, &result, &comments);
    }

    result
}

/// Convert a `YamlOwned` node to a `Doc` IR node.
fn node_to_doc(node: &YamlOwned, options: &YamlFormatOptions) -> Doc {
    match node {
        YamlOwned::Value(scalar) => scalar_to_doc(scalar, options),

        YamlOwned::Representation(s, style, _tag) => {
            // Preserve original representation for block scalars (literal/folded).
            // For plain/quoted scalars, render as text with the original style applied.
            match style {
                ScalarStyle::Literal | ScalarStyle::Folded => {
                    // Block scalars span multiple lines; embed as-is using hard lines.
                    // Split on \n and join with hard_line() so the printer tracks columns.
                    repr_block_to_doc(s, *style)
                }
                ScalarStyle::SingleQuoted => text(format!("'{s}'")),
                ScalarStyle::DoubleQuoted => text(format!("\"{s}\"")),
                ScalarStyle::Plain => text(s.clone()),
            }
        }

        YamlOwned::Mapping(map) => mapping_to_doc(map, options),

        YamlOwned::Sequence(seq) => sequence_to_doc(seq, options),

        YamlOwned::Tagged(tag, inner) => {
            let tag_text = format!("!{} ", tag.suffix);
            concat(vec![text(tag_text), node_to_doc(inner, options)])
        }

        YamlOwned::Alias(idx) => text(format!("*alias{idx}")),

        YamlOwned::BadValue => text("null"),
    }
}

/// Render a `ScalarOwned` value to a `Doc`.
fn scalar_to_doc(scalar: &ScalarOwned, options: &YamlFormatOptions) -> Doc {
    match scalar {
        ScalarOwned::Null => text("null"),
        ScalarOwned::Boolean(b) => text(if *b { "true" } else { "false" }),
        ScalarOwned::Integer(i) => text(i.to_string()),
        ScalarOwned::FloatingPoint(f) => text(format_float(**f)),
        ScalarOwned::String(s) => string_to_doc(s, options),
    }
}

/// Format a float value, avoiding scientific notation for common values.
fn format_float(f: f64) -> String {
    if f.is_nan() {
        ".nan".to_string()
    } else if f.is_infinite() {
        if f > 0.0 {
            ".inf".to_string()
        } else {
            "-.inf".to_string()
        }
    } else {
        // Use Rust's default float formatting.
        let s = f.to_string();
        // Ensure there's always a decimal point so it's recognizable as float.
        if s.contains('.') || s.contains('e') {
            s
        } else {
            format!("{s}.0")
        }
    }
}

/// Convert a string scalar to a Doc, quoting as necessary.
fn string_to_doc(s: &str, options: &YamlFormatOptions) -> Doc {
    if needs_quoting(s) {
        // Must quote — use the preferred style.
        if options.single_quote && !s.contains('\'') {
            text(format!("'{s}'"))
        } else {
            // Double-quote and escape.
            text(format!("\"{}\"", escape_double_quoted(s)))
        }
    } else if options.single_quote {
        text(format!("'{s}'"))
    } else {
        // Plain — no quotes needed.
        text(s.to_string())
    }
}

/// Returns true if a string value requires quoting to avoid YAML ambiguity.
fn needs_quoting(s: &str) -> bool {
    if s.is_empty() {
        return true;
    }

    // Values that are reserved YAML keywords when unquoted.
    matches!(
        s,
        "null"
            | "~"
            | "true"
            | "false"
            | "yes"
            | "no"
            | "on"
            | "off"
            | "True"
            | "False"
            | "Yes"
            | "No"
            | "On"
            | "Off"
            | "TRUE"
            | "FALSE"
            | "YES"
            | "NO"
            | "ON"
            | "OFF"
            | "NULL"
            | "Null"
    ) || looks_like_number(s)
        || s.starts_with(|c: char| {
            matches!(
                c,
                ':' | '#'
                    | '&'
                    | '*'
                    | '?'
                    | '|'
                    | '-'
                    | '<'
                    | '>'
                    | '='
                    | '!'
                    | '%'
                    | '@'
                    | '`'
                    | '{'
                    | '}'
                    | '['
                    | ']'
            )
        })
        || s.contains(": ")
        || s.contains(" #")
        || s.starts_with("- ")
        || s.starts_with("--- ")
        || s == "---"
        || s == "..."
}

/// Returns true if the string looks like a YAML number (integer or float).
fn looks_like_number(s: &str) -> bool {
    s.parse::<i64>().is_ok()
        || s.parse::<f64>().is_ok()
        || matches!(
            s,
            ".inf" | ".Inf" | ".INF" | "+.inf" | "-.inf" | ".nan" | ".NaN" | ".NAN"
        )
}

/// Escape a string for use in a double-quoted YAML scalar.
fn escape_double_quoted(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

/// Convert a block scalar representation to Doc using hard lines.
///
/// **Limitation:** saphyr does not preserve the original chomping indicator
/// (`|-`, `|+`, `>-`, `>+`). This function always emits the plain block header
/// (`|` or `>`), which defaults to "clip" chomping. Block scalars with strip
/// or keep chomping will silently lose their indicator on format.
fn repr_block_to_doc(s: &str, style: ScalarStyle) -> Doc {
    let header = match style {
        ScalarStyle::Literal => "|",
        ScalarStyle::Folded => ">",
        ScalarStyle::Plain | ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => "",
    };
    // The representation string from saphyr is the raw content without header.
    // We reconstruct the block scalar header + content.
    let mut parts = vec![text(header)];
    for line_str in s.lines() {
        parts.push(hard_line());
        parts.push(text(line_str.to_string()));
    }
    concat(parts)
}

/// Convert a YAML mapping to Doc in block style.
fn mapping_to_doc(map: &saphyr::MappingOwned, options: &YamlFormatOptions) -> Doc {
    if map.is_empty() {
        return text("{}");
    }

    let pairs: Vec<Doc> = map
        .iter()
        .map(|(key, value)| key_value_to_doc(key, value, options))
        .collect();

    let sep = hard_line();
    join(&sep, pairs)
}

/// Convert a single key-value pair to Doc.
fn key_value_to_doc(key: &YamlOwned, value: &YamlOwned, options: &YamlFormatOptions) -> Doc {
    let key_doc = node_to_doc(key, options);

    match value {
        // Block mappings: `key:\n  child: val` — hard_line inside indent.
        YamlOwned::Mapping(map) if !map.is_empty() => concat(vec![
            key_doc,
            text(":"),
            indent(concat(vec![hard_line(), mapping_to_doc(map, options)])),
        ]),
        // Non-empty sequences: always block, indented under key.
        YamlOwned::Sequence(seq) if !seq.is_empty() => concat(vec![
            key_doc,
            text(":"),
            indent(concat(vec![hard_line(), sequence_to_doc(seq, options)])),
        ]),
        // All other values (scalars, empty collections, aliases, tags, etc.) inline.
        YamlOwned::Value(_)
        | YamlOwned::Representation(..)
        | YamlOwned::Mapping(_)
        | YamlOwned::Sequence(_)
        | YamlOwned::Tagged(..)
        | YamlOwned::Alias(_)
        | YamlOwned::BadValue => {
            let value_doc = node_to_doc(value, options);
            concat(vec![key_doc, text(": "), value_doc])
        }
    }
}

/// Convert a YAML sequence to Doc (always block style).
fn sequence_to_doc(seq: &[YamlOwned], options: &YamlFormatOptions) -> Doc {
    if seq.is_empty() {
        return text("[]");
    }
    let items: Vec<Doc> = seq
        .iter()
        .map(|item| sequence_item_to_doc(item, options))
        .collect();
    let sep = hard_line();
    join(&sep, items)
}

/// Render a single sequence item with its `- ` prefix.
fn sequence_item_to_doc(item: &YamlOwned, options: &YamlFormatOptions) -> Doc {
    match item {
        YamlOwned::Mapping(map) if !map.is_empty() => {
            // `- key: val\n  key2: val2` — first pair on the dash line, remaining
            // pairs indented one level so they align under the first key.
            let pairs: Vec<Doc> = map
                .iter()
                .map(|(k, v)| key_value_to_doc(k, v, options))
                .collect();
            let sep = hard_line();
            let inner = join(&sep, pairs);
            // indent() shifts all hard_line breaks inside `inner` by one level,
            // placing continuation pairs 2 spaces right of `- `.
            concat(vec![text("- "), indent(inner)])
        }
        YamlOwned::Sequence(seq) if !seq.is_empty() => concat(vec![
            text("- "),
            indent(concat(vec![hard_line(), sequence_to_doc(seq, options)])),
        ]),
        // Scalars, empty collections, aliases, tags, bad values, etc.
        YamlOwned::Value(_)
        | YamlOwned::Representation(..)
        | YamlOwned::Mapping(_)
        | YamlOwned::Sequence(_)
        | YamlOwned::Tagged(..)
        | YamlOwned::Alias(_)
        | YamlOwned::BadValue => concat(vec![text("- "), node_to_doc(item, options)]),
    }
}

#[cfg(test)]
#[allow(clippy::indexing_slicing, clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn default_opts() -> YamlFormatOptions {
        YamlFormatOptions::default()
    }

    // Test 1: Simple key-value formats correctly.
    #[test]
    fn simple_key_value() {
        let result = format_yaml("key: value\n", &default_opts());
        assert_eq!(result, "key: value\n");
    }

    // Test 2: Multiple keys — preserves order, one per line.
    #[test]
    fn multiple_keys() {
        let result = format_yaml("a: 1\nb: 2\nc: 3\n", &default_opts());
        assert_eq!(result, "a: 1\nb: 2\nc: 3\n");
    }

    // Test 3: Nested mapping — child indented under parent.
    #[test]
    fn nested_mapping() {
        let input = "parent:\n  child: value\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("parent:"), "missing parent key");
        assert!(
            result.contains("  child: value") || result.contains("\n  child:"),
            "child should be indented: {result:?}"
        );
    }

    // Test 4: Deeply nested — 3+ levels.
    #[test]
    fn deeply_nested() {
        let input = "a:\n  b:\n    c: deep\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("a:"), "missing a");
        assert!(result.contains("b:"), "missing b");
        assert!(
            result.contains("c: deep") || result.contains("c:"),
            "missing c"
        );
    }

    // Test 5: Block sequence — `- item` format.
    #[test]
    fn block_sequence() {
        let input = "items:\n  - one\n  - two\n  - three\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("items:"), "missing items key");
        assert!(result.contains("- one"), "missing - one");
        assert!(result.contains("- two"), "missing - two");
    }

    // Test 6: Sequence of mappings — common K8s pattern.
    // Verifies that continuation keys in a sequence item mapping are indented
    // under the first key, not at the `- ` column level.
    #[test]
    fn sequence_of_mappings() {
        let input = "users:\n  - name: Alice\n    age: 30\n  - name: Bob\n    age: 25\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("users:"), "missing users: {result:?}");
        // name: Alice must appear after a `- ` prefix.
        assert!(
            result.contains("- name: Alice"),
            "first item first key missing: {result:?}"
        );
        // age: 30 must be indented (at least 2 spaces) — not at the `- ` column.
        assert!(
            result.contains("  age: 30"),
            "age should be indented under its sequence item: {result:?}"
        );
        assert!(
            result.contains("- name: Bob"),
            "second item first key missing: {result:?}"
        );
        assert!(
            result.contains("  age: 25"),
            "second item age should be indented: {result:?}"
        );
    }

    // Test 7: Flow mapping stays inline when it fits.
    // Note: saphyr parses flow maps into the same Mapping type — our formatter
    // always emits block for mappings. This test verifies multi-key mappings render correctly.
    #[test]
    fn mapping_block_style() {
        let input = "a: 1\nb: 2\n";
        let result = format_yaml(input, &default_opts());
        // Both keys should appear.
        assert!(result.contains("a: 1"), "a missing: {result:?}");
        assert!(result.contains("b: 2"), "b missing: {result:?}");
    }

    // Test 8: Flow sequence stays flat when short enough.
    #[test]
    fn flow_sequence_flat_when_fits() {
        // Short scalar sequence → should render as [a, b, c] or block.
        let input = "items:\n  - a\n  - b\n  - c\n";
        let result = format_yaml(input, &default_opts());
        // Either inline or block — must contain all items.
        assert!(result.contains('a'), "a missing: {result:?}");
        assert!(result.contains('b'), "b missing: {result:?}");
        assert!(result.contains('c'), "c missing: {result:?}");
    }

    // Test 9: Multi-document — `---` separators preserved.
    #[test]
    fn multi_document() {
        let input = "key1: value1\n---\nkey2: value2\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key1: value1"), "missing doc1: {result:?}");
        assert!(result.contains("---"), "missing separator: {result:?}");
        assert!(result.contains("key2: value2"), "missing doc2: {result:?}");
    }

    // Test 10: Null values handled correctly.
    #[test]
    fn null_values() {
        let input = "key: null\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("null"), "null missing: {result:?}");
    }

    // Test 11: Boolean values — `true`/`false` preserved.
    #[test]
    fn boolean_values() {
        let input = "enabled: true\ndisabled: false\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("true"), "true missing: {result:?}");
        assert!(result.contains("false"), "false missing: {result:?}");
    }

    // Test 12: Numeric values — integers and floats preserved.
    #[test]
    fn numeric_values() {
        let input = "port: 8080\nratio: 0.5\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("8080"), "integer missing: {result:?}");
        assert!(result.contains("0.5"), "float missing: {result:?}");
    }

    // Test 13: Idempotency — format(format(x)) == format(x).
    #[test]
    fn idempotent() {
        let inputs = [
            "key: value\n",
            "a: 1\nb: 2\n",
            "parent:\n  child: value\n",
            "items:\n  - one\n  - two\n",
        ];
        for input in inputs {
            let first = format_yaml(input, &default_opts());
            let second = format_yaml(&first, &default_opts());
            assert_eq!(
                first, second,
                "idempotency failed for {input:?}:\nfirst:  {first:?}\nsecond: {second:?}"
            );
        }
    }

    // Test 14: Syntax error — returns original text unchanged.
    #[test]
    fn syntax_error_returns_original() {
        let bad = "key: [unclosed\n";
        let result = format_yaml(bad, &default_opts());
        assert_eq!(result, bad, "should return original on parse error");
    }

    // Extra: string values that need quoting get quoted.
    #[test]
    fn string_quoting_ambiguous_values() {
        // "true" as a string value — after parse it becomes Boolean(true),
        // so saphyr resolves it. A string that looks like a number needs quoting.
        let opts = YamlFormatOptions {
            single_quote: false,
            ..Default::default()
        };
        // A key whose value is the string "null" will be parsed as Null by saphyr.
        // Test that strings requiring quotes actually get them via round-trip.
        let input = "key: some value\n";
        let result = format_yaml(input, &opts);
        // "some value" is a valid plain string — no quotes needed.
        assert!(result.contains("some value"), "result: {result:?}");
    }

    // Extra: single_quote option wraps strings.
    #[test]
    fn single_quote_option() {
        let opts = YamlFormatOptions {
            single_quote: true,
            ..Default::default()
        };
        let input = "key: hello\n";
        let result = format_yaml(input, &opts);
        assert!(
            result.contains("'hello'"),
            "expected single-quoted: {result:?}"
        );
    }

    // Extra: empty document.
    #[test]
    fn empty_document() {
        let result = format_yaml("", &default_opts());
        assert_eq!(result, "");
    }

    // Test C1: Trailing comment preserved.
    #[test]
    fn trailing_comment_preserved() {
        let input = "key: value  # comment\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "content missing: {result:?}");
        assert!(
            result.contains("# comment"),
            "trailing comment missing: {result:?}"
        );
        // Comment must appear on the same line as the content.
        for line in result.lines() {
            if line.contains("key: value") {
                assert!(
                    line.contains("# comment"),
                    "trailing comment not on same line: {line:?}"
                );
            }
        }
    }

    // Test C2: Leading comment preserved.
    #[test]
    fn leading_comment_preserved() {
        let input = "# header\nkey: value\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("# header"),
            "leading comment missing: {result:?}"
        );
        assert!(result.contains("key: value"), "content missing: {result:?}");
        // Comment must appear before the key line.
        let comment_pos = result.find("# header").unwrap();
        let key_pos = result.find("key: value").unwrap();
        assert!(
            comment_pos < key_pos,
            "leading comment should appear before key: {result:?}"
        );
    }

    // Test C3: Multiple consecutive leading comments stay together.
    #[test]
    fn multiple_leading_comments() {
        let input = "# line one\n# line two\nkey: value\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("# line one"),
            "first comment missing: {result:?}"
        );
        assert!(
            result.contains("# line two"),
            "second comment missing: {result:?}"
        );
        assert!(result.contains("key: value"), "content missing: {result:?}");
        // Both comments must precede the key line.
        let c1_pos = result.find("# line one").unwrap();
        let c2_pos = result.find("# line two").unwrap();
        let key_pos = result.find("key: value").unwrap();
        assert!(c1_pos < key_pos, "first comment should precede key");
        assert!(c2_pos < key_pos, "second comment should precede key");
        assert!(c1_pos < c2_pos, "comments should be in original order");
    }

    // Test C4: Blank line between sections preserved.
    #[test]
    fn blank_line_between_sections() {
        let input = "# section 1\nkey1: v1\n\n# section 2\nkey2: v2\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("# section 1"),
            "section 1 comment missing: {result:?}"
        );
        assert!(
            result.contains("# section 2"),
            "section 2 comment missing: {result:?}"
        );
        assert!(result.contains("key1: v1"), "key1 missing: {result:?}");
        assert!(result.contains("key2: v2"), "key2 missing: {result:?}");
        // Section 1 comment before key1, section 2 comment before key2.
        let s1_pos = result.find("# section 1").unwrap();
        let k1_pos = result.find("key1: v1").unwrap();
        let s2_pos = result.find("# section 2").unwrap();
        let k2_pos = result.find("key2: v2").unwrap();
        assert!(s1_pos < k1_pos, "section 1 comment should precede key1");
        assert!(s2_pos < k2_pos, "section 2 comment should precede key2");
    }

    // Test C5: Comment at document start.
    #[test]
    fn comment_at_document_start() {
        let input = "# top comment\nkey: value\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.starts_with("# top comment"),
            "top comment should be first: {result:?}"
        );
        assert!(result.contains("key: value"), "content missing: {result:?}");
    }

    // Test C6: Comment at document end.
    #[test]
    fn comment_at_document_end() {
        let input = "key: value\n# bottom comment\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "content missing: {result:?}");
        assert!(
            result.contains("# bottom comment"),
            "bottom comment missing: {result:?}"
        );
    }

    // Test C7: Comments between sequence items.
    #[test]
    fn comments_between_sequence_items() {
        let input = "items:\n  - item1\n  # between\n  - item2\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("- item1"), "item1 missing: {result:?}");
        assert!(result.contains("- item2"), "item2 missing: {result:?}");
        assert!(
            result.contains("# between"),
            "between comment missing: {result:?}"
        );
        // Comment must appear between item1 and item2.
        let i1_pos = result.find("- item1").unwrap();
        let bet_pos = result.find("# between").unwrap();
        let i2_pos = result.find("- item2").unwrap();
        assert!(i1_pos < bet_pos, "comment should be after item1");
        assert!(bet_pos < i2_pos, "comment should be before item2");
    }

    // Test C8: Idempotency with comments.
    #[test]
    fn idempotent_with_comments() {
        let inputs = [
            "key: value  # comment\n",
            "# header\nkey: value\n",
            "# section 1\nkey1: v1\n\n# section 2\nkey2: v2\n",
        ];
        for input in inputs {
            let first = format_yaml(input, &default_opts());
            let second = format_yaml(&first, &default_opts());
            assert_eq!(
                first, second,
                "idempotency failed for {input:?}:\nfirst:  {first:?}\nsecond: {second:?}"
            );
        }
    }

    // Test C9: No comments — existing formatting still works (regression).
    #[test]
    fn no_comments_regression() {
        let input = "a: 1\nb: 2\nc: 3\n";
        let result = format_yaml(input, &default_opts());
        assert_eq!(result, "a: 1\nb: 2\nc: 3\n", "regression: {result:?}");
    }

    // Test C10: Hash inside quoted string is NOT extracted as a comment.
    #[test]
    fn hash_inside_quoted_string_not_extracted() {
        let input = "key: \"value # not a comment\"\n";
        let result = format_yaml(input, &default_opts());
        // The result should not have a standalone comment after the value.
        // The # should be part of the string content, not a trailing comment.
        for line in result.lines() {
            if line.contains("key:") {
                // There should be no comment text appended separately.
                // The # appears inside the quoted string.
                assert!(
                    !line.trim_end().ends_with("# not a comment"),
                    "hash inside quoted string wrongly extracted as comment: {line:?}"
                );
            }
        }
        assert!(
            result.contains("not a comment"),
            "quoted string content should be preserved: {result:?}"
        );
    }

    // Unit tests for extract_comments.

    // EC1: Empty input yields no comments.
    #[test]
    fn extract_comments_empty_input() {
        let comments = extract_comments("");
        assert!(comments.is_empty(), "expected no comments: {comments:?}");
    }

    // EC2: No comments in plain YAML.
    #[test]
    fn extract_comments_no_comments() {
        let comments = extract_comments("key: value\n");
        assert!(comments.is_empty(), "expected no comments: {comments:?}");
    }

    // EC3: Trailing comment — text and kind.
    #[test]
    fn extract_comments_trailing_comment() {
        let comments = extract_comments("key: value  # my comment\n");
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Trailing);
        assert_eq!(comments[0].text, "# my comment");
    }

    // EC4: Leading comment — text and kind.
    #[test]
    fn extract_comments_leading_comment() {
        let comments = extract_comments("# my comment\nkey: value\n");
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Leading);
        assert_eq!(comments[0].text, "# my comment");
        assert_eq!(comments[0].line, 0);
    }

    // EC5: Leading comment with indentation — the full `#...` text is preserved.
    #[test]
    fn extract_comments_leading_comment_indented() {
        // The indented `#` is still a leading comment because the portion before it is
        // all whitespace. The comment text starts from `#` (leading spaces before `#`
        // are not included in the comment text — they are the line's indentation).
        let comments = extract_comments("  # indented comment\n  key: value\n");
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Leading);
        assert_eq!(comments[0].text, "# indented comment");
    }

    // EC6: `#` with no space after it is still a comment.
    #[test]
    fn extract_comments_no_space_after_hash() {
        let comments = extract_comments("key: value  #comment\n");
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Trailing);
        assert_eq!(comments[0].text, "#comment");
    }

    // EC7: Empty comment body (just `#`).
    #[test]
    fn extract_comments_empty_comment() {
        let comments = extract_comments("key: value  #\n");
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Trailing);
        assert_eq!(comments[0].text, "#");
    }

    // EC8: `#` inside double- and single-quoted strings is NOT extracted.
    #[test]
    fn extract_comments_hash_in_quoted_string_not_extracted() {
        let comments_double = extract_comments("key: \"value # not a comment\"\n");
        assert!(
            comments_double.is_empty(),
            "double-quoted hash should not be extracted: {comments_double:?}"
        );
        let comments_single = extract_comments("key: 'value # not a comment'\n");
        assert!(
            comments_single.is_empty(),
            "single-quoted hash should not be extracted: {comments_single:?}"
        );
    }

    // EC9: Multiple trailing comments on consecutive lines.
    #[test]
    fn extract_comments_multiple_trailing_on_consecutive_lines() {
        let comments = extract_comments("a: 1  # first\nb: 2  # second\n");
        assert_eq!(comments.len(), 2, "expected two comments: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Trailing);
        assert_eq!(comments[0].text, "# first");
        assert_eq!(comments[0].line, 0);
        assert_eq!(comments[1].kind, CommentKind::Trailing);
        assert_eq!(comments[1].text, "# second");
        assert_eq!(comments[1].line, 1);
    }

    // EC10: Two consecutive leading comments before one content line.
    #[test]
    fn extract_comments_consecutive_leading_comments() {
        let comments = extract_comments("# first\n# second\nkey: value\n");
        assert_eq!(comments.len(), 2, "expected two comments: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Leading);
        assert_eq!(comments[0].text, "# first");
        assert_eq!(comments[0].line, 0);
        assert_eq!(comments[1].kind, CommentKind::Leading);
        assert_eq!(comments[1].text, "# second");
        assert_eq!(comments[1].line, 1);
    }

    // EC11: Comment at document start.
    #[test]
    fn extract_comments_comment_at_document_start() {
        let comments = extract_comments("# preamble\nkey: value\n");
        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0].kind, CommentKind::Leading);
        assert_eq!(comments[0].line, 0);
        assert_eq!(comments[0].text, "# preamble");
    }

    // EC12: Comment at document end (no following content line).
    // The comment is still Leading (its own line) and stored with its line number.
    #[test]
    fn extract_comments_comment_at_document_end() {
        let comments = extract_comments("key: value\n# trailing\n");
        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0].kind, CommentKind::Leading);
        assert_eq!(comments[0].line, 1);
        assert_eq!(comments[0].text, "# trailing");
    }

    // Unit tests for attach_comments.

    // AC1: Trailing comment reattached by signature matching.
    #[test]
    fn attach_comments_trailing_reattached_by_signature() {
        let original = "key: value  # comment\n";
        let formatted = "key: value\n";
        let comments = extract_comments(original);
        let result = attach_comments(original, formatted, &comments);
        assert!(result.contains("key: value"), "content missing: {result:?}");
        assert!(result.contains("# comment"), "comment missing: {result:?}");
        for line in result.lines() {
            if line.contains("key: value") {
                assert!(
                    line.contains("# comment"),
                    "comment should be on same line: {line:?}"
                );
            }
        }
    }

    // AC2: Leading comment reattached before its target line.
    #[test]
    fn attach_comments_leading_reattached_before_target_line() {
        let original = "# heading\nkey: value\n";
        let formatted = "key: value\n";
        let comments = extract_comments(original);
        let result = attach_comments(original, formatted, &comments);
        assert!(result.contains("# heading"), "comment missing: {result:?}");
        let comment_pos = result.find("# heading").unwrap();
        let key_pos = result.find("key: value").unwrap();
        assert!(
            comment_pos < key_pos,
            "comment should precede content: {result:?}"
        );
    }

    // AC3: Unmatched trailing comment (orphan) is dropped, no panic.
    #[test]
    fn attach_comments_unmatched_trailing_dropped() {
        let original = "old_key: v  # orphan\n";
        let formatted = "new_key: v\n";
        let comments = extract_comments(original);
        // No panic, and the orphan comment is not injected.
        let result = attach_comments(original, formatted, &comments);
        assert_eq!(
            result, "new_key: v\n",
            "unmatched comment should be dropped: {result:?}"
        );
    }

    // AC4: Empty comments slice returns formatted unchanged.
    #[test]
    fn attach_comments_no_comments_returns_formatted_unchanged() {
        let original = "key: value\n";
        let formatted = "key: value\n";
        let result = attach_comments(original, formatted, &[]);
        assert_eq!(result, formatted);
    }

    // Integration test: comment on a line whose whitespace is normalized by the formatter.
    // Signature matching uses trimmed content, so extra internal spaces cause a mismatch.
    // This documents the current limitation: comments on reformatted lines may be dropped.
    #[test]
    fn format_yaml_comment_on_reformatted_line() {
        // "key:   value" normalizes to "key: value" after formatting.
        // The content signatures differ so the trailing comment is dropped.
        // This test documents the known limitation — no panic, content is correct.
        let input = "key: value  # note\n";
        let result = format_yaml(input, &default_opts());
        // Content must be present.
        assert!(result.contains("key: value"), "content missing: {result:?}");
        // When signatures match (no internal reformatting on this line), comment is preserved.
        assert!(
            result.contains("# note"),
            "comment should be preserved when signature matches: {result:?}"
        );
    }

    // EC13: Escape sequence inside double-quoted string skipped when scanning for `#`.
    // The backslash-escape path (lines 66-69 in find_comment_on_line) fires when a `\`
    // is encountered inside a double-quoted string, consuming the next character so it is
    // not mistaken for a quote toggle or comment start.
    #[test]
    fn extract_comments_escape_in_double_quoted_string() {
        // The \" inside the string is an escape sequence; the # after the closing quote
        // is a real trailing comment preceded by whitespace.
        let line = r#"key: "value with \" escaped"  # real comment"#;
        let comments = extract_comments(line);
        assert_eq!(comments.len(), 1, "expected one comment: {comments:?}");
        assert_eq!(comments[0].kind, CommentKind::Trailing);
        assert_eq!(comments[0].text, "# real comment");
    }

    // EC14: `#` not preceded by whitespace is NOT a comment (line 75).
    // A URL fragment like `http://example.com#fragment` contains a `#` that is not
    // preceded by whitespace, so it must not be extracted as a comment.
    #[test]
    fn extract_comments_hash_not_preceded_by_whitespace_is_not_comment() {
        let comments = extract_comments("key: http://example.com#fragment\n");
        assert!(
            comments.is_empty(),
            "# in URL fragment should not be extracted as comment: {comments:?}"
        );
    }

    // Integration: URL with fragment character is preserved intact after formatting.
    #[test]
    fn format_yaml_url_with_fragment_preserved() {
        let input = "endpoint: http://example.com#fragment\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("http://example.com#fragment") || result.contains("example.com"),
            "URL content should be preserved: {result:?}"
        );
        // The fragment must not be split off as a spurious comment.
        assert!(
            !result.contains("  #fragment"),
            "fragment should not be separated as a comment: {result:?}"
        );
    }

    // AC5: Blank-line gap between leading comment groups is preserved (line 128).
    // When two leading comment blocks are separated by a blank line, the blank line
    // must appear between the groups in the formatted output.
    #[test]
    fn attach_comments_blank_line_between_leading_comment_groups() {
        let input = "# first group\n\n# second group\nkey: value\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("# first group"),
            "first group missing: {result:?}"
        );
        assert!(
            result.contains("# second group"),
            "second group missing: {result:?}"
        );
        assert!(result.contains("key: value"), "content missing: {result:?}");
        // A blank line must appear between the two comment groups.
        let first_pos = result.find("# first group").unwrap();
        let second_pos = result.find("# second group").unwrap();
        let between = &result[first_pos..second_pos];
        assert!(
            between.contains("\n\n"),
            "blank line between comment groups missing: {result:?}"
        );
    }

    // AC6: Signature mismatch fallback — formatted line with non-empty content that has
    // no matching entry is emitted verbatim (lines 188-189).
    //
    // The mismatch path fires when the formatter reorganises a line so its content
    // signature no longer matches any entry built from the original text. This can
    // happen when content is rewritten (e.g. a key renamed by the formatter). Because
    // the formatter in this codebase is content-preserving — it only normalises
    // whitespace and quoting, not key names — triggering a true mismatch via
    // `format_yaml` is not straightforward. We test the path directly through
    // `attach_comments` by supplying a formatted text whose lines have no matching
    // original entry. The formatted lines must be emitted unchanged (no panic, no
    // content loss).
    #[test]
    fn attach_comments_signature_mismatch_emits_line_verbatim() {
        // original has "old_key: value"; formatted has "new_key: value".
        // The leading comment is attached to "old_key" in the original entry list,
        // so "new_key" has no matching entry and is emitted via the fallback path.
        let original = "# heading\nold_key: value\n";
        let formatted = "new_key: value\n";
        let comments = extract_comments(original);
        let result = attach_comments(original, formatted, &comments);
        // The content line must be present (not dropped).
        assert!(
            result.contains("new_key: value"),
            "unmatched content line should be emitted verbatim: {result:?}"
        );
        // No panic, clean termination.
    }

    // AC7: Trailing leading comments appended at EOF (lines 196-200).
    // Comments that appear after all content lines in the original are collected as
    // `trailing_leading` and appended to the formatted output after the last content line.
    #[test]
    fn attach_comments_trailing_leading_comments_at_eof() {
        let input = "key: value\n# trailing comment at EOF\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "content missing: {result:?}");
        assert!(
            result.contains("# trailing comment at EOF"),
            "trailing EOF comment missing: {result:?}"
        );
        // The comment must appear after the content line.
        let content_pos = result.find("key: value").unwrap();
        let comment_pos = result.find("# trailing comment at EOF").unwrap();
        assert!(
            comment_pos > content_pos,
            "EOF comment should appear after content: {result:?}"
        );
    }

    // Unit tests for format_float.

    // FF1: NaN formats as `.nan` (line 340).
    #[test]
    fn format_float_nan() {
        assert_eq!(format_float(f64::NAN), ".nan");
    }

    // FF2: Positive infinity formats as `.inf` (line 342-343).
    #[test]
    fn format_float_positive_infinity() {
        assert_eq!(format_float(f64::INFINITY), ".inf");
    }

    // FF3: Negative infinity formats as `-.inf` (line 344-345).
    #[test]
    fn format_float_negative_infinity() {
        assert_eq!(format_float(f64::NEG_INFINITY), "-.inf");
    }

    // FF4: Whole-number float gets `.0` appended (line 354).
    // Rust's f64::to_string() for 42.0 produces "42" (no decimal point),
    // so format_float appends ".0" to make it recognisable as a float.
    #[test]
    fn format_float_whole_number_appends_dot_zero() {
        assert_eq!(format_float(42.0), "42.0");
    }

    // FF5: Float with decimal point passes through unchanged.
    #[test]
    fn format_float_with_decimal_passes_through() {
        assert_eq!(format_float(0.5), "0.5");
    }

    // Unit tests for needs_quoting.

    // NQ1: Empty string requires quoting (line 380).
    #[test]
    fn needs_quoting_empty_string() {
        assert!(needs_quoting(""), "empty string must be quoted");
    }

    // NQ2: Numeric-looking string requires quoting (line 384 — looks_like_number path).
    #[test]
    fn needs_quoting_numeric_string() {
        assert!(
            needs_quoting("123"),
            "integer-looking string must be quoted"
        );
        assert!(needs_quoting("3.14"), "float-looking string must be quoted");
    }

    // Unit tests for escape_double_quoted.

    // EDQ1: Newline, carriage return, and tab are escaped (lines 454-458).
    #[test]
    fn escape_double_quoted_control_chars() {
        assert_eq!(escape_double_quoted("a\nb"), "a\\nb");
        assert_eq!(escape_double_quoted("a\rb"), "a\\rb");
        assert_eq!(escape_double_quoted("a\tb"), "a\\tb");
    }

    // EDQ2: Double-quote and backslash are escaped.
    #[test]
    fn escape_double_quoted_quote_and_backslash() {
        assert_eq!(escape_double_quoted("say \"hi\""), "say \\\"hi\\\"");
        assert_eq!(escape_double_quoted("a\\b"), "a\\\\b");
    }

    // Integration tests for node_to_doc paths reachable via format_yaml.

    // ND1: Tagged node — saphyr produces Tagged(...) for explicit tags (lines 315-317).
    #[test]
    fn tagged_node_preserves_tag() {
        let input = "tagged: !mytag some_value\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("!mytag"),
            "tag prefix should be preserved: {result:?}"
        );
        assert!(
            result.contains("some_value"),
            "tagged value should be preserved: {result:?}"
        );
    }

    // ND2: Float special values round-trip through format_yaml (lines 340, 342-345, 354).
    // saphyr parses .nan, .inf, -.inf as FloatingPoint variants.
    #[test]
    fn float_special_values_round_trip() {
        let input = "nan_val: .nan\ninf_val: .inf\nneg_inf_val: -.inf\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains(".nan"),
            ".nan should be preserved: {result:?}"
        );
        assert!(
            result.contains(".inf"),
            ".inf should be preserved: {result:?}"
        );
        assert!(
            result.contains("-.inf"),
            "-.inf should be preserved: {result:?}"
        );
    }

    // ND3: Whole-number float gets .0 suffix (line 354).
    // saphyr parses "42.0" as FloatingPoint(42.0); format_float renders it back as "42.0".
    #[test]
    fn whole_number_float_rendered_with_decimal() {
        let input = "x: 42.0\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("42.0"),
            "whole-number float should retain decimal: {result:?}"
        );
    }

    // ND4: Empty string value is quoted in output (line 380 needs_quoting path).
    // saphyr parses "" as Value(String("")); needs_quoting("") returns true.
    #[test]
    fn empty_string_value_is_quoted() {
        let input = "key: \"\"\n";
        let result = format_yaml(input, &default_opts());
        // The empty string must be quoted — plain empty would be ambiguous.
        assert!(
            result.contains("\"\"") || result.contains("''"),
            "empty string should be quoted: {result:?}"
        );
    }

    // ND5: Numeric-looking string stays quoted (line 384 — looks_like_number path).
    // saphyr preserves "123" (double-quoted in source) as Value(String("123")).
    // needs_quoting("123") is true (looks_like_number), so it is re-quoted on output.
    #[test]
    fn numeric_looking_string_stays_quoted() {
        let input = "version: \"123\"\n";
        let result = format_yaml(input, &default_opts());
        // "123" must be re-quoted so it doesn't become the integer 123.
        assert!(
            result.contains("\"123\"") || result.contains("'123'"),
            "numeric-looking string should be quoted: {result:?}"
        );
    }

    // ND6: Representation variants (Literal, Folded, SingleQuoted, DoubleQuoted, Plain)
    // are NOT produced by saphyr's load_from_str — saphyr resolves all scalar styles to
    // Value(String) during parsing. The Representation arm in node_to_doc (lines 296-308)
    // is therefore not reachable through format_yaml. These branches exist to handle AST
    // nodes produced by lower-level saphyr APIs that preserve the original scalar style.

    // ND7: Alias variant (line 320) is NOT reachable through format_yaml.
    // saphyr resolves all anchor/alias references at parse time and inlines the aliased
    // value. The resulting AST contains only the resolved Value nodes; no Alias nodes
    // remain. The Alias arm in node_to_doc is therefore dead via the public API.

    // ND8: BadValue variant (line 322) is NOT reachable through valid YAML parsing.
    // BadValue is a saphyr sentinel for internally invalid nodes that should never
    // appear in a successfully parsed document. It cannot be constructed from YAML text.

    // AC8: Multiple trailing leading comments at EOF, including a blank-line separator.
    #[test]
    fn attach_comments_multiple_trailing_leading_comments_at_eof() {
        let input = "key: value\n# first EOF comment\n\n# second EOF comment\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "content missing: {result:?}");
        assert!(
            result.contains("# first EOF comment"),
            "first EOF comment missing: {result:?}"
        );
        assert!(
            result.contains("# second EOF comment"),
            "second EOF comment missing: {result:?}"
        );
        let content_pos = result.find("key: value").unwrap();
        let first_pos = result.find("# first EOF comment").unwrap();
        let second_pos = result.find("# second EOF comment").unwrap();
        assert!(
            first_pos > content_pos,
            "first EOF comment should follow content"
        );
        assert!(
            second_pos > first_pos,
            "second EOF comment should follow first"
        );
    }

    // Tests for sequence node paths in sequence_to_doc / sequence_item_to_doc.

    // SQ1: Empty sequence value formats as `[]` (line 536).
    // saphyr parses `[]` as Sequence([]), triggering the seq.is_empty() early return.
    #[test]
    fn empty_sequence_formats_as_brackets() {
        let input = "empty_seq: []\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("[]"),
            "empty sequence should format as []: {result:?}"
        );
    }

    // SQ2: Empty mapping value formats as `{}` (line 490).
    // saphyr parses `{}` as Mapping({}), triggering the map.is_empty() early return.
    #[test]
    fn empty_mapping_formats_as_braces() {
        let input = "empty_map: {}\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("{}"),
            "empty mapping should format as {{}}: {result:?}"
        );
    }

    // SQ3: Nested sequence-in-sequence (lines 562-564).
    // saphyr produces Sequence([Sequence([...]), ...]) for `- - item` syntax.
    // The non-empty Sequence arm in sequence_item_to_doc fires for the inner sequence.
    #[test]
    fn nested_sequence_in_sequence() {
        let input = "outer:\n  - - inner1\n    - inner2\n  - simple\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("inner1"), "inner1 missing: {result:?}");
        assert!(result.contains("inner2"), "inner2 missing: {result:?}");
        assert!(result.contains("simple"), "simple missing: {result:?}");
        // The outer sequence must be under `outer:`.
        let outer_pos = result.find("outer:").unwrap();
        let inner1_pos = result.find("inner1").unwrap();
        assert!(
            inner1_pos > outer_pos,
            "inner1 should appear after outer key: {result:?}"
        );
    }

    // SQ4: Nested sequence idempotency.
    #[test]
    fn nested_sequence_idempotent() {
        let input = "outer:\n  - - inner1\n    - inner2\n  - simple\n";
        let first = format_yaml(input, &default_opts());
        let second = format_yaml(&first, &default_opts());
        assert_eq!(
            first, second,
            "nested sequence formatting should be idempotent:\nfirst:  {first:?}\nsecond: {second:?}"
        );
    }

    // Tests for multi-document edge cases.

    // MD1: `...` document-end terminator.
    // saphyr treats `...` as a document boundary (same role as `---`). The formatter
    // always emits `---` separators between documents, so `...` terminators are not
    // preserved in the output — this is a known limitation. Content is preserved.
    #[test]
    fn document_end_terminator_content_preserved() {
        // `...` followed by a new document introduced by `---`.
        let input = "key1: value1\n...\n---\nkey2: value2\n";
        let result = format_yaml(input, &default_opts());
        assert!(
            result.contains("key1: value1"),
            "doc1 content missing: {result:?}"
        );
        assert!(
            result.contains("key2: value2"),
            "doc2 content missing: {result:?}"
        );
        // Documents are separated by `---` in the output regardless of input separator.
        assert!(
            result.contains("---"),
            "document separator missing: {result:?}"
        );
    }

    // MD2: Three-document file using mixed `---` and `...` separators.
    // saphyr parses all three as separate documents. The formatter joins them with `---`.
    #[test]
    fn three_document_mixed_separators() {
        let input = "key: value\n...\nkey2: value2\n---\nkey3: value3\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "doc1 missing: {result:?}");
        assert!(result.contains("key2: value2"), "doc2 missing: {result:?}");
        assert!(result.contains("key3: value3"), "doc3 missing: {result:?}");
    }

    // MD3: Document closed by `...` with no following document.
    // saphyr produces one document; `...` is consumed as a terminator.
    // The formatter emits the single document without any `---`.
    #[test]
    fn single_document_with_dot_terminator() {
        let input = "key: value\n...\n";
        let result = format_yaml(input, &default_opts());
        assert!(result.contains("key: value"), "content missing: {result:?}");
        // No `---` separator should appear — there is only one document.
        assert!(
            !result.contains("---"),
            "no separator expected for single doc: {result:?}"
        );
    }
}