arblang 0.1.24

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
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
//! The YAML node model — the metadata a YAML node carries that a JSON value has
//! no place for, plus the writer that puts it back on the page.
//!
//! # Why a node model at all
//!
//! `yq`'s defining behaviour is that `yq '.' file.yaml` gives the file back
//! essentially unchanged: comments in every position, anchor names, aliases,
//! merge keys, quoting style and block scalars all survive the round trip. That
//! is not a serializer nicety — it is the reason ~60 of yq's operators exist.
//! `anchor`, `alias`, `tag`, `style`, `head_comment`/`line_comment`/`foot_comment`
//! and their assignment forms all read and write metadata that is attached to a
//! NODE, not to a value. A jq value has nowhere to put any of it.
//!
//! # Why the metadata rides ALONGSIDE the value rather than replacing it
//!
//! Three shapes were weighed:
//!
//! | shape | why not / why |
//! |---|---|
//! | a side table keyed by `Rc` pointer identity | `JqVal::Bool`/`Num`/`Null` are by-value and have no pointer, so `enabled: true # c` could not carry its comment. Fails on the commonest YAML there is. |
//! | a side table keyed by PATH | jq's model flows VALUES, not paths — `map(…)`, `add`, `to_entries` all destroy the correspondence, and the table would silently answer for the wrong node. |
//! | replace `JqVal` with a node type everywhere | rewrites the engine that currently answers jq byte-for-byte. The jq leg is at zero divergences; that is the thing not to put at risk. |
//! | **a `JqVal::Node` box, chosen** | metadata rides beside the value exactly as a number's SOURCE LITERAL already does (`JqVal::Num(f64, Option<Rc<str>>)` — same problem, same answer, already in the tree). The compiler enumerates every site that has to decide what to do with the new variant, and **JSON input never constructs one**, so the jq leg is untouched by construction rather than by inspection. |
//!
//! The last row is the load-bearing one. `crate::jqlang::parse_json` cannot emit
//! a `Node`; only `crate::yaml` can. A JSON program therefore runs over exactly
//! the values it ran over before, through exactly the same arms.
//!
//! # What is deliberately NOT modelled
//!
//! A node's `path`/`key`/`parent` are recorded as they were at READ time. yq
//! carries real parent pointers, so its `parent` survives a value being moved;
//! arb's does not, and a node that has been relocated by `map`/`pick`/`+`
//! reports where it was read from. That is stated rather than hidden — the
//! alternative is a reference cycle through `Rc` for the whole document.

use crate::jqlang::{JqVal, NumLit};
use std::rc::Rc;

/// How a scalar (or collection) was written in the source.
///
/// The names are `yq`'s own — `yq '.x | style'` answers with exactly these
/// strings, and `style = "…"` accepts them. A plain scalar's style is the empty
/// string, which is why `Plain` renders as `""` rather than `"plain"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Style {
    /// `key: value` — no quotes, no block indicator.
    #[default]
    Plain,
    /// `key: 'value'`
    Single,
    /// `key: "value"`
    Double,
    /// `key: |` — a literal block scalar, newlines kept.
    Literal,
    /// `key: >` — a folded block scalar, newlines folded to spaces.
    Folded,
    /// `key: {a: 1}` / `key: [1, 2]` — a collection written inline.
    Flow,
    /// A collection written across lines. Distinct from `Plain` only so a
    /// `style = "flow"` assignment on a block collection has something to
    /// switch back to.
    Block,
}

impl Style {
    /// The string `yq`'s `style` operator answers with.
    pub fn name(self) -> &'static str {
        match self {
            Style::Plain | Style::Block => "",
            Style::Single => "single",
            Style::Double => "double",
            Style::Literal => "literal",
            Style::Folded => "folded",
            Style::Flow => "flow",
        }
    }

    /// Parse a `style = "…"` assignment. `yq` accepts the names it prints plus
    /// `tagged`/`""`; an unknown name resets to plain, which is yq's behaviour
    /// rather than an error.
    pub fn parse(s: &str) -> Style {
        match s {
            "single" | "singleQuoted" | "single_quoted" => Style::Single,
            "double" | "doubleQuoted" | "double_quoted" => Style::Double,
            "literal" => Style::Literal,
            "folded" => Style::Folded,
            "flow" => Style::Flow,
            _ => Style::Plain,
        }
    }

    /// Is this a block scalar indicator (`|` / `>`)?
    pub fn is_block_scalar(self) -> bool {
        matches!(self, Style::Literal | Style::Folded)
    }
}

/// Everything a YAML node knows about itself beyond its value.
///
/// Cheap to clone: every owned field is an `Rc`, and a node that carries no
/// metadata at all is [`NodeMeta::is_bare`] and gets dropped on the way out so
/// an untouched document does not pay for boxes it does not need.
#[derive(Debug, Clone)]
pub struct NodeMeta {
    /// The comment block ABOVE the node, `#` and one leading space stripped,
    /// lines joined with `\n`. Empty when there is none.
    pub head: Rc<str>,
    /// The comment after the node on its own line.
    pub line: Rc<str>,
    /// The comment block BELOW the node, at the node's own indent.
    pub foot: Rc<str>,
    /// The anchor NAME (`&x` -> `x`), empty when the node is not anchored.
    pub anchor: Rc<str>,
    /// The alias NAME (`*x` -> `x`), empty when the node is not an alias.
    /// A node with a non-empty `alias` was written as `*x` and is re-emitted
    /// that way, which is what keeps `use: *anc` from expanding on round trip.
    pub alias: Rc<str>,
    /// The node's tag, in yq's spelling: `!!str`, `!!int`, `!!map`, `!mytag`.
    /// Empty means "resolve from the value", which is what `tag` answers with
    /// for an untagged node.
    pub tag: Rc<str>,
    /// How the node was written.
    pub style: Style,
    /// 1-based line, counted from the stream's first CONTENT line — a leading
    /// comment block is not counted, which is what `yq` reports.
    pub line_no: u32,
    /// 1-based column of the node's first character.
    pub col_no: u32,
    /// The path from the document root to this node, as it was at read time.
    pub path: Rc<Vec<JqVal>>,
    /// The KEY node this node is the value of, with its own metadata — `yq`'s
    /// `key` operator answers with a node, so `.a | key | line_comment` reads
    /// the comment on the key rather than on the value.
    pub key: Option<Rc<JqVal>>,
    /// True on the node `key` returned, which is what `is_key` reports.
    pub is_key: bool,
    /// 0-based index of the document this node came from, within the stream.
    pub doc: u32,
    /// The file the document was read from; `-` for standard input, which is
    /// `yq`'s own answer for a piped document.
    pub file: Rc<str>,
    /// 0-based index of that file among the inputs.
    pub file_index: u32,
    /// The scalar's SOURCE text, kept only when rendering the VALUE would not
    /// reproduce it (`0x10` holds 16, `007` holds 7). Empty otherwise.
    pub raw: Rc<str>,
    /// The node was written with NO text at all — the `empty:` in `empty:\nnext: 1`.
    /// Its value is null, and so is a node written `null` or `~`; only this says
    /// which of the three spellings the file used.
    pub blank: bool,
    /// This node is a sequence item whose first key's HEAD comment was written
    /// on the `-` marker line (`- # note`, with the mapping indented below).
    ///
    /// The comment itself lives where `yq` puts it — on the first key, so
    /// `.nested[0].k | key | head_comment` answers it and `to_props` picks it up.
    /// Only its PLACEMENT is recorded here, because that is the one thing the
    /// comment's own node cannot say.
    pub marker: bool,
    /// The document opened with an explicit `---`. `yq` keeps it; a document
    /// that began implicitly must not grow one.
    pub explicit_doc: bool,
    /// A mapping's entries as they were WRITTEN, with `<<` still in place.
    /// Readers see the merged mapping; the writer emits this, so a round trip
    /// does not expand a merge key into the keys it stood for.
    pub written: Option<Entries>,
}

thread_local! {
    /// One shared empty `Rc<str>`, because `Rc<str>::default()` ALLOCATES.
    ///
    /// `NodeMeta` has seven of those fields and a document has one `NodeMeta` per
    /// node, so the derived `Default` was making seven heap allocations for every
    /// node in the file — 1.2M of them on a 20k-record document, all of the same
    /// empty string. Handing out clones of one `Rc` makes each a refcount bump.
    static EMPTY: Rc<str> = Rc::from("");
}

/// The shared empty string every unset `NodeMeta` field points at.
pub fn empty_str() -> Rc<str> {
    EMPTY.with(Rc::clone)
}

impl Default for NodeMeta {
    fn default() -> Self {
        let e = empty_str();
        NodeMeta {
            head: e.clone(),
            line: e.clone(),
            foot: e.clone(),
            anchor: e.clone(),
            alias: e.clone(),
            tag: e.clone(),
            style: Style::Plain,
            line_no: 0,
            col_no: 0,
            path: Rc::new(Vec::new()),
            key: None,
            is_key: false,
            doc: 0,
            file: e.clone(),
            file_index: 0,
            raw: e,
            blank: false,
            marker: false,
            explicit_doc: false,
            written: None,
        }
    }
}

impl NodeMeta {
    /// Is every field still at its default — nothing to record?
    ///
    /// Such metadata is dropped rather than boxed, which is what makes
    /// `. anchor = ""` on a JSON value give the value straight back instead of a
    /// box holding nothing.
    ///
    /// POSITION counts. `line_no`, `path` and `key` are as real as a comment is:
    /// `yq` answers `.a | line` and `.a | key` for a document with no comments in
    /// it at all, and a node that dropped them would answer wrongly rather than
    /// cheaply. So a node the YAML reader produced is always boxed — one `Rc`
    /// per node, which a configuration file affords and a `.` over it does not
    /// notice.
    pub fn is_bare(&self) -> bool {
        self.head.is_empty()
            && self.line.is_empty()
            && self.foot.is_empty()
            && self.anchor.is_empty()
            && self.alias.is_empty()
            && self.tag.is_empty()
            && self.raw.is_empty()
            && self.written.is_none()
            && !self.blank
            && !self.marker
            && !self.explicit_doc
            && self.line_no == 0
            && self.col_no == 0
            && self.path.is_empty()
            && self.key.is_none()
            && !self.is_key
            && self.file.is_empty()
            && matches!(self.style, Style::Plain | Style::Block)
    }
}

/// A mapping's entry list. Named because it appears in both `NodeMeta` and the
/// composer's return, and spelling it out at both sites reads worse than this.
pub type Entries = Rc<Vec<(Rc<str>, JqVal)>>;

/// A value plus the metadata YAML recorded about it.
#[derive(Debug, Clone)]
pub struct YNode {
    pub meta: NodeMeta,
    /// The value itself. Never another `JqVal::Node` — [`crate::jqlang::JqVal::wrap`]
    /// collapses a re-wrap so `bare()` is one hop, not a chain.
    pub val: JqVal,
}

/// What the writer would put on the page for a bare value, with no style and no
/// metadata. Used by the reader to decide whether a scalar's source text needs
/// keeping.
pub fn quote_scalar_value(v: &JqVal) -> String {
    match v.bare() {
        JqVal::Null => "null".to_string(),
        JqVal::Bool(b) => b.to_string(),
        JqVal::Num(n, lit) => match lit {
            NumLit::Text(t) => t.to_string(),
            _ => crate::jqlang::fmt_num(*n),
        },
        JqVal::Str(s) => quote_scalar(s, Style::Plain),
        other => crate::jqlang::render(other),
    }
}

/// The tag a value resolves to when the node carries none, in `yq`'s spelling.
pub fn implicit_tag(v: &JqVal) -> &'static str {
    match v.bare() {
        JqVal::Null => "!!null",
        JqVal::Bool(_) => "!!bool",
        JqVal::Num(n, lit) => {
            let is_int = match lit {
                NumLit::Text(l) => !l.contains(['.', 'e', 'E']),
                _ => n.fract() == 0.0 && n.is_finite(),
            };
            if is_int {
                "!!int"
            } else {
                "!!float"
            }
        }
        JqVal::Str(_) => "!!str",
        JqVal::Arr(_) => "!!seq",
        JqVal::Obj(_) => "!!map",
        JqVal::Node(_) => "!!str",
    }
}

/// The tag `yq` reports for an untagged node as READ from a document: a PLAIN
/// scalar spelled like a YAML 1.1 timestamp resolves to `!!timestamp` (go-yaml
/// resolves it so), where [`implicit_tag`] alone sees only a string. Quoted
/// scalars and computed strings stay `!!str`.
pub fn resolved_tag(v: &JqVal) -> &'static str {
    if let JqVal::Node(n) = v {
        if n.meta.style == Style::Plain {
            if let JqVal::Str(s) = &n.val {
                if is_timestamp(s) {
                    return "!!timestamp";
                }
            }
        }
    }
    implicit_tag(v)
}

/// YAML 1.1 timestamp: `YYYY-M-D`, optionally followed by `T`/`t`/blanks, a
/// `H:M:S[.frac]` time, and an optional blank-separated `Z` or `±H[:MM]` zone.
fn is_timestamp(s: &str) -> bool {
    fn digits(s: &str, min: usize, max: usize) -> Option<&str> {
        let n = s.bytes().take_while(u8::is_ascii_digit).count();
        (min..=max).contains(&n).then(|| &s[n..])
    }
    let Some(r) = digits(s, 4, 4) else {
        return false;
    };
    let Some(r) = r.strip_prefix('-').and_then(|r| digits(r, 1, 2)) else {
        return false;
    };
    let Some(r) = r.strip_prefix('-').and_then(|r| digits(r, 1, 2)) else {
        return false;
    };
    if r.is_empty() {
        return true;
    }
    let r = match r.strip_prefix(['T', 't']) {
        Some(r) => r,
        None if r.starts_with([' ', '\t']) => r.trim_start_matches([' ', '\t']),
        None => return false,
    };
    let Some(r) = digits(r, 1, 2) else {
        return false;
    };
    let Some(r) = r.strip_prefix(':').and_then(|r| digits(r, 2, 2)) else {
        return false;
    };
    let Some(mut r) = r.strip_prefix(':').and_then(|r| digits(r, 2, 2)) else {
        return false;
    };
    if let Some(f) = r.strip_prefix('.') {
        r = f.trim_start_matches(|c: char| c.is_ascii_digit());
    }
    let r = r.trim_start_matches([' ', '\t']);
    match r.strip_prefix(['Z', '+', '-']) {
        _ if r.is_empty() => true,
        Some(z) if r.starts_with('Z') => z.is_empty(),
        Some(z) => digits(z, 1, 2).is_some_and(|t| {
            t.is_empty()
                || t.strip_prefix(':')
                    .and_then(|m| digits(m, 2, 2))
                    .is_some_and(str::is_empty)
        }),
        None => false,
    }
}

/// `yq`'s `kind`: the four shapes a YAML node can have.
pub fn kind_of(v: &JqVal) -> &'static str {
    if let JqVal::Node(n) = v {
        if !n.meta.alias.is_empty() {
            return "alias";
        }
    }
    match v.bare() {
        JqVal::Arr(_) => "seq",
        JqVal::Obj(_) => "map",
        _ => "scalar",
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// The YAML writer
//
// This is the half that makes the metadata worth carrying: `yq '.' file.yaml`
// gives the file back essentially unchanged, and so must arb's `out.yaml`.
// Every rule below was measured against `yq v4.53.6` and is checked
// byte-for-byte by `yq_roundtrip_probe` in `scripts/jq_parity.sh`.
// ─────────────────────────────────────────────────────────────────────────────

/// Rendering options. `indent` is `yq`'s `-I`.
#[derive(Debug, Clone, Copy)]
pub struct Emit {
    pub indent: usize,
}

impl Default for Emit {
    fn default() -> Self {
        Emit { indent: 2 }
    }
}

/// Render a stream of documents. Two or more are separated by `---`, which is
/// what makes a multi-document file round-trip and what `splitDoc` relies on.
pub fn emit_docs(docs: &[JqVal], o: Emit) -> String {
    let mut out = String::new();
    for (i, d) in docs.iter().enumerate() {
        // Every document after the first needs the separator; the FIRST gets one
        // only if the source wrote one, so an implicit document does not grow a
        // `---` it never had.
        if i > 0 || d.meta().is_some_and(|m| m.explicit_doc) {
            out.push_str("---\n");
        }
        out.push_str(&emit_doc(d, o));
    }
    out
}

/// Render one document, newline-terminated.
pub fn emit_doc(v: &JqVal, o: Emit) -> String {
    let mut out = String::new();
    let m = v.meta();
    if let Some(m) = m {
        push_comment(&mut out, &m.head, 0);
    }
    match v.bare() {
        JqVal::Obj(map) if !map.is_empty() && !is_flow(v) && !is_alias(v) => {
            push_block_map(&mut out, entries(v, map), 0, o)
        }
        JqVal::Arr(a) if !a.is_empty() && !is_flow(v) && !is_alias(v) => {
            push_block_seq(&mut out, a, 0, o)
        }
        _ => {
            out.push_str(&inline(v, o));
            out.push('\n');
        }
    }
    if let Some(m) = m {
        push_foot(&mut out, &m.foot, 0);
    }
    // A foot comment at the END of the document has nothing after it, so the
    // blank `push_foot` always writes is trimmed back to the single newline every
    // document ends with.
    while out.ends_with("\n\n") {
        out.pop();
    }
    out
}

fn is_flow(v: &JqVal) -> bool {
    v.meta().is_some_and(|m| m.style == Style::Flow)
}

fn is_alias(v: &JqVal) -> bool {
    v.meta().is_some_and(|m| !m.alias.is_empty())
}

/// Emit a FOOT comment block, which is always followed by a blank line.
///
/// The blank is what made it a foot rather than the next entry's head, so
/// writing one back is what closes the round trip. A foot at the very end of a
/// document has no blank after it in the source; rather than tracking "is this
/// the last thing anywhere" down through every nesting level, `emit_doc` trims
/// the trailing blank once, at the top, where the question is answerable.
fn push_foot(out: &mut String, text: &str, ind: usize) {
    if text.is_empty() {
        return;
    }
    push_comment(out, text, ind);
    out.push('\n');
}

/// Emit a comment block, one `# `-prefixed line per stored line.
fn push_comment(out: &mut String, text: &str, ind: usize) {
    if text.is_empty() {
        return;
    }
    for line in text.split('\n') {
        for _ in 0..ind {
            out.push(' ');
        }
        out.push('#');
        if !line.is_empty() {
            out.push(' ');
            out.push_str(line);
        }
        out.push('\n');
    }
}

/// The prefix a node writes before its own content: `&anchor` and `!tag`, in
/// the order `yq` emits them.
fn decorations(v: &JqVal) -> String {
    let Some(m) = v.meta() else {
        return String::new();
    };
    let mut s = String::new();
    if !m.anchor.is_empty() {
        s.push('&');
        s.push_str(&m.anchor);
        s.push(' ');
    }
    if !m.tag.is_empty() {
        s.push_str(&m.tag);
        s.push(' ');
    }
    s
}

/// The entries the writer walks: the mapping as it was WRITTEN when a `<<` merge
/// key was in it, and the value's own entries otherwise.
fn entries<'a>(v: &'a JqVal, map: &'a [(Rc<str>, JqVal)]) -> &'a [(Rc<str>, JqVal)] {
    match v.meta().and_then(|m| m.written.as_ref()) {
        Some(w) => w.as_slice(),
        None => map,
    }
}

/// Emit a block mapping at `ind`. Each entry is `head comment`, the `key: value`
/// line, then the key's foot comment — and a foot comment that is not the last
/// thing in the mapping is followed by the BLANK line that is what made it a
/// foot rather than the next entry's head.
fn push_block_map(out: &mut String, map: &[(Rc<str>, JqVal)], ind: usize, o: Emit) {
    for (k, v) in map.iter() {
        let key_node = v.meta().and_then(|m| m.key.clone());
        let km = key_node.as_deref().and_then(JqVal::meta);
        let head: Rc<str> = km.map_or(Rc::from(""), |m| m.head.clone());
        // The reader puts an entry's foot on its KEY node, but `.a |= (foot_comment
        // = "f")` sets it on the VALUE — the node the update operator hands the
        // filter. Both spellings have to reach the page, so either carries it.
        let foot: Rc<str> = match km.map(|m| m.foot.clone()).filter(|f| !f.is_empty()) {
            Some(f) => f,
            None => v.meta().map_or(Rc::from(""), |m| m.foot.clone()),
        };
        push_comment(out, &head, ind);
        pad(out, ind);
        out.push_str(&scalar_key(k, key_node.as_deref()));
        out.push(':');
        push_value(out, v, ind, o);
        push_foot(out, &foot, ind);
    }
}

/// The head comment on a mapping's FIRST key, which is where a `- # note` on the
/// marker line is filed.
fn first_key_head(item: &JqVal) -> Rc<str> {
    let JqVal::Obj(m) = item.bare() else {
        return Rc::from("");
    };
    m.first()
        .and_then(|(_, v)| v.meta())
        .and_then(|mm| mm.key.as_deref())
        .and_then(JqVal::meta)
        .map_or(Rc::from(""), |km| km.head.clone())
}

/// Drop the leading `#` comment lines from a rendered block, which the marker
/// line has already carried.
fn strip_leading_comment(body: &str) -> &str {
    let mut rest = body;
    while rest.trim_start_matches(' ').starts_with('#') {
        match rest.find('\n') {
            Some(at) => rest = &rest[at + 1..],
            None => return "",
        }
    }
    rest
}

fn push_block_seq(out: &mut String, items: &[JqVal], ind: usize, o: Emit) {
    for item in items {
        if let Some(m) = item.meta() {
            push_comment(out, &m.head, ind);
        }
        pad(out, ind);
        out.push('-');
        // The item's first key carries a head comment that was WRITTEN on the
        // marker line. Placing it back there ends the line, so the mapping starts
        // below at its own indent instead of sharing the `- `.
        let marker = item.meta().is_some_and(|m| m.marker);
        if marker {
            let note = first_key_head(item);
            out.push_str(" # ");
            out.push_str(&note);
            out.push('\n');
        }
        match item.bare() {
            JqVal::Obj(map) if !map.is_empty() && !is_flow(item) && !is_alias(item) => {
                let mut body = String::new();
                push_block_map(&mut body, entries(item, map), ind + o.indent, o);
                if marker {
                    // The head was already written on the marker line above.
                    out.push_str(strip_leading_comment(&body));
                } else {
                    out.push(' ');
                    out.push_str(&decorations(item));
                    // The mapping's FIRST line shares the `- ` the caller just
                    // wrote, so its indent is dropped; every later line keeps the
                    // indent that lines it up under the first key.
                    out.push_str(body.trim_start_matches(' '));
                }
            }
            JqVal::Arr(a) if !a.is_empty() && !is_flow(item) && !is_alias(item) => {
                out.push('\n');
                push_block_seq(out, a, ind + o.indent, o);
            }
            _ => {
                out.push(' ');
                out.push_str(&inline(item, o));
                push_line_comment(out, item);
                out.push('\n');
            }
        }
        if let Some(m) = item.meta() {
            push_foot(out, &m.foot, ind);
        }
    }
}

/// Write the value half of `key: …`, choosing between an inline scalar, a block
/// scalar and a nested collection.
fn push_value(out: &mut String, v: &JqVal, ind: usize, o: Emit) {
    let style = v.meta().map_or(Style::Plain, |m| m.style);
    // A head comment on the VALUE node of a mapping entry, which is what
    // `.a head_comment = "x"` sets. The reader never produces one — it files an
    // entry's head on the KEY — so this is the assignment's shape, and `yq`
    // renders it AFTER the entry's own content: after `a: 1`, and after `c:` (so
    // before the block that follows it). Both are "where the value's rendering
    // begins", and both are measured.
    let head: Rc<str> = v.meta().map_or(Rc::from(""), |m| m.head.clone());
    match v.bare() {
        JqVal::Obj(map) if !map.is_empty() && !is_flow(v) && !is_alias(v) => {
            let deco = decorations(v);
            if !deco.is_empty() {
                out.push(' ');
                out.push_str(deco.trim_end());
            }
            push_line_comment(out, v);
            out.push('\n');
            push_comment(out, &head, ind + o.indent);
            push_block_map(out, entries(v, map), ind + o.indent, o);
        }
        JqVal::Arr(a) if !a.is_empty() && !is_flow(v) && !is_alias(v) => {
            let deco = decorations(v);
            if !deco.is_empty() {
                out.push(' ');
                out.push_str(deco.trim_end());
            }
            push_line_comment(out, v);
            out.push('\n');
            push_comment(out, &head, ind + o.indent);
            push_block_seq(out, a, ind + o.indent, o);
        }
        JqVal::Str(s) if style.is_block_scalar() && !is_alias(v) => {
            out.push(' ');
            out.push_str(&decorations(v));
            // A folded block's SOURCE body, where the reader kept one: the value
            // has already lost the line breaks folding replaced. The CHOMPING
            // indicator still comes from the value — it is the value's trailing
            // newlines that `-`/`+` encode, not the body's.
            let raw = v
                .meta()
                .map(|m| m.raw.to_string())
                .filter(|r| !r.is_empty());
            // A block scalar's trailing comment belongs on the INDICATOR line,
            // which is the line the reader took it from.
            let note = v.meta().map_or(Rc::from(""), |m| m.line.clone());
            push_block_scalar(out, s, raw.as_deref(), style, &note, ind + o.indent);
            push_comment(out, &head, ind);
        }
        _ => {
            let text = inline(v, o);
            if !text.is_empty() {
                out.push(' ');
                out.push_str(&text);
            }
            push_line_comment(out, v);
            out.push('\n');
            push_comment(out, &head, ind);
        }
    }
}

fn push_line_comment(out: &mut String, v: &JqVal) {
    if let Some(m) = v.meta() {
        if !m.line.is_empty() {
            out.push_str(" # ");
            out.push_str(&m.line);
        }
    }
}

/// `|` / `>` with the body indented, plus the chomping indicator the text needs:
/// `-` when it does not end in a newline, `+` when it ends in more than one.
fn push_block_scalar(
    out: &mut String,
    s: &str,
    raw: Option<&str>,
    style: Style,
    note: &str,
    ind: usize,
) {
    out.push(if style == Style::Literal { '|' } else { '>' });
    let trailing = s.len() - s.trim_end_matches('\n').len();
    match trailing {
        0 => out.push('-'),
        1 => {}
        _ => out.push('+'),
    }
    if !note.is_empty() {
        out.push_str(" # ");
        out.push_str(note);
    }
    out.push('\n');
    let body = if trailing > 1 {
        &s[..s.len() - (trailing - 1)]
    } else {
        s
    };
    // A kept SOURCE body is written line for line. Its continuation lines still
    // carry the indent they were read at, so that is stripped and the target
    // indent applied — otherwise re-emitting at the same depth doubles it.
    let body = raw.unwrap_or(body);
    let lines: Vec<&str> = body.trim_end_matches('\n').split('\n').collect();
    let strip = lines
        .iter()
        .skip(1)
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start_matches(' ').len())
        .min()
        .unwrap_or(0);
    for (i, line) in lines.iter().enumerate() {
        if line.trim().is_empty() {
            out.push('\n');
            continue;
        }
        pad(out, ind);
        out.push_str(if i == 0 {
            line
        } else {
            &line[strip.min(line.len())..]
        });
        out.push('\n');
    }
    for _ in 1..trailing {
        out.push('\n');
    }
}

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

/// A mapping KEY, quoted only when it has to be.
fn scalar_key(k: &str, node: Option<&JqVal>) -> String {
    let style = node.and_then(JqVal::meta).map_or(Style::Plain, |m| m.style);
    let deco = node.map(decorations).unwrap_or_default();
    // A KEY is quoted only when the SYNTAX needs it. The type rule that applies
    // to a value does not apply here: `false: false` keeps its key bare, because
    // a mapping key is read as a key whatever it looks like, and quoting it would
    // not round-trip.
    let body = match style {
        Style::Plain | Style::Block if !needs_single_quote(k) && !k.is_empty() => k.to_string(),
        _ => quote_scalar(k, style),
    };
    format!("{deco}{body}")
}

/// Render a node on ONE line: a scalar, an alias, or a flow collection.
fn inline(v: &JqVal, o: Emit) -> String {
    // `o` rides along unused by the scalar arms; a flow collection needs it for
    // its children, which is why it is threaded rather than dropped.
    let _ = o;
    if let Some(m) = v.meta() {
        if !m.alias.is_empty() {
            return format!("*{}", m.alias);
        }
    }
    let deco = decorations(v);
    let style = v.meta().map_or(Style::Plain, |m| m.style);
    // A scalar whose source text the reader kept (`0x10`, `007`) is written back
    // as it was written.
    if let Some(m) = v.meta() {
        if !m.raw.is_empty() {
            return format!("{deco}{}", m.raw);
        }
    }
    let body = match v.bare() {
        // `key:` with nothing after it round-trips as nothing; a node written
        // `null` or `~` keeps the spelling it was written with (`raw` above).
        JqVal::Null if v.meta().is_some_and(|m| m.blank) && deco.is_empty() => {
            return String::new()
        }
        JqVal::Null => "null".to_string(),
        JqVal::Bool(b) => b.to_string(),
        JqVal::Num(n, lit) => match lit {
            NumLit::Text(t) => t.to_string(),
            _ => crate::jqlang::fmt_num(*n),
        },
        // `!!str 123` needs no quotes — the tag is what makes it a string, and
        // quoting it as well is not what the file said.
        JqVal::Str(s) if !deco.is_empty() && style == Style::Plain => s.to_string(),
        JqVal::Str(s) => quote_scalar(s, style),
        JqVal::Arr(a) => {
            let parts: Vec<String> = a.iter().map(|e| inline(e, o)).collect();
            format!("[{}]", parts.join(", "))
        }
        JqVal::Obj(m) => {
            if m.is_empty() {
                "{}".to_string()
            } else {
                let parts: Vec<String> = m
                    .iter()
                    .map(|(k, val)| {
                        let kn = val.meta().and_then(|mm| mm.key.clone());
                        format!("{}: {}", scalar_key(k, kn.as_deref()), inline(val, o))
                    })
                    .collect();
                format!("{{{}}}", parts.join(", "))
            }
        }
        JqVal::Node(_) => unreachable!("bare() never returns a Node"),
    };
    format!("{deco}{body}")
}

/// Quote a string exactly as far as YAML requires, in `yq`'s own two-tier rule
/// (both halves measured, `yq -n '["null","a: b"]'`):
///
/// * a text that would RE-READ as another type (`null`, `1.5`, `true`) takes
///   DOUBLE quotes, because the quoting is about the type, and
/// * a text that would break the SYNTAX (`a: b`, `#x`, `*x`, a leading `- `)
///   takes SINGLE quotes, because the quoting is about the characters.
///
/// Everything else is written plain, which is why `yes`, `no` and `a b` come
/// back unquoted where a naive "quote if in doubt" writer would not round-trip.
pub fn quote_scalar(s: &str, style: Style) -> String {
    match style {
        Style::Single => format!("'{}'", s.replace('\'', "''")),
        Style::Double => double_quote(s),
        _ => {
            if s.is_empty() || reparses_as_non_string(s) {
                return double_quote(s);
            }
            if needs_single_quote(s) {
                return format!("'{}'", s.replace('\'', "''"));
            }
            s.to_string()
        }
    }
}

/// Would writing this text plain change what it reads back as, or break the
/// syntax around it? The two quoting tests as one question, for the reader's
/// fast path.
pub fn needs_quoting(s: &str) -> bool {
    s.is_empty() || reparses_as_non_string(s) || needs_single_quote(s)
}

/// Would this text, written plain, come back as something other than a string?
fn reparses_as_non_string(s: &str) -> bool {
    if matches!(s, "null" | "Null" | "NULL" | "~") {
        return true;
    }
    if matches!(s, "true" | "True" | "TRUE" | "false" | "False" | "FALSE") {
        return true;
    }
    if matches!(s, ".inf" | "-.inf" | ".nan" | ".Inf" | ".NaN") {
        return true;
    }
    let body = s.strip_prefix(['-', '+']).unwrap_or(s);
    !body.is_empty()
        && body
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-' | 'x' | 'o'))
        && body.chars().any(|c| c.is_ascii_digit())
}

/// Would this text, written plain, break the surrounding syntax?
fn needs_single_quote(s: &str) -> bool {
    let first = s.chars().next().unwrap_or(' ');
    if matches!(
        first,
        '#' | '&'
            | '*'
            | '!'
            | '|'
            | '>'
            | '%'
            | '@'
            | '`'
            | '{'
            | '}'
            | '['
            | ']'
            | ','
            | '\''
            | '"'
            | ' '
    ) {
        return true;
    }
    if (first == '-' || first == '?' || first == ':') && s.len() > 1 && s.as_bytes()[1] == b' ' {
        return true;
    }
    if s == "-" || s == "?" || s == ":" {
        return true;
    }
    if s.ends_with(' ') || s.contains('\n') || s.contains('\t') {
        return true;
    }
    // A `: ` or a ` #` inside the text would be read as a mapping separator or a
    // comment where the value is written.
    s.contains(": ") || s.contains(" #") || s.ends_with(':')
}

fn double_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\x{:02x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}