quillmark-core 0.74.0

Core types and functionality for Quillmark
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
//! Canonical Markdown emission for [`Document`].
//!
//! This module implements [`Document::to_markdown`], which converts a typed
//! in-memory `Document` back into canonical Quillmark Markdown.
//!
//! ## YAML emission strategy
//!
//! `serde-saphyr::SerializerOptions::quote_all` was evaluated (spike, 2026-04-21)
//! and found to emit single-quoted strings for ordinary scalars like `"on"` and
//! `"01234"` — switching to double quotes only when the string contains a single
//! quote, backslash, or control character.  That behaviour is correct for
//! round-trip type-fidelity (single-quoted YAML strings are re-parsed as strings),
//! but the Quillmark spec (§5.2) requires **always double-quoted, JSON-style
//! escaping**.  Because `SerializerOptions` provides no "force double-quote" knob,
//! the YAML value block is generated by a hand-written emitter in this module.
//!
//! The hand-written emitter is small (< 120 lines), covers exactly the
//! `QuillValue` type variants, and gives complete control over quoting style and
//! indentation without pulling in additional abstractions.

use serde_json::Value as JsonValue;

use super::frontmatter::FrontmatterItem;
use super::prescan::{CommentPathSegment, NestedComment};
use super::{Card, Document, Sentinel};

// ── Public entry point ────────────────────────────────────────────────────────

impl Document {
    /// Emit canonical Quillmark Markdown from this document.
    ///
    /// # Contract
    ///
    /// 1. **Type-fidelity round-trip.** `Document::from_markdown(&doc.to_markdown())`
    ///    returns a `Document` equal to `doc` by value *and* by type variant.
    ///    `QuillValue::String("on")` round-trips as a string, never as a bool.
    ///    `QuillValue::String("01234")` round-trips as a string, never as an
    ///    integer.  This guarantee is the whole point of owning emission.
    ///
    /// 2. **Emit-idempotent.** `to_markdown` is a pure function of `doc`; two
    ///    calls on the same `doc` return byte-equal strings.
    ///
    /// Byte-equality with the *original source* is **not** guaranteed.
    ///
    /// # Emission rules (§5.2)
    ///
    /// - Line endings: `\n` only.  CRLF normalization happens on import.
    /// - Frontmatter: `---\n`, `QUILL: <ref>` first, remaining fields in
    ///   `IndexMap` insertion order, `---\n`, blank line.
    /// - Cards: one blank line before each, fence `---\nCARD: <tag>\n<fields>\n---\n<body>`.
    /// - Body: emitted verbatim after frontmatter (and cards).
    /// - Mappings and sequences: **block style** at every nesting level.
    /// - Booleans: `true` / `false`.
    /// - Null: `null`.
    /// - Numbers: bare literals (integer or float as stored in `serde_json::Value`).
    /// - **Strings: always double-quoted**, JSON-style escaping
    ///   (`\"`, `\\`, `\n`, `\t`, `\uXXXX` for control chars).  This is the
    ///   load-bearing rule that guarantees type fidelity.
    /// - Multi-line strings: double-quoted with `\n` escape sequences.  No block
    ///   scalars (`|`, `>`) in v1.
    ///
    /// # Open decisions (resolved)
    ///
    /// - **Nested-map order.** `QuillValue` is backed by `serde_json::Value`
    ///   whose object type (`serde_json::Map`) preserves insertion order when the
    ///   `serde_json/preserve_order` feature is enabled (it is in this workspace).
    ///   Insertion order is therefore preserved for nested maps at emit time.
    ///
    /// - **Empty containers.**
    ///   - Empty object (`{}`) → the key is **omitted** from emit entirely.
    ///   - Empty array (`[]`) → emitted as `key: []\n`.
    ///
    /// # What is preserved
    ///
    /// - **YAML comments**: own-line and inline trailing comments round-trip
    ///   at their source position. Inline comments on sentinel lines
    ///   (`QUILL: r # …` / `CARD: t # …`) round-trip too. Comments whose
    ///   host disappears at emit time (empty-mapping omission, programmatic
    ///   field removal) degrade to own-line comments at the same indent so
    ///   the comment text is preserved even when its position shifts.
    /// - **`!fill` tags**: round-trip via the `fill` flag on `FrontmatterItem::Field`.
    ///
    /// # What is lost
    ///
    /// - **Other custom tags** (`!include`, `!env`, …): the tag is dropped;
    ///   the scalar value is preserved.
    /// - **Original quoting style**: all strings are re-emitted double-quoted
    ///   regardless of how they were written in the source.
    pub fn to_markdown(&self) -> String {
        let mut out = String::new();

        // ── Main card (first fence + global body) ─────────────────────────────
        emit_card_fence(&mut out, self.main());
        out.push_str(self.main().body());

        // ── Composable cards ──────────────────────────────────────────────────
        // `emit_card` normalises the separator before each fence, so edited
        // bodies (which may lack a trailing blank line) still round-trip.
        for card in self.cards() {
            ensure_f2_before_fence(&mut out);
            emit_card_fence(&mut out, card);
            if !card.body().is_empty() {
                out.push_str(card.body());
            }
        }

        out
    }
}

// ── Card emission ─────────────────────────────────────────────────────────────

/// Emit a card's metadata fence (between `---\n` markers), including the
/// sentinel line and every frontmatter item.
///
/// ## Inline-comment handling
///
/// - **Sentinel-inline preview.** If `items[0]` is a `Comment{inline:true}`,
///   its text is appended to the sentinel line (`QUILL: r # text` /
///   `CARD: tag # text`) and the item is skipped. This is the only way to
///   round-trip a source-level inline comment on the sentinel line.
/// - **Field + trailing inline.** When iterating items, a `Field` peeks at
///   its successor: if the next item is `Comment{inline:true}`, the comment
///   text is passed to `emit_field` as a trailer and consumed here. The
///   trailer lands on the field's key/value line.
/// - **Orphan inline.** A `Comment{inline:true}` that is *not* consumed by
///   either the sentinel preview or a field's lookahead has no host. It is
///   emitted as an own-line `# text` comment instead. This is also the
///   degrade path for empty-object fields (whose key is omitted) — the
///   trailer becomes an own-line comment at the same indent.
fn emit_card_fence(out: &mut String, card: &Card) {
    out.push_str("---\n");

    // Sentinel line.
    match card.sentinel() {
        Sentinel::Main(r) => {
            out.push_str("QUILL: ");
            out.push_str(&r.to_string());
            out.push('\n');
        }
        Sentinel::Card(tag) => {
            out.push_str("CARD: ");
            out.push_str(tag);
            out.push('\n');
        }
    }

    let nested = card.frontmatter().nested_comments();
    let items = card.frontmatter().items();
    let mut i = 0;

    // Sentinel-inline preview.
    if let Some(FrontmatterItem::Comment { text, inline: true }) = items.first() {
        attach_inline_to_last_line(out, text);
        i = 1;
    }

    while i < items.len() {
        match &items[i] {
            FrontmatterItem::Field { key, value, fill } => {
                let trailer = items.get(i + 1).and_then(|next| match next {
                    FrontmatterItem::Comment { text, inline: true } => Some(text.as_str()),
                    _ => None,
                });
                let path = vec![CommentPathSegment::Key(key.clone())];
                emit_field(out, key, value.as_json(), 0, *fill, &path, nested, trailer);
                i += if trailer.is_some() { 2 } else { 1 };
            }
            FrontmatterItem::Comment { text, .. } => {
                // Either own-line, or an inline orphan (lookahead would have
                // consumed any inline whose predecessor was a Field). Both
                // render as own-line.
                out.push_str("# ");
                out.push_str(text);
                out.push('\n');
                i += 1;
            }
        }
    }

    out.push_str("---\n");
}

/// Ensures `out` ends with a `\n\n` suffix suitable for the F2 precondition
/// of the next metadata fence.
///
/// Under the F2-separator-never-stored invariant, stored bodies may end with
/// their content (no newline), a content line terminator (`\n`), or an
/// author-intended blank line (`\n\n`, `\n\n\n`, …). In every case we append
/// exactly one `\n` to produce the F2 blank line. If the body doesn't already
/// end in `\n`, we also append a line terminator first so content lines are
/// terminated in the emitted markdown.
///
/// Empty `out` satisfies F2 via the "line 1" clause (MARKDOWN.md §3 F2) and
/// needs no separator.
fn ensure_f2_before_fence(out: &mut String) {
    if out.is_empty() {
        return;
    }
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out.push('\n');
}

// ── YAML value emission ───────────────────────────────────────────────────────

/// Strip the trailing `\n` from `out`, append ` # text`, and restore `\n`.
///
/// The caller is responsible for ensuring the previous line is a valid host
/// for an inline comment (a field/sequence-item line, not a fence or another
/// comment line).
fn attach_inline_to_last_line(out: &mut String, text: &str) {
    if !out.ends_with('\n') {
        // Defensive: shouldn't happen given how this is called.
        out.push_str(" # ");
        out.push_str(text);
        out.push('\n');
        return;
    }
    out.pop();
    out.push_str(" # ");
    out.push_str(text);
    out.push('\n');
}

/// Emit own-line nested comments at `position` in `path` as `# text` lines
/// indented by `indent` spaces. Inline comments are skipped here — they are
/// consumed by `find_inline_trailer` at the host's emission site.
fn emit_own_line_pending(
    out: &mut String,
    path: &[CommentPathSegment],
    position: usize,
    indent: usize,
    nested: &[NestedComment],
) {
    for c in nested {
        if c.position == position && !c.inline && c.container_path.as_slice() == path {
            push_indent(out, indent);
            out.push_str("# ");
            out.push_str(&c.text);
            out.push('\n');
        }
    }
}

/// Look up the inline trailer for the child at `position` in `path`. If
/// multiple inline comments share this slot (programmatic edge case), the
/// first one is returned and the rest are emitted as own-line comments at
/// `indent` to preserve their text.
fn find_inline_trailer<'a>(
    out: &mut String,
    path: &[CommentPathSegment],
    position: usize,
    indent: usize,
    nested: &'a [NestedComment],
) -> Option<&'a str> {
    let mut chosen: Option<&str> = None;
    for c in nested {
        if c.position == position && c.inline && c.container_path.as_slice() == path {
            if chosen.is_none() {
                chosen = Some(c.text.as_str());
            } else {
                push_indent(out, indent);
                out.push_str("# ");
                out.push_str(&c.text);
                out.push('\n');
            }
        }
    }
    chosen
}

/// Emit any orphan inline comments (`inline=true` with `position >=
/// container_len`) as own-line comments at the trailing slot. These are
/// programmatic edge cases — well-formed prescan output never produces them.
fn emit_orphan_inlines(
    out: &mut String,
    path: &[CommentPathSegment],
    container_len: usize,
    indent: usize,
    nested: &[NestedComment],
) {
    for c in nested {
        if c.inline && c.position >= container_len && c.container_path.as_slice() == path {
            push_indent(out, indent);
            out.push_str("# ");
            out.push_str(&c.text);
            out.push('\n');
        }
    }
}

/// Append ` # trailer` to `out` if `trailer` is `Some`. Caller writes the
/// terminating `\n` afterwards.
fn push_trailer(out: &mut String, trailer: Option<&str>) {
    if let Some(t) = trailer {
        out.push_str(" # ");
        out.push_str(t);
    }
}

/// Emit a `key: <value>\n` pair at `indent` spaces.
///
/// `path` is the path to *this* field (parent path + this key). It's used as
/// the *container* path when recursing into the value: nested comments
/// captured at this path are interleaved between the value's children.
///
/// `inline_trailer`, when `Some`, is rendered as ` # text` on the field's
/// key/value line. For scalars this trails the value; for containers it
/// trails the `key:` line (before the indented children).
///
/// - Empty objects are **omitted** (caller skips them). An empty-object
///   field with an inline trailer degrades the trailer to an own-line
///   comment at `indent`, so the comment text is preserved even though its
///   host disappears.
/// - Empty arrays emit `key: []\n`.
/// - All other values follow the block-style rules.
/// - When `fill` is `true`, the emitted form is `key: !fill <value>` for
///   scalars, `key: !fill\n  - …` for non-empty sequences,
///   `key: !fill []` for empty sequences, and `key: !fill` for null.
///   Mappings are rejected at parse and never reach this path.
fn emit_field(
    out: &mut String,
    key: &str,
    value: &JsonValue,
    indent: usize,
    fill: bool,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
    inline_trailer: Option<&str>,
) {
    if fill {
        push_indent(out, indent);
        out.push_str(key);
        match value {
            JsonValue::Null => {
                out.push_str(": !fill");
                push_trailer(out, inline_trailer);
                out.push('\n');
            }
            JsonValue::Bool(_) | JsonValue::Number(_) | JsonValue::String(_) => {
                out.push_str(": !fill ");
                emit_scalar(out, value);
                push_trailer(out, inline_trailer);
                out.push('\n');
            }
            JsonValue::Array(items) if items.is_empty() => {
                out.push_str(": !fill []");
                push_trailer(out, inline_trailer);
                out.push('\n');
            }
            JsonValue::Array(items) => {
                out.push_str(": !fill");
                push_trailer(out, inline_trailer);
                out.push('\n');
                emit_sequence_children(out, items, indent + 2, path, nested);
            }
            JsonValue::Object(_) => {
                // Parser rejects !fill on mappings; recovery path only.
                out.push_str(": ");
                emit_scalar(out, value);
                push_trailer(out, inline_trailer);
                out.push('\n');
            }
        }
        return;
    }
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            // Empty object → omit the key entirely. If there's an inline
            // trailer, degrade it to an own-line comment so its text isn't
            // lost.
            if let Some(t) = inline_trailer {
                push_indent(out, indent);
                out.push_str("# ");
                out.push_str(t);
                out.push('\n');
            }
        }
        JsonValue::Object(map) => {
            push_indent(out, indent);
            out.push_str(key);
            out.push(':');
            push_trailer(out, inline_trailer);
            out.push('\n');
            emit_mapping_children(out, map, indent + 2, path, nested);
        }
        JsonValue::Array(items) if items.is_empty() => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(": []");
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
        JsonValue::Array(items) => {
            push_indent(out, indent);
            out.push_str(key);
            out.push(':');
            push_trailer(out, inline_trailer);
            out.push('\n');
            emit_sequence_children(out, items, indent + 2, path, nested);
        }
        _ => {
            push_indent(out, indent);
            out.push_str(key);
            out.push_str(": ");
            emit_scalar(out, value);
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
    }
}

/// Emit the children of a mapping value with comment interleaving.
///
/// `child_indent` is the indent at which each child key sits; nested
/// comments inside this mapping are emitted at the same indent. `path` is
/// the path to the mapping container (its key in the parent).
fn emit_mapping_children(
    out: &mut String,
    map: &serde_json::Map<String, JsonValue>,
    child_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    for (i, (k, v)) in map.iter().enumerate() {
        emit_own_line_pending(out, path, i, child_indent, nested);
        let trailer = find_inline_trailer(out, path, i, child_indent, nested);
        let mut child_path = path.to_vec();
        child_path.push(CommentPathSegment::Key(k.clone()));
        emit_field(out, k, v, child_indent, false, &child_path, nested, trailer);
    }
    emit_own_line_pending(out, path, map.len(), child_indent, nested);
    emit_orphan_inlines(out, path, map.len(), child_indent, nested);
}

/// Emit the children of a sequence value with comment interleaving.
///
/// `base_indent` is the indent at which each `- ` sits; nested comments
/// inside this sequence are emitted at the same indent.
fn emit_sequence_children(
    out: &mut String,
    items: &[JsonValue],
    base_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
) {
    for (i, item) in items.iter().enumerate() {
        emit_own_line_pending(out, path, i, base_indent, nested);
        let trailer = find_inline_trailer(out, path, i, base_indent, nested);
        let mut child_path = path.to_vec();
        child_path.push(CommentPathSegment::Index(i));
        emit_sequence_item(out, item, base_indent, &child_path, nested, trailer);
    }
    emit_own_line_pending(out, path, items.len(), base_indent, nested);
    emit_orphan_inlines(out, path, items.len(), base_indent, nested);
}

/// Emit a single `- <value>\n` sequence item at `base_indent` spaces.
///
/// `path` is the path to *this* item (parent path + item index).
///
/// `inline_trailer`, when `Some`, is rendered as ` # text` on the `-` line.
/// For mapping items the trailer co-exists with any inline trailer at index
/// 0 of the inner mapping (the latter would be on the same physical line);
/// in well-formed input only one of them is present, but if both appear
/// the inner one degrades to an own-line comment beneath the `- ` line.
fn emit_sequence_item(
    out: &mut String,
    value: &JsonValue,
    base_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
    inline_trailer: Option<&str>,
) {
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            // Empty nested object in a sequence: emit as `- {}`
            push_indent(out, base_indent);
            out.push_str("- {}");
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
        JsonValue::Object(map) => {
            // Block mapping inside a sequence. First key on the same line
            // as `- `; subsequent keys indented by 2. Comments inside this
            // mapping use this item's path as the container.
            emit_own_line_pending(out, path, 0, base_indent, nested);

            let mut first = true;
            for (i, (k, v)) in map.iter().enumerate() {
                if !first {
                    emit_own_line_pending(out, path, i, base_indent + 2, nested);
                }
                let inner_trailer = find_inline_trailer(out, path, i, base_indent + 2, nested);
                let mut child_path = path.to_vec();
                child_path.push(CommentPathSegment::Key(k.clone()));
                if first {
                    // The seq-item's trailer and the first key's trailer
                    // both target the `- key: ...` line. Prefer the
                    // seq-item's; degrade the loser to own-line.
                    let line_trailer = inline_trailer.or(inner_trailer);
                    push_indent(out, base_indent);
                    out.push_str("- ");
                    emit_field_inline(
                        out,
                        k,
                        v,
                        base_indent + 2,
                        &child_path,
                        nested,
                        line_trailer,
                    );
                    if let (Some(_), Some(loser)) = (inline_trailer, inner_trailer) {
                        push_indent(out, base_indent + 2);
                        out.push_str("# ");
                        out.push_str(loser);
                        out.push('\n');
                    }
                    first = false;
                } else {
                    emit_field(
                        out,
                        k,
                        v,
                        base_indent + 2,
                        false,
                        &child_path,
                        nested,
                        inner_trailer,
                    );
                }
            }
            emit_own_line_pending(out, path, map.len(), base_indent + 2, nested);
            emit_orphan_inlines(out, path, map.len(), base_indent + 2, nested);
        }
        JsonValue::Array(inner) if inner.is_empty() => {
            push_indent(out, base_indent);
            out.push_str("- []");
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
        JsonValue::Array(inner) => {
            // Nested sequence: `-` line then recurse.
            push_indent(out, base_indent);
            out.push('-');
            push_trailer(out, inline_trailer);
            out.push('\n');
            emit_sequence_children(out, inner, base_indent + 2, path, nested);
        }
        _ => {
            push_indent(out, base_indent);
            out.push_str("- ");
            emit_scalar(out, value);
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
    }
}

/// Emit a `key: <value>\n` pair where the key is already on a `- ` line.
/// The key/value go on the same line as the `- ` prefix (caller already wrote it).
fn emit_field_inline(
    out: &mut String,
    key: &str,
    value: &JsonValue,
    child_indent: usize,
    path: &[CommentPathSegment],
    nested: &[NestedComment],
    inline_trailer: Option<&str>,
) {
    match value {
        JsonValue::Object(map) if map.is_empty() => {
            out.push_str(key);
            out.push_str(": {}");
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
        JsonValue::Object(map) => {
            out.push_str(key);
            out.push(':');
            push_trailer(out, inline_trailer);
            out.push('\n');
            emit_mapping_children(out, map, child_indent, path, nested);
        }
        JsonValue::Array(items) if items.is_empty() => {
            out.push_str(key);
            out.push_str(": []");
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
        JsonValue::Array(items) => {
            out.push_str(key);
            out.push(':');
            push_trailer(out, inline_trailer);
            out.push('\n');
            emit_sequence_children(out, items, child_indent + 2, path, nested);
        }
        _ => {
            out.push_str(key);
            out.push_str(": ");
            emit_scalar(out, value);
            push_trailer(out, inline_trailer);
            out.push('\n');
        }
    }
}

/// Emit a scalar value (no key, no newline) onto `out`.
fn emit_scalar(out: &mut String, value: &JsonValue) {
    match value {
        JsonValue::Null => out.push_str("null"),
        JsonValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        JsonValue::Number(n) => out.push_str(&n.to_string()),
        JsonValue::String(s) => emit_double_quoted(out, s),
        // Arrays/objects should not reach here via emit_field — handled above.
        // As a fallback, emit JSON representation.
        other => out.push_str(&other.to_string()),
    }
}

/// Emit a string as a JSON-style double-quoted YAML scalar.
///
/// Escape rules (same as JSON string encoding):
/// - `\` → `\\`
/// - `"` → `\"`
/// - `\n` → `\n`
/// - `\r` → `\r`
/// - `\t` → `\t`
/// - Other control characters (U+0000–U+001F, U+007F–U+009F) → `\uXXXX`
pub(crate) fn emit_double_quoted(out: &mut String, s: &str) {
    out.push('"');
    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 if (c as u32) < 0x20 || (0x7F..=0x9F).contains(&(c as u32)) => {
                out.push_str(&format!("\\u{:04X}", c as u32));
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

// ── Utilities ─────────────────────────────────────────────────────────────────

fn push_indent(out: &mut String, spaces: usize) {
    for _ in 0..spaces {
        out.push(' ');
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    #[test]
    fn double_quoted_basic() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "hello");
        assert_eq!(s, r#""hello""#);
    }

    #[test]
    fn double_quoted_ambiguous_strings() {
        // These must remain strings on re-parse — the double-quoting is the guarantee.
        for ambiguous in &[
            "on", "off", "yes", "no", "true", "false", "null", "~", "01234", "1e10",
        ] {
            let mut s = String::new();
            emit_double_quoted(&mut s, ambiguous);
            assert!(
                s.starts_with('"') && s.ends_with('"'),
                "should be double-quoted: {}",
                s
            );
            // Verify the content is correct (no extra escaping for these).
            assert_eq!(&s[1..s.len() - 1], *ambiguous);
        }
    }

    #[test]
    fn double_quoted_escapes() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "a\\b\"c\nd\te");
        assert_eq!(s, r#""a\\b\"c\nd\te""#);
    }

    #[test]
    fn double_quoted_control_chars() {
        let mut s = String::new();
        emit_double_quoted(&mut s, "\x01\x1F");
        assert_eq!(s, "\"\\u0001\\u001F\"");
    }

    fn p(key: &str) -> Vec<CommentPathSegment> {
        vec![CommentPathSegment::Key(key.to_string())]
    }

    #[test]
    fn empty_object_omitted() {
        let value = QuillValue::from_json(serde_json::json!({}));
        let mut out = String::new();
        emit_field(
            &mut out,
            "empty_map",
            value.as_json(),
            0,
            false,
            &p("empty_map"),
            &[],
            None,
        );
        assert_eq!(out, ""); // omitted
    }

    #[test]
    fn empty_object_with_inline_trailer_degrades() {
        let value = QuillValue::from_json(serde_json::json!({}));
        let mut out = String::new();
        emit_field(
            &mut out,
            "empty_map",
            value.as_json(),
            0,
            false,
            &p("empty_map"),
            &[],
            Some("orphan"),
        );
        // Host omitted; trailer survives as own-line at the same indent.
        assert_eq!(out, "# orphan\n");
    }

    #[test]
    fn empty_array_emitted() {
        let value = QuillValue::from_json(serde_json::json!([]));
        let mut out = String::new();
        emit_field(
            &mut out,
            "empty_seq",
            value.as_json(),
            0,
            false,
            &p("empty_seq"),
            &[],
            None,
        );
        assert_eq!(out, "empty_seq: []\n");
    }

    #[test]
    fn scalar_field_with_inline_trailer() {
        let value = QuillValue::from_json(serde_json::json!("Hello"));
        let mut out = String::new();
        emit_field(
            &mut out,
            "title",
            value.as_json(),
            0,
            false,
            &p("title"),
            &[],
            Some("greeting"),
        );
        assert_eq!(out, "title: \"Hello\" # greeting\n");
    }

    #[test]
    fn container_field_with_inline_trailer_lands_on_key_line() {
        let value = QuillValue::from_json(serde_json::json!({"inner": 1}));
        let mut out = String::new();
        emit_field(
            &mut out,
            "outer",
            value.as_json(),
            0,
            false,
            &p("outer"),
            &[],
            Some("note"),
        );
        // Trailer lands on the key line, not after the children.
        assert_eq!(out, "outer: # note\n  inner: 1\n");
    }

    #[test]
    fn fill_null_emits_bare_tag() {
        let value = QuillValue::from_json(serde_json::Value::Null);
        let mut out = String::new();
        emit_field(
            &mut out,
            "recipient",
            value.as_json(),
            0,
            true,
            &p("recipient"),
            &[],
            None,
        );
        assert_eq!(out, "recipient: !fill\n");
    }

    #[test]
    fn fill_string_emits_tag_with_value() {
        let value = QuillValue::from_json(serde_json::json!("placeholder"));
        let mut out = String::new();
        emit_field(
            &mut out,
            "dept",
            value.as_json(),
            0,
            true,
            &p("dept"),
            &[],
            None,
        );
        assert_eq!(out, "dept: !fill \"placeholder\"\n");
    }

    #[test]
    fn fill_with_inline_trailer() {
        let value = QuillValue::from_json(serde_json::json!("placeholder"));
        let mut out = String::new();
        emit_field(
            &mut out,
            "dept",
            value.as_json(),
            0,
            true,
            &p("dept"),
            &[],
            Some("note"),
        );
        assert_eq!(out, "dept: !fill \"placeholder\" # note\n");
    }

    #[test]
    fn fill_integer_emits_tag_with_value() {
        let value = QuillValue::from_json(serde_json::json!(42));
        let mut out = String::new();
        emit_field(
            &mut out,
            "count",
            value.as_json(),
            0,
            true,
            &p("count"),
            &[],
            None,
        );
        assert_eq!(out, "count: !fill 42\n");
    }
}