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
//! Tcl-flavored lexer.
//!
//! Words are whitespace-separated. `{ ... }` is a verbatim (brace-quoted) block
//! whose inner text is re-lexed by the parser when it is known to be a command
//! body. `"..."` is a literal string (no interpolation in M1). `#` begins a
//! comment to end-of-line, but only where a command is expected (start of line,
//! after `;`) and only in a brace that holds commands — `sel { … }` holds a CSS
//! selector, so `#` is an ID selector there (see `lex_opts`). `;` and newline
//! terminate commands.

#[derive(Debug, Clone, PartialEq)]
pub enum Tok {
    /// A bare word: paths (`.x`), flags (`-opt`), values, `<-`, verbs.
    Word(String),
    /// A `"..."` literal.
    Str(String),
    /// Raw inner text of a `{ ... }` block, parsed recursively by the parser.
    Block(String),
    /// Command terminator: `;` or newline.
    Sep,
}

/// Tokenize a spec source string. Each token carries its start char-offset (used
/// by the LSP to anchor a diagnostic); errors carry the offending span.
///
/// `jq_ok` says whether a jq literal may start a command here. It is true only
/// inside a `{ … }` body, where a leading `.` is unambiguous. At top level a
/// command legitimately starts with a widget path — `.x <- in` (bind shorthand)
/// and `.g configure -max 200` — so reading `.`-first commands as jq literals
/// there would swallow those whole.
///
/// Comments are enabled. `lex_opts` is the spelling that can turn them off, for
/// the one brace whose contents are not commands.
pub fn lex(src: &str, jq_ok: bool) -> Result<Vec<(Tok, usize)>, crate::err::SpecError> {
    lex_opts(src, jq_ok, true)
}

/// `lex`, with the `#` comment rule made optional.
///
/// `hash_comments` is false for exactly one brace: `sel { … }`, whose contents
/// are a CSS SELECTOR rather than a command list. `#main` is an ID selector
/// there, and reading it as a comment to end-of-line emptied the block, so the
/// documented spelling `sel { #main }` reported `sel: expected a CSS selector`
/// instead of selecting the element. Every other brace in the language holds
/// commands, where `#` keeps its comment meaning.
pub fn lex_opts(
    src: &str,
    jq_ok: bool,
    hash_comments: bool,
) -> Result<Vec<(Tok, usize)>, crate::err::SpecError> {
    use crate::err::SpecError;
    let cs: Vec<char> = src.chars().collect();
    let n = cs.len();
    let mut i = 0;
    let mut toks = Vec::new();
    // `#` is a comment only where a command is expected.
    let mut at_cmd_start = true;

    while i < n {
        let c = cs[i];
        match c {
            ' ' | '\t' | '\r' => i += 1,
            '\n' | ';' => {
                toks.push((Tok::Sep, i));
                i += 1;
                at_cmd_start = true;
            }
            '#' if at_cmd_start && hash_comments => {
                while i < n && cs[i] != '\n' {
                    i += 1;
                }
            }
            // A jq literal occupies a whole body command (`.a | select(.k ==
            // "v")`, `reduce .[] as $x (0; . + $x)`, `{k: .v}`). Lex it as ONE
            // verbatim atom so the jq front-end receives the exact source text.
            // Splitting it into verb + args and space-joining them back (what
            // the parser would otherwise hand downstream) is lossy three times
            // over: `Arg::Str` drops its quotes, so `select(.k == "v")`
            // reconstructs as `select(.k == v )` and silently compares against a
            // bareword; the rejoin injects spaces, so `.["k"]` becomes `.[ "k" ]`
            // and no longer parses as a path; and a `;` — jq's ARGUMENT
            // separator — is an arb command terminator, so `setpath(["a"];9)`
            // would be cut in half.
            //
            // The scan tracks `"` strings (honouring `\"`) and `(`/`[`/`{` depth
            // so a `;` or a brace inside any of them does not end the command. A
            // `}` at depth 0 is the ENCLOSING arb block closing, and ends it.
            //
            // This arm sits ahead of the `"` and `{` arms deliberately: a jq
            // program may BEGIN with either (`"\(.a)"`, `{k: .v}`), and those
            // arms would otherwise take the opener first.
            _ if jq_ok && at_cmd_start && jq_literal_at(&cs, i) => {
                let start = i;
                let mut depth = 0i32;
                // `def NAME: BODY;` ends its definition with a `;` at depth 0 —
                // the same character arb uses to end a command. A jq program that
                // holds a top-level `def` therefore runs to end of line (or to
                // the block's `}`), which is the only reading under which
                // `def f: . * 2; map(f)` is one program rather than two commands.
                // jq's grammar allows a `def` after a pipe too (`. | def f: 1;
                // f`, `1 as $x | def f: $x; f`), so the keyword counts wherever
                // it starts a term, not only at the front.
                let mut def_led = false;
                while i < n {
                    if depth == 0 && !def_led {
                        def_led = def_keyword_at(&cs, i);
                    }
                    match cs[i] {
                        // A string, interpolations included, is skipped whole; an
                        // unterminated one runs to the end of the text.
                        '"' => i = skip_jq_string(&cs, i).unwrap_or(n - 1),
                        // A `#` comment runs to the end of the line: a `;` or `)`
                        // in it is comment text, not a terminator or a bracket.
                        '#' => {
                            while i + 1 < n && cs[i + 1] != '\n' {
                                i += 1;
                            }
                        }
                        '(' | '[' | '{' => depth += 1,
                        ')' | ']' => depth -= 1,
                        '}' => {
                            if depth == 0 {
                                break;
                            }
                            depth -= 1;
                        }
                        ';' if depth == 0 && !def_led => break,
                        '\n' if depth == 0 => break,
                        _ => {}
                    }
                    i += 1;
                }
                let w: String = cs[start..i].iter().collect();
                toks.push((Tok::Word(w.trim_end().to_string()), start));
                at_cmd_start = false;
            }
            '"' => {
                let q = i;
                i += 1;
                let mut s = String::new();
                while i < n && cs[i] != '"' {
                    if cs[i] == '\\' && i + 1 < n {
                        i += 1;
                        s.push(match cs[i] {
                            'n' => '\n',
                            't' => '\t',
                            o => o,
                        });
                    } else {
                        s.push(cs[i]);
                    }
                    i += 1;
                }
                if i >= n {
                    return Err(SpecError {
                        msg: "unterminated string".into(),
                        span: Some((q, n)),
                    });
                }
                i += 1; // closing quote
                toks.push((Tok::Str(s), q));
                at_cmd_start = false;
            }
            '{' => {
                let open = i;
                let mut depth = 1;
                i += 1;
                let start = i;
                while i < n {
                    match cs[i] {
                        '{' => depth += 1,
                        '}' => {
                            depth -= 1;
                            if depth == 0 {
                                break;
                            }
                        }
                        // Skip a "..." string so a `{`/`}` inside it does not
                        // miscount block depth (honoring the `\"` escape). An
                        // unterminated string runs to EOF -> unterminated block.
                        '"' => match skip_jq_string(&cs, i) {
                            Some(close) => i = close,
                            None => {
                                i += 1;
                                while i < n && cs[i] != '"' {
                                    if cs[i] == '\\' && i + 1 < n {
                                        i += 1;
                                    }
                                    i += 1;
                                }
                            }
                        },
                        // Skip a /regex/ literal so a `{`/`}` in the pattern does
                        // not miscount depth — but only when it actually closes
                        // before end-of-line. A non-closing `/` (division, a path)
                        // is treated as an ordinary char, matching the main lexer.
                        // A `/` that follows an OPERAND is jq division, never a
                        // regex: `. / "/"` must not swallow the `"` as pattern
                        // text (which left the string open and the block
                        // "unterminated").
                        '/' if slash_is_division(&cs[start..i]) => {}
                        '/' => {
                            let mut j = i + 1;
                            let mut closed = false;
                            while j < n {
                                match cs[j] {
                                    '\\' if j + 1 < n => j += 2,
                                    '/' => {
                                        closed = true;
                                        break;
                                    }
                                    '\n' => break,
                                    _ => j += 1,
                                }
                            }
                            if closed {
                                i = j; // land on the closing `/`; the `i += 1` below steps past it
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                if depth != 0 {
                    return Err(SpecError {
                        msg: "unterminated block".into(),
                        span: Some((open, n)),
                    });
                }
                let inner: String = cs[start..i].iter().collect();
                i += 1; // closing brace
                toks.push((Tok::Block(inner), open));
                at_cmd_start = false;
            }
            '/' if at_cmd_start => {
                // An xpath location path at command position (`/a/b`, `//tag`,
                // `//a/@href`). Regex literals only ever appear as ARGS, so a
                // leading `/` here is never a regex — lex the whole path as one
                // atom so `xpath::translate` receives an intact token.
                //
                // A `[…]` PREDICATE is part of that atom, quotes and spaces
                // included. XPath accepts either quote for an attribute value, so
                // `//div[@class="card"]` is as legal as `[@class='card']` — but a
                // bare stop at `"` split it into `//div[@class=`, a `Str` arg whose
                // quotes the parser drops, and `]`, which rejoined as
                // `[@class= card ]` and was rejected as "must be quoted". That is
                // the same lossy verb+args reconstruction the jq branch below
                // documents, so it gets the same fix: track quote state and `[`
                // depth, and only treat a delimiter as one at depth 0.
                let start = i;
                let mut depth = 0i32;
                let mut in_str: Option<char> = None;
                while i < n {
                    let c = cs[i];
                    match in_str {
                        Some(q) if c == q => in_str = None,
                        Some(_) => {}
                        None => match c {
                            '\'' | '"' if depth > 0 => in_str = Some(c),
                            '[' => depth += 1,
                            ']' => depth -= 1,
                            ' ' | '\t' | '\r' | '\n' | ';' | '{' | '"' if depth <= 0 => break,
                            _ => {}
                        },
                    }
                    i += 1;
                }
                toks.push((Tok::Word(cs[start..i].iter().collect()), start));
                at_cmd_start = false;
            }
            '/' => {
                // A regex literal `/.../` — reads to the closing unescaped `/`,
                // spanning quotes and spaces (unlike a bare word), so patterns
                // like `/" (4|5)\d\d /` lex as a single token. `\/` is an escaped
                // slash inside the pattern, not the terminator. If no closing `/`
                // appears before the line ends, it falls back to a bare word.
                let start = i;
                let mut j = i + 1;
                let mut closed = false;
                while j < n {
                    match cs[j] {
                        '\\' if j + 1 < n => j += 2,
                        '/' => {
                            j += 1;
                            closed = true;
                            break;
                        }
                        '\n' => break,
                        _ => j += 1,
                    }
                }
                if closed {
                    let w: String = cs[start..j].iter().collect();
                    toks.push((Tok::Word(w), start));
                    i = j;
                } else {
                    while i < n && !matches!(cs[i], ' ' | '\t' | '\r' | '\n' | ';' | '{' | '"') {
                        i += 1;
                    }
                    let w: String = cs[start..i].iter().collect();
                    toks.push((Tok::Word(w), start));
                }
                at_cmd_start = false;
            }
            _ => {
                let start = i;
                while i < n && !matches!(cs[i], ' ' | '\t' | '\r' | '\n' | ';' | '{' | '"') {
                    i += 1;
                }
                let w: String = cs[start..i].iter().collect();
                toks.push((Tok::Word(w), start));
                at_cmd_start = false;
            }
        }
    }
    Ok(toks)
}

/// Index of the `"` closing the jq string literal that opens at `cs[open]`, or
/// `None` when it never closes. A `\(…)` interpolation holds jq code again — its
/// own strings (`"\("a\"b")"`), parens and `;` — so it is skipped as a nested
/// expression rather than scanned as string text.
fn skip_jq_string(cs: &[char], open: usize) -> Option<usize> {
    let mut i = open + 1;
    while i < cs.len() {
        match cs[i] {
            '\\' if cs.get(i + 1) == Some(&'(') => i = skip_jq_interpolation(cs, i + 2)?,
            '\\' => i += 2,
            '"' => return Some(i),
            _ => i += 1,
        }
    }
    None
}

/// Index just past the `)` closing a `\(` interpolation whose body starts at
/// `cs[i]`.
pub(crate) fn skip_jq_interpolation(cs: &[char], mut i: usize) -> Option<usize> {
    let mut depth = 1;
    while i < cs.len() {
        match cs[i] {
            '"' => i = skip_jq_string(cs, i)?,
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// jq's KEYWORDS. None of them is an arb verb, and each one starts a jq
/// expression that runs over several whitespace-separated tokens, so the whole
/// command has to be taken verbatim for the jq front-end to see it at all.
const JQ_KEYWORDS: &[&str] = &["reduce", "foreach", "if", "try", "label", "def"];

/// jq builtins in their CALL spelling (`name(`). The call form is what
/// distinguishes them from arb's own verbs, which are space-separated
/// (`split DELIM`, `join SEP`, `del KEY`, `first`) — SPEC §8's context rule.
/// Every one of these was an `unknown verb` error before the jq engine existed,
/// so claiming them takes nothing away.
///
/// `where(` is deliberately ABSENT: it is arb's own predicate verb.
const JQ_CALLS: &[&str] = &[
    "select",
    "map",
    "map_values",
    "has",
    "with_entries",
    "group_by",
    "unique_by",
    "sort_by",
    "min_by",
    "max_by",
    "any",
    "all",
    "range",
    "limit",
    "first",
    "last",
    "nth",
    "until",
    "while",
    "repeat",
    "recurse",
    "paths",
    "del",
    "path",
    "getpath",
    "setpath",
    "delpaths",
    "splits",
    "split",
    "join",
    "ltrimstr",
    "rtrimstr",
    "startswith",
    "endswith",
    "test",
    "match",
    "capture",
    "scan",
    "sub",
    "gsub",
    "error",
    "add",
    "flatten",
    "contains",
    "inside",
    "index",
    "rindex",
    "indices",
    "walk",
    "combinations",
    "tostream",
    "fromstream",
    "truncate_stream",
    "IN",
    "INDEX",
    "isempty",
    "pick",
    "todate",
    "strftime",
    "strptime",
    "strflocaltime",
    "ascii",
    "implode",
    "debug",
    "halt_error",
    "pow",
    "atan2",
    "ltrim",
    "isvalid",
    "env",
    "not",
    "abs",
    "toarray",
    "tojson",
    "getpath",
    "objects",
    "arrays",
    "values",
    // jq's two- and three-argument libm surface, plus the remaining call-form
    // builtins. None is an arb verb.
    "drem",
    "fdim",
    "fmin",
    "fmax",
    "fmod",
    "hypot",
    "ldexp",
    "scalb",
    "scalbln",
    "nextafter",
    "nexttoward",
    "jn",
    "yn",
    "fma",
    "copysign",
    "remainder",
    "format",
    "bsearch",
    "skip",
    "JOIN",
    "trimstr",
    "modulemeta",
    "toboolean",
    // The yq surface's CALL forms. `;` is jq's argument separator and arb's
    // command terminator, so `with(.a; .b = 5)` was cut in half and reported as
    // `unknown verb \`with(.a\`` — a name arb HAS, refused by the lexer before
    // the engine ever saw it. None of these is an arb verb.
    "with",
    "ref",
    "ireduce",
    "with_dtf",
    "omit",
    "sort_keys",
    "sortKeys",
    "strenv",
    "load",
    "load_str",
    "load_props",
    "load_xml",
    "format_datetime",
    "tz",
    "eval",
    "to_json",
    "to_yaml",
    "to_xml",
];

/// jq builtins in their BARE spelling that arb has no verb for. A bare word is
/// arb's native verb wherever the two share a spelling (SPEC §8's context rule),
/// so this list is exactly the jq names arb does NOT define — every one of them
/// was an `unknown verb` error before the jq engine existed.
///
/// Being here matters only for a MULTI-token command: it makes the whole line one
/// verbatim atom, so `env | has("PATH")` keeps its quotes. A one-word command
/// reaches the jq engine either way.
const JQ_BARE: &[&str] = &[
    // jq's literal keywords: `null | setpath([0]; 1)` must reach the engine as
    // one atom, not stop at the `;`. None is an arb verb.
    "null",
    "true",
    "false",
    "env",
    "tostring",
    "tonumber",
    "tojson",
    "fromjson",
    "type",
    "keys_unsorted",
    "to_entries",
    "from_entries",
    "values",
    "paths",
    "leaf_paths",
    "any",
    "all",
    "unique",
    "not",
    "empty",
    "error",
    "input",
    "inputs",
    "ascii_downcase",
    "ascii_upcase",
    "explode",
    "implode",
    "transpose",
    "combinations",
    "tostream",
    "todate",
    "fromdate",
    "todateiso8601",
    "fromdateiso8601",
    "now",
    "infinite",
    "nan",
    "isnan",
    "isinfinite",
    "isnormal",
    "halt",
    "halt_error",
    "arrays",
    "objects",
    "booleans",
    "numbers",
    "strings",
    "nulls",
    "iterables",
    "scalars",
    "recurse",
    "toarray",
    // The yq surface's BARE forms, for the same reason the call forms are listed
    // above: a MULTI-token command such as `.a | line_comment` must reach the
    // engine as one atom. None is an arb verb.
    "anchor",
    "alias",
    "tag",
    "style",
    "kind",
    "line",
    "column",
    "head_comment",
    "headComment",
    "line_comment",
    "lineComment",
    "foot_comment",
    "footComment",
    "comments",
    "key",
    "is_key",
    "parent",
    "document_index",
    "documentIndex",
    "di",
    "filename",
    "fileIndex",
    "splitDoc",
    "split_doc",
    "from_json",
    "from_yaml",
    "from_xml",
    "to_props",
    "from_props",
    "to_csv",
    "from_csv",
    "to_tsv",
    "from_tsv",
    "envsubst",
    "from_unix",
    "to_unix",
    "shuffle",
    "pivot",
    "downcase",
    "upcase",
    "to_string",
    "to_number",
    "utf8bytelength",
    "input_line_number",
    "builtins",
    "stderr",
    "debug",
    "mktime",
    "gmtime",
    "localtime",
    "reverse",
    "date",
    "finites",
    "normals",
    "ltrim",
    "rtrim",
    "sqrt",
    "log",
    "log2",
    "log10",
    "exp",
    "exp2",
    "exp10",
    "cbrt",
    "trunc",
    "nearbyint",
    "fabs",
    "significand",
    "logb",
    "sin",
    "cos",
    "tan",
    "asin",
    "acos",
    "atan",
    "sinh",
    "cosh",
    "tanh",
    "acosh",
    "asinh",
    "atanh",
    "expm1",
    "log1p",
    "rint",
    "gamma",
    "lgamma",
    "tgamma",
    "erf",
    "erfc",
    "j0",
    "j1",
    "y0",
    "y1",
    "frexp",
    "modf",
    "lgamma_r",
    "isfinite",
    "toboolean",
    "get_jq_origin",
    "get_prog_origin",
    "get_search_list",
    "modulemeta",
];

use crate::jqlang::FORMAT_NAMES as JQ_FORMATS;

/// Does a jq literal begin at `cs[i]`, which is at command position inside a
/// body block?
///
/// A leading `.` is unambiguous there — a body holds query verbs, and the
/// widget-path commands that also start with `.` are top-level only, which is
/// why the caller gates this on `jq_ok`. The bracket/brace/paren/`$`/`"`
/// openers are jq's array, object, grouping, variable and string forms; none of
/// them can begin an arb command (a leading `{` is `command cannot start with a
/// block`, the rest are `unknown verb`), so none is taken from arb.
///
/// A bare alphanumeric word is still arb's NATIVE verb, per SPEC §8 — only the
/// jq keywords, the `name(` call spelling and the `@format` names are claimed.
/// Whether a `/` whose preceding block text is `before` is jq DIVISION rather
/// than the start of a `/regex/` literal. Division follows an operand: a closing
/// `)`/`]`, a bare `.`, a number, or a jq path/variable token (`.a.b`, `$x`). A
/// regex literal is a verb ARGUMENT, so it follows an arb word (`grep /x/`,
/// `in.json /x/`) — those words never begin with `.` or `$`.
fn slash_is_division(before: &[char]) -> bool {
    let mut end = before.len();
    while end > 0 && matches!(before[end - 1], ' ' | '\t') {
        end -= 1;
    }
    let Some(&last) = end.checked_sub(1).map(|k| &before[k]) else {
        return false;
    };
    if matches!(last, '.' | ')' | ']') {
        return true;
    }
    let is_tok = |c: char| c.is_alphanumeric() || matches!(c, '_' | '.' | '$');
    if !is_tok(last) {
        return false;
    }
    let mut start = end;
    while start > 0 && is_tok(before[start - 1]) {
        start -= 1;
    }
    let tok = &before[start..end];
    matches!(tok[0], '.' | '$') || tok.iter().all(|c| c.is_ascii_digit() || *c == '.')
}

/// Does the jq keyword `def` start a term at `cs[i]`? It must be a whole word
/// followed by a blank, and not the tail of a path, variable or name (`.def`,
/// `$def`, `undef`).
fn def_keyword_at(cs: &[char], i: usize) -> bool {
    let after = cs.get(i + 3).is_some_and(|c| matches!(c, ' ' | '\t'));
    let before = i
        .checked_sub(1)
        .map(|k| cs[k])
        .is_none_or(|c| !(c.is_alphanumeric() || matches!(c, '_' | '.' | '$' | '@')));
    after && before && cs[i..].starts_with(&['d', 'e', 'f'])
}

fn jq_literal_at(cs: &[char], i: usize) -> bool {
    if matches!(cs[i], '.' | '[' | '(' | '$' | '"') {
        return true;
    }
    // A `{` is jq's object construction ONLY when what follows looks like an
    // object KEY. Without that test a nested arb block (`bind C-a { { … } }`)
    // would be swallowed whole, and the parser's block-depth guard — the thing
    // that stops a pathological spec from overflowing the stack — would never
    // see a block at all.
    if cs[i] == '{' {
        return jq_object_at(cs, i);
    }
    // A jq program may open with a NUMBER literal (`0 | todate`). No arb verb
    // starts with a digit, so nothing is taken from arb here either.
    if cs[i].is_ascii_digit() {
        return true;
    }
    // Or with a NEGATED term (`-1 as $x | …`, `- .a`): no arb verb starts with
    // `-` either.
    if cs[i] == '-' {
        let mut k = i + 1;
        while k < cs.len() && matches!(cs[k], ' ' | '\t') {
            k += 1;
        }
        return cs
            .get(k)
            .is_some_and(|c| c.is_ascii_digit() || matches!(c, '.' | '(' | '$'));
    }
    let mut j = i;
    if cs[i] == '@' {
        j += 1;
        let start = j;
        while j < cs.len() && (cs[j].is_ascii_alphanumeric() || cs[j] == '_') {
            j += 1;
        }
        let name: String = cs[start..j].iter().collect();
        // `@name "…"` is a jq FORMAT STRING whatever the name: jq applies the
        // format to the interpolations and decides at run time whether it knows
        // it (`@foo "lit"` is `"lit"`, and `@foo "\(.)"` is `foo is not a valid
        // format`). An xpath attribute step is never followed by a string, so
        // nothing is taken from xpath.
        let mut k = j;
        while k < cs.len() && matches!(cs[k], ' ' | '\t') {
            k += 1;
        }
        return JQ_FORMATS.contains(&name.as_str()) || (j > start && cs.get(k) == Some(&'"'));
    }
    while j < cs.len() && (cs[j].is_ascii_alphanumeric() || cs[j] == '_') {
        j += 1;
    }
    let name: String = cs[i..j].iter().collect();
    if JQ_KEYWORDS.contains(&name.as_str()) {
        // `if`/`try`/... only start a jq expression when a token follows them on
        // the same line; a bare word that happens to spell one is left alone.
        return cs
            .get(j)
            .is_some_and(|c| matches!(c, ' ' | '\t' | '(' | '.' | '$' | '"'));
    }
    if JQ_BARE.contains(&name.as_str()) {
        // Only when the word ENDS here: `envelope` is not `env`.
        return !cs.get(j).is_some_and(|c| c.is_alphanumeric() || *c == '_');
    }
    // The CALL spelling is jq's even for a name arb also has as a bare verb:
    // `first(range(1;3))` carries a `;` that must not end the command, and the
    // native `first` takes no parenthesised argument.
    if cs.get(j) == Some(&'(') && JQ_CALLS.contains(&name.as_str()) {
        return true;
    }
    NATIVE_SHARED.contains(&name.as_str()) && jq_continues_at(cs, j)
}

/// Native verbs spelled exactly like a jq 0-arity builtin. As a bare word each
/// is arb's verb (SPEC §8's context rule), and none takes an argument except
/// `sort`'s `-n`/`-r` flags. So a jq operator after one cannot be an argument:
/// `length | . + 1` and `length as $l | …` are jq programs. Lexed as verb +
/// args, the verb ran and the ignored args were the rest of the program —
/// `length | . + 1` printed the length, exit 0.
const NATIVE_SHARED: &[&str] = &[
    "abs", "add", "ceil", "first", "flatten", "floor", "last", "length", "max", "min", "round",
    "sort", "trim",
];

/// After a word ending at `cs[j]`, does a jq operator continue the program on
/// the same line? Blanks are skipped; `-` is not counted, since it opens
/// `sort`'s flags.
fn jq_continues_at(cs: &[char], j: usize) -> bool {
    let mut k = j;
    while k < cs.len() && matches!(cs[k], ' ' | '\t') {
        k += 1;
    }
    if k == j && cs.get(k).is_some_and(|c| c.is_alphanumeric() || *c == '_') {
        return false;
    }
    let word = |w: &str| {
        let wc: Vec<char> = w.chars().collect();
        cs[k..].starts_with(&wc)
            && cs
                .get(k + wc.len())
                .is_some_and(|c| matches!(c, ' ' | '\t' | '$' | '[' | '{' | '('))
    };
    match cs.get(k) {
        Some('|' | ',' | '+' | '*' | '/' | '%' | '<' | '>' | '=' | '!' | '?') => true,
        Some(_) => word("as") || word("and") || word("or"),
        None => false,
    }
}

/// Does `cs[i] == '{'` open a jq OBJECT construction rather than an arb block?
///
/// The test is the first token inside: an object is `{}`, or `{key…` where the
/// key is an identifier, a `"string"`, a `$var`, a `(expr)` or an `@format`. An
/// arb block opens with a command, and the only commands that could be confused
/// with a key are followed by neither `:` nor `,` nor `}`.
fn jq_object_at(cs: &[char], i: usize) -> bool {
    let mut j = i + 1;
    while j < cs.len() && matches!(cs[j], ' ' | '\t' | '\r' | '\n') {
        j += 1;
    }
    match cs.get(j) {
        None => false,
        Some('}') => true,
        Some('"' | '$' | '(' | '@') => true,
        Some(c) if c.is_alphabetic() || *c == '_' => {
            while j < cs.len() && (cs[j].is_alphanumeric() || cs[j] == '_') {
                j += 1;
            }
            while j < cs.len() && matches!(cs[j], ' ' | '\t') {
                j += 1;
            }
            matches!(cs.get(j), Some(':' | ',' | '}'))
        }
        _ => false,
    }
}