frazaro 0.9.2

The command-line door to frazaro-core
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
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
//! frazaro: the command-line door to frazaro-core.
//!
//! The commands this door will carry, in the order the slices of
//! docs/HORIZON.md section 12 deliver them: compile (PORT.5), check,
//! build, run, ask, diff, rebuild, prove. The door reads the files; the
//! core sees text and gives text back. The conformance contract is
//! conformance/README.md: an oracle this version does not attempt exits 3,
//! a refusal writes its words to stderr and exits 1.

use std::process::ExitCode;

const USAGE: &str = "\
frazaro - a compiler from sentences to spreadsheets

usage:
  frazaro compile <program.vla> [--prelude <prelude.vla>]
                         the VBA of a VLA program, to stdout (PORT.5)
  frazaro load <phrasebook.vla> [--prelude <prelude.vla>] [--allow-raw]
                         load a phrasebook, its proofs run as the add-in
                         runs them, and report what it holds, the line
                         EnglishVocabStats prints (PORT.6, slice 6c);
                         --allow-raw is the consent a (raw ...) form needs
  frazaro prove <phrasebook.vla|folder> [--prelude <prelude.vla>] [--allow-raw]
                         the treaty's oracle 3: every proof run, each
                         failure printed, then PASS n/n or FAIL k/n (k of
                         n passed), exit 0 or 1 (PORT.6, slice 6d); the
                         prelude is prelude.vla beside the file or in its
                         parent folder, else the one inside frazaro, unless
                         --prelude names one; an engine proof file exits 3
                         (not attempted, PORT.9); a folder holding
                         distro.vla is a distro (KERNEL.2), proved whole:
                         its base phrasebook alone, then its overlay and
                         each dialect over the base, as the doors load
                         them, one line a book, a library listed and not
                         scored, the manifest's prelude unless --prelude
                         names one, and the total last
  frazaro translate-vla <program.txt> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]
                         the treaty's oracle 1: the program's VLA, the text
                         EnglishToVla writes, to stdout (PORT.6, slice 6e);
                         each phrasebook loads in order, its proofs run
  frazaro translate-vba <program.txt> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]
                         oracle 1a: that VLA compiled, the VBA the add-in
                         would write (EnglishToVba)
  frazaro build <program.txt> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] --out <file.xlsx> [--into <model.xlsx>] [--replace] [--allow-raw]
                         the writer (PORT.7): the program translated as
                         translate-vla translates it, then written as a
                         workbook: the Frazaro sheet holds the sentences in
                         column B with OK beside each in column C, as the
                         add-in's Check marks them (slice 7a), and the sheets
                         the sentences describe hold what a sheet can hold
                         with nothing running - values and formulas into
                         cells, on the sheet the program names (slice 7b); a
                         sentence that needs the add-in's Run is refused by
                         name, and a file already at --out is refused unless
                         --replace is given; the workbook carries its build
                         stamp, the defined name Frazaro.Build (slice 7c);
                         with --into, the sheets are added to that workbook,
                         whose own parts are copied byte for byte and never
                         written to by a sentence (slice 7d)
  frazaro rebuild <file.xlsx> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]
                         the sentences read back out of a built workbook's
                         Frazaro sheet, its stamp checked against them and
                         the files given, the build done again and compared
                         whole: one line, yes (exit 0) or no with why (exit
                         1); a file that is not a build is refused (slice 7c)
  frazaro reflect <file.xlsx|.ods> [--counts] [--functions] [--cone <Sheet!A1> ...]
                         the reader (PORT.8, slices 8a and 8b; an
                         OpenDocument .ods file reads the same from slice
                         8e, its formulas spelled as the formula bar shows
                         them): the workbook's relations to stdout in a
                         fixed order,
                         one form a line - every sheet with its state, every
                         name, every Table, then sheet by sheet each cell's
                         value as the file holds it, each formula's text as
                         the formula bar shows it, and what the formula
                         refers to, one row per distinct reference; with
                         --counts, counts and times alone, one line a sheet
                         by position and one for the workbook, the distinct
                         formulas in R1C1 and the INDIRECT and OFFSET calls
                         among them, so that nothing confidential leaves the
                         machine; with --cone, a cell's cone sized through
                         names and Tables and across sheets, counts alone,
                         and where it is blind; with --functions, one row
                         per function the formulas call with the number of
                         cells calling it, most called first, counts alone
                         (KERNEL.6's instrument); a file that is not a
                         workbook, a part with a DOCTYPE, or a shape this
                         version does not read is refused by name
  frazaro diff <old.xlsx|.ods> <new.xlsx|.ods> [--counts]
                         the difference between two workbooks (PORT.8, slice
                         8c), read as reflect reads them: the sheets in one
                         file alone, then the names and Tables that differ,
                         then cell by cell on the matched sheets what
                         changed, old and new side by side - a value, a
                         formula with its cached value, or blank - one form
                         a line in a fixed order, nothing when the two hold
                         the same; with --counts, the counts and times alone
  frazaro audit <file.xlsx|.ods> [--counts]
                         the audit list (PORT.8, slice 8d): where a
                         workbook's risks are, read from the file - a
                         constant typed over a column of formulas, a formula
                         inconsistent with its neighbours, a name nothing
                         refers to, a reference to an empty cell, a hidden
                         sheet, a link to another workbook - one finding a
                         line in a fixed order, nothing when there is
                         nothing to report; with --counts, the six counts
                         and the times alone
  frazaro calc <file.xlsx|.ods> [--counts | --shapes]
                         recalculation (KERNEL.7): the workbook read as
                         reflect reads it into the grid, every formula
                         computed in dependency order under the declared
                         subset, and one row per formula cell - the sheet,
                         the cell, the formula, the computed value, the
                         value the host saved, and agree, differ or
                         unchecked - sheet by sheet in row order, every
                         cycle named first by its cells; a function this
                         version does not compute shows not computed here
                         with its name, and a cell that reads it inherits
                         the label; with --counts, the counts and times
                         alone; with --shapes, nothing computed and the
                         plan an engine's machine makes of the grid printed,
                         its census (KERNEL.30): a plan row of totals, a
                         readers row a sheet and a shape row a formula
                         shape - its cells, the levels it spans, its runs
                         and the path each of its reads takes; exit 0
                         whenever the calculation or the plan ran
                         the view record (KERNEL.4): the program translated
                         and built as build builds it, into the sheet model
                         alone with nothing written, and one window of one
                         sheet printed as the lines a viewport draws from -
                         every sheet, the window, the sheet's extent and
                         gridlines, the window's columns and formats, then
                         cell by cell in row order the value or the formula
                         as reflect spells it, each formula followed by its
                         computed value (KERNEL.7) or not computed here with
                         the function named, the cell's format and the row
                         of the sentence that wrote it; without --window,
                         the sheet's whole extent; a sheet the program does
                         not make, or a window that is not a rectangle of
                         cells, is refused by name
  frazaro version        the version of the core this door is built on
  frazaro help           this text

Without --prelude a command uses the prelude inside frazaro, and without
--phrasebook its english.vla: the repository's scripts/prelude.vla and
scripts/polyglotta/english.vla, byte for byte, so that an installed frazaro
needs no file beside it. --phrasebook names the whole list, in order, as
the add-in loads them, english.vla first; `--phrasebook english.vla` with
no such file beside you is the one inside frazaro.

Not in this version (docs/HORIZON.md, section 12, slice by slice):
  check, run, ask
";

/// A file as text: UTF-8, a leading byte-order mark dropped, line endings
/// as they are on disk (the core and the reference both leave them alone).
fn read_text(path: &str) -> Result<String, String> {
    let bytes = std::fs::read(path).map_err(|e| format!("cannot read {path}: {e}"))?;
    let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes);
    String::from_utf8(bytes.to_vec()).map_err(|_| format!("{path} is not valid UTF-8"))
}

/// A file a command needs but cannot find: the catalogue's refusal for that
/// kind of file (the reference's `english-program-file-not-found` and
/// `english-vocab-file-not-found`; a VLA source and the prelude take
/// VLA.bas's two), to stderr with exit 1, as any refusal.
fn refuse_missing(id: &str, path: &str) -> ExitCode {
    eprintln!("{}", frazaro_core::messages::raise(id, &[("path", path)]));
    ExitCode::from(1)
}

fn is_file(path: &str) -> bool {
    std::path::Path::new(path).is_file()
}

fn option_after<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
    args.iter()
        .position(|a| a == name)
        .and_then(|i| args.get(i + 1))
        .map(String::as_str)
}

/// The prelude and the English phrasebook inside the door, byte for byte the
/// repository's scripts/prelude.vla and scripts/polyglotta/english.vla
/// (tools/check_crate_data.ps1 holds the copies under cli/data/ to them):
/// what a command uses when --prelude or --phrasebook is not given, so that
/// an installed frazaro needs no file beside it.
const BUILT_IN_PRELUDE: &str = include_str!("../data/prelude.vla");
const BUILT_IN_ENGLISH: &str = include_str!("../data/english.vla");
/// The name the built-in phrasebook loads under, which a refusal shows.
const BUILT_IN_ENGLISH_NAME: &str = "english.vla (inside frazaro)";

/// The prelude a command works with: the file --prelude names, read and
/// checked, or the one inside the door; the exit code to end the command
/// with comes back as the error.
fn prelude_of(args: &[String]) -> Result<String, ExitCode> {
    match option_after(args, "--prelude") {
        Some(path) => {
            if !is_file(path) {
                return Err(refuse_missing("vla-file-not-found", path));
            }
            read_text(path).map_err(|e| {
                eprintln!("frazaro: {e}");
                ExitCode::from(2)
            })
        }
        None => Ok(BUILT_IN_PRELUDE.to_string()),
    }
}

/// A phrasebook holds a `<lingua>-vla` rule or a proof form at the top
/// level; the same lexical rule tools/prove.ps1 inventories by (a file with
/// neither is a library, or an engine proof file).
fn is_phrasebook_text(text: &str) -> bool {
    text.lines().any(|l| {
        if l.starts_with("(test-success") || l.starts_with("(test-fail") {
            return true;
        }
        let Some(rest) = l.strip_prefix('(') else {
            return false;
        };
        let head: String = rest
            .chars()
            .take_while(|c| !c.is_whitespace() && *c != '(' && *c != ')')
            .collect();
        head.ends_with("-vla") || head.ends_with("-vla-override")
    })
}

/// `prelude.vla` beside a file, or in its parent folder, as a path string.
fn prelude_beside(file: &str) -> Option<String> {
    let dir = std::path::Path::new(file)
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(std::path::Path::to_path_buf)
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    for candidate in [dir.join("prelude.vla"), dir.join("..").join("prelude.vla")] {
        if candidate.is_file() {
            return Some(candidate.to_string_lossy().into_owned());
        }
    }
    None
}

fn compile(args: &[String]) -> ExitCode {
    let Some(program) = args.first() else {
        eprintln!("usage: frazaro compile <program.vla> [--prelude <prelude.vla>]");
        return ExitCode::from(2);
    };
    if !is_file(program) {
        return refuse_missing("vla-source-not-found", program);
    }
    let prelude = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let source = match read_text(program) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    match frazaro_core::emit::compile(&source, &prelude) {
        Ok(vba) => {
            use std::io::Write;
            let mut out = std::io::stdout().lock();
            if out
                .write_all(vba.as_bytes())
                .and_then(|_| out.flush())
                .is_err()
            {
                return ExitCode::from(2);
            }
            ExitCode::SUCCESS
        }
        Err(refusal) => {
            eprintln!("{refusal}");
            ExitCode::from(1)
        }
    }
}

/// `frazaro load`: a phrasebook through the core's loader, with the two
/// gates the reference's file loader runs and its text loader leaves to
/// the door: a required capability (none can be granted yet), and SEC.2's
/// consent for a `(raw ...)` form, which the person gives with --allow-raw.
fn load(args: &[String]) -> ExitCode {
    let Some(book) = args.first() else {
        eprintln!("usage: frazaro load <phrasebook.vla> [--prelude <prelude.vla>] [--allow-raw]");
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    if !is_file(book) {
        return refuse_missing("english-vocab-file-not-found", book);
    }
    let prelude = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let text = match read_text(book) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    if let Err(refusal) = frazaro_core::api::vocab_gate(&text, book, allow_raw) {
        eprintln!("{refusal}");
        return ExitCode::from(1);
    }
    let mut grammar = frazaro_core::english::Grammar::new(&prelude);
    match grammar.load_vocabulary_text(&text, book) {
        Ok(_rules) => {
            // `EnglishVocabStats`' line: the proofs ran at load, as the
            // reference runs them, and a failing one refused the load above.
            println!("{}", grammar.vocab_stats());
            let warnings = grammar.lint_warnings();
            if !warnings.is_empty() {
                print!("{}", grammar.lint_report());
            }
            ExitCode::SUCCESS
        }
        Err(refusal) => {
            eprintln!("{refusal}");
            ExitCode::from(1)
        }
    }
}

/// One book's proofs over the books before it: the earlier texts load first
/// as the doors load them (a failing proof there refuses, as a load would),
/// then the book under Collect, its own failures printed and counted. The
/// book's `(n, k)`, n proofs and k passed, or the refusal that stopped a load.
fn prove_over(
    prelude: &str,
    earlier: &[(&str, &str)],
    book: (&str, &str),
) -> Result<(u64, u64), frazaro_core::messages::Refusal> {
    let mut grammar = frazaro_core::english::Grammar::new(prelude);
    for (name, text) in earlier {
        grammar.load_vocabulary_text(text, name)?;
    }
    grammar.set_proof_mode(frazaro_core::english::grammar::ProofMode::Collect);
    let (t0, f0) = grammar.proofs_run();
    let before = grammar.proof_failures().len();
    grammar.load_vocabulary_text(book.1, book.0)?;
    let (t1, f1) = grammar.proofs_run();
    let n = (t1 + f1) - (t0 + f0);
    let failures = &grammar.proof_failures()[before..];
    for f in failures {
        println!("{}", f.refusal.text);
        println!();
    }
    Ok((n, n - failures.len() as u64))
}

/// `frazaro prove <folder>` (KERNEL.2): the folder's `distro.vla` read, the
/// base phrasebook proved alone as oracle 3 proves a file, then the overlay
/// and each dialect proved over the base as the doors load them, one line a
/// book (`<name>: PASS n/n`, `<name> over <base>: FAIL k/n`), a library
/// listed and not scored, and the last line the total, `PASS n/n` or
/// `FAIL k/n`, exit 0 or 1. The manifest's prelude is the prelude unless
/// `--prelude` names another. A folder with no `distro.vla`, or a manifest
/// this version cannot read, is refused through the catalogue; a file the
/// manifest names that is not there is refused as a named file is.
fn prove_distro(folder: &str, args: &[String], allow_raw: bool) -> ExitCode {
    use frazaro_core::distro::Book;
    let dir = std::path::Path::new(folder);
    let manifest = dir.join("distro.vla");
    let label = manifest.to_string_lossy().into_owned();
    if !manifest.is_file() {
        let edition = dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| folder.to_string());
        eprintln!(
            "{}",
            frazaro_core::messages::raise(
                "distro-manifest-missing",
                &[("edition", &edition), ("path", &label)]
            )
        );
        return ExitCode::from(1);
    }
    let text = match read_text(&label) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    let distro = match frazaro_core::distro::parse(&text, &label) {
        Ok(d) => d,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let prelude_path = match option_after(args, "--prelude") {
        Some(p) => p.to_string(),
        None => dir.join(&distro.prelude).to_string_lossy().into_owned(),
    };
    if !is_file(&prelude_path) {
        return refuse_missing("vla-file-not-found", &prelude_path);
    }
    let prelude = match read_text(&prelude_path) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    // A book's text, read from where the manifest points and gated as any
    // phrasebook a door did not ship is gated.
    let read_book = |b: &Book| -> Result<String, ExitCode> {
        let path = dir.join(&b.path).to_string_lossy().into_owned();
        if !is_file(&path) {
            return Err(refuse_missing("english-vocab-file-not-found", &path));
        }
        let t = read_text(&path).map_err(|e| {
            eprintln!("frazaro: {e}");
            ExitCode::from(2)
        })?;
        if let Err(refusal) = frazaro_core::api::vocab_gate(&t, &path, allow_raw) {
            eprintln!("{refusal}");
            return Err(ExitCode::from(1));
        }
        Ok(t)
    };
    let base_text = match read_book(&distro.base) {
        Ok(t) => t,
        Err(code) => return code,
    };
    let base_name = distro.base.name.as_str();
    let (mut total, mut passed) = (0u64, 0u64);
    let mut line =
        |what: String, result: Result<(u64, u64), frazaro_core::messages::Refusal>| match result {
            Ok((n, k)) => {
                total += n;
                passed += k;
                if n == k {
                    println!("{what}: PASS {n}/{n}");
                } else {
                    println!("{what}: FAIL {k}/{n}");
                }
                true
            }
            Err(refusal) => {
                eprintln!("{refusal}");
                false
            }
        };
    if !line(
        base_name.to_string(),
        prove_over(&prelude, &[], (base_name, &base_text)),
    ) {
        return ExitCode::from(1);
    }
    let over: Vec<&Book> = distro
        .overlay
        .iter()
        .chain(distro.dialects.iter())
        .collect();
    for book in over {
        let text = match read_book(book) {
            Ok(t) => t,
            Err(code) => return code,
        };
        if !line(
            format!("{} over {base_name}", book.name),
            prove_over(
                &prelude,
                &[(base_name, &base_text)],
                (book.name.as_str(), &text),
            ),
        ) {
            return ExitCode::from(1);
        }
    }
    for lib in &distro.libraries {
        println!("{}: a library of macros, not scored", lib.name);
    }
    if passed == total {
        println!("PASS {total}/{total}");
        ExitCode::SUCCESS
    } else {
        println!("FAIL {passed}/{total}");
        ExitCode::from(1)
    }
}

/// `frazaro prove <phrasebook.vla> --prelude <prelude.vla> [--allow-raw]`:
/// the treaty's oracle 3. The phrasebook loads with every proof run and
/// every failure kept, each failure is printed as the reference would have
/// refused it, and the last line is `PASS n/n` or `FAIL k/n` (k passed of
/// n), exit 0 or 1. A load that refuses before its proofs (a library, a
/// malformed rule) prints the refusal and exits 1 with no verdict line.
fn prove(args: &[String]) -> ExitCode {
    let Some(book) = args.first() else {
        eprintln!(
            "usage: frazaro prove <phrasebook.vla|folder> [--prelude <prelude.vla>] [--allow-raw]"
        );
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    if std::path::Path::new(book).is_dir() {
        return prove_distro(book, args, allow_raw);
    }
    if !is_file(book) {
        return refuse_missing("english-vocab-file-not-found", book);
    }
    let text = match read_text(book) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    // The treaty's oracle 3 is a phrasebook's proofs; an engine proof file
    // (scripts/proofs/) is PORT.9's, not attempted, which the runner
    // reads from exit 3.
    if !is_phrasebook_text(&text) {
        eprintln!(
            "frazaro: 'prove' attempts a phrasebook's proofs; engine proofs are not attempted in this version (PORT.9)"
        );
        return ExitCode::from(3);
    }
    // The contract is `prove <proofs.vla>` alone, so the prelude is found
    // beside the file or in its parent folder (scripts/polyglotta/x.vla
    // reads scripts/prelude.vla), else it is the one inside the door;
    // --prelude names another.
    let prelude_path = option_after(args, "--prelude")
        .map(str::to_string)
        .or_else(|| prelude_beside(book));
    let prelude = match prelude_path {
        Some(path) => {
            if !is_file(&path) {
                return refuse_missing("vla-file-not-found", &path);
            }
            match read_text(&path) {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("frazaro: {e}");
                    return ExitCode::from(2);
                }
            }
        }
        None => BUILT_IN_PRELUDE.to_string(),
    };
    if let Err(refusal) = frazaro_core::api::vocab_gate(&text, book, allow_raw) {
        eprintln!("{refusal}");
        return ExitCode::from(1);
    }
    let mut grammar = frazaro_core::english::Grammar::new(&prelude);
    grammar.set_proof_mode(frazaro_core::english::grammar::ProofMode::Collect);
    match grammar.load_vocabulary_text(&text, book) {
        Ok(_rules) => {
            let (tests, fails) = grammar.proofs_run();
            let n = tests + fails;
            let failures = grammar.proof_failures();
            for f in failures {
                println!("{}", f.refusal.text);
                println!();
            }
            let k = n - failures.len() as u64;
            if failures.is_empty() {
                println!("PASS {n}/{n}");
                ExitCode::SUCCESS
            } else {
                println!("FAIL {k}/{n}");
                ExitCode::from(1)
            }
        }
        Err(refusal) => {
            eprintln!("{refusal}");
            ExitCode::from(1)
        }
    }
}

/// `frazaro translate-vla|translate-vba <program.txt> [--prelude <prelude.vla>]
/// [--phrasebook <file.vla> ...] [--allow-raw]`: the treaty's oracles 1 and
/// 1a. Each phrasebook loads in order, its proofs run as the add-in runs
/// them (a failing proof refuses, as EnglishLoadVocabulary does), then
/// EnglishToVla (or EnglishToVba: its text compiled with the prelude) writes
/// to stdout. A refusal goes to stderr with exit 1.
fn translate(kind: &str, args: &[String]) -> ExitCode {
    let Some(program) = args.first() else {
        eprintln!(
            "usage: frazaro {kind} <program.txt> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]"
        );
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    if !is_file(program) {
        return refuse_missing("english-program-file-not-found", program);
    }
    let prelude = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let text = match read_text(program) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    let grammar = match load_books(&prelude, args, allow_raw) {
        Ok((g, _)) => g,
        Err(code) => return code,
    };
    let out = if kind == "translate-vla" {
        grammar.translate_program(&text).map(|t| t.vla)
    } else {
        grammar.translate_program_to_vba(&text)
    };
    match out {
        Ok(s) => {
            print!("{s}");
            ExitCode::SUCCESS
        }
        Err(refusal) => {
            eprintln!("{refusal}");
            ExitCode::from(1)
        }
    }
}

/// The phrasebooks a command loads, in order, as (name, text): the files
/// --phrasebook names, each read and passed through the door's two gates
/// (`api::vocab_gate`); `english.vla` with no such file beside the caller is
/// the one inside the door, as is the whole list when no --phrasebook is
/// given. The exit code to end the command with comes back as the error.
fn read_books(args: &[String], allow_raw: bool) -> Result<Vec<(String, String)>, ExitCode> {
    let named: Vec<&str> = args
        .windows(2)
        .filter(|w| w[0] == "--phrasebook")
        .map(|w| w[1].as_str())
        .collect();
    let built_in = || {
        (
            BUILT_IN_ENGLISH_NAME.to_string(),
            BUILT_IN_ENGLISH.to_string(),
        )
    };
    if named.is_empty() {
        return Ok(vec![built_in()]);
    }
    let mut books = Vec::with_capacity(named.len());
    for book in named {
        if !is_file(book) {
            if book == "english.vla" {
                books.push(built_in());
                continue;
            }
            return Err(refuse_missing("english-vocab-file-not-found", book));
        }
        let vocab = read_text(book).map_err(|e| {
            eprintln!("frazaro: {e}");
            ExitCode::from(2)
        })?;
        if let Err(refusal) = frazaro_core::api::vocab_gate(&vocab, book, allow_raw) {
            eprintln!("{refusal}");
            return Err(ExitCode::from(1));
        }
        books.push((book.to_string(), vocab));
    }
    Ok(books)
}

/// The grammar a command translates with: the prelude, then each phrasebook
/// text loaded in order under its name, its proofs run; the first refusal
/// ends the command, and the exit code to end it with comes back as the
/// error. The texts come back too, for the build stamp.
fn load_books(
    prelude: &str,
    args: &[String],
    allow_raw: bool,
) -> Result<(frazaro_core::english::Grammar, Vec<String>), ExitCode> {
    let books = read_books(args, allow_raw)?;
    let mut grammar = frazaro_core::english::Grammar::new(prelude);
    for (name, vocab) in &books {
        if let Err(refusal) = grammar.load_vocabulary_text(vocab, name) {
            eprintln!("{refusal}");
            return Err(ExitCode::from(1));
        }
    }
    Ok((grammar, books.into_iter().map(|(_, text)| text).collect()))
}

/// `frazaro rebuild` (PORT.7, slice 7c): a built workbook read back, its
/// stamp checked against its sentences and the files given, the build done
/// again and compared whole; one line, yes or no with why, exit 0 or 1. A
/// file that is not a build this core can verify is refused through the
/// catalogue.
fn rebuild(args: &[String]) -> ExitCode {
    let Some(file) = args.first() else {
        eprintln!(
            "usage: frazaro rebuild <file.xlsx> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]"
        );
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    if !is_file(file) {
        return refuse_missing("vla-file-not-found", file);
    }
    let prelude_text = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("frazaro: cannot read {file}: {e}");
            return ExitCode::from(2);
        }
    };
    let books = match read_books(args, allow_raw) {
        Ok(b) => b,
        Err(code) => return code,
    };
    let texts: Vec<&str> = books.iter().map(|(_, text)| text.as_str()).collect();
    match frazaro_core::api::english_rebuild_xlsx(&bytes, &prelude_text, &texts) {
        Ok(r) => {
            println!("{}", r.line());
            if r.matches {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        Err(r) => {
            eprintln!("{}", r.refusal);
            ExitCode::from(1)
        }
    }
}

/// `frazaro build` (PORT.7): the program translated as translate-vla
/// translates it, then written as a workbook at --out. The door writes the
/// one file and nothing else; a file already there is refused through the
/// catalogue unless --replace says to replace it.
fn build(args: &[String]) -> ExitCode {
    let (Some(program), Some(out)) = (args.first(), option_after(args, "--out")) else {
        eprintln!(
            "usage: frazaro build <program.txt> [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] --out <file.xlsx> [--into <model.xlsx>] [--replace] [--allow-raw]"
        );
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    let replace = args.iter().any(|a| a == "--replace");
    let into = option_after(args, "--into");
    if !is_file(program) {
        return refuse_missing("english-program-file-not-found", program);
    }
    let prelude_text = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    if let Some(model) = into {
        if !is_file(model) {
            return refuse_missing("vla-file-not-found", model);
        }
    }
    if std::path::Path::new(out).exists() && !replace {
        eprintln!(
            "{}",
            frazaro_core::messages::raise("build-output-exists", &[("path", out)])
        );
        return ExitCode::from(1);
    }
    let text = match read_text(program) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    let (grammar, texts) = match load_books(&prelude_text, args, allow_raw) {
        Ok(gt) => gt,
        Err(code) => return code,
    };
    let translation = match grammar.translate_program(&text) {
        Ok(t) => t,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let texts: Vec<&str> = texts.iter().map(String::as_str).collect();
    let built = match into {
        None => frazaro_core::build::build_xlsx(&text, &translation.vla, &prelude_text, &texts),
        Some(model) => match std::fs::read(model) {
            Ok(bytes) => frazaro_core::build::build_xlsx_into(
                &text,
                &translation.vla,
                &prelude_text,
                &texts,
                bytes,
                model,
            ),
            Err(e) => {
                eprintln!("frazaro: cannot read {model}: {e}");
                return ExitCode::from(2);
            }
        },
    };
    let bytes = match built {
        Ok(b) => b,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    if let Err(e) = std::fs::write(out, &bytes) {
        eprintln!("frazaro: cannot write {out}: {e}");
        return ExitCode::from(2);
    }
    // The file's own digest, for a reader to compare with another door's
    // (the page shows the same digest beside its download, slice 7e).
    println!(
        "wrote {out}: {} bytes, sha256 {}",
        bytes.len(),
        frazaro_core::sha256::sha256_hex(&bytes)
    );
    ExitCode::SUCCESS
}

/// `frazaro view <program.txt> --sheet <name> [--window <A1:F20>] ...`
/// (KERNEL.4): the program translated as translate-vla translates it and
/// built into the sheet model as build builds it, nothing written, and one
/// window of one sheet printed as the view record, one form a line in the
/// fixed order; without --window, the sheet's whole extent. A refusal, the
/// translation's, the build's or the view's, goes to stderr with exit 1; a
/// missing --sheet is a usage error.
fn view(args: &[String]) -> ExitCode {
    let (Some(program), Some(sheet)) = (args.first(), option_after(args, "--sheet")) else {
        eprintln!(
            "usage: frazaro view <program.txt> --sheet <name> [--window <A1:F20>] [--prelude <prelude.vla>] [--phrasebook <file.vla> ...] [--allow-raw]"
        );
        return ExitCode::from(2);
    };
    let allow_raw = args.iter().any(|a| a == "--allow-raw");
    let window = option_after(args, "--window");
    if !is_file(program) {
        return refuse_missing("english-program-file-not-found", program);
    }
    let prelude_text = match prelude_of(args) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let text = match read_text(program) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("frazaro: {e}");
            return ExitCode::from(2);
        }
    };
    let (grammar, texts) = match load_books(&prelude_text, args, allow_raw) {
        Ok(gt) => gt,
        Err(code) => return code,
    };
    let translation = match grammar.translate_program(&text) {
        Ok(t) => t,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let texts: Vec<&str> = texts.iter().map(String::as_str).collect();
    let model =
        match frazaro_core::build::build_workbook(&text, &translation.vla, &prelude_text, &texts) {
            Ok(wb) => wb,
            Err(refusal) => {
                eprintln!("{refusal}");
                return ExitCode::from(1);
            }
        };
    let window = match frazaro_core::view::window_of(&model, sheet, window) {
        Ok(w) => w,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    // KERNEL.7: the model recalculated under Excel's library, so each
    // formula row carries its value row.
    let library = frazaro_core::excel::library();
    let calc = frazaro_core::calc::Calc::run(&model, &library);
    print!(
        "{}",
        frazaro_core::view::view_text_valued(&model, &window, &calc)
    );
    ExitCode::SUCCESS
}

/// Milliseconds since `since`, for the counts' lines.
fn ms_since(since: std::time::Instant) -> f64 {
    since.elapsed().as_secs_f64() * 1000.0
}

/// `frazaro reflect <file.xlsx> [--counts] [--cone <Sheet!A1> ...]`
/// (PORT.8, slices 8a and 8b): the workbook's relations to stdout in the
/// fixed order, streamed sheet by sheet through the core's reader, which
/// holds no model of the workbook. With --counts, counts and times alone:
/// one line a sheet by position and one for the workbook, AXM.1's
/// discipline (no file name, sheet name, address, formula text or value
/// leaves the machine), which is how the reader gives that measurement its
/// second number; from 8b the distinct formulas in R1C1 and the unreadable
/// calls are among them. With --cone, the one exception to streaming: an
/// index of every formula is built in one walk and each root's cone is
/// sized through it, counts alone, the root being the one address printed
/// because the caller typed it. A refusal goes to stderr with exit 1; the
/// rows printed before it stand, since the read streams.
fn reflect(args: &[String]) -> ExitCode {
    const USAGE_LINE: &str =
        "usage: frazaro reflect <file.xlsx|.ods> [--counts] [--functions] [--cone <Sheet!A1> ...]";
    let Some(file) = args.first() else {
        eprintln!("{USAGE_LINE}");
        return ExitCode::from(2);
    };
    let counts = args.iter().any(|a| a == "--counts");
    let functions = args.iter().any(|a| a == "--functions");
    let mut cones: Vec<String> = Vec::new();
    let mut at = 1;
    while at < args.len() {
        if args[at] == "--cone" {
            match args.get(at + 1) {
                Some(root) => cones.push(root.clone()),
                None => {
                    eprintln!("{USAGE_LINE}");
                    return ExitCode::from(2);
                }
            }
            at += 2;
        } else {
            at += 1;
        }
    }
    if !is_file(file) {
        return refuse_missing("vla-file-not-found", file);
    }
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("frazaro: cannot read {file}: {e}");
            return ExitCode::from(2);
        }
    };
    let opened = std::time::Instant::now();
    let package = match frazaro_core::reflect::open(&bytes, file) {
        Ok(p) => p,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let open_ms = ms_since(opened);
    if functions {
        // KERNEL.6's instrument (built with KERNEL.7): the functions the
        // formulas call, each the number of cells calling it, counts alone.
        let mut histogram = frazaro_core::reflect::histogram::Histogram::default();
        for i in 0..package.sheets().len() {
            if let Err(refusal) = package.walk_sheet(i, &mut histogram) {
                eprintln!("{refusal}");
                return ExitCode::from(1);
            }
        }
        print!("{}", histogram.text());
        return ExitCode::SUCCESS;
    }
    if counts {
        let (mut cells, mut formulas, mut arrays, mut unreadable, mut part_bytes) =
            (0u64, 0u64, 0u64, 0u64, 0usize);
        let mut book_distinct: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut read_ms = 0.0f64;
        for i in 0..package.sheets().len() {
            let started = std::time::Instant::now();
            let s = match package.walk_sheet_with(
                i,
                &mut frazaro_core::reflect::Discard,
                &mut book_distinct,
            ) {
                Ok(s) => s,
                Err(refusal) => {
                    eprintln!("{refusal}");
                    return ExitCode::from(1);
                }
            };
            let took = ms_since(started);
            println!(
                "sheet {}: cells {} formulas {} distinct-r1c1 {} unreadable {} arrays {} rows {} columns {} bytes {} read {took:.1} ms",
                i + 1,
                s.cells,
                s.formulas,
                s.distinct_r1c1,
                s.unreadable,
                s.array_anchors,
                s.rows,
                s.columns,
                s.part_bytes
            );
            cells += s.cells;
            formulas += s.formulas;
            arrays += s.array_anchors;
            unreadable += s.unreadable;
            part_bytes += s.part_bytes;
            read_ms += took;
        }
        let summary = package.summary();
        println!(
            "workbook: sheets {} cells {cells} formulas {formulas} distinct-r1c1 {} unreadable {unreadable} arrays {arrays} names {} placeholders {} tables {} books {} strings {} bytes {part_bytes} string-bytes {} open {open_ms:.1} ms read {read_ms:.1} ms",
            package.sheets().len(),
            book_distinct.len(),
            summary.names,
            summary.placeholders,
            summary.tables,
            summary.external_books,
            summary.strings,
            summary.string_bytes
        );
        return ExitCode::SUCCESS;
    }
    if !cones.is_empty() {
        let mut index = frazaro_core::reflect::cone::Index::new(package.as_ref());
        let started = std::time::Instant::now();
        for i in 0..package.sheets().len() {
            if let Err(refusal) = package.walk_sheet(i, &mut index) {
                eprintln!("{refusal}");
                return ExitCode::from(1);
            }
        }
        let indexed_ms = ms_since(started);
        for root in &cones {
            let Some((sheet, row, col)) = frazaro_core::refers::parse_home(root) else {
                eprintln!("frazaro: --cone wants a cell as Sheet!A1 or 'Q1 Data'!A1, not {root}");
                return ExitCode::from(2);
            };
            let wanted = frazaro_core::intrinsics::fold(&sheet);
            let Some(s) = package
                .sheets()
                .iter()
                .position(|info| frazaro_core::intrinsics::fold(&info.name) == wanted)
            else {
                eprintln!("frazaro: --cone {root}: the workbook has no sheet so named");
                return ExitCode::from(2);
            };
            let started = std::time::Instant::now();
            let stats = frazaro_core::reflect::cone::cone(&index, package.as_ref(), s, row, col);
            println!(
                "cone {root}: {} indexed {indexed_ms:.1} ms walked {:.1} ms",
                stats.line(),
                ms_since(started)
            );
        }
        return ExitCode::SUCCESS;
    }
    use std::io::Write;
    struct Lines<W: Write>(W);
    impl<W: Write> frazaro_core::reflect::Sink for Lines<W> {
        fn row(&mut self, row: &frazaro_core::reflect::Row<'_>) {
            let _ = writeln!(self.0, "{}", frazaro_core::reflect::print::line(row));
        }
    }
    let mut out = Lines(std::io::BufWriter::new(std::io::stdout().lock()));
    package.header_rows(&mut out);
    for i in 0..package.sheets().len() {
        if let Err(refusal) = package.walk_sheet(i, &mut out) {
            let _ = out.0.flush();
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    }
    if out.0.flush().is_err() {
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

/// `frazaro diff <old.xlsx> <new.xlsx> [--counts]` (PORT.8, slice 8c): both
/// files opened as `reflect` opens them, the difference streamed one row a
/// line in the fixed order, or with `--counts` one line of counts and times.
/// Exit 0 whenever the comparison ran, rows or none; a refusal exits 1 and
/// the rows before it stand; a usage error or an unreadable file exits 2.
fn diff(args: &[String]) -> ExitCode {
    const USAGE_LINE: &str = "usage: frazaro diff <old.xlsx|.ods> <new.xlsx|.ods> [--counts]";
    let mut files: Vec<&str> = Vec::new();
    let mut counts = false;
    for a in args {
        if a == "--counts" {
            counts = true;
        } else if a.starts_with("--") || files.len() == 2 {
            eprintln!("{USAGE_LINE}");
            return ExitCode::from(2);
        } else {
            files.push(a);
        }
    }
    if files.len() != 2 {
        eprintln!("{USAGE_LINE}");
        return ExitCode::from(2);
    }
    let mut bytes: Vec<Vec<u8>> = Vec::new();
    for file in &files {
        if !is_file(file) {
            return refuse_missing("vla-file-not-found", file);
        }
        match std::fs::read(file) {
            Ok(b) => bytes.push(b),
            Err(e) => {
                eprintln!("frazaro: cannot read {file}: {e}");
                return ExitCode::from(2);
            }
        }
    }
    let opened = std::time::Instant::now();
    let mut packages = Vec::new();
    for (i, file) in files.iter().enumerate() {
        match frazaro_core::reflect::open(&bytes[i], file) {
            Ok(p) => packages.push(p),
            Err(refusal) => {
                eprintln!("{refusal}");
                return ExitCode::from(1);
            }
        }
    }
    let open_ms = ms_since(opened);
    let (old, new) = (packages[0].as_ref(), packages[1].as_ref());
    use frazaro_core::reflect::diff::{self as d, ChangeSink};
    if counts {
        let started = std::time::Instant::now();
        return match d::diff(old, new, &mut d::Discard) {
            Ok(stats) => {
                println!(
                    "diff: {} open {open_ms:.1} ms compared {:.1} ms",
                    stats.line(),
                    ms_since(started)
                );
                ExitCode::SUCCESS
            }
            Err(refusal) => {
                eprintln!("{refusal}");
                ExitCode::from(1)
            }
        };
    }
    use std::io::Write;
    struct Changes<W: Write>(W);
    impl<W: Write> ChangeSink for Changes<W> {
        fn change(&mut self, change: &d::Change<'_>) {
            let _ = writeln!(self.0, "{}", d::line(change));
        }
    }
    let mut out = Changes(std::io::BufWriter::new(std::io::stdout().lock()));
    if let Err(refusal) = d::diff(old, new, &mut out) {
        let _ = out.0.flush();
        eprintln!("{refusal}");
        return ExitCode::from(1);
    }
    if out.0.flush().is_err() {
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

/// `frazaro audit <file.xlsx> [--counts]` (PORT.8, slice 8d): the file read
/// as `reflect` reads it into the audit's index, then the six walks, one
/// finding a line in the fixed order, or with `--counts` one line of counts
/// and times. Exit 0 whenever the walks ran, findings or none; a refusal
/// exits 1; a usage error or an unreadable file exits 2.
fn audit(args: &[String]) -> ExitCode {
    const USAGE_LINE: &str = "usage: frazaro audit <file.xlsx|.ods> [--counts]";
    let mut file: Option<&str> = None;
    let mut counts = false;
    for a in args {
        if a == "--counts" {
            counts = true;
        } else if a.starts_with("--") || file.is_some() {
            eprintln!("{USAGE_LINE}");
            return ExitCode::from(2);
        } else {
            file = Some(a);
        }
    }
    let Some(file) = file else {
        eprintln!("{USAGE_LINE}");
        return ExitCode::from(2);
    };
    if !is_file(file) {
        return refuse_missing("vla-file-not-found", file);
    }
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("frazaro: cannot read {file}: {e}");
            return ExitCode::from(2);
        }
    };
    let opened = std::time::Instant::now();
    let package = match frazaro_core::reflect::open(&bytes, file) {
        Ok(p) => p,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let open_ms = ms_since(opened);
    use frazaro_core::reflect::audit::{self as au, FindingSink};
    let started = std::time::Instant::now();
    let mut index = au::AuditIndex::new(package.as_ref());
    for i in 0..package.sheets().len() {
        if let Err(refusal) = package.walk_sheet(i, &mut index) {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    }
    let indexed_ms = ms_since(started);
    if counts {
        let started = std::time::Instant::now();
        let stats = au::audit(&index, package.as_ref(), &mut au::Discard);
        println!(
            "audit: {} open {open_ms:.1} ms indexed {indexed_ms:.1} ms walked {:.1} ms",
            stats.line(),
            ms_since(started)
        );
        return ExitCode::SUCCESS;
    }
    use std::io::Write;
    struct Findings<W: Write>(W);
    impl<W: Write> FindingSink for Findings<W> {
        fn finding(&mut self, finding: &au::Finding<'_>) {
            let _ = writeln!(self.0, "{}", au::line(finding));
        }
    }
    let mut out = Findings(std::io::BufWriter::new(std::io::stdout().lock()));
    au::audit(&index, package.as_ref(), &mut out);
    if out.0.flush().is_err() {
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

/// `frazaro calc <file.xlsx|.ods> [--counts | --shapes]` (KERNEL.7): the
/// file read as `reflect` reads it into the grid, every formula computed by
/// the language's evaluator under Excel's library (`frazaro_core::excel`),
/// and one `calc` row per formula cell in the fixed order, the computed
/// value against the host's cached one with the verdict, every cycle named
/// first; with `--counts`, one line of counts and times; with `--shapes`,
/// nothing computed and the grid's census printed, the plan an engine's
/// machine makes of it (KERNEL.30). Exit 0 whenever the calculation or the
/// plan ran, agree or differ; a refusal exits 1; a usage error, the two
/// flags together among them, or an unreadable file exits 2.
fn calc(args: &[String]) -> ExitCode {
    const USAGE_LINE: &str = "usage: frazaro calc <file.xlsx|.ods> [--counts | --shapes]";
    let mut file: Option<&str> = None;
    let mut counts = false;
    let mut shapes = false;
    for a in args {
        if a == "--counts" {
            counts = true;
        } else if a == "--shapes" {
            shapes = true;
        } else if a.starts_with("--") || file.is_some() {
            eprintln!("{USAGE_LINE}");
            return ExitCode::from(2);
        } else {
            file = Some(a);
        }
    }
    let Some(file) = file.filter(|_| !(counts && shapes)) else {
        eprintln!("{USAGE_LINE}");
        return ExitCode::from(2);
    };
    if !is_file(file) {
        return refuse_missing("vla-file-not-found", file);
    }
    let bytes = match std::fs::read(file) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("frazaro: cannot read {file}: {e}");
            return ExitCode::from(2);
        }
    };
    let opened = std::time::Instant::now();
    let collected = match frazaro_core::reflect::calc::collect(&bytes, file) {
        Ok(c) => c,
        Err(refusal) => {
            eprintln!("{refusal}");
            return ExitCode::from(1);
        }
    };
    let read_ms = ms_since(opened);
    let library = frazaro_core::excel::library();
    if shapes {
        print!(
            "{}",
            frazaro_core::reflect::calc::census_of(&collected, &library)
        );
        return ExitCode::SUCCESS;
    }
    let started = std::time::Instant::now();
    let (rows, tally) = frazaro_core::reflect::calc::rows_of(&collected, &library);
    if counts {
        println!(
            "calc: {} read {read_ms:.1} ms calc {:.1} ms",
            tally.line(),
            ms_since(started)
        );
        return ExitCode::SUCCESS;
    }
    print!("{rows}");
    ExitCode::SUCCESS
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.first().map(String::as_str) {
        Some("compile") => compile(&args[1..]),
        Some("load") => load(&args[1..]),
        Some("prove") => prove(&args[1..]),
        Some("translate-vla") => translate("translate-vla", &args[1..]),
        Some("translate-vba") => translate("translate-vba", &args[1..]),
        Some("build") => build(&args[1..]),
        Some("rebuild") => rebuild(&args[1..]),
        Some("reflect") => reflect(&args[1..]),
        Some("diff") => diff(&args[1..]),
        Some("audit") => audit(&args[1..]),
        Some("view") => view(&args[1..]),
        Some("calc") => calc(&args[1..]),
        Some("version") | Some("--version") | Some("-V") => {
            let core = frazaro_core::version();
            let abi = frazaro_core::frazaro_abi_version();
            println!("frazaro {core} (core abi {abi})");
            ExitCode::SUCCESS
        }
        None | Some("help") | Some("--help") | Some("-h") => {
            print!("{USAGE}");
            ExitCode::SUCCESS
        }
        Some(other) => {
            eprintln!(
                "frazaro: '{other}' is not a command in this version; \
                 'frazaro help' lists the commands."
            );
            ExitCode::from(2)
        }
    }
}