aless 0.3.0

Terminal viewer and JSON CLI for JSON, YAML, TOML, CSV, XML and more
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! Custom grammars: ABNF text given on the command line (`--grammar
//! NAME=FILE`, `--grammar-expr NAME=ABNF`), compiled once at startup by the
//! tabnas ABNF compiler and kept in a process-wide registry that
//! [`Format::Custom`](crate::load::Format::Custom) indexes.
//!
//! A registered grammar is a format like any built-in one: it has a name,
//! it is detected from a file's extension or whole file name (`x.hosts`,
//! `/etc/hosts`), `-k NAME` selects it, and its parser is made afresh for
//! every parse from the compiled spec, as the built-in grammars' are. What
//! a parse builds is whatever the grammar says: with `; @object` and
//! `; @array` annotations a JSON value of strings, without them the
//! compiler's `{rule, src, kids}` tree. Either is a value the document
//! model takes as it takes any grammar's, so the viewer and every headless
//! operation work on it unchanged.
//!
//! The registry is filled from the command line before any load, and
//! looked up by name from then on. It only grows: a name registered twice
//! resolves to the later grammar, as a repeated option would be expected
//! to. Tests register grammars of their own under names of their own.

use std::ffi::{OsStr, OsString};
use std::fmt;
use std::path::PathBuf;
use std::sync::{mpsc, RwLock};
use std::time::{Duration, Instant};

use serde_json::{json, Map, Value};
use tabnas::Tabnas;
use tabnas_abnf::{AbnfConvertOptions, Element, GrammarSpec, Kind};

use crate::load::{self, Limits, LoadError};

/// The index of a custom grammar in the registry: what `Format::Custom`
/// carries. Only [`register`] makes one, so every id names a grammar.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CustomId(u16);

/// Where a grammar's text came from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Source {
    /// `--grammar NAME=FILE`: the file, as given.
    File(PathBuf),
    /// `--grammar-expr NAME=ABNF`: the text itself.
    Inline(String),
}

impl Source {
    /// The option that gives a grammar this way.
    pub fn option(&self) -> &'static str {
        match self {
            Source::File(_) => "--grammar",
            Source::Inline(_) => "--grammar-expr",
        }
    }

    /// The file, as a report names it; `None` for inline text.
    pub fn file(&self) -> Option<String> {
        match self {
            Source::File(p) => Some(p.display().to_string()),
            Source::Inline(_) => None,
        }
    }
}

/// A grammar as the command line defines it, before it is compiled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Definition {
    /// The names a file must match, as given; the first is the format's
    /// name. Matching is case-insensitive.
    pub names: Vec<String>,
    pub source: Source,
}

impl Definition {
    /// Read an option's value: `NAME[,NAME…]=FILE` for `--grammar`,
    /// `NAME[,NAME…]=ABNF` for `--grammar-expr`. The first `=` separates
    /// the names from the rest, which for `--grammar-expr` is the grammar
    /// text and contains `=` itself.
    pub fn parse(option: &str, value: &str) -> Result<Definition, String> {
        let inline = option == "--grammar-expr";
        let what = if inline { "ABNF" } else { "FILE" };
        let Some((names, rest)) = value.split_once('=') else {
            return Err(format!(
                "{option} needs NAME={what}, not {value:?} (NAME is the extension or file name \
                 the grammar reads; NAME,NAME2={what} shares one grammar)"
            ));
        };
        let mut seen = Vec::new();
        for name in names.split(',') {
            let name = name.trim();
            if name.is_empty() {
                return Err(format!(
                    "{option} {value:?}: a name is missing before the `=`"
                ));
            }
            if name
                .chars()
                .any(|c| c.is_whitespace() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"'))
            {
                return Err(format!(
                    "{option} {value:?}: {name:?} cannot be a file's extension or name"
                ));
            }
            if !seen
                .iter()
                .any(|s: &String| s.to_lowercase() == name.to_lowercase())
            {
                seen.push(name.to_string());
            }
        }
        if rest.trim().is_empty() {
            return Err(format!("{option} {value:?}: nothing after the `=`"));
        }
        let source = if inline {
            Source::Inline(rest.to_string())
        } else {
            Source::File(PathBuf::from(rest))
        };
        Ok(Definition {
            names: seen,
            source,
        })
    }

    /// [`Definition::parse`] for a value as the command line gives it:
    /// the names and ABNF text are read as text, and FILE, a path, keeps
    /// bytes that are not UTF-8, as an input path does.
    pub fn parse_os(option: &str, value: &OsStr) -> Result<Definition, String> {
        let mut def = Definition::parse(option, &value.to_string_lossy())?;
        if let Source::File(path) = &mut def.source {
            *path = PathBuf::from(after_eq(value));
        }
        Ok(def)
    }
}

/// What follows the first `=` of a command-line value, with its bytes as
/// given. `=` is ASCII, so the raw value and its lossy text cut at the
/// same `=`, and what follows it is not re-encoded.
pub fn after_eq(raw: &OsStr) -> OsString {
    let bytes = raw.as_encoded_bytes();
    let at = bytes
        .iter()
        .position(|&b| b == b'=')
        .map_or(bytes.len(), |i| i + 1);
    // SAFETY: the cut is just after an ASCII `=`, which the encoding
    // allows (`OsStr::from_encoded_bytes_unchecked`: split before or after
    // any non-empty valid UTF-8 substring).
    unsafe { OsStr::from_encoded_bytes_unchecked(&bytes[at..]) }.to_owned()
}

/// The engine's options for a grammar of plain text, merged into the
/// compiled spec's `options` before it is installed.
///
/// The compiler emits the tokens the grammar names and nothing else, and a
/// fresh engine's defaults for everything else are JSON's: `{ } [ ] : ,`
/// are tokens, `//` and `/* */` open comments, digits make numbers, quotes
/// make strings and `true` `false` `null` are values. Every one of those
/// breaks plain text (`::1` would be three tokens, `//server/share` a
/// comment, `0` a number where the grammar asked for a word), so they are
/// turned off, and the grammar's own tokens define the language: a word
/// (`TX`) runs to a space, tab, newline, `#` or one of the grammar's
/// literals, and a literal the grammar names is a token whatever it is
/// (`":"` splits `root:x:0:0`). What stays: `#` comments to the end of the
/// line, since every format this is for has them, and the number, string
/// and value lexers where the grammar names `NR`, `ST` or `VL`. A carriage
/// return becomes a space character, so a CRLF file parses as an LF file
/// does: the lexer skips the `\r` and reaches the `\n`, which the grammar
/// takes as its `%x0A` token (a fixed token is tried before a line end is
/// skipped, which is why a grammar needs no option to see its newlines).
/// Measured against tabnas-abnf 0.4.16 with the fixture grammars under
/// `tests/fixtures/grammars/`, whose README explains each setting.
pub(crate) fn plain_text_options(spec: &mut GrammarSpec) {
    /// The object at `key`, made one if it is missing or something else.
    fn object<'a>(map: &'a mut Map<String, Value>, key: &str) -> &'a mut Map<String, Value> {
        let value = map.entry(key).or_insert_with(|| json!({}));
        if !value.is_object() {
            *value = json!({});
        }
        value.as_object_mut().expect("made an object above")
    }
    // The token names the grammar uses, wherever they appear in the
    // emitted document (an alternate's `s`, a token set): `"#NR"` says the
    // grammar wants numbers.
    let document = spec.to_value().to_string();
    let names = |token: &str| document.contains(&format!("\"#{token}\""));
    let options = &mut spec.options;
    let tokens = object(object(options, "fixed"), "token");
    // A grammar with a production of one of these names keeps its token.
    for name in ["#OB", "#CB", "#OS", "#CS", "#CL", "#CA"] {
        tokens.entry(name).or_insert(Value::Null);
    }
    let defs = object(object(options, "comment"), "def");
    for name in ["slash", "multi"] {
        defs.entry(name).or_insert(Value::Null);
    }
    for (token, option) in [("NR", "number"), ("ST", "string"), ("VL", "value")] {
        if !names(token) {
            object(options, option).insert("lex".into(), json!(false));
        }
    }
    object(options, "space").insert("chars".into(), json!(" \t\r"));
}

/// A grammar's text, compiled: what [`register`] keeps, and what a test of
/// a grammar file checks without registering it.
pub struct Compiled {
    spec: GrammarSpec,
}

impl fmt::Debug for Compiled {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Compiled({} rules)", self.spec.rule.len())
    }
}

impl Compiled {
    /// A fresh engine with the grammar installed.
    pub fn parser(&self) -> Result<Tabnas, String> {
        let mut parser = Tabnas::new();
        self.spec.install(&mut parser).map_err(|e| e.to_string())?;
        Ok(parser)
    }
}

/// The largest count a repetition may carry (`1024"a"`, `1*1024word`).
/// The compiler writes out every copy: `min` copies of the element, then
/// one nested optional rule per copy up to `max`, so a count in the
/// millions takes gigabytes and minutes before any input is read
/// (`10000000"a"` reached 5 GB; `99999999999999999999999"a"` saturates to
/// 2^64 copies). Measured: `1*1000"a"` compiles in 1 s, `1*5000"a"` in
/// 35 s. Real grammars stay in the hundreds (`1*255`). Counts within it
/// can still add up to more than aless compiles: [`MAX_REPEAT_TOTAL`].
pub const MAX_REPEAT: usize = 1024;

/// The most rules a grammar's repetitions may have the compiler write,
/// counted as [`repeat_rules`] counts them: the rules the compiler writes
/// for the copies a repetition may make, wherever it writes them. The
/// compile's time, and the time the engine takes to assemble the grammar
/// at the start of every parse, grow much faster than the rules do:
/// measured in a release build, 1,000 rules compile in under half a
/// second and add about 1 s to each parse, 2,000 add 9 s, 3,000 add 20 s.
/// Real grammars write tens (RFC 3986's URI grammar, 113); `1*255`
/// writes 509.
///
/// This bounds what repetitions cost and nothing else: a grammar's other
/// shapes cost time too (a rule is copied into every alternative that
/// starts with it, so rules of several alternatives that start with each
/// other multiply), and only `--timeout` bounds a compile.
pub const MAX_REPEAT_TOTAL: usize = 1024;

/// The deepest element nesting the compiler walks: tabnas-bnf's
/// `MAX_ELEMENT_DEPTH`, which tabnas-abnf does not re-export. The compiler
/// refuses a deeper grammar before it rewrites one, so [`repeat_rules`]
/// does not rewrite one either.
const COMPILER_ELEMENT_DEPTH: usize = 128;

/// Compile ABNF text: the compiler's parse, a check of the repetition
/// counts against [`MAX_REPEAT`] each and of the rules they write against
/// [`MAX_REPEAT_TOTAL`], then its conversion, with the start rule its
/// default (the grammar's first production) and `word_keywords` on, so a
/// quoted keyword (`"nameserver"`) matches whole words and not the front
/// of a longer one; then the engine options of [`plain_text_options`]; and
/// the result installed once on a fresh engine to be sure it takes. The
/// error is the compiler's own message, or the engine's, on one line and
/// without its colour codes.
pub fn compile(source: &str) -> Result<Compiled, String> {
    let options = AbnfConvertOptions {
        word_keywords: true,
        ..AbnfConvertOptions::default()
    };
    let grammar = tabnas_abnf::parse_abnf(source).map_err(|e| one_line(&e.to_string()))?;
    check_repeats(&grammar)?;
    let mut spec = tabnas_abnf::emit_grammar_spec(&grammar, Some(&options))
        .map_err(|e| one_line(&e.to_string()))?;
    plain_text_options(&mut spec);
    let compiled = Compiled { spec };
    compiled.parser().map_err(|e| one_line(&e))?;
    Ok(compiled)
}

/// A compiler's message as a report carries it: the engine colours its
/// diagnostics and the regex crate's run to several lines, where a
/// `message` is one line of plain text. Escapes are stripped, control
/// characters shown escaped (`\n`).
fn one_line(message: &str) -> String {
    load::escape_controls(&load::strip_ansi(message))
}

/// Refuse a repetition count over [`MAX_REPEAT`], or repetitions that
/// would have the compiler write more than [`MAX_REPEAT_TOTAL`] rules,
/// before it writes any. A count over the limit is named first, wherever
/// it is. The elements are walked with a stack of their own, and their
/// nesting measured for [`repeat_rules`]; the compiler bounds it itself,
/// later.
fn check_repeats(grammar: &tabnas_abnf::Grammar) -> Result<(), String> {
    let mut stack: Vec<(&Element, usize)> = grammar
        .productions
        .iter()
        .flat_map(|p| p.alts.iter().flatten())
        .map(|el| (el, 1))
        .collect();
    let mut deepest = 0;
    while let Some((el, depth)) = stack.pop() {
        deepest = deepest.max(depth);
        match &el.kind {
            Kind::Rep { min, max, inner } => {
                let count = max.unwrap_or(0).max(*min);
                if count > MAX_REPEAT {
                    let at = match el.sp.and_then(|sp| sp.r.zip(sp.c)) {
                        Some((row, col)) => format!(" at line {row}, column {col}"),
                        None => String::new(),
                    };
                    return Err(format!(
                        "abnf: a repetition count of {count}{at} is more than aless compiles \
                         (at most {MAX_REPEAT}): the compiler writes out every copy, so write \
                         `*word` or `1*word` for a run of any length"
                    ));
                }
                stack.push((inner, depth + 1));
            }
            Kind::Opt { inner } | Kind::Star { inner, .. } | Kind::Plus { inner } => {
                stack.push((inner, depth + 1))
            }
            Kind::Group { alts } => stack.extend(alts.iter().flatten().map(|el| (el, depth + 1))),
            _ => {}
        }
    }
    let rules = repeat_rules(grammar, deepest);
    if rules > MAX_REPEAT_TOTAL {
        return Err(format!(
            "abnf: the repetitions would have the compiler write {rules} rules, more than aless \
             compiles (at most {MAX_REPEAT_TOTAL}): it writes a rule or two for every copy a \
             repetition may make past its minimum, and writes a rule's repetitions again into \
             every alternative that starts with that rule, so write `*word` or `1*word` for a \
             run of any length"
        ));
    }
    Ok(())
}

/// About how many rules the compiler writes for a grammar's repetitions,
/// counted where it writes them. Its first rewrite, which removes left
/// recursion, copies every rule an alternative starts with into that
/// alternative, once for each of the rule's alternatives, with the rest
/// of the alternative after each copy; that rewrite is the compiler's own
/// (`eliminate_left_recursion`), run here on the grammar, and the rules
/// are counted on what it gives. A later rewrite writes the rest of an
/// alternative twice after an optional prefix that it cannot tell from
/// what follows (`[ userinfo "@" ] host`); [`alternative_repeat_rules`]
/// counts that. A grammar nested deeper than the compiler walks is
/// counted as written: the compiler refuses it.
fn repeat_rules(grammar: &tabnas_abnf::Grammar, deepest: usize) -> usize {
    let rules: std::collections::HashSet<&str> = grammar
        .productions
        .iter()
        .map(|p| p.name.as_str())
        .collect();
    let rewritten = (deepest <= COMPILER_ELEMENT_DEPTH)
        .then(|| tabnas_abnf::eliminate_left_recursion(grammar).ok())
        .flatten();
    let productions = rewritten
        .as_ref()
        .map_or(&grammar.productions, |g| &g.productions);
    productions
        .iter()
        .flat_map(|p| &p.alts)
        .fold(0usize, |sum, alt| {
            sum.saturating_add(alternative_repeat_rules(alt, &rules))
        })
}

/// The rules an alternative's repetitions write: each element's, and the
/// rest of the alternative twice after an optional group that ends in a
/// terminal (`[ X "@" ] Y`), which the compiler may write as two branches
/// (`X "@" Y` and `Y`) when it cannot tell X from Y by their first tokens.
fn alternative_repeat_rules(alt: &[Element], rules: &std::collections::HashSet<&str>) -> usize {
    let probe_prefix = |el: &Element| match &el.kind {
        Kind::Opt { inner } => matches!(&inner.kind, Kind::Group { alts }
            if alts.len() == 1
                && alts[0].len() >= 2
                && alts[0].last().is_some_and(Element::is_terminal)),
        _ => false,
    };
    let mut total = 0usize;
    let mut twice = false;
    for (i, el) in alt.iter().enumerate() {
        let n = element_repeat_rules(el, rules);
        total = total.saturating_add(if twice { n.saturating_mul(2) } else { n });
        twice = twice || (i + 1 < alt.len() && probe_prefix(el));
    }
    total
}

/// The rules an element's repetitions write, as the compiler's desugaring
/// writes them: for `m*nX`, one rule for the repetition, two for each copy
/// past `m` (an optional and its group, nested), and, when X is a rule or
/// a group rather than a terminal, one more for every copy (the step that
/// follows it); `m*X` writes one rule for its tail. X itself is written
/// once, however many copies refer to it, so nesting adds.
fn element_repeat_rules(el: &Element, rules: &std::collections::HashSet<&str>) -> usize {
    let terminal = |el: &Element| match &el.kind {
        Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } | Kind::Prose { .. } => true,
        // A name that is no rule of the grammar is an engine token (`TX`).
        Kind::Ref { name, .. } => !rules.contains(name.as_str()),
        _ => false,
    };
    let mut total = 0usize;
    let mut stack = vec![el];
    while let Some(el) = stack.pop() {
        match &el.kind {
            Kind::Rep { min, max, inner } => {
                let (chain, beyond) = match max {
                    Some(max) => {
                        let beyond = max.saturating_sub(*min);
                        (beyond.saturating_mul(2), beyond)
                    }
                    None => (1, 1),
                };
                let steps = if terminal(inner) {
                    0
                } else {
                    min.saturating_add(beyond)
                };
                total = total
                    .saturating_add(1)
                    .saturating_add(chain)
                    .saturating_add(steps);
                stack.push(inner);
            }
            Kind::Opt { inner } | Kind::Star { inner, .. } | Kind::Plus { inner } => {
                stack.push(inner)
            }
            Kind::Group { alts } => stack.extend(alts.iter().flatten()),
            _ => {}
        }
    }
    total
}

/// [`compile`] on a thread of its own, within `timeout`. A compile cannot
/// be interrupted, so past the deadline the thread is left to itself (the
/// process exits on the error, which ends it) and the error says so. A
/// panic in the compiler is a `grammar` error, as one in a parse is.
fn compile_within(source: &str, timeout: Option<Duration>) -> Result<Compiled, LoadError> {
    let (tx, rx) = mpsc::channel();
    let text = source.to_string();
    let spawned = std::thread::Builder::new()
        .name("aless-grammar".into())
        .stack_size(load::PARSE_STACK)
        .spawn(move || {
            let _ = tx.send(load::catch_grammar(|| compile(&text)));
        });
    let outcome = match spawned {
        // A time too far off to reach is no limit.
        Ok(_) => match timeout.filter(|t| std::time::Instant::now().checked_add(*t).is_some()) {
            Some(limit) => rx
                .recv_timeout(limit)
                .map_err(|_| LoadError::compile_timed_out(limit))?,
            None => rx
                .recv()
                .map_err(|_| LoadError::tagged("grammar", "the compiler gave no answer"))?,
        },
        // No thread to be had: compile on this one, timed.
        Err(_) => return compile_here(source, timeout),
    };
    settle(outcome)
}

/// [`compile`] on this thread, for when no other can be had. It cannot be
/// stopped, so it is timed: one that ends past `timeout`, with a grammar
/// or an error, is a `timeout`, as it is when a thread waits on it, and
/// its hint says the compile ran to its end.
fn compile_here(source: &str, timeout: Option<Duration>) -> Result<Compiled, LoadError> {
    let start = Instant::now();
    let outcome = load::catch_grammar(|| compile(source));
    let took = start.elapsed();
    if let Some(limit) = timeout.filter(|t| took >= *t) {
        return Err(LoadError::compile_finished_late(limit, took));
    }
    settle(outcome)
}

/// A compile's outcome as [`compile_within`] reports it.
fn settle(outcome: Result<Result<Compiled, String>, String>) -> Result<Compiled, LoadError> {
    match outcome {
        Ok(Ok(compiled)) => Ok(compiled),
        Ok(Err(message)) => Err(LoadError::tagged("grammar", message)),
        Err(panic) => Err(LoadError::tagged(
            "grammar",
            format!("the compiler failed: {panic}"),
        )),
    }
}

/// A registered grammar.
pub struct Grammar {
    /// The format's name: the first name given.
    pub name: &'static str,
    /// Every name given, lower-cased (Unicode, as the documented "in any
    /// case" says): what a file's extension or whole name is compared
    /// with.
    pub matches: Vec<String>,
    /// The ABNF text.
    pub source: String,
    pub origin: Source,
    pub compiled: Compiled,
}

impl Grammar {
    /// A fresh engine with the grammar installed, as every parse gets one.
    pub fn parser(&self) -> Result<Tabnas, String> {
        self.compiled.parser()
    }

    /// Whether `name` (an extension, or a whole file name) is one of this
    /// grammar's, case-insensitively.
    pub fn matches(&self, name: &str) -> bool {
        self.matches.contains(&name.to_lowercase())
    }
}

/// Why a grammar could not be registered.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GrammarError {
    /// The option that named the grammar.
    pub option: &'static str,
    /// The format's name.
    pub grammar: String,
    /// The grammar file, as given; `None` for `--grammar-expr`.
    pub file: Option<String>,
    /// What went wrong: reading the file (`io`, `too_large`), the compile
    /// running past its time (`timeout`), or the compiler's refusal
    /// (`grammar`), which is a mistake in the command.
    pub error: LoadError,
    /// The grammar file's size, when it is a regular file.
    pub size: Option<u64>,
    /// The limits the grammar was read and compiled under.
    pub limits: Limits,
}

impl GrammarError {
    /// Whether the command asked for what cannot be done (the grammar does
    /// not compile), as against the file not being readable or the compile
    /// not finishing in time.
    pub fn is_usage(&self) -> bool {
        !self.error.is_io() && !self.error.is_too_large() && !self.error.is_timeout()
    }
}

impl fmt::Display for GrammarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {}: {}",
            self.option, self.grammar, self.error.message
        )
    }
}

impl std::error::Error for GrammarError {}

/// The grammars registered so far. Each is leaked once, so the name a
/// [`Format`](crate::load::Format) reports can be `&'static str` as the
/// built-in names are.
static REGISTRY: RwLock<Vec<&'static Grammar>> = RwLock::new(Vec::new());

fn registry() -> std::sync::RwLockReadGuard<'static, Vec<&'static Grammar>> {
    REGISTRY.read().unwrap_or_else(|e| e.into_inner())
}

/// Register a grammar: read its file (within the size limit, as any input
/// is), compile it (within the time limit, as any parse runs), and give it
/// a place in the registry. A later grammar with one of the same names is
/// the one that name resolves to. (The error is boxed: it carries a whole
/// report.)
pub fn register(def: Definition, limits: Limits) -> Result<CustomId, Box<GrammarError>> {
    let name = def.names.first().cloned().unwrap_or_default();
    let size = match &def.source {
        Source::File(path) => std::fs::metadata(path)
            .ok()
            .filter(|m| m.is_file())
            .map(|m| m.len()),
        Source::Inline(_) => None,
    };
    let fail = |error: LoadError| {
        Box::new(GrammarError {
            option: def.source.option(),
            grammar: name.clone(),
            file: def.source.file(),
            error,
            size,
            limits,
        })
    };
    let source = match &def.source {
        Source::File(path) => load::read_path_within(path, limits.max_size).map_err(|e| {
            let mut e = if e.is_too_large() {
                // Worded for a grammar file: no parse of it is coming.
                LoadError::grammar_too_large(size, limits.max_size.unwrap_or(0))
                    .with_origin(&load::origin_of(path))
            } else {
                e
            };
            e.message = format!("{}: {}", path.display(), e.message);
            fail(e)
        })?,
        Source::Inline(text) => text.clone(),
    };
    let compiled = compile_within(&source, limits.timeout).map_err(fail)?;
    let mut all = REGISTRY.write().unwrap_or_else(|e| e.into_inner());
    let id = u16::try_from(all.len()).map_err(|_| {
        fail(LoadError::tagged(
            "grammar",
            format!("no room for another grammar: {} are registered", all.len()),
        ))
    })?;
    let grammar: &'static Grammar = Box::leak(Box::new(Grammar {
        name: Box::leak(name.into_boxed_str()),
        matches: def.names.iter().map(|n| n.to_lowercase()).collect(),
        source,
        origin: def.source,
        compiled,
    }));
    all.push(grammar);
    Ok(CustomId(id))
}

/// Register every definition in turn, stopping at the first that fails.
pub fn register_all(
    defs: impl IntoIterator<Item = Definition>,
    limits: Limits,
) -> Result<Vec<CustomId>, Box<GrammarError>> {
    defs.into_iter().map(|d| register(d, limits)).collect()
}

/// The grammar an id names.
pub fn get(id: CustomId) -> Option<&'static Grammar> {
    registry().get(usize::from(id.0)).copied()
}

/// The grammar a name (a format name, a file's extension or its whole
/// name) selects, case-insensitively: the last registered that has it.
pub fn lookup(name: &str) -> Option<CustomId> {
    let name = name.trim();
    if name.is_empty() {
        return None;
    }
    registry()
        .iter()
        .rposition(|g| g.matches(name))
        .map(|i| CustomId(i as u16))
}

/// Every registered grammar, in registration order.
pub fn registered() -> Vec<(CustomId, &'static Grammar)> {
    registry()
        .iter()
        .enumerate()
        .map(|(i, g)| (CustomId(i as u16), *g))
        .collect()
}

/// The format names of the registered grammars, in registration order.
pub fn names() -> Vec<&'static str> {
    registry().iter().map(|g| g.name).collect()
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::load::Format;

    /// `key = value` lines, one object each; `#` comments are the engine's
    /// and are skipped.
    pub(crate) const KV: &str = "\
settings = *entry            ; @array
entry    = key \"=\" val      ; @object key val
key      = ( TX )
val      = ( TX / NR )
";

    #[cfg(unix)]
    #[test]
    fn a_file_keeps_path_bytes_that_are_not_utf8() {
        use std::os::unix::ffi::{OsStrExt, OsStringExt};
        let raw = OsStr::from_bytes(b"hosts=g\xff/x=y.abnf");
        let d = Definition::parse_os("--grammar", raw).unwrap();
        assert_eq!(d.names, ["hosts"]);
        let file = PathBuf::from(OsString::from_vec(b"g\xff/x=y.abnf".to_vec()));
        assert_eq!(d.source, Source::File(file));
        // Inline text is text, as `parse` reads it.
        let d = Definition::parse_os("--grammar-expr", OsStr::new("kv=doc = *TX\n")).unwrap();
        assert_eq!(d.source, Source::Inline("doc = *TX\n".into()));
        // The attached form cuts at the argument's first `=`.
        assert_eq!(
            after_eq(OsStr::from_bytes(b"--grammar=hosts=g\xff.abnf")).as_bytes(),
            b"hosts=g\xff.abnf"
        );
    }

    fn inline(names: &str, text: &str) -> Definition {
        Definition::parse("--grammar-expr", &format!("{names}={text}")).unwrap()
    }

    fn parse_json(id: CustomId, input: &str) -> serde_json::Value {
        let g = get(id).unwrap();
        let parser = g.parser().unwrap();
        let value = parser
            .parse(input)
            .unwrap_or_else(|e| panic!("{}: {e}", g.name));
        value.to_json()
    }

    #[test]
    fn definitions_parse_names_and_the_first_equals_sign() {
        let d = Definition::parse("--grammar", "hosts=hosts.abnf").unwrap();
        assert_eq!(d.names, ["hosts"]);
        assert_eq!(d.source, Source::File(PathBuf::from("hosts.abnf")));
        assert_eq!(d.source.option(), "--grammar");
        assert_eq!(d.source.file(), Some("hosts.abnf".to_string()));

        let d = Definition::parse("--grammar", "hosts, hostsfile ,Hosts=etc/hosts.abnf").unwrap();
        assert_eq!(d.names, ["hosts", "hostsfile"], "repeats are dropped");
        let d = Definition::parse("--grammar", "Ärger,ÄRGER=x.abnf").unwrap();
        assert_eq!(d.names, ["Ärger"], "in any case, not only ASCII");

        // Everything after the first `=` is the text, `=` included.
        let d = Definition::parse("--grammar-expr", "kv=doc = *TX\n").unwrap();
        assert_eq!(d.names, ["kv"]);
        assert_eq!(d.source, Source::Inline("doc = *TX\n".to_string()));
        assert_eq!(d.source.option(), "--grammar-expr");
        assert_eq!(d.source.file(), None);

        for bad in [
            "hosts",
            "=x.abnf",
            "hosts=",
            "hosts= ",
            ",hosts=x.abnf",
            "a b=x.abnf",
            "a/b=x.abnf",
        ] {
            let e = Definition::parse("--grammar", bad).unwrap_err();
            assert!(e.starts_with("--grammar"), "{bad:?}: {e}");
        }
        let e = Definition::parse("--grammar-expr", "kv").unwrap_err();
        assert!(e.contains("NAME=ABNF"), "{e}");
    }

    /// The engine's JSON defaults are off for a grammar of plain text: its
    /// punctuation, its `//` comments, and the number, string and value
    /// tokens the grammar does not name. `#` comments stay. (Measured, so a
    /// change in the compiler or the engine shows up here.)
    #[test]
    fn plain_text_has_the_grammars_tokens_only() {
        const WORDS: &str = "doc = *word   ; @array\nword = ( TX )\n";
        let c = compile(WORDS).unwrap();
        let words = |src: &str| c.parser().unwrap().parse(src).unwrap().to_json();
        assert_eq!(
            words("::1 root:x:0:0 0,30 [a] {b} //server/share # c\ntrue 0 17 \"q\" 'r'"),
            json!([
                "::1",
                "root:x:0:0",
                "0,30",
                "[a]",
                "{b}",
                "//server/share",
                "true",
                "0",
                "17",
                "\"q\"",
                "'r'"
            ])
        );
        // The classes come back when the grammar names them: a quoted string
        // is one token, quotes and spaces included.
        const TYPED: &str = "\
doc  = *( word / num / str / val )   ; @array
word = ( TX )
num  = ( NR )
str  = ( ST )
val  = ( VL )
";
        let c = compile(TYPED).unwrap();
        let value = c
            .parser()
            .unwrap()
            .parse("a 17 \"q r\" true")
            .unwrap()
            .to_json();
        assert_eq!(value, json!(["a", "17", "\"q r\"", "true"]));
        // A literal the grammar names is a token, and cuts a word.
        const FIELDS: &str = "doc = a \":\" b   ; @object a b\na = ( TX )\nb = ( TX )\n";
        let c = compile(FIELDS).unwrap();
        let value = c.parser().unwrap().parse("root:x").unwrap().to_json();
        assert_eq!(value, json!({"a": "root", "b": "x"}));
        // A keyword matches whole words only.
        const KW: &str = "doc = 1*( kw / word )   ; @array\nkw = \"default\" %x20\nword = ( TX )\n";
        let c = compile(KW).unwrap();
        let value = c
            .parser()
            .unwrap()
            .parse("default defaults")
            .unwrap()
            .to_json();
        assert_eq!(value, json!(["default ", "defaults"]));
    }

    /// A line-oriented grammar: the newline it names is a token, so a
    /// repetition stops at the line's end, blank lines and comments cost
    /// nothing, and a CRLF file reads as an LF file.
    #[test]
    fn line_oriented_grammars_read_lf_and_crlf_alike() {
        const HOSTS: &str = "\
hosts   = *( host %x0A / %x0A ) [ host ]   ; @array
host    = address names                    ; @object address names
address = word
names   = 1*word                           ; @array
word    = ( TX )
";
        let want = json!([
            {"address": "127.0.0.1", "names": ["localhost", "myhost"]},
            {"address": "::1", "names": ["localhost"]}
        ]);
        let lf = "# hosts\n\n127.0.0.1 localhost myhost\n\n::1 localhost # v6\n";
        let crlf = lf.replace('\n', "\r\n");
        let c = compile(HOSTS).unwrap();
        for src in [lf, crlf.as_str(), lf.trim_end()] {
            let value = c
                .parser()
                .unwrap()
                .parse(src)
                .unwrap_or_else(|e| panic!("{src:?}: {e}"));
            assert_eq!(value.to_json(), want, "{src:?}");
        }
        // Without the carriage return as a space, the lexer skips `\r\n`
        // whole as a line end before the grammar's `\n` is tried, and the
        // first line never ends.
        let mut spec = tabnas_abnf::abnf_convert(HOSTS, None).unwrap();
        plain_text_options(&mut spec);
        spec.options.insert("space".into(), json!({"chars": " \t"}));
        let mut parser = Tabnas::new();
        spec.install(&mut parser).unwrap();
        let e = parser.parse(&crlf).unwrap_err();
        assert_eq!(e.row, 6, "{e}");
    }

    #[test]
    fn a_grammar_compiles_once_and_parses_to_the_value_it_builds() {
        let id = register(inline("impl-kv-a", KV), Limits::NONE).unwrap();
        let g = get(id).unwrap();
        assert_eq!(g.name, "impl-kv-a");
        assert_eq!(
            parse_json(id, "a=1\nb = two\n# note\nc=3\n"),
            json!([
                {"key": "a", "val": "1"},
                {"key": "b", "val": "two"},
                {"key": "c", "val": "3"}
            ])
        );
        // Without annotations, the compiler's tree.
        let id = register(inline("impl-tree-a", "pair = TX \"=\" TX\n"), Limits::NONE).unwrap();
        let v = parse_json(id, "a=b");
        assert_eq!(v["rule"], "pair");
        assert_eq!(v["src"], "a=b");
        assert_eq!(v["kids"], json!([]));
    }

    #[test]
    fn names_resolve_case_insensitively_and_the_latest_wins() {
        let first = register(inline("impl-hosts-a,impl-hostsfile-a", KV), Limits::NONE).unwrap();
        assert_eq!(lookup("impl-hosts-a"), Some(first));
        assert_eq!(lookup("IMPL-HOSTSFILE-A"), Some(first));
        assert_eq!(lookup(" impl-hosts-a "), Some(first));
        assert_eq!(lookup("impl-nope-a"), None);
        assert_eq!(lookup(""), None);
        // In any case means Unicode case, as the README says.
        let umlaut = register(inline("Impl-Ärger-a", KV), Limits::NONE).unwrap();
        assert_eq!(lookup("impl-ärger-a"), Some(umlaut));
        assert_eq!(lookup("IMPL-ÄRGER-A"), Some(umlaut));
        assert_eq!(
            Format::from_name("impl-ärger-a"),
            Some(Format::Custom(umlaut))
        );
        assert_eq!(
            Format::detect(std::path::Path::new("x.IMPL-ÄRGER-A")),
            Format::Custom(umlaut)
        );
        assert_eq!(Format::Custom(umlaut).name(), "Impl-Ärger-a");
        let second = register(inline("impl-hostsfile-a", KV), Limits::NONE).unwrap();
        assert_ne!(first, second);
        assert_eq!(lookup("impl-hostsfile-a"), Some(second));
        assert_eq!(lookup("impl-hosts-a"), Some(first));
        assert_eq!(get(first).unwrap().name, "impl-hosts-a");
        assert_eq!(get(second).unwrap().name, "impl-hostsfile-a");
        assert!(names().contains(&"impl-hosts-a"));
        assert!(registered().iter().any(|(id, _)| *id == second));
        // The format names list a name once, however often it is registered.
        register(inline("impl-dup-a", KV), Limits::NONE).unwrap();
        register(inline("IMPL-DUP-A", KV), Limits::NONE).unwrap();
        let dup = |list: &[&str]| {
            list.iter()
                .filter(|n| n.eq_ignore_ascii_case("impl-dup-a"))
                .count()
        };
        assert_eq!(dup(&names()), 2);
        assert_eq!(dup(&Format::known_names()), 1);

        // Through Format: the name, the extension, the whole file name.
        assert_eq!(
            Format::from_name("impl-hosts-a"),
            Some(Format::Custom(first))
        );
        assert_eq!(Format::Custom(first).name(), "impl-hosts-a");
        assert_eq!(Format::Custom(first).to_string(), "impl-hosts-a");
        assert_eq!(
            Format::from_extension("Impl-Hosts-A"),
            Some(Format::Custom(first))
        );
        assert_eq!(
            Format::detect(std::path::Path::new("/etc/impl-hosts-a")),
            Format::Custom(first)
        );
        assert_eq!(
            Format::detect(std::path::Path::new("dir/x.impl-hostsfile-a")),
            Format::Custom(second)
        );
        assert_eq!(
            Format::detect(std::path::Path::new("dir/impl-hosts-a.bak")),
            Format::Text
        );
    }

    #[test]
    fn a_custom_name_shadows_a_built_in() {
        // `webmanifest` is a JSON extension nothing else here relies on.
        assert_eq!(Format::from_extension("webmanifest"), Some(Format::Json));
        let id = register(inline("webmanifest", KV), Limits::NONE).unwrap();
        assert_eq!(
            Format::from_extension("webmanifest"),
            Some(Format::Custom(id))
        );
        assert_eq!(Format::from_name("webmanifest"), Some(Format::Custom(id)));
        assert_eq!(
            Format::detect(std::path::Path::new("app.webmanifest")),
            Format::Custom(id)
        );
        // The built-ins are untouched.
        assert_eq!(Format::from_name("json"), Some(Format::Json));
        assert!(!Format::ALL.iter().any(|f| matches!(f, Format::Custom(_))));
    }

    #[test]
    fn a_grammar_that_does_not_compile_is_the_commands_mistake() {
        let e = register(inline("impl-bad-a", "doc = undefined_rule\n"), Limits::NONE).unwrap_err();
        assert_eq!(e.option, "--grammar-expr");
        assert_eq!(e.grammar, "impl-bad-a");
        assert_eq!(e.file, None);
        assert!(e.is_usage());
        assert_eq!(e.error.code, "grammar");
        assert!(e.error.message.starts_with("abnf"), "{}", e.error.message);
        assert!(
            e.to_string().starts_with("--grammar-expr impl-bad-a: abnf"),
            "{e}"
        );
        assert_eq!(lookup("impl-bad-a"), None, "nothing is registered");
        // A grammar file that cannot be read is an io error.
        let d = Definition::parse("--grammar", "impl-missing-a=/nonexistent/x.abnf").unwrap();
        let e = register(d, Limits::NONE).unwrap_err();
        assert_eq!(e.option, "--grammar");
        assert_eq!(e.file, Some("/nonexistent/x.abnf".to_string()));
        assert!(!e.is_usage());
        assert!(e.error.is_io());
        assert!(
            e.to_string()
                .starts_with("--grammar impl-missing-a: /nonexistent/x.abnf: "),
            "{e}"
        );
        // Or too large for --max-size.
        let dir = std::env::temp_dir().join(format!("aless-grammar-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("big.abnf");
        std::fs::write(&file, KV).unwrap();
        let d = Definition::parse("--grammar", &format!("impl-big-a={}", file.display())).unwrap();
        let e = register(
            d.clone(),
            Limits {
                max_size: Some(8),
                timeout: None,
                started: None,
            },
        )
        .unwrap_err();
        assert!(e.error.is_too_large() && !e.is_usage());
        assert_eq!(e.size, Some(KV.len() as u64));
        assert_eq!(e.limits.max_size, Some(8));
        assert!(
            e.error.message.ends_with(&format!(
                "the grammar file is {} B, over the 8 B limit",
                KV.len()
            )),
            "{}",
            e.error.message
        );
        assert!(
            e.error
                .hint
                .starts_with("A grammar file over --max-size is not read"),
            "{}",
            e.error.hint
        );
        assert!(
            e.error.plain_report().contains("--> "),
            "{}",
            e.error.plain_report()
        );
        // And within it, a file registers.
        let id = register(
            d,
            Limits {
                max_size: Some(1 << 20),
                timeout: None,
                started: None,
            },
        )
        .unwrap();
        assert_eq!(get(id).unwrap().origin, Source::File(file.clone()));
        assert_eq!(get(id).unwrap().source, KV);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A repetition count the compiler would write out in the millions is
    /// refused before it starts, as the command's mistake; one within
    /// [`MAX_REPEAT`] compiles. A count too large for the grammar's
    /// number type saturates, and is refused the same way.
    #[test]
    fn repetition_counts_are_bounded() {
        for (text, count) in [
            ("doc = 10000000\"a\"\n", "10000000".to_string()),
            ("doc = *99999999\"a\"\n", "99999999".to_string()),
            ("doc = 1*1000000000\"a\"\n", "1000000000".to_string()),
            (
                "doc = 99999999999999999999999\"a\"\n",
                usize::MAX.to_string(),
            ),
            ("doc = word\nword = ( 2000TX )\n", "2000".to_string()),
            ("doc = 1025\"a\"\n", "1025".to_string()),
        ] {
            let e = compile(text).unwrap_err();
            assert!(
                e.starts_with(&format!("abnf: a repetition count of {count}")),
                "{text:?}: {e}"
            );
            assert!(e.contains("at most 1024") && e.contains("`*word`"), "{e}");
        }
        for text in [
            "doc = 1024\"a\"\n",
            "doc = 1*255\"a\"\n",
            "doc = *word\nword = ( TX )\n",
        ] {
            compile(text).unwrap_or_else(|e| panic!("{text:?}: {e}"));
        }
        let e = register(inline("impl-rep-a", "doc = 5000\"a\"\n"), Limits::NONE).unwrap_err();
        assert!(e.is_usage());
        assert_eq!(e.error.code, "grammar");
        assert!(
            e.to_string()
                .starts_with("--grammar-expr impl-rep-a: abnf: a repetition count of 5000"),
            "{e}"
        );
    }

    /// Repetitions within [`MAX_REPEAT`] each still add up, and they are
    /// counted where the compiler writes them: a rule's again in every
    /// alternative that starts with that rule, a repeated rule or group
    /// with a step for every copy, the rest of an alternative twice after
    /// a prefix the compiler may branch on. Over [`MAX_REPEAT_TOTAL`]
    /// rules is the command's mistake; copies of a terminal up to the
    /// minimum write none.
    #[test]
    fn repetition_rules_are_bounded_in_total() {
        // Sixteen `1*1024` took 153 s and 870 MB before the total was
        // checked. Registered under a time limit, so that a regression
        // fails in seconds, as a `timeout`, rather than holding the suite.
        let many = inline(
            "impl-rep-total",
            &format!("doc ={}\n", " 1*1024\"a\"".repeat(16)),
        );
        let limits = Limits {
            max_size: None,
            timeout: Some(Duration::from_secs(10)),
            started: None,
        };
        let e = register(many, limits).unwrap_err();
        assert!(
            e.is_usage() && e.error.code == "grammar",
            "{}",
            e.error.message
        );
        // 16 x (1 + 2 x 1023).
        assert!(
            e.error
                .message
                .contains("the repetitions would have the compiler write 32752 rules"),
            "{}",
            e.error.message
        );
        assert!(
            e.error.message.contains("at most 1024") && e.error.message.contains("`*word`"),
            "{}",
            e.error.message
        );
        assert_eq!(lookup("impl-rep-total"), None);
        // A rule an alternative starts with is written again into it, so
        // a chain of such rules writes `1*300` once per rule: 3 x 599.
        // Counted once, as a rule named once, it was 599, and a chain of
        // seven wrapping `1*1024` held the compiler for minutes.
        let e = compile("doc = s \"x\"\ns = r \"x\"\nr = 1*300\"q\"\n").unwrap_err();
        assert!(e.contains("write 1797 rules"), "{e}");
        // Named alone, or after the start of an alternative, it is not.
        for text in [
            "doc = r\nr = 1*300\"q\"\n",
            "doc = \"x\" r r\nr = 1*300\"q\"\n",
        ] {
            compile(text).unwrap_or_else(|e| panic!("{text:?}: {e}"));
        }
        // The rest of an alternative starting with a rule is written once
        // per alternative of that rule.
        let e = compile("doc = r 1*300\"x\"\nr = \"a\" / \"b\"\n").unwrap_err();
        assert!(e.contains("write 1198 rules"), "{e}");
        // A repeated group is written once, with a step for every copy:
        // 599 inside, 1 + 2 x 299 + 300 outside.
        let e = compile("doc = 1*300(1*300\"a\" \"x\")\n").unwrap_err();
        assert!(e.contains("write 1498 rules"), "{e}");
        // What follows an optional prefix the compiler may branch on is
        // written twice.
        let e = compile("doc = [\"a\" \"@\"] 1*300\"a\"\n").unwrap_err();
        assert!(e.contains("write 1198 rules"), "{e}");
        // One count over the limit is named as such, wherever it is.
        let e = compile("doc = 1024\"a\" 1024\"a\" 5000\"a\"\n").unwrap_err();
        assert!(e.contains("a repetition count of 5000"), "{e}");
        let e = compile("doc = 5000\"a\" 1024\"a\" 1024\"a\"\n").unwrap_err();
        assert!(e.contains("a repetition count of 5000"), "{e}");
        // Copies of a terminal up to the minimum are one sequence, and
        // write no rules however many there are.
        compile("doc = 1024\"a\" 1024\"b\" 1024\"c\"\n").unwrap();
    }

    /// What [`repeat_rules`] counts is what the compiler writes, for each
    /// way it has of writing a repetition: it counts no more, and the
    /// compiler writes no more than a few rules of the grammar's own
    /// besides. (Measured, so a compiler that writes a repetition some
    /// other way shows up here.)
    #[test]
    fn repetition_rules_are_counted_as_the_compiler_writes_them() {
        for text in [
            "doc = 1*40\"a\"\n",
            "doc = 1*40TX\n",
            "doc = 3*40\"a\" *\"b\" 4*\"c\"\n",
            "doc = r \"x\"\nr = 1*40\"q\"\n",
            "doc = s \"x\"\ns = r \"x\"\nr = 1*40\"q\"\n",
            "doc = r 1*40\"x\"\nr = \"a\" / \"b\" / \"c\"\n",
            "doc = 1*20(1*20\"a\" \"x\")\n",
            "doc = 40r\nr = \"a\" \"b\"\n",
            "doc = 40(40\"a\")\n",
            "doc = [\"a\" \"@\"] 1*40\"a\"\n",
            "doc = 0*20\"x\" doc 1*20\"y\" / \"z\"\n",
            "a = b \"x\" / \"c\"\nb = a 1*20\"y\" / \"d\"\n",
        ] {
            let grammar = tabnas_abnf::parse_abnf(text).unwrap();
            let counted = repeat_rules(&grammar, 1);
            let written = compile(text)
                .unwrap_or_else(|e| panic!("{text:?}: {e}"))
                .spec
                .rule
                .len();
            assert!(
                counted <= written && written <= counted + 16,
                "{text:?}: counted {counted}, the compiler wrote {written}"
            );
        }
        // A grammar nested deeper than the compiler walks is counted as
        // written, and the compiler refuses it.
        let chain =
            tabnas_abnf::parse_abnf("doc = s \"x\"\ns = r \"x\"\nr = 1*300\"q\"\n").unwrap();
        assert_eq!(repeat_rules(&chain, 1), 1797);
        assert_eq!(repeat_rules(&chain, COMPILER_ELEMENT_DEPTH + 1), 599);
        let deep = format!(
            "doc = {}1*3\"a\"{}\n",
            "(".repeat(COMPILER_ELEMENT_DEPTH),
            ")".repeat(COMPILER_ELEMENT_DEPTH)
        );
        let e = compile(&deep).unwrap_err();
        assert!(e.contains("more than 128 deep"), "{e}");
    }

    /// The compile runs within the time limit a parse would, on a thread
    /// of its own: past it, the grammar is a `timeout` error, and the
    /// compiler is left to finish on its own.
    #[test]
    fn a_compile_past_the_time_limit_is_a_timeout() {
        // Some 300 nested optionals take the compiler well over a
        // millisecond (`1*1000"a"` takes about a second in a release build).
        let slow = inline("impl-slow-a", "doc = 1*300\"a\"\n");
        let limits = Limits {
            max_size: None,
            timeout: Some(Duration::from_millis(1)),
            started: None,
        };
        let e = register(slow, limits).unwrap_err();
        assert!(!e.is_usage());
        assert!(e.error.is_timeout(), "{}", e.error.message);
        assert_eq!(e.limits, limits);
        assert_eq!(
            e.to_string(),
            "--grammar-expr impl-slow-a: timeout: the grammar took longer than 0.001 s to compile"
        );
        assert!(
            e.error.hint.contains("--timeout 0 for no limit"),
            "{}",
            e.error.hint
        );
        // On a thread of its own, the compile is left running: aless
        // stopped waiting for it.
        assert!(
            e.error
                .hint
                .starts_with("The compiler cannot be interrupted, so aless stopped waiting"),
            "{}",
            e.error.hint
        );
        assert!(e.error.plain_report().starts_with("[aless/timeout]"));
        assert_eq!(lookup("impl-slow-a"), None);
        // With time enough, a grammar registers under a limit.
        let limits = Limits {
            max_size: None,
            timeout: Some(Duration::from_secs(600)),
            started: None,
        };
        assert!(register(inline("impl-slow-b", "doc = 1*20\"a\"\n"), limits).is_ok());
    }

    /// With no thread to be had, the compile runs on the caller's and
    /// cannot be stopped, but its time is still measured: a grammar
    /// compiled past the limit is a `timeout`, not registered.
    #[test]
    fn a_compile_on_this_thread_past_the_time_limit_is_a_timeout() {
        let slow = "doc = 1*300\"a\"\n";
        let e = compile_here(slow, Some(Duration::from_millis(1)))
            .err()
            .unwrap();
        assert!(e.is_timeout(), "{}", e.message);
        assert_eq!(
            e.message,
            "timeout: the grammar took longer than 0.001 s to compile"
        );
        // The hint says what happened: the compile ran to its end, on
        // aless's own thread, and was refused for its time.
        assert!(
            e.hint.starts_with(
                "No thread could be started for the compiler, so it ran to its end on \
                 aless's own and took "
            ),
            "{}",
            e.hint
        );
        assert!(!e.hint.contains("stopped waiting"), "{}", e.hint);
        // A late refusal is late too: the time is the answer, not the error.
        let late_error = "doc = 1*300\"a\"\nbad = 99999999999999999999999\"a\"\n";
        let e = compile_here(late_error, Some(Duration::from_nanos(1)))
            .err()
            .unwrap();
        assert!(e.is_timeout(), "{}", e.message);
        // Within the limit, or with none, it compiles as on a thread.
        assert!(compile_here("doc = 1*20\"a\"\n", Some(Duration::from_secs(600))).is_ok());
        assert!(compile_here("doc = 1*20\"a\"\n", None).is_ok());
        let e = compile_here("doc = \"a\n", Some(Duration::from_secs(600)))
            .err()
            .unwrap();
        assert_eq!(e.code, "grammar");
    }

    /// A compiler message is one line of plain text: the engine's colour
    /// codes are stripped and control characters shown escaped, as a
    /// report's `message` is for a parse error.
    #[test]
    fn compiler_messages_are_one_plain_line() {
        for text in ["doc = *\n", "doc = \"a\u{1}b\"\n", "doc = %x7E-21\n"] {
            let e = compile(text).unwrap_err();
            assert!(!e.contains('\u{1b}'), "{text:?}: {e:?}");
            assert!(!e.chars().any(char::is_control), "{text:?}: {e:?}");
            assert!(e.starts_with("abnf: "), "{text:?}: {e}");
        }
        let e = compile("doc = *\n").unwrap_err();
        assert!(
            e.contains("[tabnas/unexpected]: unexpected character(s): *"),
            "{e}"
        );
        let e = compile("doc = %x7E-21\n").unwrap_err();
        assert!(e.contains("regex parse error:\\n"), "{e}");
    }
}