quarb 0.26.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
//! Path-pattern round-trips: groups, alternation, quantifiers, and
//! their sugars reprint in canonical (strict) form, and the
//! canonical form is a fixpoint.

use quarb::Defs;
use quarb::expand;

fn canon(q: &str) -> String {
    expand(q, &Defs::default()).unwrap()
}

fn refuse(q: &str) -> String {
    expand(q, &Defs::default()).unwrap_err().to_string()
}

#[test]
fn tolerated_reprints_strict() {
    assert_eq!(canon("//body/(p|div)"), "//body(/p|/div)");
    assert_eq!(canon("//body(/p|/div)"), "//body(/p|/div)");
}

#[test]
fn sugar_reprints_as_dot_group() {
    assert_eq!(canon("/{2}"), "(/.){2}");
    assert_eq!(canon("/div{2}"), "(/div){2}");
    assert_eq!(canon("(/.){2}"), "(/.){2}");
    // single-hop crosslink sugar
    assert_eq!(canon("/a->{2}"), "/a(->.){2}");
}

#[test]
fn quantifier_zoo_round_trips() {
    for q in [
        "/a(/b)+",
        "/a(/b)*",
        "/a(/b){2}",
        "/a(/b){1,3}",
        "/a(/b){2,}",
        "/a(/b)+?",
        "/a(/b)+!",
        "/a(/b){1,3}?",
        "/a(->mgr)+!",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // {2,2} normalizes to {2}
    assert_eq!(canon("/a(/b){2,2}"), "/a(/b){2}");
}

#[test]
fn nesting_round_trips() {
    let q = "//div(/ul/li|/ol/li|/dl(/dt|/dd))+";
    assert_eq!(canon(q), q);
    // tolerated form distributes at both levels
    assert_eq!(canon("//div/(ul/li|ol/li|dl/(dt|dd))+"), q);
}

#[test]
fn groups_in_operand_position() {
    assert_eq!(canon("/*[(->ref)+]"), "/*[(->ref)+]");
    // boolean groups keep their reading
    assert_eq!(canon("/*[(::a = 1 or ::b)]"), "/*[(::a = 1 || ::b)]");
    assert_eq!(canon("/*[(::a = 1 || ::b)]"), "/*[(::a = 1 || ::b)]");
    assert_eq!(canon("/*[(not ::a and ::b)]"), "/*[(!::a && ::b)]");
    for q in [
        "//order::amt <=>? //user[::id = $$::uid] | ...?",
        "//u <=> //v <=>? //order[::uid = $*1::id]",
        "//commit[::::short = ^/tags/*::::short]",
        "/movie .m <-ACTED_IN[::born > ((m))::released] | %(::name; ((m))::title)",
        "/c/* | (::kind ?= 'a' ? 1 : (/^b/) ? 2 : 0)",
        "/tags/* | .t(:::name) | `cloc --git ${$.t}` | %($.t; lines = $_)",
        "/x::v | base64 | decode('base64')",
        "/x::v @| sort('ru-RU')",
        "/a/*[^//error] | %(n = :::name; of = (^//*.rs @| count))",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // a value group still computes
    assert_eq!(canon("/a | (::x + 1) * 2"), "/a | (::x + 1) * 2");
}

#[test]
fn pattern_errors() {
    assert!(refuse("(/a){3,2}").contains("max below min"));
    assert!(refuse("(|/a)").contains("at least one hop"));
    // a push alone does not walk
    assert!(refuse("(.(::q))+").contains("at least one hop"));
    assert!(refuse("/(p|/div)").contains("strict form"));
    assert!(refuse("//{2}").contains("single-hop"));
    // `+` and `*` are name characters: quantifying an unquoted named
    // hop with them is not expressible — the name absorbs the mark.
    assert_eq!(canon("/a/g++"), "/a/g++");
}

#[test]
fn edge_accessor_round_trips() {
    for q in [
        "/a->e[$-::qty > 1]",
        "/a->*[$- = 'e']",
        "/a<-mgr[$-::since = 2020]::name",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // core/adapter metadata do not live on edges
    assert!(refuse("/a->e[$-:::depth = 1]").contains("plain properties"));
}

#[test]
fn group_predicates_round_trip() {
    for q in [
        "/a(->e)+[::q > 1]?",
        "/a(/b|/c/d)[::x]",
        "(/employees .($-))+[::name = 'Meg']?",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    assert!(refuse("/a(/b)+[1]").contains("expression predicates only"));
    assert!(refuse("/a(/b)+[1..2]").contains("expression predicates only"));
}

#[test]
fn pattern_pushes_round_trip() {
    for q in [
        "/a(->e .($-::qty))+ | @. | product",
        "/a(->e .w($-))+",
        "(/employees .($-))+?",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // a glued named push after a named hop stays part of the name
    // (the /x.rs(...) rule): "e.q" becomes the matcher and the
    // parenthesized rest cannot parse as a group — the spaced form
    // is the push
    assert!(expand("/a(->e.q($-))+", &Defs::default()).is_err());
}

#[test]
fn arrived_edges_round_trip() {
    for q in [
        "/a->e | .(@-::qty)",
        "/a->e | .(@-)",
        "/a | %(::x; l = @-)",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    assert!(refuse("/a | .(@-:::depth)").contains("plain properties"));
}

#[test]
fn context_and_piped_round_trip() {
    for q in [
        "/a | .p(((::x div (@*::x @| sum)) * 100 | round))",
        "/a | %(::n; all = (@*:::name @| sort @| join(', ')))",
        "/a[@* = null]",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    assert!(refuse("/a | .x((@* | .bad))").contains("real capsae"));
}

#[test]
fn conditional_round_trip() {
    for q in [
        "/a | %(::n; era = (::y < 2000 ? 'old' : 'new'))",
        "/a[(::x ? 1 : 2) = 1]",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // chains normalize to explicit nesting, and the normal form is
    // a fixpoint
    assert_eq!(
        canon("/a | (::x < 2 ? 'lo' : ::x < 9 ? 'mid' : 'hi')"),
        "/a | (::x < 2 ? 'lo' : (::x < 9 ? 'mid' : 'hi'))"
    );
    assert!(refuse("/a | (::x ? 'lo')").contains("':'"));
}

#[test]
fn trait_algebra_round_trip() {
    for q in [
        "/a<code>",
        "/a<block || inline>",
        "/a<Person && !Employee>",
        "/a<!*>",
        "/a<(a || b) && !c>",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // stacking still parses; canonical form is one bracket
    assert_eq!(canon("/a<x><y>"), "/a<x && y>");
    // distribution: OR over AND normalizes to CNF
    assert_eq!(canon("/a<(x && y) || z>"), "/a<(x || z) && (y || z)>");
    // double negation eliminates
    assert_eq!(canon("/a<!!x>"), "/a<x>");
}

#[test]
fn spread_round_trip() {
    for q in [
        "/a->e | @-::roles | ... | ...",
        "/a | (@*::x | ...) @| count",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    // `each` is gone: it parses as an unknown function now
    assert!(refuse("/a | @-::x | each").contains("each"));
}

#[test]
fn map_pipe_round_trip() {
    for q in [
        "/a | @-::roles $| upper",
        "/a | @. $| [$_ > 1] $| [1..2]",
        "/a | .p((@. $| $_ * 2))",
    ] {
        assert_eq!(canon(q), q, "not a fixpoint: {q}");
    }
    assert!(refuse("/a | @. $| .bad").contains("real capsae"));
}

#[test]
fn defs_substitute_into_groups() {
    // a fragment parameter inside a grouped step's predicate
    let src = "def &chain($n): /employees(/reports[::id = $n])+; &chain(7)";
    assert_eq!(canon(src), "/employees(/reports[::id = 7])+");
}

#[test]
fn headless_arrow_round_trips() {
    // `--` — the either-direction crosslink — parses in path,
    // group, and predicate-operand position, and reprints as
    // itself. Glued after a row name it is still the hop, like
    // `->` (the name lexer breaks on the dash run).
    assert_eq!(canon("/posts/5--ip"), "/posts/5--ip");
    assert_eq!(
        canon("/cookies/c1(--cookie--ip--ip--cookie)+::id"),
        "/cookies/c1(--cookie--ip--ip--cookie)+::id"
    );
    assert_eq!(canon("/a(--*--*)+::name"), "/a(--*--*)+::name");
    assert_eq!(canon("/ips/*[--ip]::id"), "/ips/*[--ip]::id");
    // A dash-leading matcher keeps a separating space on reprint,
    // so the axis survives the round trip.
    assert_eq!(canon("/a-- -b"), "/a-- -b");
}

#[test]
fn resolution_respell_canonicalizes() {
    // `-->` / `<--` are canonical; the tilde forms remain accepted
    // and canonicalize on unparse, like `;;;` to `::::`.
    assert_eq!(canon("/tracks/1::album_id~>::title"), "/tracks/1::album_id-->::title");
    assert_eq!(canon("/tracks/1::album_id-->::title"), "/tracks/1::album_id-->::title");
    assert_eq!(canon("/loan::book~>shelf"), "/loan::book-->shelf");
    assert_eq!(canon("/page::id<~"), "/page::id<--");
    assert_eq!(canon("/page::id<--cite"), "/page::id<--cite");
    // the digit guard holds: `<-3` is still a comparison shape
    assert_eq!(canon("/x[::a <-3]"), "/x[::a < -3]");
}

#[test]
fn rounded_predicate_alias_canonicalizes() {
    // `(?…)` — the rounded predicate — is a permanent
    // typing-friendly alias of `[…]` in every bracket position:
    // predicate, index, range, map-pipe filter and slice. An
    // index is a positional predicate — one bracket family, so
    // one alias covers it.
    assert_eq!(
        canon("//user(?::age >= 18)(?1)->profile/name"),
        canon("//user[::age >= 18][1]->profile/name")
    );
    assert_eq!(canon("/a(?::x = 'y')"), "/a[::x = 'y']");
    assert_eq!(canon("/a(?2..3)"), "/a[2..3]");
    assert_eq!(canon("/a(?-1)"), "/a[-1]");
    assert_eq!(canon("/a $| (?::n > 2)"), canon("/a $| [::n > 2]"));
    assert_eq!(canon("/a $| (?..3)"), canon("/a $| [..3]"));
    // inner parens balance independently of the predicate pair
    assert_eq!(
        canon("/a(?(::x = 1 || ::y = 2) && ::z = 3)"),
        canon("/a[(::x = 1 || ::y = 2) && ::z = 3]")
    );
    // the two spellings nest freely, and a regex body stays raw
    assert_eq!(canon("/a[::x = 1](?::y = 2)"), "/a[::x = 1][::y = 2]");
    assert_eq!(canon("/~((?i)bob)(?::x = 1)"), "/(/(?i)bob/)[::x = 1]");
    // the pair does not mix spellings
    assert!(refuse("/a(?::x = 1]").contains("closes with ')'"));
    // and the pointy family is untouched: a group stays a group
    assert_eq!(canon("/a(/b|/c)"), "/a(/b|/c)");
}

#[test]
fn rounded_family_canonicalizes() {
    // The second slice of the rounded family (ruling #40): every
    // alias canonicalizes to its pointy form.
    // reverse arrows
    assert_eq!(canon("/page::id--:cite"), "/page::id<--cite");
    assert_eq!(canon("/a-:b"), "/a<-b");
    assert_eq!(canon("/a(-:b)+::name"), canon("/a(<-b)+::name"));
    // the edge accessors are untouched, in either spelling
    assert_eq!(canon("/a:-b(?$-::w > 1)"), canon("/a->b[$-::w > 1]"));
    // sibling hops and reaches
    assert_eq!(canon("/a;-b"), canon("/a>b"));
    assert_eq!(canon("/a-;b"), canon("/a<b"));
    assert_eq!(canon("/a;;-?b"), canon("/a>>?b"));
    assert_eq!(canon("/a-;;!b"), canon("/a<<!b"));
    // the sibling alias names the hop only — never the comparison
    assert!(!refuse("/x[::a ;- 3]").is_empty());
    // ascent
    assert_eq!(canon("/a/b../c"), canon("/a/b\\c"));
    assert_eq!(canon("/a/b..//c"), canon("/a/b\\\\c"));
    assert_eq!(canon("/a/b..//?c"), canon("/a/b\\\\?c"));
    assert_eq!(canon("/a/b..//!c"), canon("/a/b\\\\!c"));
    // traits
    assert_eq!(
        canon("//user(:admin && !banned)::name"),
        canon("//user<admin && !banned>::name")
    );
    assert_eq!(canon("//user(:admin)(?::age > 18)"), canon("//user<admin>[::age > 18]"));
    assert_eq!(canon("//x(:.custom)"), canon("//x<.custom>"));
    // a group opening on a projection, or on the :- arrow, stays a group
    assert_eq!(canon("/a(?(::x = 1 || ::y = 2))"), "/a[(::x = 1 || ::y = 2)]");
    assert_eq!(canon("/e(:-manager_id)+::name"), "/e(->manager_id)+::name");
    // quantifier
    assert_eq!(canon("/a(/b)(;2,3)"), "/a(/b){2,3}");
    assert_eq!(canon("/a(/b)(;2)"), "/a(/b){2}");
    assert_eq!(canon("/a(/b)(;2,)"), "/a(/b){2,}");
    // the appendix example, rounded to pointy
    assert_eq!(
        canon("//user(:admin)(?::age >= 18)(?1):-profile/name"),
        canon("//user<admin>[::age >= 18][1]->profile/name")
    );
}

#[test]
fn root_anchor_and_comparison_words_canonicalize() {
    // Ruling #41 (respelled by #43): `(())` is the root anchor's
    // rounded spelling …
    assert_eq!(canon("(())/a/b::x"), canon("^/a/b::x"));
    assert_eq!(canon("(())//x"), canon("^//x"));
    assert_eq!(canon("/a[::x = (())/set/*::x]"), canon("/a[::x = ^/set/*::x]"));
    assert_eq!(canon("(()) | count"), canon("^ | count"));
    // … but a glued pair is a call's argument list, untouched
    assert_eq!(canon("/x[::t < now()]"), canon("/x[::t < now()]"));
    // … and the spelled comparisons — Latin, French, Russian, Greek —
    // canonicalize to the symbols
    assert_eq!(canon("/u[::age .minor. 18]"), "/u[::age < 18]");
    assert_eq!(canon("/u[::age .nonmaior. 18]"), "/u[::age <= 18]");
    assert_eq!(canon("/u[::age .maior. 18]"), "/u[::age > 18]");
    assert_eq!(canon("/u[::age .nonminor. 18]"), "/u[::age >= 18]");
    assert_eq!(canon("/u[::age .inf. 18]"), "/u[::age < 18]");
    assert_eq!(canon("/u[::age .nonsup. 18]"), "/u[::age <= 18]");
    assert_eq!(canon("/u[::age .sup. 18]"), "/u[::age > 18]");
    assert_eq!(canon("/u[::age .noninf. 18]"), "/u[::age >= 18]");
    // a glued word is a name, never an operator
    assert_eq!(canon("/u[::age.minor.18]"), "/u[::age.minor.18]");
    assert_eq!(canon("/u(?::age .менее. 18)"), "/u[::age < 18]");
    assert_eq!(canon("/u(?::age .неболее. 18)"), "/u[::age <= 18]");
    assert_eq!(canon("/u(?::age .более. 18)"), "/u[::age > 18]");
    assert_eq!(canon("/u(?::age .неменее. 18)"), "/u[::age >= 18]");
    assert_eq!(canon("/u(?::age .μικρότερο. 18)"), "/u[::age < 18]");
    assert_eq!(canon("/u(?::age .τοπολύ. 18)"), "/u[::age <= 18]");
    assert_eq!(canon("/u(?::age .μεγαλύτερο. 18)"), "/u[::age > 18]");
    assert_eq!(canon("/u(?::age .τουλάχιστον. 18)"), "/u[::age >= 18]");
    assert_eq!(canon("/u(?::age .τουλαχιστον. 18)"), "/u[::age >= 18]");
    // the full rounded query, once more, with a word comparison
    assert_eq!(
        canon("(())//user(:admin)(?::age .nonminor. 18)(?1):-profile/name"),
        canon("^//user<admin>[::age >= 18][1]->profile/name")
    );
}

#[test]
fn boolean_words_canonicalize() {
    // Ruling #42: `and` / `or` / `not` in each language of the
    // rounded family, all canonicalizing to the symbols.
    let pointy = canon("/u[::a = 1 and ::b = 2 or not ::c]");
    for q in [
        "/u[::a = 1 et ::b = 2 vel non ::c]",
        "/u[::a = 1 et ::b = 2 ou non ::c]",
        "/u(?::a = 1 и ::b = 2 или не ::c)",
        "/u(?::a = 1 και ::b = 2 ή όχι ::c)",
        "/u(?::a = 1 και ::b = 2 η οχι ::c)",
    ] {
        assert_eq!(canon(q), pointy, "{q}");
    }
    // the words are loose like `not`: they negate a whole condition
    assert_eq!(canon("/u(?не ::age .nonminor. 18)"), canon("/u[not ::age >= 18]"));
    // a quoted field keeps a word as its name
    assert!(canon("/u[::'и' = 1]").contains("и"));
}

#[test]
fn rounded_pipes_registers_anchors_canonicalize() {
    // Ruling #43. The pipe family: `__` the bar lying down, `*__`
    // all-then, `,__` each-then.
    assert_eq!(canon("/a __ count"), canon("/a | count"));
    assert_eq!(canon("/a::x *__ max"), canon("/a::x @| max"));
    assert_eq!(canon("/a::x ,__ (?(_) .maior. 2)"), canon("/a::x $| [$_ > 2]"));
    assert_eq!(canon("/a __ ..."), canon("/a | ..."));
    assert_eq!(canon("/a __ ...?"), canon("/a | ...?"));
    // the correlation, mirrored like the arrows
    assert_eq!(
        canon("//user :=: //order(?::uid = ((_))::id)"),
        canon("//user <=> //order[::uid = $$::id]")
    );
    assert_eq!(
        canon("//order::amt :=:? //user(?::id = ((_))::uid) __ ...?"),
        canon("//order::amt <=>? //user[::id = $$::uid] | ...?")
    );
    // the value side: single parens
    assert_eq!(canon("/a ,__ (?(_) .maior. 2)"), canon("/a $| [$_ > 2]"));
    assert_eq!(canon("/a .s /b __ (.s)"), canon("/a .s /b | $.s"));
    assert_eq!(canon("/a . /b . __ (.2)"), canon("/a . /b . | $.2"));
    assert_eq!(canon("/a :-b(?(-)::w .maior. 1)"), canon("/a->b[$-::w > 1]"));
    assert_eq!(
        canon("/users/* :=: /orders/*(?/uid:: = ((_))/id::) __ rec(::name, 'amt', (*1)/amt::)"),
        canon("/users/* <=> /orders/*[/uid:: = $$/id::] | rec(::name, 'amt', $*1/amt::)")
    );
    // the node side: double parens are canonical, single parens the
    // deprecated alias — and `(.)` is now the register file
    assert_eq!(canon("/a . /b .m | ((1))/c | ((.))/d | ((@))/e | ((@m))/f"), "/a . /b .m | ((1))/c | ((.))/d | ((@))/e | ((@m))/f");
    assert_eq!(canon("/a . /b .m | (@)/e | (@m)/f"), "/a . /b .m | ((@))/e | ((@m))/f");
    // `(N)` is the match capture `$N` — a value; the mark at N is `((N))`
    assert_eq!(
        canon("/row __ (?::name =~ (/^(\\w+), (\\w+)/)) __ rec('k', (1), 'j', (2))"),
        canon("/row | [::name =~ /^(\\w+), (\\w+)/] | rec('k', $1, 'j', $2)")
    );
    assert_eq!(canon("/a .s /b | ((*s))::x"), canon("/a .s /b | (@s)::x"));
    assert_eq!(canon("((m))/address"), canon("(m)/address"));
    assert_eq!(canon("(m)/address"), "((m))/address");
}

#[test]
fn regex_literal_canonicalizes() {
    // Ruling #44: `(/…/)` is the regex literal, canonical in both
    // positions; `~(…)` is a deprecated alias, the bare `/…/` after
    // `=~` / `!~` sugar, and `= (/…/)` a match by the pattern
    // doctrine.
    assert_eq!(canon("//~(^ch)"), "//(/^ch/)");
    assert_eq!(canon("//(/^ch/)"), "//(/^ch/)");
    assert_eq!(canon("/u[::name =~ /^bob/i]"), "/u[::name =~ (/^bob/i)]");
    assert_eq!(canon("/u[::name =~ (/^bob/i)]"), "/u[::name =~ (/^bob/i)]");
    assert_eq!(canon("/u(?::name = (/^bob/i))"), "/u[::name =~ (/^bob/i)]");
    assert_eq!(canon("/u[::name != (/x/)]"), "/u[::name !~ (/x/)]");
    assert_eq!(canon("/u[::name !~ /x/]"), "/u[::name !~ (/x/)]");
    assert_eq!(canon("/u[::name =~ 'x']"), "/u[::name =~ (/x/)]");
    assert_eq!(canon("/u[::name = ~(x)]"), "/u[::name =~ (/x/)]");
    // a slash in the body escapes on the way out
    assert_eq!(canon("//(/a\\/b/)"), "//(/a\\/b/)");
    // a dynamic right operand is untouched
    assert_eq!(canon("/u[::name =~ ::pat]"), "/u[::name =~ ::pat]");
    // the value-match arms take the literal too
    assert_eq!(
        canon("/c/* | (::kind ?= 'a' ? 1 : ~(^b) ? 2 : 0)"),
        "/c/* | (::kind ?= 'a' ? 1 : (/^b/) ? 2 : 0)"
    );
    // a group ending in a hop named x is still a group
    assert_eq!(canon("/a(/src/x)+"), "/a(/src/x)+");
}

#[test]
fn boolean_words_in_traits_canonicalize() {
    // Ruling #42, completed: the trait algebra takes the words.
    let pointy = canon("//user<admin && !banned || staff>::name");
    for q in [
        "//user<admin and not banned or staff>::name",
        "//user(:admin et non banned vel staff)::name",
        "//user(:admin et non banned ou staff)::name",
        "//user(:admin и не banned или staff)::name",
        "//user(:admin και όχι banned ή staff)::name",
    ] {
        assert_eq!(canon(q), pointy, "{q}");
    }
    assert_eq!(canon("/div(:(a ou b) et non c)"), canon("/div<(a || b) && !c>"));
    // a lone word is still a trait name
    assert_eq!(canon("/x<and>"), "/x<and>");
    assert_eq!(canon("/x<и>"), "/x<и>");
}

#[test]
fn record_field_colon_canonicalizes() {
    // Ruling #48: `:name` is a record's field — the bottom rung of
    // the colon ladder; `%+` the named-captures record.
    assert_eq!(canon("/a | .r | $.r:x"), "/a | .r | $.r:x");
    assert_eq!(canon("/a | .r | (.r):x"), "/a | .r | $.r:x");
    assert_eq!(canon("/a | $.r:a:b"), "/a | $.r:a:b");
    assert_eq!(canon("/a | :n"), "/a | :n");
    assert_eq!(canon("/a | $_:n"), "/a | :n");
    assert_eq!(canon("/a | [:n .maior. 1]"), canon("/a | [$_:n > 1]"));
    assert_eq!(canon("/a | %+"), "/a | %+");
    assert_eq!(canon("/a | %+:year"), "/a | %+:year");
    assert_eq!(canon("/a | [%+:year .maior. 2000]"), "/a | [%+:year > 2000]");
    // a node has properties, not fields
    assert!(refuse("/user/*:name").contains("::name"));
    // the else colon is spaced; glued, it reads as a field
    assert_eq!(canon("/x | (::a ?= 1 ? 2 : 0)"), "/x | (::a ?= 1 ? 2 : 0)");
    assert!(refuse("/x | (::a ?= 1 ? 2 :zero)").contains("':'"));
}

#[test]
fn keyed_aggregates_refuse_the_plain_pipe() {
    // A keyed aggregate ranks a context: `@|`, or per group after
    // `@| group`; alone on the plain pipe it is refused, loudly.
    assert!(refuse("/a | top(3, ::x)").contains("@| top"));
    assert!(refuse("/a | sort_by(::x)").contains("@| sort_by"));
    assert!(canon("/a @| top(3, ::x)").contains("@| top"));
    assert!(canon("/a @| group(::k) | top(3, ::x)").contains("| top"));
    assert!(canon("/a *__ top(3, ::x)").contains("@| top"));
    // a field of the topic record is a key like any other
    for q in [
        "/a | %(::n, 't', ::t) @| sort_by(:t)",
        "/a | %(::n, 't', ::t) @| unique_by(:t)",
        "/a | %(::n, 't', ::t) @| min_by(:t)",
        "/a | %(::n, 't', ::t) @| max_by(:t)",
        "/a | %(::n, 't', ::t) @| top(2, :t)",
        "/a | %(::n, 't', ::t) @| group(:t) | top(1, :n)",
    ] {
        assert!(canon(q).contains("(:"), "{q}: {}", canon(q));
    }
}

#[test]
fn record_push_canonicalizes() {
    // Ruling #49: the record push in one step, anonymous or named,
    // plain or enriched; the sigil spelling is canonical.
    assert_eq!(canon("/a | .%(::x, 'n', 1)"), "/a | .%(::x; n = 1)");
    assert_eq!(canon("/a | .r%(::x)"), "/a | .r%(::x)");
    assert_eq!(canon("/a | .r%%(::x)"), "/a | .r%%(::x)");
    assert_eq!(canon("/a | .r%(::x) | $.r:x"), "/a | .r%(::x) | $.r:x");
    assert!(refuse("/a | .r%").contains("record push"));
    // a push returns the thread to navigation mode, as any push does
    assert_eq!(canon("/a | .r%(::x) | /b"), "/a | .r%(::x) | /b");
}

#[test]
fn operand_paths_ascend_and_step_sideways() {
    // A path operand may ascend and step sideways, as a branch may.
    assert_eq!(canon("/a/b[\\*::x = 1]"), "/a/b[\\*::x = 1]");
    assert_eq!(canon("/a/b[\\\\?c::x = 1]"), "/a/b[\\\\?c::x = 1]");
    // (a bare key is a string; canonical output quotes it)
    assert_eq!(canon("/p | rec(dir, \\*:::name, me, ::city)"), "/p | %(dir = \\*:::name; me = ::city)");
    assert_eq!(canon("/a[;-*::x = 1]"), "/a[>*::x = 1]");
    assert_eq!(canon("/a[>>?*::x = 1]"), "/a[>>?*::x = 1]");
    assert_eq!(canon("/a | rec(up, ../*::n)"), "/a | %(up = \\*::n)");
}

#[test]
fn record_convention_canonicalizes() {
    // Ruling #50: `%(k = v; k2 = v2)` — the kaiv form — is the
    // record's canonical spelling; keys bare when identifiers.
    assert_eq!(canon("/a | %(n = ::age; city = /profile::city)"), "/a | %(n = ::age; city = /profile::city)");
    // the flat Perl-list form and the comma both parse, and canonicalize
    assert_eq!(canon("/a | rec(\"n\", ::age, \"city\", /profile::city)"), "/a | %(n = ::age; city = /profile::city)");
    assert_eq!(canon("/a | %(n = ::age, city = /profile::city)"), "/a | %(n = ::age; city = /profile::city)");
    assert_eq!(canon("/a | record(n, ::age)"), "/a | %(n = ::age)");
    // auto-named values mix with keyed ones
    assert_eq!(canon("/a | %(::name; kb = ::size)"), "/a | %(::name; kb = ::size)");
    // a non-identifier key quotes; a value may be a comparison
    assert_eq!(canon("/a | %('my-key' = 1; adult = ::age >= 18)"), "/a | %('my-key' = 1; adult = (::age >= 18))");
    assert_eq!(canon("/a | %(and = 1)"), "/a | %('and' = 1)");
    // the same convention in the enriched view, the record push, and group
    assert_eq!(canon("/a | %%(k = 2)"), "/a | %%(k = 2)");
    assert_eq!(canon("/a | .r%(k = ::x; j = 1)"), "/a | .r%(k = ::x; j = 1)");
    assert_eq!(canon("/a @| group(k = ::x, ::y)"), "/a @| group(k = ::x, ::y)");
    assert_eq!(canon("/a @| group(\"k\", ::x)"), "/a @| group(k = ::x)");
}

#[test]
fn list_literal_canonicalizes() {
    // Ruling #52: `@(a; b)` is the list literal; the comma also
    // separates on input; items are operands.
    assert_eq!(canon("/a | @(1; 2; 3)"), "/a | @(1; 2; 3)");
    assert_eq!(canon("/a | @(1, 2, 3)"), "/a | @(1; 2; 3)");
    assert_eq!(canon("/a | @()"), "/a | @()");
    assert_eq!(canon("/a | %(tags = @(::x; 'y'); n = 1)"), "/a | %(tags = @(::x; 'y'); n = 1)");
    assert_eq!(canon("/a | @(/tags/*::)"), "/a | @(/tags/*::)");
    // the expression head canonicalizes as `^ | …` (exprhead.rs)
    assert_eq!(canon("= @(1; 2) | count"), "^ | @(1; 2) | count");
    // the rounded spelling `*(…)` — only where a value can begin
    assert_eq!(canon("/a | *(1; 2)"), "/a | @(1; 2)");
    assert_eq!(canon("/a[::x = *(1; 2)]"), "/a[::x = @(1; 2)]");
    assert_eq!(canon("/*(?::x = 1)"), "/*[::x = 1]");
}

#[test]
fn tail_colon_aliases_canonicalize() {
    // `:-` and `:--` — the tail-colon spellings — are permanent
    // typing-friendly aliases of `->` and `-->`.
    assert_eq!(canon("/employees/6(:-manager_id)+::name"), "/employees/6(->manager_id)+::name");
    assert_eq!(canon("/tracks/1::album_id:--::title"), "/tracks/1::album_id-->::title");
    assert_eq!(canon("/a:-b"), "/a->b");
    // a conditional's glued else-negative is untouched
    assert_eq!(
        canon("/x | (::a ?= 1 ? 2 :-3)"),
        canon("/x | (::a ?= 1 ? 2 : -3)")
    );
}