quarb 0.33.0

Query engine for arbors (arboreal graphs - tree-spanned or tree-dominated graphs)
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
//! The unparser: render a parsed (and expanded) [`Query`] back to
//! canonical query text.
//!
//! This is the synthesis half of reflection — the parser reads
//! queries into arbors, the unparser writes them back out — and the
//! engine of `qua --expand` (LISP's *macroexpand*: show the query
//! the fragments wrote). The output round-trips: parsing it yields a
//! query with the same meaning, and unparsing is a fixpoint
//! (`unparse(parse(unparse(q))) == unparse(q)`).

use crate::ast::{
    Arg, ArithOp, Axis, Branch, CmpOp, Group, InterpSeg, Matcher, Operand, PatSeg, PathElem,
    PredExpr, Predicate, Projection, PushBody, Query, Reach, RefProp, RegRef, Stage, Step,
    TraitClause,
};
use crate::value::Value;

/// Render `query` as canonical query text. Driver-first: the
/// query's own branches lead, each joined expression follows its
/// `<=>` (the outer marker glued to the operator), and the driving
/// pipeline closes the text.
pub fn unparse(query: &Query) -> String {
    // The expression head: `= expr` parses as `^ | (expr)`, and
    // prints as it was written, since `| (3)` would reparse as the
    // capture `$3`.
    if let [branch] = query.branches.as_slice()
        && branch.steps.is_empty()
        && branch.projection.is_none()
        && matches!(branch.anchor, crate::ast::Anchor::Root)
        && query.correlations.is_empty()
        && let Some((Stage::Expr(head), rest)) = query.pipeline.split_first()
    {
        let mut out = format!("= {}", operand(head));
        for stage_ast in rest {
            out.push(' ');
            out.push_str(&stage(stage_ast));
        }
        return out;
    }
    let n = query.correlations.len();
    // The join prints where it binds: the driver's stages before
    // `join_at` precede the `<=>` entries, the rest follow them.
    let at = if n == 0 {
        0
    } else {
        query.join_at.min(query.pipeline.len())
    };
    let (pre, post) = query.pipeline.split_at(at);
    let main_pipes = post.first().is_some_and(|s| stage(s).starts_with('|'));
    let pre_pipes = pre.first().is_some_and(|s| stage(s).starts_with('|'));
    let mut out = branches_join(
        query,
        if at > 0 {
            pre_pipes
        } else {
            n == 0 && main_pipes
        },
    );
    for stage_ast in pre {
        out.push(' ');
        out.push_str(&stage(stage_ast));
    }
    for (i, corr) in query.correlations.iter().enumerate() {
        out.push_str(if corr.outer { " <=>? " } else { " <=> " });
        let followed_by_main_pipe = (i + 1 == n) && main_pipes;
        let own_pipes = corr
            .pipeline
            .first()
            .is_some_and(|s| stage(s).starts_with('|'));
        out.push_str(&branches_join(corr, followed_by_main_pipe || own_pipes));
        // A non-final entry may retain its own pre-join pipeline.
        for stage_ast in &corr.pipeline {
            out.push(' ');
            out.push_str(&stage(stage_ast));
        }
    }
    for stage_ast in post {
        out.push(' ');
        out.push_str(&stage(stage_ast));
    }
    out
}

/// The union of a query's branches. A trailing leaf anchor before a
/// plain pipe would reparse as the map pipe (`/a$ | f` relexes as
/// `/a $| f` — the token stream cannot spell them apart), so such a
/// branch reprints as a single-alternative group: `(/a$) | f`.
fn branches_join(q: &Query, followed_by_plain_pipe: bool) -> String {
    let mut parts: Vec<String> = q.branches.iter().map(branch).collect();
    if followed_by_plain_pipe
        && let Some(last) = q.branches.last()
        && branch_ends_bare_leaf(last)
    {
        let text = parts.pop().expect("branches and parts zip");
        parts.push(format!("({text})"));
    }
    parts.join(" || ")
}

/// Whether a branch's emitted text ends with the bare leaf anchor
/// `$` (a trailing leaf-anchored step with no projection after it).
fn branch_ends_bare_leaf(b: &Branch) -> bool {
    b.projection.is_none() && matches!(b.steps.last(), Some(PathElem::Step(s)) if s.leaf)
}

fn branch(b: &Branch) -> String {
    // Anchors are semantic (the root differs from the current
    // node inside a subcontext body; marks are the thread's own),
    // so they reprint whenever set.
    let mut out = String::new();
    if !universal_head(&b.anchor, &b.steps) {
        out.push_str(&anchor(&b.anchor));
    }
    for e in &b.steps {
        out.push_str(&elem(e));
    }
    if let Some(p) = &b.projection {
        out.push_str(&projection(p));
    }
    // A final mark (or named push) prints with a trailing space
    // for lexing; at the branch end the joiner supplies its own
    // spacing.
    out.truncate(out.trim_end().len());
    out
}

/// `*//` is root-anchored by construction and spells its own
/// head: the `^` is not reprinted before it.
fn universal_head(a: &crate::ast::Anchor, steps: &[PathElem]) -> bool {
    matches!(a, crate::ast::Anchor::Root)
        && matches!(
            steps.first(),
            Some(PathElem::Step(s)) if matches!(s.axis, crate::ast::Axis::Universal)
        )
}

/// An anchor's canonical spelling; empty for the default.
fn anchor(a: &crate::ast::Anchor) -> String {
    use crate::ast::Anchor;
    match a {
        Anchor::Current => String::new(),
        Anchor::Root => "^".to_string(),
        // Double parentheses are the node side.
        // `$$.name` / `$$.N` / `$$.` — the marks, node-side; the
        // rounded spellings are the double-paren anchors.
        Anchor::Mark(m) => format!("$$.{m}"),
        Anchor::MarkIndex(n) => format!("$$.{n}"),
        Anchor::MarkTop => "$$.".to_string(),
        Anchor::MarksAll => "((@))".to_string(),
        Anchor::MarksNamed(m) => format!("((@{m}))"),
        Anchor::Id(op) => format!("((!{}))", operand(op)),
    }
}

pub(crate) fn elem(e: &PathElem) -> String {
    match e {
        // A mark prints spaced for the same lexing reason as the
        // named push below; the anonymous mark is a lone dot.
        PathElem::Mark(Some(name)) => format!(" .{} ", push_name(name)),
        PathElem::Mark(None) => " . ".to_string(),
        PathElem::Step(s) => step(s),
        PathElem::Group(g) => group(g),
        PathElem::Push { name, body } => {
            // A push prints spaced: the push dot stands after
            // whitespace; glued, it would be a name
            // character.
            let lead = " .";
            let n = name.as_deref().unwrap_or("");
            match body {
                PushBody::Query(q) => format!("{lead}{n}({})", unparse(q)),
                PushBody::Expr(e) => format!("{lead}{n}({})", operand(e)),
            }
        }
    }
}

/// A path-pattern group in canonical (strict) form: every
/// alternative spells its nav-ops, `{2,2}` reprints as `{2}`, and
/// the open-ended forms reprint as `+` / `*`.
pub(crate) fn group(g: &Group) -> String {
    let alts: Vec<String> = g
        .alts
        .iter()
        .map(|alt| alt.iter().map(elem).collect())
        .collect();
    let quant = match (g.quant.min, g.quant.max) {
        (1, Some(1)) => String::new(),
        (1, None) => "+".to_string(),
        (0, None) => "*".to_string(),
        (m, Some(n)) if m == n => format!("{{{m}}}"),
        // the semicolon separates the bounds; the regex comma is sugar
        (m, Some(n)) => format!("{{{m};{n}}}"),
        (m, None) => format!("{{{m};}}"),
    };
    let preds: String = g.predicates.iter().map(predicate).collect();
    format!(
        "({}){}{}{}{}",
        alts.join("|"),
        quant,
        trait_suffix(&g.traits),
        preds,
        reach_mark(&g.reach)
    )
}

pub(crate) fn step(s: &Step) -> String {
    let mut out = String::new();
    match &s.axis {
        Axis::Child => out.push('/'),
        Axis::Descendant(Reach::All) => out.push_str("//"),
        Axis::Descendant(Reach::Proximal) => out.push_str("//?"),
        Axis::Descendant(Reach::Distal) => out.push_str("//!"),
        Axis::Universal => out.push_str("*//"),
        Axis::Parent => out.push('\\'),
        Axis::Ancestor(Reach::All) => out.push_str("\\\\"),
        Axis::Ancestor(Reach::Proximal) => out.push_str("\\\\?"),
        Axis::Ancestor(Reach::Distal) => out.push_str("\\\\!"),
        Axis::NextSibling => out.push('>'),
        Axis::PrevSibling => out.push('<'),
        Axis::FollowingSiblings(r) => out.push_str(&format!(">>{}", reach_mark(r))),
        Axis::PrecedingSiblings(r) => out.push_str(&format!("<<{}", reach_mark(r))),
        Axis::OutLink => out.push_str("->"),
        Axis::InLink => out.push_str("<-"),
        Axis::BothLink => out.push_str("--"),
        Axis::Resolve {
            property,
            label: hint,
        } => {
            if let Some(p) = property {
                out.push_str("::");
                out.push_str(&name_text(p));
            }
            out.push_str("-->");
            if let Some(h) = hint {
                out.push_str(&name_text(h));
            }
            // A resolution step carries no matcher of its own.
            return out + &step_suffix(s);
        }
        Axis::ReverseResolve {
            label,
            scope,
            property,
        } => {
            out.push_str("<--");
            if let Some(h) = label {
                out.push_str(&name_text(h));
            }
            if scope.is_some() || *property != RefProp::Default {
                out.push('(');
                if let Some(sp) = scope {
                    for e in &sp.0 {
                        out.push_str(&elem(e));
                    }
                }
                match property {
                    RefProp::Named(p) => {
                        out.push_str("::");
                        out.push_str(&name_text(p));
                    }
                    RefProp::Any => out.push_str("::*"),
                    RefProp::Default => {}
                }
                out.push(')');
            }
            return out + &step_suffix(s);
        }
        Axis::ValueMatch {
            property,
            scope,
            target,
        } => {
            out.push_str("::");
            out.push_str(&name_text(property));
            out.push_str("=>(");
            if let Some(sp) = scope {
                for e in &sp.0 {
                    out.push_str(&elem(e));
                }
            }
            out.push_str("::");
            out.push_str(&name_text(target));
            out.push(')');
            return out + &step_suffix(s);
        }
    }
    // The parent and the ancestors take no name: the wildcard is
    // implied, and the bare axis is the canonical spelling.
    let m = if matches!(s.axis, Axis::Parent | Axis::Ancestor(_))
        && matches!(s.matcher, Matcher::Any)
    {
        String::new()
    } else {
        matcher(&s.matcher)
    };
    // The lexer reads `<-3` as less-than-minus-three and `<-x` as
    // an incoming crosslink, so a digit-leading matcher after `<-`
    // needs a separating space to keep its axis on reparse; the
    // space is meaning-preserving there. A dash-leading name after
    // the sibling hop `<` cannot take a space (spaced, `<` is the
    // comparison) and reprints quoted instead: `<"-x"`. A glob led
    // by a dash has no spelling after `<` at all (quoting would make
    // it a literal name); it prints as it is and does not reparse.
    let m = if matches!(s.axis, Axis::PrevSibling)
        && matches!(s.matcher, Matcher::Name(_))
        && m.starts_with('-')
    {
        crate::value::quarb_string(&m)
    } else {
        m
    };
    let glue_breaks = match &s.axis {
        Axis::InLink => m.starts_with(|c: char| c.is_ascii_digit()),
        // `--` then a dash-leading matcher would fuse into a longer
        // dash run on reparse.
        Axis::BothLink => m.starts_with('-'),
        _ => false,
    };
    if glue_breaks {
        out.push(' ');
    }
    out.push_str(&m);
    out + &step_suffix(s)
}

fn reach_mark(r: &Reach) -> &'static str {
    match r {
        Reach::All => "",
        Reach::Proximal => "?",
        Reach::Distal => "!",
    }
}

/// `<...>` trait clauses, CNF-shaped: clauses joined by `&&`,
/// each a `||`-disjunction, parenthesized when both dimensions are
/// in play. Empty for no traits.
fn trait_suffix(traits: &[TraitClause]) -> String {
    let mut out = String::new();
    if !traits.is_empty() {
        let many = traits.len() > 1;
        let clauses: Vec<String> = traits
            .iter()
            .map(|t| {
                let body = t
                    .alts
                    .iter()
                    .map(|a| trait_lit(a))
                    .collect::<Vec<_>>()
                    .join(" || ");
                if many && t.alts.len() > 1 {
                    format!("({body})")
                } else {
                    body
                }
            })
            .collect();
        out.push('<');
        out.push_str(&clauses.join(" && "));
        out.push('>');
    }
    out
}

fn step_suffix(s: &Step) -> String {
    let mut out = trait_suffix(&s.traits);
    for p in &s.predicates {
        out.push_str(&predicate(p));
    }
    if s.leaf {
        out.push('$');
    }
    out
}

/// The canonical regex literal: `(/body/mods)`. In
/// operand position a leading inline-flag group splits out as
/// trailing modifiers; in name position (`mods` false) it stays
/// inline, the closer there being strictly `/)`. A slash in the body
/// escapes.
fn regex_literal(pat: &str, mods: bool) -> String {
    let split = || {
        let rest = pat.strip_prefix("(?")?;
        let k = rest.find(')')?;
        let flags = &rest[..k];
        (!flags.is_empty() && flags.chars().all(|c| matches!(c, 'i' | 'm' | 's' | 'x')))
            .then(|| (flags.to_string(), rest[k + 1..].to_string()))
    };
    let (flags, body) = if mods { split() } else { None }.unwrap_or_default_with(pat);
    format!("(/{}/{})", body.replace('/', "\\/"), flags)
}

trait OrPat {
    fn unwrap_or_default_with(self, pat: &str) -> (String, String);
}
impl OrPat for Option<(String, String)> {
    fn unwrap_or_default_with(self, pat: &str) -> (String, String) {
        self.unwrap_or_else(|| (String::new(), pat.to_string()))
    }
}

pub(crate) fn matcher(m: &Matcher) -> String {
    match m {
        Matcher::Name(n) => name_text(n),
        Matcher::Glob(g) => g.glob().glob().to_string(),
        Matcher::Regex(r) => regex_literal(r.as_str(), false),
        Matcher::Any => "*".to_string(),
        Matcher::Dot => ".".to_string(),
    }
}

/// A CNF trait literal (`name` / `!name`): the negation mark stays
/// bare; the name quotes when it would not lex back as one name
/// token (a trait named "my trait" must reprint as `<'my trait'>`).
/// The bare set is the lexer's name characters — wider than
/// [`name_text`]'s, since `<*>`-style wildcards are bare traits.
fn trait_lit(lit: &str) -> String {
    let quote = |n: &str| {
        let bare = !n.is_empty()
            && n.chars()
                .all(|c| c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | '*' | '+'));
        if bare {
            n.to_string()
        } else {
            crate::value::quarb_string(n)
        }
    };
    match lit.strip_prefix('!') {
        Some(name) => format!("!{}", quote(name)),
        None => quote(lit),
    }
}

/// A name, quoted when it does not lex as a bare name.
fn name_text(n: &str) -> String {
    let bare = !n.is_empty()
        && n.chars()
            .all(|c| c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
        && !n.starts_with('.');
    if bare {
        n.to_string()
    } else {
        crate::value::quarb_string(n)
    }
}

/// A projection key. Like [`name_text`], but also quotes the
/// predicate keywords `and`/`or`/`not`: `opt_projection_name` refuses
/// them unquoted (a bare `::and` is the default projection followed by
/// the connective keyword), so a field with one of those names must
/// reprint quoted (`::'and'`) to round-trip.
fn proj_name(k: &str) -> String {
    if matches!(k, "and" | "or" | "not") {
        crate::value::quarb_string(k)
    } else {
        name_text(k)
    }
}

pub(crate) fn projection(p: &Projection) -> String {
    match p {
        Projection::Property(None) => "::".to_string(),
        Projection::Property(Some(k)) => format!("::{}", proj_name(k)),
        Projection::CoreMeta(k) => format!(":::{}", proj_name(k)),
        Projection::AdapterMeta(k) => format!("::::{}", proj_name(k)),
    }
}

pub(crate) fn predicate(p: &Predicate) -> String {
    match p {
        Predicate::Index(n) => format!("[{n}]"),
        Predicate::Range(from, to) => {
            let f = from.map(|v| v.to_string()).unwrap_or_default();
            let t = to.map(|v| v.to_string()).unwrap_or_default();
            format!("[{f}..{t}]")
        }
        Predicate::Expr(e) => format!("[{}]", pred_expr(e)),
    }
}

pub(crate) fn pred_expr(e: &PredExpr) -> String {
    match e {
        PredExpr::Or(a, b) => format!("{} || {}", pred_term(a), pred_term(b)),
        PredExpr::And(a, b) => format!("{} && {}", pred_term(a), pred_term(b)),
        // `!` binds tightest: a negated comparison or connective
        // prints with its parentheses so the text re-parses as
        // written (`.not. ::x > 1` is `!(::x > 1)`).
        PredExpr::Not(a) => match a.as_ref() {
            PredExpr::Truthy(_) | PredExpr::Not(_) => format!("!{}", pred_expr(a)),
            _ => format!("!({})", pred_expr(a)),
        },
        PredExpr::Compare(l, op, r) => {
            // Ruling #33: the canonical spelling of a literal
            // substring test is the pattern form — `*= "x"` prints
            // as `== *"x"*`. A dynamic right operand keeps `*=`
            // (patterns are literal syntax only).
            if matches!(op, CmpOp::Contains)
                && let Operand::Lit(Value::Str(t)) = r
            {
                let pat =
                    Operand::Pattern(vec![PatSeg::Star, PatSeg::Lit(t.clone()), PatSeg::Star]);
                return format!("{} == {}", operand(l), operand(&pat));
            }
            // A pattern literal is a pattern comparison however it
            // was spelled (`= *"x"*` is heritage): `==` / `!==`.
            if let Operand::Pattern(_) = r
                && matches!(op, CmpOp::Eq | CmpOp::Ne)
            {
                let eq = if matches!(op, CmpOp::Eq) { "==" } else { "!==" };
                return format!("{} {} {}", operand(l), eq, operand(r));
            }
            // A match's literal pattern prints as `== (/x/i)` /
            // `!== (/x/i)`; a dynamic pattern (a non-literal right
            // operand) prints its operand.
            if matches!(op, CmpOp::Match | CmpOp::NotMatch)
                && let Operand::Lit(Value::Str(t)) = r
            {
                return format!("{} {} {}", operand(l), cmp(*op), regex_literal(t, true));
            }
            format!("{} {} {}", operand(l), cmp(*op), operand(r))
        }
        PredExpr::Truthy(o) => operand(o),
    }
}

/// A sub-expression of a connective: parenthesized when it is itself
/// a binary connective, so precedence survives the round-trip.
/// `!` binds tightest, so a negation never needs wrapping.
fn pred_term(e: &PredExpr) -> String {
    match e {
        PredExpr::Or(..) | PredExpr::And(..) => {
            format!("({})", pred_expr(e))
        }
        _ => pred_expr(e),
    }
}

fn cmp(op: CmpOp) -> &'static str {
    match op {
        CmpOp::Eq => "=",
        CmpOp::Ne => "!=",
        CmpOp::Lt => "<",
        CmpOp::Le => "<=",
        CmpOp::Gt => ">",
        CmpOp::Ge => ">=",
        // the pattern comparisons; `=~` / `!~` parse as heritage sugar
        CmpOp::Match => "==",
        CmpOp::NotMatch => "!==",
        CmpOp::Contains => "*=",
    }
}

/// The canonical text of one operand form (macro argument splicing
/// and the expansion arbor's `::form` property).
pub(crate) fn operand_text(o: &Operand) -> String {
    operand(o)
}

fn operand(o: &Operand) -> String {
    match o {
        Operand::Match {
            scrutinee,
            arms,
            other,
        } => {
            let mut out = format!("({} ?=", operand(scrutinee));
            for (test, regex, result) in arms {
                if *regex {
                    let Operand::Lit(Value::Str(pat)) = test else {
                        unreachable!("regex arms hold their pattern literal");
                    };
                    out.push(' ');
                    out.push_str(&regex_literal(pat, true));
                } else {
                    out.push_str(&format!(" {}", operand(test)));
                }
                out.push_str(&format!(" ? {} :", operand(result)));
            }
            out.push_str(&format!(" {})", operand(other)));
            out
        }
        Operand::Rel {
            steps,
            projection: p,
            anchor: a,
        } => {
            let mut out = String::new();
            if !universal_head(a, steps) {
                out.push_str(&anchor(a));
            }
            out.extend(steps.iter().map(elem));
            if let Some(p) = p {
                out.push_str(&projection(p));
            }
            out
        }
        Operand::Lit(v) => literal(v),
        // The canonical tight spelling: stars outside the quotes,
        // no whitespace inside the chain.
        Operand::Pattern(segs) => segs
            .iter()
            .map(|seg| match seg {
                PatSeg::Star => "*".to_string(),
                PatSeg::Lit(t) => literal(&Value::Str(t.clone())),
            })
            .collect::<String>(),
        Operand::Arith { op, left, right } => {
            format!(
                "{} {} {}",
                arith_term(left, *op, false),
                arith(*op),
                arith_term(right, *op, true)
            )
        }
        Operand::Neg(inner) => format!(
            "- {}",
            match **inner {
                Operand::Arith { .. } => format!("({})", operand(inner)),
                _ => operand(inner),
            }
        ),
        Operand::Group(e) => format!("({})", pred_expr(e)),
        Operand::Recall(r) => reg(r),
        Operand::Topic => "$_".to_string(),
        Operand::Field { base, name } => match **base {
            Operand::Topic => format!(":{name}"),
            _ => format!("{}:{name}", operand(base)),
        },
        Operand::ValueMeta { base, key } => format!("{}:::{key}", operand(base)),
        Operand::PeerReg { at, reg: r } => {
            format!("{}:{}", operand(at), reg(r).trim_start_matches('$'))
        }
        Operand::NamedCaptures => "%+".to_string(),
        Operand::List(items) => {
            let inner: Vec<String> = items.iter().map(operand).collect();
            format!("@({})", inner.join("; "))
        }
        Operand::Now => "now()".to_string(),
        Operand::Edge { projection: p } => match p {
            Some(p) => format!("$-{}", projection(p)),
            None => "$-".to_string(),
        },
        Operand::Edges { projection: p } => match p {
            Some(p) => format!("@-{}", projection(p)),
            None => "@-".to_string(),
        },
        Operand::Capsae { projection: p } => match p {
            Some(p) => format!("@*{}", projection(p)),
            None => "@*".to_string(),
        },
        Operand::Piped { expr, stages } => {
            let tail: Vec<String> = stages.iter().map(stage).collect();
            let mut head = operand(expr);
            // The same `$`-then-`|` hazard as at query level: a
            // path operand ending in a bare leaf anchor regroups
            // before a plain pipe.
            if let Operand::Rel {
                steps,
                projection: None,
                ..
            } = expr.as_ref()
                && matches!(steps.last(), Some(PathElem::Step(s)) if s.leaf)
                && tail.first().is_some_and(|t| t.starts_with('|'))
            {
                head = format!("({head})");
            }
            format!("({} {})", head, tail.join(" "))
        }
        Operand::Cond { cond, then, other } => format!(
            "({} ? {} : {})",
            pred_expr(cond),
            operand(then),
            operand(other)
        ),
        Operand::Ordinal => "$ord".to_string(),
        Operand::Param(name) => format!("${name}"),
        Operand::Capture(n) => format!("${n}"),
        // The outer-scope wrapper prefixes one more `$` to the inner
        // spelling (`$.x` → `$$.x`).
        // Each `Outer` wrap adds one `$`. Capsa-scope inners
        // (`$.name`, `$_`) already start with a dollar; the node
        // form (`::prop`, `/child::x`) needs the full `$$` spelled.
        // `$$_` is the driver; its register `$$_.name`, its node
        // form `$$_::prop` / `$$_/kid`; one `$` more per scope out.
        // `_` — the served node, projected or navigated.
        Operand::Outer(inner) => format!("_{}", operand(inner)),
        // An interpolated string reprints double-quoted, with its
        // escapes restored and each hole's expression unparsed.
        Operand::Interp(segs) => {
            let mut out = String::from("\"");
            for seg in segs {
                match seg {
                    InterpSeg::Text(t) => {
                        for c in t.chars() {
                            if matches!(c, '"' | '\\' | '$') {
                                out.push('\\');
                            }
                            out.push(c);
                        }
                    }
                    InterpSeg::Expr(e) => {
                        out.push_str("${");
                        out.push_str(&operand(e));
                        out.push('}');
                    }
                    InterpSeg::Strict(e, msg) => {
                        out.push_str("${");
                        out.push_str(&operand(e));
                        out.push_str(":?");
                        if let Some(m) = msg {
                            out.push_str(m);
                        }
                        out.push('}');
                    }
                    InterpSeg::Default(e, f) => {
                        out.push_str("${");
                        out.push_str(&operand(e));
                        out.push_str(":-");
                        out.push_str(&operand(f));
                        out.push('}');
                    }
                }
            }
            out.push('"');
            out
        }
        Operand::Ctx {
            index,
            steps,
            projection: p,
        } => {
            let mut out = match index {
                Some(k) => format!("$${k}"),
                None => "$*".to_string(),
            };
            for e in steps {
                out.push_str(&elem(e));
            }
            if let Some(p) = p {
                out.push_str(&projection(p));
            }
            out
        }
    }
}

/// An arithmetic sub-expression under `parent`: parenthesized
/// where the parse would group it otherwise — a looser operator
/// below a tighter one, or, on the right, the same precedence
/// (the parse is left-associative). A long left-leaning chain
/// `1 + 1 + 1 + …` therefore prints flat, within the nesting the
/// parser accepts.
fn arith_term(o: &Operand, parent: ArithOp, right: bool) -> String {
    match o {
        Operand::Arith { op, .. } => {
            let (inner, outer) = (arith_precedence(*op), arith_precedence(parent));
            if inner < outer || (right && inner == outer) {
                format!("({})", operand(o))
            } else {
                operand(o)
            }
        }
        _ => operand(o),
    }
}

fn arith_precedence(op: ArithOp) -> u8 {
    match op {
        ArithOp::Add | ArithOp::Sub => 1,
        _ => 2,
    }
}

fn arith(op: ArithOp) -> &'static str {
    match op {
        ArithOp::Add => "+",
        ArithOp::Sub => "-",
        ArithOp::Mul => "*",
        ArithOp::Div => "div",
        ArithOp::IDiv => "idiv",
        ArithOp::Mod => "mod",
    }
}

fn literal(v: &Value) -> String {
    match v {
        // The one string-literal rule, shared with the display form.
        Value::Str(s) => crate::value::quarb_string(s),
        // Null displays as empty text; as a literal it must spell
        // its keyword or the round-trip drops it.
        Value::Null => "null".to_string(),
        other => other.to_string(),
    }
}

pub(crate) fn stage(st: &Stage) -> String {
    match st {
        // `s/pat/repl/mods` keeps its substitution spelling.
        Stage::Func(call)
            if call.name == "s"
                && call.args.len() == 3
                && call.args.iter().all(|a| matches!(a, Arg::Lit(_))) =>
        {
            let lit = |a: &Arg| match a {
                Arg::Lit(v) => v.to_string(),
                _ => unreachable!("matched literals"),
            };
            // A literal `/` in the pattern or replacement must be
            // re-escaped as `\/`: the lexer unescaped `\/` to `/` when
            // it read the substitution, and a bare `/` would relex as a
            // section delimiter. The mods are `[a-z]` only — no escaping.
            format!(
                "| s/{}/{}/{}",
                lit(&call.args[0]).replace('/', "\\/"),
                lit(&call.args[1]).replace('/', "\\/"),
                lit(&call.args[2])
            )
        }
        // The sh stage canonicalizes to its backtick sugar when it
        // has the sugarable shape (one literal or interpolated
        // command).
        Stage::Func(call)
            if call.name == "sh"
                && call.args.len() == 1
                && matches!(
                    call.args[0],
                    Arg::Lit(Value::Str(_)) | Arg::Expr(Operand::Interp(_))
                ) =>
        {
            let mut out = String::from("| `");
            let escape = |out: &mut String, t: &str| {
                for c in t.chars() {
                    if matches!(c, '`' | '\\' | '$') {
                        out.push('\\');
                    }
                    out.push(c);
                }
            };
            match &call.args[0] {
                Arg::Lit(Value::Str(t)) => escape(&mut out, t),
                Arg::Expr(Operand::Interp(segs)) => {
                    for seg in segs {
                        match seg {
                            InterpSeg::Text(t) => escape(&mut out, t),
                            InterpSeg::Expr(e) => {
                                out.push_str("${");
                                out.push_str(&operand(e));
                                out.push('}');
                            }
                            InterpSeg::Strict(e, msg) => {
                                out.push_str("${");
                                out.push_str(&operand(e));
                                out.push_str(":?");
                                if let Some(m) = msg {
                                    out.push_str(m);
                                }
                                out.push('}');
                            }
                            InterpSeg::Default(e, f) => {
                                out.push_str("${");
                                out.push_str(&operand(e));
                                out.push_str(":-");
                                out.push_str(&operand(f));
                                out.push('}');
                            }
                        }
                    }
                }
                _ => unreachable!("guarded above"),
            }
            out.push('`');
            out
        }
        // `%(...)` is the record constructor's canonical spelling
        //; `rec` / `record` are its aliases.
        Stage::Func(call) if is_record_call(&call.name) => {
            format!("| %{}", record_args(call, "; "))
        }
        Stage::Func(call) => format!("| {}", fn_call(call)),
        // `%%(...)`: the record sigil's enriched register view.
        Stage::RecordWith(call) => format!("| %%{}", record_args(call, "; ")),
        // `.%(...)` / `.name%(...)`: the record push, sigil-spelled.
        Stage::RecordPush {
            name,
            call,
            enriched,
        } => {
            let sigil = if *enriched { "%%" } else { "%" };
            format!(
                "| .{}{sigil}{}",
                name.as_deref().map(push_name).unwrap_or_default(),
                record_args(call, "; ")
            )
        }
        // `group(...)` follows the record convention: its keys print
        // as a record's do.
        Stage::Agg(call) if call.name == "group" => format!("@| group{}", record_args(call, "; ")),
        Stage::Agg(call) => format!("@| {}", fn_call(call)),
        Stage::Spread { outer: false } => "| ...".to_string(),
        Stage::Spread { outer: true } => "| ...?".to_string(),
        Stage::Repeat {
            stage: inner,
            min,
            max,
        } => {
            let quant = match max {
                Some(n) if n == min => format!("{{{min}}}"),
                Some(n) => format!("{{{min};{n}}}"),
                None => format!("{{{min};}}"),
            };
            format!("{}{quant}", stage(inner))
        }
        Stage::Map(inner) => {
            let body = stage(inner);
            let body = body
                .strip_prefix("@| ")
                .or_else(|| body.strip_prefix("| "))
                .unwrap_or(&body)
                .to_string();
            format!("$| {body}")
        }
        Stage::Nav(b) => format!("| {}", branch(b)),
        Stage::Push(None) => "| .".to_string(),
        Stage::Push(Some(n)) => format!("| .{}", push_name(n)),
        Stage::FieldsPush => "| .%".to_string(),
        Stage::Subcontext { name, body } => match name {
            Some(n) => format!("| .{}({})", push_name(n), unparse(body)),
            None => format!("| .({})", unparse(body)),
        },
        // Only some operand spellings are self-delimiting after `|`
        // (the starts pipe_item's expression arms accept: a paren,
        // a quoted string, a projection, the `$` family, `@-`);
        // everything else — `(3)`, `(now())`, `(@*)`, `(^/a)` —
        // must keep parens, or the reparse reads it as a function
        // name. A bare PATH must keep parens too: unparenthesized
        // it would reparse as a navigation stage.
        Stage::Expr(e) => {
            let text = operand(e);
            let delimited = text.starts_with(['(', '\'', '"', ':', ';', '$', '%', '_'])
                || text.starts_with("@-")
                || text.starts_with("@(");
            if delimited {
                format!("| {text}")
            } else {
                format!("| ({text})")
            }
        }
        Stage::ExprPush { name, expr } => match name {
            Some(n) => format!("| .{}({})", push_name(n), operand(expr)),
            None => format!("| .({})", operand(expr)),
        },
        Stage::Select(p) => format!("@| {}", predicate(p)),
        Stage::Filter(e) => format!("| [{}]", pred_expr(e)),
        Stage::Recall(r) => format!("| {}", reg(r)),
    }
}

fn is_record_call(name: &str) -> bool {
    matches!(name, "rec" | "record")
}

/// A key of the record convention prints bare when it is an
/// identifier (`[A-Za-z_][A-Za-z0-9_]*`, and not a boolean word),
/// quoted otherwise — the canonical display of a record.
/// A push name prints bare when it is an identifier, quoted
/// otherwise (`."3"`, a pivot's data-driven column).
fn push_name(n: &str) -> String {
    if n.chars().next().is_some_and(|c| c.is_alphabetic())
        && n.chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    {
        n.to_string()
    } else {
        crate::value::quarb_string(n)
    }
}

fn is_bare_key(k: &str) -> bool {
    // An identifier in any script (names are Unicode alphanumerics
    // and `_`), never a boolean word; and `.N`, the key of an
    // anonymous regula in `%%.`.
    if k.len() > 1 && k.starts_with('.') && k[1..].bytes().all(|c| c.is_ascii_digit()) {
        return true;
    }
    let mut cs = k.chars();
    matches!(cs.next(), Some(c) if c.is_alphabetic() || c == '_')
        && cs.all(|c| c.is_alphanumeric() || c == '_')
        && !crate::parser::is_bool_word(k)
}

/// The record convention's argument list: a literal
/// string is a key and prints as `key = value` — bare when it is an
/// identifier, quoted otherwise — with `sep` between the items; an
/// auto-named value prints alone. The kaiv form, which the record
/// is emitted as.
fn record_args(call: &crate::ast::FnCall, sep: &str) -> String {
    let mut out = Vec::new();
    let mut i = 0;
    while i < call.args.len() {
        match &call.args[i] {
            Arg::Lit(Value::Str(k)) if i + 1 < call.args.len() => {
                let key = if is_bare_key(k) {
                    k.clone()
                } else {
                    literal(&Value::Str(k.clone()))
                };
                out.push(format!("{key} = {}", arg_text(&call.args[i + 1])));
                i += 2;
            }
            a => {
                out.push(arg_text(a));
                i += 1;
            }
        }
    }
    format!("({})", out.join(sep))
}

fn arg_text(a: &Arg) -> String {
    match a {
        Arg::Lit(v) => literal(v),
        Arg::Expr(e) => operand(e),
        Arg::Range(a, b) => format!(
            "{}..{}",
            a.map(|n| n.to_string()).unwrap_or_default(),
            b.map(|n| n.to_string()).unwrap_or_default()
        ),
    }
}

fn fn_call(call: &crate::ast::FnCall) -> String {
    if call.args.is_empty() {
        return call.name.clone();
    }
    let args: Vec<String> = call
        .args
        .iter()
        .map(|a| match a {
            // `csv(";"; …)`: the delimiter the parser carried as
            // `delimiter=;` reads back as the quoted character.
            Arg::Lit(Value::Str(s)) if call.name == "csv" && s.starts_with("delimiter=") => {
                match &s["delimiter=".len()..] {
                    "\t" => "\"tab\"".to_string(),
                    "\"" => "'\"'".to_string(),
                    d => format!("\"{d}\""),
                }
            }
            other => arg_text(other),
        })
        .collect();
    format!("{}({})", call.name, args.join("; "))
}

fn reg(r: &RegRef) -> String {
    match r {
        RegRef::Top => "$.".to_string(),
        RegRef::Index(n) => format!("$.{n}"),
        RegRef::Named(n) => format!("$.{n}"),
        RegRef::Whole => "@.".to_string(),
        RegRef::Record => "%.".to_string(),
        RegRef::FullRecord => "%%.".to_string(),
    }
}

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

    /// Parse `q`, unparse it, and return the canonical text.
    fn rt(q: &str) -> String {
        let toks = crate::lexer::lex(q).expect("lex");
        let ast = crate::parser::parse(&toks).expect("parse");
        unparse(&ast)
    }

    /// Assert the unparse output reparses and is a fixpoint
    /// (`unparse(parse(text)) == unparse(parse(unparse(parse(text))))`),
    /// returning the canonical text for further assertions.
    fn assert_fixpoint(q: &str) -> String {
        let once = rt(q);
        assert_eq!(rt(&once), once, "unparse is !a fixpoint for {q:?}");
        once
    }

    // Finding: `::::` is the canonical adapter-metadata spelling; the
    // deprecated `::;` alias must parse to the same AST and reprint
    // as `::::`.
    #[test]
    fn peer_reads_round_trip() {
        for q in [
            "//x | .v(::a) | <-link:.v",
            "//x | .v(::a) | (<-link:.v @| sum)",
            "/a | /*:.",
            "/a | /*:.2",
            "/a | \\/*:@.",
            "/a | \\/*:%.",
            "/a | \\/*:%%.",
            "/a | \\/*:%.:v",
            "/a | <-link:.v:::provenance",
            "/a | ((!3))::name",
            "/a | .v(1) | ((!$.v:::origin)):::name",
            "/a | ((!@(2; 3)))/*::x",
            "/a | $.v:::%provenance",
            "/a | $.v:::@origin:::source",
        ] {
            // A path-headed expression stage prints parenthesized,
            // as every such stage does; the spelling inside is the
            // written one.
            let canon = assert_fixpoint(q);
            assert!(
                canon.contains(&q[q.rfind("| ").unwrap() + 2..]),
                "{q:?} -> {canon:?}"
            );
        }
        // The rounded twin prints pointy.
        assert_eq!(rt("/a | \\/*:(*.)"), rt("/a | \\/*:@."));
    }

    #[test]
    fn expression_heads_strings_and_chains_round_trip() {
        // `= 3` is not `| (3)`, which is the capture `$3`
        assert_eq!(rt("= 3"), "= 3");
        assert_eq!(rt("= 1 + 2 | $_ * 2"), "= 1 + 2 | $_ * 2");
        // the rounded hole's opener is escaped inside a string
        assert_eq!(rt("= 'a(,b'"), r#"= "a\(,b""#);
        assert_fixpoint(r#"= "a\(,b""#);
        // grouping prints only where the parse needs it
        assert_eq!(rt("= (1 + 2) * 3"), "= (1 + 2) * 3");
        assert_eq!(rt("= 1 + 2 * 3"), "= 1 + 2 * 3");
        assert_eq!(rt("= 1 - (2 - 3)"), "= 1 - (2 - 3)");
        assert_eq!(rt("= 1 - 2 - 3"), "= 1 - 2 - 3");
        assert_eq!(rt("= - (1 + 2)"), "= - (1 + 2)");
        let chain = format!("= {}", vec!["1"; 70].join(" + "));
        assert_eq!(rt(&chain), chain);
    }

    #[test]
    fn adapter_meta_alias_canonicalizes() {
        assert_eq!(rt("//*.txt::::size"), "//*.txt::::size");
        assert_eq!(rt("//*.txt::::size"), "//*.txt::::size");
        assert_eq!(rt("//*.txt::::size"), "//*.txt::::size");
        assert_eq!(
            rt("/commits/*[::::short = ^/tags/*::::short]"),
            "/commits/*[::::short = ^/tags/*::::short]"
        );
        // The def statement terminator still lexes as a single `;`.
        assert_eq!(rt("def &f: //x::::size; &f"), rt("def &f: //x::::size; &f"));
    }

    // Finding: a projection key named `and`/`or`/`not` must reprint
    // quoted, or the bare `::and` relexes as the default projection
    // followed by the connective keyword.
    #[test]
    fn projection_keyword_key_is_quoted() {
        assert_eq!(assert_fixpoint("/x::\"and\""), "/x::\"and\"");
        assert_eq!(assert_fixpoint("/x::\"or\""), "/x::\"or\"");
        assert_eq!(assert_fixpoint("/x:::\"not\""), "/x:::\"not\"");
        assert_eq!(assert_fixpoint("/x::::\"and\""), "/x::::\"and\"");
        // A near-miss name is not a keyword and stays bare.
        assert_eq!(assert_fixpoint("/x::android"), "/x::android");
    }

    // Finding: the double-quote fallback for a string holding a single
    // quote must escape `"`, `\`, and `$`.
    #[test]
    fn double_quote_fallback_escapes() {
        // Embedded double quotes.
        assert_eq!(
            assert_fixpoint("/x[::msg = \"it's \\\"fine\\\"\"]"),
            "/x[::msg = \"it's \\\"fine\\\"\"]"
        );
        // A `${…}` that must NOT become a live interpolation hole.
        assert_eq!(
            assert_fixpoint("/x[::msg = \"don't pay \\${fee}\"]"),
            "/x[::msg = \"don't pay \\${fee}\"]"
        );
        // A literal backslash beside the single quote.
        assert_eq!(
            assert_fixpoint("/x[::msg = \"it's a\\\\b\"]"),
            "/x[::msg = \"it's a\\\\b\"]"
        );
    }

    // Finding: a substitution pattern/replacement holding a literal
    // slash must reprint it escaped as `\/`.
    #[test]
    fn substitution_reescapes_slash() {
        assert_eq!(assert_fixpoint("/x | s/a\\/b/x/"), "/x | s/a\\/b/x/");
        assert_eq!(assert_fixpoint("/x | s/a/c\\/d/"), "/x | s/a/c\\/d/");
        // No slash in the parts — output is unchanged from before.
        assert_eq!(assert_fixpoint("/x | s/a/b/g"), "/x | s/a/b/g");
    }
}