frazaro-core 0.9.2

The Frazaro language, host-free: sentences in, spreadsheets out
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
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
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
//! The build (PORT.7): a program's sentences to a workbook's bytes, through
//! the sheet model and the OOXML writer.
//!
//! Slice 7a writes the room's first sheet, `Frazaro`: the program's lines in
//! column B from row 1 exactly as written, blank lines included, and OK in
//! green in column C beside every line that holds text, which is what the
//! add-in's Check marks (`DoCheck`, VLA_IDE.bas: once the program
//! translates, a row whose column B is not blank is marked OK). The widths,
//! the fills, the hidden column A and the gridlines are `BuildWorkspace`'s
//! (VLA_IDE.bas), so the room looks the same through this door.
//!
//! Slice 7b walks the program's VLA, read and macro-expanded exactly as
//! `VlaTranspile` reads it (the prelude first, every `defmacro` defined, every
//! other form expanded to its fixpoint), and writes what a sheet can hold
//! with nothing running: a value or a formula string into a cell, a range,
//! rows of a column or a cell of a named sheet; `Work on sheet` and `Go to
//! sheet`; a `Define`d constant or a variable set to a value that folds; a
//! parameterless step, inlined where it is called; an `If` whose condition
//! folds over literals, so that `set-formula-rows`' guard works. Everything
//! else is refused by name with the sentence quoted (`build-not-representable`),
//! and a sheet named before anything made it is refused too
//! (`build-sheet-unknown`). The scaffold `EnglishToVla` writes around a
//! program (`on-error goto vla-fail`, the `vla-step` counter, the trace
//! guards, `exit-sub`, the fail label) is recognised and stepped over.
//!
//! A formula into more than one cell is written as Excel writes a filled
//! formula, a shared formula, so the host adjusts the references for each
//! cell as `Range.Formula2` would have; a newer function takes its file
//! prefix (`sheet::xlfn`). New ground, said plainly: the reference runs the
//! program in Excel, and Excel does all of this.
//!
//! The build is a pure function of its texts: the same sentences and the
//! same core give the same bytes on every machine, which the build golden
//! (`scripts/build/fixture_golden.xlsx`, the treaty's amendment of
//! 2026-10-03) holds it to.

use std::collections::HashMap;

use crate::expand::Expander;
use crate::form::{Form, List};
use crate::intrinsics::{fold, is_numeric, val};
use crate::messages::{raise, Refusal};
use crate::reader::{count_lf, parse_all, tokenize};
use crate::sha256::sha256_hex_skipping_whitespace;
use crate::sheet::merge::{self, HostInfo, Model};
use crate::sheet::xlfn::{can_return_array, prefix_future_functions};
use crate::sheet::{
    ooxml, parse_a1_range, xml, zip, A1Range, Cell, Column, Content, NumFmt, Rgb, Sheet, Style,
    Styles, Workbook,
};

/// The defined name that carries the build stamp.
pub const STAMP_NAME: &str = "Frazaro.Build";

/// The sheet that holds the program, named as the add-in names its
/// workspace (`IDE_SHEET`).
pub const FRAZARO_SHEET: &str = "Frazaro";
/// The sheet a program's results go to unless it says `Work on sheet`
/// (`OUT_SHEET`).
pub const OUTPUT_SHEET: &str = "Output";
/// `BuildWorkspace`'s whisper of the logo's lavender on the sentence column.
pub const LAVENDER: Rgb = Rgb(247, 244, 252);
/// The result column's gray, under the marks.
pub const RESULT_GRAY: Rgb = Rgb(242, 242, 242);
/// `MarkOK`'s green.
pub const OK_GREEN: Rgb = Rgb(221, 235, 221);
/// `BuildWorkspace`'s column widths, in characters.
pub const SENTENCE_COLUMN_WIDTH: f64 = 72.0;
pub const RESULT_COLUMN_WIDTH: f64 = 60.0;
/// The most cells one sentence may fill: one whole column's worth.
pub const MAX_CELLS_PER_WRITE: u64 = 1_048_576;
/// How deep steps may call steps before the build calls it a loop.
const MAX_INLINE_DEPTH: u32 = 32;

/// The `Frazaro` sheet of a program whose text translated: each line of the
/// text in column B of its own row, and OK in column C beside a line that
/// is not blank. Blank is `Len(Trim$(...)) = 0`, and VBA's `Trim$` trims
/// spaces only, so a line of tabs is marked and a line of spaces is not.
pub fn frazaro_sheet(program_text: &str, styles: &mut Styles) -> Sheet {
    let sentence = styles.id(Style {
        fill: Some(LAVENDER),
        num_fmt: NumFmt::Text,
        wrap: false,
    });
    let result = styles.id(Style {
        fill: Some(RESULT_GRAY),
        num_fmt: NumFmt::General,
        wrap: true,
    });
    let ok = styles.id(Style {
        fill: Some(OK_GREEN),
        num_fmt: NumFmt::General,
        wrap: true,
    });
    let mut sheet = Sheet::new(FRAZARO_SHEET);
    sheet.gridlines = false;
    sheet.active_cell = (1, 2);
    sheet.columns = vec![
        Column {
            index: 1,
            width: None,
            hidden: true,
            style: None,
        },
        Column {
            index: 2,
            width: Some(SENTENCE_COLUMN_WIDTH),
            hidden: false,
            style: Some(sentence),
        },
        Column {
            index: 3,
            width: Some(RESULT_COLUMN_WIDTH),
            hidden: false,
            style: Some(result),
        },
    ];
    for (i, line) in program_text.lines().enumerate() {
        let row = i as u32 + 1;
        if line.is_empty() {
            continue;
        }
        sheet.set(
            row,
            2,
            Cell {
                content: Content::Text(line.to_string()),
                style: sentence,
            },
        );
        // The sentence's own row wrote its cell, and the mark beside it.
        sheet.sentences.insert((row, 2), row);
        if !line.trim_matches(' ').is_empty() {
            sheet.set(
                row,
                3,
                Cell {
                    content: Content::Text("OK".to_string()),
                    style: ok,
                },
            );
            sheet.sentences.insert((row, 3), row);
        }
    }
    sheet
}

/// A value the build can put in a cell, or fold a condition from.
#[derive(Clone, Debug, PartialEq)]
enum Value {
    Num(f64),
    Text(String),
    Bool(bool),
}

/// VBA's `CStr` of a value, as `&` spells its operands: an integral number
/// without a decimal point, anything else as Rust spells it (close enough
/// for the cell addresses a program builds).
fn cstr(v: &Value) -> String {
    match v {
        Value::Num(n) => {
            if n.fract() == 0.0 && n.abs() < 1e15 {
                format!("{}", *n as i64)
            } else {
                format!("{n}")
            }
        }
        Value::Text(t) => t.clone(),
        Value::Bool(b) => (if *b { "True" } else { "False" }).to_string(),
    }
}

/// Why Excel would refuse a sheet name, or `None` for a name it takes: the
/// rules `VlaCheckSheetName` (VLA_Runtime.bas) holds a program to at run
/// time, with the runtime's own words; here the build's.
fn sheet_name_problem(name: &str) -> Option<String> {
    if name.is_empty() {
        return Some("it is empty".to_string());
    }
    let n = name.chars().count();
    if n > 31 {
        return Some(format!("it is {n} characters long"));
    }
    // The first offending character in the runtime's own order, as its
    // message names it.
    if let Some(c) = ":\\/?*[]".chars().find(|c| name.contains(*c)) {
        return Some(format!("it contains {c}"));
    }
    if name.starts_with('\'') || name.ends_with('\'') {
        return Some("it begins or ends with an apostrophe".to_string());
    }
    if fold(name) == "history" {
        return Some("History is a name Excel keeps for itself".to_string());
    }
    None
}

/// What the build keeps of a program's procedure: how many parameters it
/// takes, and its body.
#[derive(Clone)]
struct Step {
    params: usize,
    body: Vec<Form>,
}

/// Whether a statement let the walk go on, or ended the procedure.
enum Flow {
    Next,
    Exit,
}

/// Where `(range ...)` writes: a sheet of this build's, or one of the host
/// workbook's, which a program may go to but never write into.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Target {
    Ours(usize),
    Host(String),
}

struct Walker<'a> {
    lines: Vec<&'a str>,
    wb: Workbook,
    /// The host workbook's own sheets, when the build adds to one.
    host_sheets: Vec<String>,
    /// The sheet a `(range ...)` means: `None` until something writes, then
    /// `Output` unless `Work on sheet` chose another.
    current: Option<Target>,
    /// Constants and variables whose values fold, by folded name.
    bindings: HashMap<String, Value>,
    /// The program's procedures, by folded name.
    steps: HashMap<String, Step>,
    /// The program line the walk is on, from the nearest `(at-line N ...)`.
    line: u32,
    depth: u32,
}

impl<'a> Walker<'a> {
    fn new(program_text: &'a str, host_sheets: Vec<String>) -> Walker<'a> {
        Walker {
            lines: program_text.lines().collect(),
            wb: Workbook::new(),
            host_sheets,
            current: None,
            bindings: HashMap::new(),
            steps: HashMap::new(),
            line: 0,
            depth: 0,
        }
    }

    /// The sentence the walk is on, quoted in a refusal.
    fn sentence(&self) -> String {
        if self.line == 0 {
            return "the program's own setup".to_string();
        }
        match self.lines.get(self.line as usize - 1).map(|s| s.trim()) {
            Some(s) if !s.is_empty() => s.to_string(),
            _ => format!("the sentence on line {}", self.line),
        }
    }

    fn refuse_sentence(&self) -> Refusal {
        raise(
            "build-not-representable",
            &[
                ("line", &self.line.to_string()),
                ("sentence", &self.sentence()),
            ],
        )
    }

    fn refuse_sheet(&self, name: &str) -> Refusal {
        raise(
            "build-sheet-unknown",
            &[("line", &self.line.to_string()), ("name", name)],
        )
    }

    /// A top-level form: a constant is bound, a procedure kept, an include
    /// refused as the compiler refuses it (no file system here either), and
    /// the declarations the compiled module needs are nothing to a sheet.
    fn collect_top(&mut self, f: &Form) -> Result<(), Refusal> {
        let Form::List(l) = f else { return Ok(()) };
        let Ok(head) = l.head_sym() else {
            return Ok(());
        };
        match fold(&head).as_str() {
            "const" => {
                if l.count() >= 3 {
                    if let Some(name) = l.items[1].atom_text() {
                        if let Some(v) = self.fold_expr(&l.items[2]) {
                            self.bindings.insert(fold(&name), v);
                        }
                    }
                }
            }
            "sub" => {
                if l.count() >= 3 {
                    if let (Some(name), Form::List(params)) = (l.items[1].atom_text(), &l.items[2])
                    {
                        let mut body: &[Form] = &l.items[3..];
                        if let Some(Form::Str(_)) = body.first() {
                            body = &body[1..]; // a docstring
                        }
                        self.steps.insert(
                            fold(&name),
                            Step {
                                params: params.count(),
                                body: body.to_vec(),
                            },
                        );
                    }
                }
            }
            "include" => {
                let name = l
                    .items
                    .get(1)
                    .and_then(|f| f.atom_text())
                    .unwrap_or_default();
                return Err(raise(
                    "vla-include-cannot-read",
                    &[("name", &name), ("path", &name)],
                ));
            }
            _ => {}
        }
        Ok(())
    }

    fn walk_main(&mut self) -> Result<(), Refusal> {
        let Some(main) = self.steps.get("main").cloned() else {
            return Ok(()); // a program with no statements builds its sheet alone
        };
        self.walk_body(&main.body)?;
        Ok(())
    }

    fn walk_body(&mut self, body: &[Form]) -> Result<Flow, Refusal> {
        for f in body {
            if let Flow::Exit = self.walk_stmt(f)? {
                return Ok(Flow::Exit);
            }
        }
        Ok(Flow::Next)
    }

    fn walk_stmt(&mut self, f: &Form) -> Result<Flow, Refusal> {
        let Form::List(l) = f else {
            return Err(self.refuse_sentence());
        };
        let head = match l.head_sym() {
            Ok(h) => fold(&h),
            Err(_) => return Err(self.refuse_sentence()),
        };
        match head.as_str() {
            "at-line" => {
                if let Some(n) = l.items.get(1).and_then(|f| f.atom_text()) {
                    self.line = val(&n) as u32;
                }
                self.walk_body(&l.items[2.min(l.items.len())..])
            }
            "begin" => self.walk_body(&l.items[1..]),
            // Locals, and the scaffold's own report call.
            "dim" | "vla-report-error" => Ok(Flow::Next),
            // The scaffold's error handler; a `Try:` block's handlers are not it.
            "on-error" => {
                let target = l
                    .items
                    .last()
                    .and_then(|f| f.atom_text())
                    .unwrap_or_default();
                if fold(&target) == "vla-fail" || target == "0" {
                    Ok(Flow::Next)
                } else {
                    Err(self.refuse_sentence())
                }
            }
            "label" => {
                let name = l
                    .items
                    .get(1)
                    .and_then(|f| f.atom_text())
                    .unwrap_or_default();
                if fold(&name) == "vla-fail" {
                    Ok(Flow::Exit)
                } else {
                    Err(self.refuse_sentence())
                }
            }
            "exit-sub" | "exit-function" => Ok(Flow::Exit),
            "set!" => self.walk_set(l),
            "if" => self.walk_if(l),
            "vlaensuresheet" => {
                let name = self.fold_text(l.items.get(1))?;
                if self.host_sheet(&name).is_some() {
                    return Ok(Flow::Next); // the host has it; nothing to make
                }
                if let Some(reason) = sheet_name_problem(&name) {
                    return Err(raise(
                        "build-sheet-name-invalid",
                        &[
                            ("line", &self.line.to_string()),
                            ("name", &name),
                            ("reason", &reason),
                        ],
                    ));
                }
                self.wb.ensure_sheet(&name);
                Ok(Flow::Next)
            }
            "." => self.walk_dot(l),
            _ => self.walk_call(l, &head),
        }
    }

    /// `(set! place value)`: a variable bound, a cell or range written, a
    /// formula written, a cell of a named sheet written.
    fn walk_set(&mut self, l: &List) -> Result<Flow, Refusal> {
        if l.count() != 3 {
            return Err(self.refuse_sentence());
        }
        let place = &l.items[1];
        let value = &l.items[2];
        match place {
            Form::Sym(name) => {
                let v = self
                    .fold_expr(value)
                    .ok_or_else(|| self.refuse_sentence())?;
                self.bindings.insert(fold(name), v);
                Ok(Flow::Next)
            }
            Form::Str(_) => Err(self.refuse_sentence()),
            Form::List(pl) => {
                let phead = pl.head_sym().map(|h| fold(&h)).unwrap_or_default();
                if phead == "range" && pl.count() == 2 {
                    let range = self.range_of(&pl.items[1])?;
                    let v = self
                        .fold_expr(value)
                        .ok_or_else(|| self.refuse_sentence())?;
                    let sheet = self.writable_current()?;
                    self.write_value(sheet, range, &v)?;
                    return Ok(Flow::Next);
                }
                if phead != "." || pl.count() < 3 {
                    return Err(self.refuse_sentence());
                }
                let obj = &pl.items[1];
                let member = fold(&pl.items[2].atom_text().unwrap_or_default());
                // (. (range R) formula) and (. (range R) value)
                if let (Some(rl), true) = (obj.as_list(), obj.head_is("range")) {
                    if pl.count() == 3
                        && rl.count() == 2
                        && matches!(member.as_str(), "formula" | "formula2" | "value")
                    {
                        let range = self.range_of(&rl.items[1])?;
                        let v = self
                            .fold_expr(value)
                            .ok_or_else(|| self.refuse_sentence())?;
                        let sheet = self.writable_current()?;
                        if member == "value" {
                            self.write_value(sheet, range, &v)?;
                        } else {
                            self.write_formula(sheet, range, &v)?;
                        }
                        return Ok(Flow::Next);
                    }
                }
                // (. (worksheets S) range R): put-into-cell-of-sheet
                if let (Some(wl), true) = (obj.as_list(), obj.head_is("worksheets")) {
                    if pl.count() == 4 && wl.count() == 2 && member == "range" {
                        let name = self.fold_text(wl.items.get(1))?;
                        let sheet = self.writable_named(&name)?;
                        let range = self.range_of(&pl.items[3])?;
                        let v = self
                            .fold_expr(value)
                            .ok_or_else(|| self.refuse_sentence())?;
                        self.write_value(sheet, range, &v)?;
                        return Ok(Flow::Next);
                    }
                }
                Err(self.refuse_sentence())
            }
        }
    }

    /// `(if cond (then ...) [(else ...)])`: the trace guard is skipped (no
    /// trace runs in a build); another condition must fold.
    fn walk_if(&mut self, l: &List) -> Result<Flow, Refusal> {
        let Some(cond) = l.items.get(1) else {
            return Err(self.refuse_sentence());
        };
        if cond.head_is("vlatraceon") {
            return Ok(Flow::Next);
        }
        let truth = match self.fold_expr(cond) {
            Some(Value::Bool(b)) => b,
            Some(Value::Num(n)) => n != 0.0,
            _ => return Err(self.refuse_sentence()),
        };
        for branch in &l.items[2..] {
            if let Form::List(bl) = branch {
                let taken = (truth && bl.head_is("then")) || (!truth && bl.head_is("else"));
                if taken {
                    return self.walk_body(&bl.items[1..]);
                }
            }
        }
        Ok(Flow::Next)
    }

    /// `(. (worksheets S) activate)`: `Go to sheet`, and the second half of
    /// `Work on sheet`.
    fn walk_dot(&mut self, l: &List) -> Result<Flow, Refusal> {
        let obj = &l.items[1];
        let member = fold(
            &l.items
                .get(2)
                .and_then(|f| f.atom_text())
                .unwrap_or_default(),
        );
        if let (Some(wl), true) = (obj.as_list(), obj.head_is("worksheets")) {
            if l.count() == 3 && wl.count() == 2 && member == "activate" {
                let name = self.fold_text(wl.items.get(1))?;
                let target = self.target_named(&name)?;
                self.current = Some(target);
                return Ok(Flow::Next);
            }
        }
        Err(self.refuse_sentence())
    }

    /// A call of one of the program's own steps, with no values passed:
    /// its body inlined here. Anything else a sentence calls needs a host.
    fn walk_call(&mut self, l: &List, head: &str) -> Result<Flow, Refusal> {
        let Some(step) = self.steps.get(head).cloned() else {
            return Err(self.refuse_sentence());
        };
        if step.params != 0 || l.count() != 1 || self.depth >= MAX_INLINE_DEPTH {
            return Err(self.refuse_sentence());
        }
        self.depth += 1;
        let saved = self.line;
        let flow = self.walk_body(&step.body);
        self.depth -= 1;
        self.line = saved;
        flow?; // a step's own Exit Sub ends the step, not its caller
        Ok(Flow::Next)
    }

    fn fold_text(&self, f: Option<&Form>) -> Result<String, Refusal> {
        match f.and_then(|f| self.fold_expr(f)) {
            Some(Value::Text(t)) => Ok(t),
            _ => Err(self.refuse_sentence()),
        }
    }

    fn range_of(&self, f: &Form) -> Result<A1Range, Refusal> {
        let text = self.fold_text(Some(f))?;
        parse_a1_range(&text).ok_or_else(|| self.refuse_sentence())
    }

    /// The host workbook's sheet of that name, as the host spells it.
    fn host_sheet(&self, name: &str) -> Option<String> {
        let want = fold(name);
        self.host_sheets.iter().find(|s| fold(s) == want).cloned()
    }

    /// Where `(range ...)` writes: `Output` made on first use, unless the
    /// host workbook has an `Output` of its own.
    fn current_target(&mut self) -> Target {
        if let Some(t) = &self.current {
            return t.clone();
        }
        let t = match self.host_sheet(OUTPUT_SHEET) {
            Some(h) => Target::Host(h),
            None => Target::Ours(self.wb.ensure_sheet(OUTPUT_SHEET)),
        };
        self.current = Some(t.clone());
        t
    }

    /// A sheet named by the program: one it made, one of the host's, or
    /// `Output`, which the add-in has at the start of every run.
    fn target_named(&mut self, name: &str) -> Result<Target, Refusal> {
        if let Some(i) = self.wb.find_sheet(name) {
            return Ok(Target::Ours(i));
        }
        if let Some(h) = self.host_sheet(name) {
            return Ok(Target::Host(h));
        }
        if fold(name) == fold(OUTPUT_SHEET) {
            return Ok(Target::Ours(self.wb.ensure_sheet(OUTPUT_SHEET)));
        }
        Err(self.refuse_sheet(name))
    }

    /// A target a sentence may write to: one of this build's sheets. One
    /// of the host's is refused by name, since the build leaves the host's
    /// own sheets as they are.
    fn writable(&self, t: Target) -> Result<usize, Refusal> {
        match t {
            Target::Ours(i) => Ok(i),
            Target::Host(name) => Err(raise(
                "build-into-model-sheet",
                &[("line", &self.line.to_string()), ("name", &name)],
            )),
        }
    }

    fn writable_current(&mut self) -> Result<usize, Refusal> {
        let t = self.current_target();
        self.writable(t)
    }

    fn writable_named(&mut self, name: &str) -> Result<usize, Refusal> {
        let t = self.target_named(name)?;
        self.writable(t)
    }

    fn write_value(&mut self, sheet: usize, range: A1Range, v: &Value) -> Result<(), Refusal> {
        if range.cells() > MAX_CELLS_PER_WRITE {
            return Err(self.refuse_sentence());
        }
        let content = match v {
            Value::Num(n) => Content::Number(*n),
            Value::Text(t) => Content::Text(t.clone()),
            Value::Bool(b) => Content::Bool(*b),
        };
        let sh = &mut self.wb.sheets[sheet];
        for row in range.top..=range.bottom {
            for col in range.left..=range.right {
                sh.set(
                    row,
                    col,
                    Cell {
                        content: content.clone(),
                        style: 0,
                    },
                );
            }
        }
        sh.wrote(range, self.line);
        Ok(())
    }

    /// `Range.Formula2 = text`: a text beginning with `=` is a formula, with
    /// newer functions under their file prefix; anything else is the value
    /// itself, as Excel stores it. SEC.15: the text is scanned first, as the
    /// add-in's `VlaSetFormula` scans it, and a formula that reaches outside
    /// the workbook on its own is refused by name with the sentence quoted
    /// (`build-formula-egress`), nothing written.
    fn write_formula(&mut self, sheet: usize, range: A1Range, v: &Value) -> Result<(), Refusal> {
        if range.cells() > MAX_CELLS_PER_WRITE {
            return Err(self.refuse_sentence());
        }
        if let Value::Text(t) = v {
            if let Some(name) = crate::egress::egress_call(t) {
                return Err(raise(
                    "build-formula-egress",
                    &[
                        ("line", &self.line.to_string()),
                        ("name", &name),
                        ("sentence", &self.sentence()),
                    ],
                ));
            }
            if let Some(body) = t.strip_prefix('=') {
                let text = prefix_future_functions(body);
                if can_return_array(&text) {
                    // What Excel stores for a Formula2 entry of such a formula,
                    // and reads back without its @.
                    self.wb.sheets[sheet].set_formula_dynamic(range, &text, 0);
                } else {
                    self.wb.sheets[sheet].set_formula(range, &text, 0);
                }
                self.wb.sheets[sheet].wrote(range, self.line);
                return Ok(());
            }
        }
        self.write_value(sheet, range, v)
    }

    /// A value from literals, constants, variables set to literals, and the
    /// operators over them; `None` for anything that needs a host.
    fn fold_expr(&self, f: &Form) -> Option<Value> {
        match f {
            Form::Str(s) => Some(Value::Text(s.clone())),
            Form::Sym(s) => {
                if is_numeric(s) {
                    return Some(Value::Num(val(s)));
                }
                let key = fold(s);
                match key.as_str() {
                    "true" => Some(Value::Bool(true)),
                    "false" => Some(Value::Bool(false)),
                    _ => self.bindings.get(&key).cloned(),
                }
            }
            Form::List(l) => {
                let head = fold(&l.head_sym().ok()?);
                let args: Vec<Value> = l.items[1..]
                    .iter()
                    .map(|a| self.fold_expr(a))
                    .collect::<Option<Vec<Value>>>()?;
                fold_op(&head, &args)
            }
        }
    }
}

fn nums(args: &[Value]) -> Option<Vec<f64>> {
    args.iter()
        .map(|v| match v {
            Value::Num(n) => Some(*n),
            _ => None,
        })
        .collect()
}

fn bools(args: &[Value]) -> Option<Vec<bool>> {
    args.iter()
        .map(|v| match v {
            Value::Bool(b) => Some(*b),
            _ => None,
        })
        .collect()
}

/// The operators the build folds: arithmetic and comparison over numbers,
/// `&` over anything, comparison over texts, `not`/`and`/`or` over truths.
fn fold_op(head: &str, args: &[Value]) -> Option<Value> {
    match head {
        "&" => Some(Value::Text(
            args.iter().map(cstr).collect::<Vec<_>>().join(""),
        )),
        "+" | "*" | "/" | "-" => {
            let n = nums(args)?;
            if n.is_empty() {
                return None;
            }
            if head == "-" && n.len() == 1 {
                return Some(Value::Num(-n[0]));
            }
            let mut acc = n[0];
            for x in &n[1..] {
                acc = match head {
                    "+" => acc + x,
                    "*" => acc * x,
                    "-" => acc - x,
                    _ => {
                        if *x == 0.0 {
                            return None;
                        }
                        acc / x
                    }
                };
            }
            Some(Value::Num(acc))
        }
        "=" | "<>" | "<" | ">" | "<=" | ">=" => {
            if args.len() != 2 {
                return None;
            }
            let ord = match (&args[0], &args[1]) {
                (Value::Num(a), Value::Num(b)) => a.partial_cmp(b)?,
                (Value::Text(a), Value::Text(b)) => a.cmp(b),
                (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
                _ => return None,
            };
            Some(Value::Bool(match head {
                "=" => ord.is_eq(),
                "<>" => ord.is_ne(),
                "<" => ord.is_lt(),
                ">" => ord.is_gt(),
                "<=" => ord.is_le(),
                _ => ord.is_ge(),
            }))
        }
        "not" => {
            let b = bools(args)?;
            (b.len() == 1).then(|| Value::Bool(!b[0]))
        }
        "and" => Some(Value::Bool(bools(args)?.iter().all(|b| *b))),
        "or" => Some(Value::Bool(bools(args)?.iter().any(|b| *b))),
        _ => None,
    }
}

/// One source's identity in the stamp: `EnglishSourceHash`'s digest of its
/// non-whitespace bytes, and how many there were.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceHash {
    pub hex: String,
    pub count: usize,
}

impl SourceHash {
    pub fn of(text: &str) -> SourceHash {
        let (hex, count) = sha256_hex_skipping_whitespace(text.as_bytes());
        SourceHash { hex, count }
    }

    fn text(&self) -> String {
        format!(
            "sha256:{} over {} non-whitespace bytes",
            self.hex, self.count
        )
    }

    fn parse(s: &str) -> Option<SourceHash> {
        let rest = s.strip_prefix("sha256:")?;
        let (hex, tail) = rest.split_once(" over ")?;
        let count = tail.strip_suffix(" non-whitespace bytes")?.parse().ok()?;
        if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
        Some(SourceHash {
            hex: hex.to_string(),
            count,
        })
    }
}

/// What the stamp records of the workbook a build was added to
/// (`--into`): enough for `rebuild` to render the build's sheets again
/// exactly, without the model at hand.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IntoStamp {
    /// The SHA-256 of the model's bytes.
    pub model_hex: String,
    /// How many cell formats the model had: where this build's begin.
    pub style_base: u32,
    /// The cell-metadata index the build's dynamic-array formulas point
    /// at; 0 when none was needed.
    pub cm: u32,
}

/// The build stamp: the core's version, the workbook added to when there
/// was one, and the identity of the sentences, the prelude and each
/// phrasebook in order, as the defined name `Frazaro.Build` carries it in
/// one string.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stamp {
    pub version: String,
    pub into: Option<IntoStamp>,
    pub sentences: SourceHash,
    pub prelude: SourceHash,
    pub phrasebooks: Vec<SourceHash>,
}

impl Stamp {
    pub fn of(program_text: &str, prelude: &str, books: &[&str], into: Option<IntoStamp>) -> Stamp {
        Stamp {
            version: crate::VERSION.to_string(),
            into,
            sentences: SourceHash::of(program_text),
            prelude: SourceHash::of(prelude),
            phrasebooks: books.iter().map(|b| SourceHash::of(b)).collect(),
        }
    }

    /// `Frazaro 0.7.1; [into sha256:... with N cell formats and metadata
    /// M; ]sentences sha256:... over N non-whitespace bytes; prelude ...;
    /// phrasebook 1 ...`.
    pub fn text(&self) -> String {
        let mut s = format!("Frazaro {}", self.version);
        if let Some(into) = &self.into {
            s.push_str(&format!(
                "; into sha256:{} with {} cell formats and metadata {}",
                into.model_hex, into.style_base, into.cm
            ));
        }
        s.push_str(&format!(
            "; sentences {}; prelude {}",
            self.sentences.text(),
            self.prelude.text()
        ));
        for (i, b) in self.phrasebooks.iter().enumerate() {
            s.push_str(&format!("; phrasebook {} {}", i + 1, b.text()));
        }
        s
    }

    pub fn parse(text: &str) -> Option<Stamp> {
        let mut fields = text.split("; ").peekable();
        let version = fields.next()?.strip_prefix("Frazaro ")?.to_string();
        let into = if fields.peek().is_some_and(|f| f.starts_with("into ")) {
            let f = fields.next()?.strip_prefix("into sha256:")?;
            let (hex, rest) = f.split_once(" with ")?;
            let (base, cm) = rest.split_once(" cell formats and metadata ")?;
            if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
                return None;
            }
            Some(IntoStamp {
                model_hex: hex.to_string(),
                style_base: base.parse().ok()?,
                cm: cm.parse().ok()?,
            })
        } else {
            None
        };
        let sentences = SourceHash::parse(fields.next()?.strip_prefix("sentences ")?)?;
        let prelude = SourceHash::parse(fields.next()?.strip_prefix("prelude ")?)?;
        let mut phrasebooks = Vec::new();
        for (i, f) in fields.enumerate() {
            let rest = f.strip_prefix(&format!("phrasebook {} ", i + 1))?;
            phrasebooks.push(SourceHash::parse(rest)?);
        }
        Some(Stamp {
            version,
            into,
            sentences,
            prelude,
            phrasebooks,
        })
    }

    /// Why the stamp does not name these sources, or `None` when it does.
    pub fn disagreement(
        &self,
        program_text: &str,
        prelude: &str,
        books: &[&str],
    ) -> Option<String> {
        if self.sentences != SourceHash::of(program_text) {
            return Some(
                "the sentences in its Frazaro sheet are not the ones the stamp names".to_string(),
            );
        }
        if self.prelude != SourceHash::of(prelude) {
            return Some("the prelude given is not the one the stamp names".to_string());
        }
        if self.phrasebooks.len() != books.len() {
            return Some(format!(
                "the stamp names {} phrasebook(s) and {} were given",
                self.phrasebooks.len(),
                books.len()
            ));
        }
        for (i, (want, text)) in self.phrasebooks.iter().zip(books.iter()).enumerate() {
            if *want != SourceHash::of(text) {
                return Some(format!(
                    "phrasebook {} given is not the one the stamp names",
                    i + 1
                ));
            }
        }
        None
    }
}

/// The stamp as a defined name's formula: a string constant.
fn stamp_formula(stamp: &Stamp) -> String {
    format!("\"{}\"", stamp.text().replace('"', "\"\""))
}

/// What `frazaro rebuild` reads out of a built workbook before building it
/// again.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BuildFile {
    pub stamp: Stamp,
    /// The program, line by line, as the `Frazaro` sheet holds it.
    pub program_text: String,
    /// The lines with text in them, which Check marks and the stamp counts.
    pub sentences: usize,
    /// The sheets that are not the build's: the model's, when the build
    /// was added to one.
    pub host_sheets: Vec<String>,
}

/// What `frazaro rebuild` answers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rebuilt {
    pub sentences: usize,
    pub built_by: String,
    pub matches: bool,
    /// Empty when it matches.
    pub why: String,
    /// Whether only the build's own sheets were checked, as for a workbook
    /// the build was added to, whose own parts the rebuild cannot remake.
    pub partial: bool,
}

impl Rebuilt {
    /// The one line `frazaro rebuild` prints.
    pub fn line(&self) -> String {
        let head = if self.partial {
            format!(
                "This workbook's Frazaro sheets were built from these {} sentences by Frazaro {}, into a workbook whose own sheets are not checked:",
                self.sentences, self.built_by
            )
        } else {
            format!(
                "This workbook was built from these {} sentences by Frazaro {}:",
                self.sentences, self.built_by
            )
        };
        if self.matches {
            format!("{head} yes.")
        } else {
            format!("{head} no. Why: {}.", self.why)
        }
    }
}

/// A stored part of a build, as text, for `rebuild` to compare with what
/// it renders again; `None` when the part is missing or not stored.
pub fn own_part_text(file: &[u8], name: &str) -> Option<String> {
    let entries = zip::entries(file)?;
    let e = entries.iter().find(|e| e.name == name)?;
    String::from_utf8(zip::stored_data(file, e)?.to_vec()).ok()
}

fn refuse_rebuild(why: &str) -> Refusal {
    raise("rebuild-not-a-build", &[("why", why)])
}

/// The text between `<open ...>` and `</close>` after `from`, with the
/// element's start tag given up to its name.
fn element_text<'a>(xml_text: &'a str, start_tag: &str, end_tag: &str) -> Option<&'a str> {
    let open = xml_text.find(start_tag)?;
    let after_open = open + xml_text[open..].find('>')? + 1;
    let close = after_open + xml_text[after_open..].find(end_tag)?;
    Some(&xml_text[after_open..close])
}

/// A stored part of our own archive, as text.
fn stored_part(file: &[u8], entries: &[zip::Entry], name: &str) -> Result<String, Refusal> {
    let e = entries
        .iter()
        .find(|e| e.name == name)
        .ok_or_else(|| refuse_rebuild(&format!("it has no part {name}")))?;
    let data = zip::stored_data(file, e).ok_or_else(|| {
        refuse_rebuild(
            "its parts are not stored as frazaro build stores them, so a host has saved it since it was built, if it was built at all",
        )
    })?;
    String::from_utf8(data.to_vec())
        .map_err(|_| refuse_rebuild(&format!("its part {name} is not UTF-8")))
}

/// A built workbook read back: its stamp and its sentences.
pub fn read_build(file: &[u8]) -> Result<BuildFile, Refusal> {
    let entries = zip::entries(file)
        .ok_or_else(|| refuse_rebuild("it is not a zip archive this reader knows"))?;
    let workbook = stored_part(file, &entries, "xl/workbook.xml")?;
    let raw = element_text(
        &workbook,
        &format!("<definedName name=\"{STAMP_NAME}\""),
        "</definedName>",
    )
    .ok_or_else(|| refuse_rebuild("it carries no Frazaro.Build stamp"))?;
    let formula = xml::unescape(raw);
    let quoted = formula
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .ok_or_else(|| refuse_rebuild("its Frazaro.Build stamp is not a text"))?;
    let stamp = Stamp::parse(&quoted.replace("\"\"", "\""))
        .ok_or_else(|| refuse_rebuild("its Frazaro.Build stamp does not read"))?;
    // The Frazaro sheet is the first sheet part; its column B is the program.
    let sheet = stored_part(file, &entries, &ooxml::sheet_part(1))?;
    let mut lines: Vec<String> = Vec::new();
    let mut rest = sheet.as_str();
    while let Some(i) = rest.find("<c r=\"B") {
        let cell = &rest[i + 7..];
        let Some(q) = cell.find('"') else { break };
        let row: usize = match cell[..q].parse() {
            Ok(n) => n,
            Err(_) => {
                rest = cell;
                continue;
            }
        };
        let Some(end) = cell.find("</c>") else { break };
        let body = &cell[..end];
        let text = element_text(body, "<t", "</t>")
            .map(xml::unescape)
            .unwrap_or_default();
        if row >= 1 {
            if lines.len() < row {
                lines.resize(row, String::new());
            }
            lines[row - 1] = text;
        }
        rest = &cell[end..];
    }
    let sentences = lines
        .iter()
        .filter(|l| !l.trim_matches(' ').is_empty())
        .count();
    let rels = stored_part(file, &entries, "xl/_rels/workbook.xml.rels")?;
    let host_sheets = merge::host_sheets_of(&workbook, &rels);
    Ok(BuildFile {
        stamp,
        program_text: lines.join("\n"),
        sentences,
        host_sheets,
    })
}

/// The workbook a translated program builds: the `Frazaro` sheet, then
/// the sheets its static subset writes, and the stamp. `vla` is the
/// program's VLA as `EnglishToVla` wrote it, read with the prelude and
/// expanded as the compiler reads it; `books` are the phrasebook texts the
/// translation used, in order, for the stamp alone. With a `host`, the
/// build is being added to that workbook: the host's sheets may be named
/// but not written to, and the stamp records the host.
pub fn build_workbook_with(
    program_text: &str,
    vla: &str,
    prelude: &str,
    books: &[&str],
    host: Option<&HostInfo>,
) -> Result<Workbook, Refusal> {
    let line_offset = count_lf(prelude) as u32 + 1;
    let text = format!("{prelude}\r\n{vla}");
    let forms = parse_all(&tokenize(&text), line_offset)?;
    let mut expander = Expander::new();
    let body = expander.collect(forms)?;
    let mut expanded = Vec::with_capacity(body.len());
    for f in &body {
        expanded.push(expander.expand(f, 0)?);
    }
    let mut w = Walker::new(
        program_text,
        host.map(|h| h.sheet_names.clone()).unwrap_or_default(),
    );
    if let Some(h) = host {
        if let Some(taken) = w.host_sheet(FRAZARO_SHEET) {
            return Err(raise(
                "build-into-sheet-name-taken",
                &[("path", &h.label), ("name", &taken)],
            ));
        }
    }
    let sheet = frazaro_sheet(program_text, &mut w.wb.styles);
    w.wb.sheets.push(sheet);
    w.wb.active_sheet = 0;
    for f in &expanded {
        w.collect_top(f)?;
    }
    w.walk_main()?;
    let into = match host {
        None => None,
        Some(h) => {
            if h.cm.is_none() && w.wb.has_dynamic_formulas() {
                return Err(raise(
                    "build-into-unsupported",
                    &[
                        ("path", &h.label),
                        ("part", "xl/metadata.xml"),
                        ("why", "its cell metadata has no dynamic-array block for this build's formulas to point at"),
                    ],
                ));
            }
            Some(IntoStamp {
                model_hex: h.model_hex.clone(),
                style_base: h.style_base,
                cm: h.cm.unwrap_or(0),
            })
        }
    };
    let stamp = Stamp::of(program_text, prelude, books, into);
    w.wb.defined_names
        .push((STAMP_NAME.to_string(), stamp_formula(&stamp)));
    Ok(w.wb)
}

/// A fresh workbook from a translated program.
pub fn build_workbook(
    program_text: &str,
    vla: &str,
    prelude: &str,
    books: &[&str],
) -> Result<Workbook, Refusal> {
    build_workbook_with(program_text, vla, prelude, books, None)
}

/// The workbook's bytes, or the catalogue's refusal when they would not fit
/// the file format. Every formula the declared subset computes holds its
/// value (KERNEL.20, the values folded at build time): the workbook is
/// recalculated once under Excel's library, as the view record's `value`
/// rows are, so that a reader that does not calculate shows what the host
/// would. A formula outside the subset holds none, and the host still
/// computes every formula when it opens the file.
pub fn build_xlsx(
    program_text: &str,
    vla: &str,
    prelude: &str,
    books: &[&str],
) -> Result<Vec<u8>, Refusal> {
    let wb = build_workbook(program_text, vla, prelude, books)?;
    let library = crate::excel::library();
    let values = crate::calc::Calc::run(&wb, &library);
    ooxml::workbook_bytes_valued(&wb, &values).ok_or_else(|| raise("build-workbook-too-large", &[]))
}

/// The model with the program's sheets added, as bytes (`--into`): the
/// model's parts as they were, this build's appended (`sheet::merge`).
/// `label` is what a refusal calls the model. No formula holds a value: the
/// build's formulas may read the model's own cells and names, which the
/// build does not read, so a value computed without them could be wrong.
pub fn build_xlsx_into(
    program_text: &str,
    vla: &str,
    prelude: &str,
    books: &[&str],
    model_bytes: Vec<u8>,
    label: &str,
) -> Result<Vec<u8>, Refusal> {
    let model = Model::read(model_bytes, label)?;
    let host = model.host_info();
    let wb = build_workbook_with(program_text, vla, prelude, books, Some(&host))?;
    merge::write(&model, &wb, host.cm.unwrap_or(0))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sheet::zip;

    const PRELUDE: &str = include_str!("../../scripts/prelude.vla");
    const ENGLISH: &str = include_str!("../../scripts/polyglotta/english.vla");
    const FIXTURE: &str = include_str!("../../scripts/build/fixture.txt");
    const GOLDEN: &[u8] = include_bytes!("../../scripts/build/fixture_golden.xlsx");

    fn text_of(cell: &Cell) -> &str {
        match &cell.content {
            Content::Text(t) => t,
            other => panic!("not a text: {other:?}"),
        }
    }

    #[test]
    fn the_frazaro_sheet_is_the_room() {
        let mut styles = Styles::new();
        let sh = frazaro_sheet(
            "Put 5 into cell B2.\n\n# a comment\n   \n\tindented\nlast",
            &mut styles,
        );
        assert_eq!(sh.name, "Frazaro");
        assert!(!sh.gridlines);
        assert_eq!(sh.active_cell, (1, 2));
        assert!(sh.columns[0].hidden);
        assert_eq!(sh.columns[1].width, Some(72.0));
        assert_eq!(sh.columns[2].width, Some(60.0));
        // Row 1: the sentence and its OK. Row 2, blank: nothing. Row 3, a
        // comment: marked, as Check marks any row with text. Row 4, spaces
        // only: the text kept, no mark. Row 5, a tab: marked, as Trim$ would
        // leave the tab. Row 6: the last line, without a line break after it.
        assert_eq!(text_of(&sh.cells[&(1, 2)]), "Put 5 into cell B2.");
        assert_eq!(text_of(&sh.cells[&(1, 3)]), "OK");
        assert!(!sh.cells.contains_key(&(2, 2)));
        assert_eq!(text_of(&sh.cells[&(3, 2)]), "# a comment");
        assert_eq!(text_of(&sh.cells[&(3, 3)]), "OK");
        assert_eq!(text_of(&sh.cells[&(4, 2)]), "   ");
        assert!(!sh.cells.contains_key(&(4, 3)));
        assert_eq!(text_of(&sh.cells[&(5, 3)]), "OK");
        assert_eq!(text_of(&sh.cells[&(6, 2)]), "last");
        assert_eq!(sh.cells.len(), 9);
        // The three formats, in order of first use, after the default.
        let xfs = styles.xfs();
        assert_eq!(xfs.len(), 4);
        assert_eq!(xfs[1].fill, Some(LAVENDER));
        assert_eq!(xfs[1].num_fmt, NumFmt::Text);
        assert_eq!(xfs[2].fill, Some(RESULT_GRAY));
        assert_eq!(xfs[3].fill, Some(OK_GREEN));
        assert!(xfs[3].wrap);
    }

    /// A program's VLA as EnglishToVla scaffolds it, written by hand.
    const STATIC_VLA: &str = r#"(const rate 0.2)

(dim vla-step Long)

(sub main ()
  (dim total)
  (on-error goto vla-fail)
  (set! vla-step 1)
  (if (vlatraceon) (then (vlatracestep 1 (vla-step-text 1))))
  (at-line 1
  (set! (range "b2") 5))
  (at-line 2
  (set! (. (range "b3") formula) "=B2*2"))
  (at-line 3
  (if (>= 4 2) (then (set! (. (range (& "c" 2 ":" "c" 4)) formula) "=IFS(B2>3,\"big\",TRUE,\"small\")"))))
  (at-line 4
  (begin (vlaensuresheet "data") (. (worksheets "data") activate)))
  (at-line 5
  (set! (range "a1") "west"))
  (at-line 6
  (set! (. (worksheets "output") range "b1") 7))
  (at-line 7
  (set! total 5))
  (at-line 8
  (set! (range "a2") (+ total rate)))
  (at-line 9
  (if (> total 3) (then (at-line 10 (set! (range "a3") true))) (else (at-line 11 (set! (range "a3") false)))))
  (at-line 12
  (set! (. (range "a4:b4") value) (& "x" 1)))
  (at-line 13
  (tally))
  (at-line 14
  (set! (. (range "a5") formula) "plain text"))
  (at-line 15
  (exit-sub))
  (at-line 16
  (set! (range "a6") 1))
  (exit-sub)
  (label vla-fail)
  (vla-report-error))

(sub tally ()
  (on-error goto vla-fail)
  (at-line 20
  (set! (range "a7") 70))
  (at-line 21
  (exit-sub))
  (at-line 22
  (set! (range "a8") 80))
  (exit-sub)
  (label vla-fail)
  (vla-report-error))

(sub vla-report-error ()
  (vlareportstop vla-step (vla-step-text vla-step) err.description))
"#;

    #[test]
    fn the_static_subset_lands_in_cells() {
        let wb = build_workbook("", STATIC_VLA, "", &[]).expect("the static subset builds");
        let names: Vec<&str> = wb.sheets.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["Frazaro", "Output", "data"]);
        let out = &wb.sheets[1];
        assert_eq!(out.cells[&(2, 2)].content, Content::Number(5.0));
        assert_eq!(
            out.cells[&(3, 2)].content,
            Content::Formula("B2*2".to_string())
        );
        // IFS can return an array, so the fill is a dynamic-array formula per
        // cell with its references moved (7c), not a shared formula.
        for (row, moved) in [(2, "B2"), (3, "B3"), (4, "B4")] {
            assert_eq!(
                out.cells[&(row, 3)].content,
                Content::DynamicFormula(format!("_xlfn.IFS({moved}>3,\"big\",TRUE,\"small\")"))
            );
        }
        assert_eq!(out.cells[&(1, 2)].content, Content::Number(7.0));
        assert!(wb.has_dynamic_formulas());
        assert_eq!(wb.defined_names.len(), 1);
        assert_eq!(wb.defined_names[0].0, "Frazaro.Build");
        assert!(wb.defined_names[0]
            .1
            .starts_with(&format!("\"Frazaro {}; sentences sha256:", crate::VERSION)));
        let data = &wb.sheets[2];
        assert_eq!(
            data.cells[&(1, 1)].content,
            Content::Text("west".to_string())
        );
        assert_eq!(data.cells[&(2, 1)].content, Content::Number(5.2));
        assert_eq!(data.cells[&(3, 1)].content, Content::Bool(true));
        assert_eq!(data.cells[&(4, 1)].content, Content::Text("x1".to_string()));
        assert_eq!(data.cells[&(4, 2)].content, Content::Text("x1".to_string()));
        // The step inlined up to its own Stop; the main's Stop ends the walk.
        assert_eq!(data.cells[&(7, 1)].content, Content::Number(70.0));
        assert!(!data.cells.contains_key(&(8, 1)));
        assert_eq!(
            data.cells[&(5, 1)].content,
            Content::Text("plain text".to_string())
        );
        assert!(!data.cells.contains_key(&(6, 1)));
    }

    fn vla_with(stmt: &str) -> String {
        format!(
            "(sub main ()\n  (on-error goto vla-fail)\n  (at-line 1\n  (set! (range \"b2\") 5))\n  (at-line 2\n  {stmt})\n  (exit-sub)\n  (label vla-fail)\n  (vla-report-error))\n"
        )
    }

    #[test]
    fn a_formula_that_reaches_outside_is_refused_by_name() {
        // SEC.15: the writer asks the egress scan before it writes a formula,
        // through either spelling of the member and whatever the text begins
        // with; the refusal names the line, the function and the sentence.
        let program = "Put 5 into cell B2.\nPut formula \"=HYPERLINK(\"\"https://example.com/\"\",\"\"go\"\")\" into cell B3.\n";
        for (stmt, name) in [
            (
                "(set! (. (range \"b3\") formula) \"=HYPERLINK(\\\"https://example.com/\\\",\\\"go\\\")\")",
                "HYPERLINK",
            ),
            (
                "(set! (. (range \"b3\") formula) \"=cmd|'/c calc'!A0\")",
                "DDE",
            ),
            (
                "(set! (. (range \"b3\") formula2) \"=_xlfn.WEBSERVICE(\\\"https://example.com/\\\")\")",
                "WEBSERVICE",
            ),
            (
                "(set! (. (range \"b3:b5\") formula) \"WEBSERVICE(1)\")",
                "WEBSERVICE",
            ),
        ] {
            let r = build_workbook(program, &vla_with(stmt), "", &[]).expect_err(stmt);
            assert_eq!(r.id, "build-formula-egress", "{stmt}");
            assert!(
                r.text
                    .contains(&format!("Line 2 would write a formula that uses {name}")),
                "{}",
                r.text
            );
            assert!(r.text.contains("Put formula \"=HYPERLINK"), "{}", r.text);
            assert!(r.text.ends_with("Nothing was written."), "{}", r.text);
        }
        // The same text through the value member is a text in the cell, as
        // Excel stores a value, so nothing is refused and nothing runs.
        let wb = build_workbook(
            program,
            &vla_with(
                "(set! (. (range \"b3\") value) \"=HYPERLINK(\\\"https://example.com/\\\",\\\"go\\\")\")",
            ),
            "",
            &[],
        )
        .expect("a value");
        assert_eq!(
            wb.sheets[1].cells[&(3, 2)].content,
            Content::Text("=HYPERLINK(\"https://example.com/\",\"go\")".to_string())
        );
        // A listed name inside a string literal is text, and the formula is
        // written as before.
        let wb = build_workbook(
            program,
            &vla_with("(set! (. (range \"b3\") formula) \"=\\\"WEBSERVICE(\\\"\")"),
            "",
            &[],
        )
        .expect("a name inside a string");
        assert_eq!(
            wb.sheets[1].cells[&(3, 2)].content,
            Content::Formula("\"WEBSERVICE(\"".to_string())
        );
    }

    #[test]
    fn what_needs_a_host_is_refused_with_its_sentence() {
        let program = "Put 5 into cell B2.\nSay \"hello\".\n";
        for stmt in [
            "(msgbox \"hello\")",
            "(set! (range \"c:c\") 0)",
            "(set! (range \"a1\") (range \"b1\"))",
            "(set! (. (range \"a1\") interior.color) 255)",
            "(if (> (range \"a1\") 1) (then (set! (range \"a2\") 1)))",
            "(dotimes i 3 (set! (range \"a1\") 1))",
            "(on-error goto vla-tryf-1)",
            "(set! x (range \"a1\"))",
        ] {
            let r = build_workbook(program, &vla_with(stmt), "", &[]).expect_err(stmt);
            assert_eq!(r.id, "build-not-representable", "{stmt}");
            assert!(
                r.text.contains("Line 2 asks for more: Say \"hello\"."),
                "{}",
                r.text
            );
        }
        let r = build_workbook(
            program,
            &vla_with("(. (worksheets \"nowhere\") activate)"),
            "",
            &[],
        )
        .expect_err("an unmade sheet");
        assert_eq!(r.id, "build-sheet-unknown");
        assert!(r.text.contains("Line 2 names sheet nowhere"), "{}", r.text);
        // A step that takes values, and a step that calls itself.
        let r = build_workbook(
            program,
            &format!(
                "{}(sub taxed ((byval a Variant))\n  (at-line 5 (set! (range \"a1\") a)))\n",
                vla_with("(taxed 5)")
            ),
            "",
            &[],
        )
        .expect_err("a step with values");
        assert_eq!(r.id, "build-not-representable");
        let r = build_workbook(
            program,
            &format!(
                "{}(sub again ()\n  (at-line 5 (again)))\n",
                vla_with("(again)")
            ),
            "",
            &[],
        )
        .expect_err("a step calling itself");
        assert_eq!(r.id, "build-not-representable");
        assert!(r.text.contains("Line 5"), "{}", r.text);
        // A library the build cannot read, as the compiler says it.
        let r =
            build_workbook(program, "(include \"alien.vla\")\n", "", &[]).expect_err("an include");
        assert_eq!(r.id, "vla-include-cannot-read");
        // A sheet name Excel would refuse.
        for (name, why) in [
            (
                "abcdefghijklmnopqrstuvwxyz123456",
                "it is 32 characters long",
            ),
            ("a:b", "it contains :"),
            ("'q1", "it begins or ends with an apostrophe"),
            ("History", "History is a name Excel keeps for itself"),
        ] {
            let r = build_workbook(
                program,
                &vla_with(&format!("(vlaensuresheet \"{name}\")")),
                "",
                &[],
            )
            .expect_err(name);
            assert_eq!(r.id, "build-sheet-name-invalid", "{name}");
            assert!(r.text.contains(why), "{}", r.text);
        }
        assert_eq!(sheet_name_problem("Q1 Data"), None);
        assert_eq!(sheet_name_problem(""), Some("it is empty".to_string()));
    }

    #[test]
    fn folding_spells_values_as_vba_does() {
        assert_eq!(
            fold_op(
                "&",
                &[
                    Value::Text("c".into()),
                    Value::Num(2.0),
                    Value::Text(":".into())
                ]
            ),
            Some(Value::Text("c2:".into()))
        );
        assert_eq!(cstr(&Value::Num(2.5)), "2.5");
        assert_eq!(cstr(&Value::Num(-3.0)), "-3");
        assert_eq!(cstr(&Value::Bool(true)), "True");
        assert_eq!(fold_op("-", &[Value::Num(5.0)]), Some(Value::Num(-5.0)));
        assert_eq!(fold_op("/", &[Value::Num(5.0), Value::Num(0.0)]), None);
        assert_eq!(
            fold_op("<", &[Value::Text("a".into()), Value::Text("b".into())]),
            Some(Value::Bool(true))
        );
        assert_eq!(fold_op("and", &[Value::Bool(true), Value::Num(1.0)]), None);
        assert_eq!(fold_op("sum", &[Value::Num(1.0)]), None);
    }

    #[test]
    fn the_same_text_gives_the_same_bytes() {
        let vla = "(sub main ()\n  (at-line 1\n  (set! (range \"b2\") 5)))";
        let a = build_xlsx("Put 5 into cell B2.\n", vla, "", &[]).unwrap();
        let b = build_xlsx("Put 5 into cell B2.\n", vla, "", &[]).unwrap();
        assert_eq!(a, b);
        assert!(build_xlsx("Log 1.\n", "(sub main", "", &[]).is_err());
    }

    #[test]
    fn the_refusals_come_from_the_catalogue() {
        let r = raise("build-output-exists", &[("path", "out.xlsx")]);
        assert_eq!(r.source, "VLA-Build");
        assert!(r.text.contains("out.xlsx"));
        assert!(r.text.contains("--replace"));
        let r = raise("build-workbook-too-large", &[]);
        assert_eq!(r.source, "VLA-Build");
        let r = raise(
            "build-not-representable",
            &[("line", "4"), ("sentence", "Say \"hi\".")],
        );
        assert_eq!(r.source, "VLA-Build");
        assert!(r.text.contains("Line 4 asks for more: Say \"hi\"."));
        let r = raise("build-sheet-unknown", &[("line", "4"), ("name", "data")]);
        assert_eq!(r.source, "VLA-Build");
        assert!(r.text.contains("Work on sheet data."));
    }

    #[test]
    fn the_stamp_round_trips() {
        let stamp = Stamp::of(
            "Put 5 into cell B2.\r\n",
            "(defmacro (a) 1)",
            &["book one", "book\ttwo"],
            None,
        );
        assert_eq!(stamp.version, crate::VERSION);
        assert_eq!(stamp.phrasebooks.len(), 2);
        let text = stamp.text();
        assert!(text.starts_with(&format!("Frazaro {}; sentences sha256:", crate::VERSION)));
        assert!(text.contains("; prelude sha256:"));
        assert!(text.contains("; phrasebook 1 sha256:"));
        assert!(text.contains("; phrasebook 2 sha256:"));
        assert!(text.ends_with(" non-whitespace bytes"));
        assert_eq!(Stamp::parse(&text), Some(stamp.clone()));
        assert_eq!(Stamp::parse("Frazaro 0.1.0; sentences nonsense"), None);
        assert_eq!(Stamp::parse(""), None);
        // The same sentences in another spelling of their whitespace agree.
        assert_eq!(
            stamp.disagreement(
                "Put 5 into cell B2.",
                "(defmacro (a) 1)",
                &["book one", "book two"]
            ),
            None
        );
        assert_eq!(
            stamp.disagreement(
                "Put 6 into cell B2.",
                "(defmacro (a) 1)",
                &["book one", "book two"]
            ),
            Some("the sentences in its Frazaro sheet are not the ones the stamp names".to_string())
        );
        assert_eq!(
            stamp.disagreement(
                "Put 5 into cell B2.",
                "(defmacro (a) 2)",
                &["book one", "book two"]
            ),
            Some("the prelude given is not the one the stamp names".to_string())
        );
        assert_eq!(
            stamp.disagreement("Put 5 into cell B2.", "(defmacro (a) 1)", &["book one"]),
            Some("the stamp names 2 phrasebook(s) and 1 were given".to_string())
        );
        assert_eq!(
            stamp.disagreement(
                "Put 5 into cell B2.",
                "(defmacro (a) 1)",
                &["book one", "book three"]
            ),
            Some("phrasebook 2 given is not the one the stamp names".to_string())
        );
    }

    #[test]
    fn a_built_workbook_reads_back() {
        let program = " Put 5 into cell B2.\n\n# a & b <c>\n   \nlast";
        let vla = "(sub main ()\n  (at-line 1\n  (set! (range \"b2\") 5)))";
        let bytes = build_xlsx(program, vla, "pre", &["book"]).unwrap();
        let read = read_build(&bytes).expect("a build reads back");
        assert_eq!(
            read.program_text,
            " Put 5 into cell B2.\n\n# a & b <c>\n   \nlast"
        );
        assert_eq!(read.sentences, 3);
        assert_eq!(read.stamp, Stamp::of(program, "pre", &["book"], None));
        assert!(read.host_sheets.is_empty());
        assert_eq!(
            read.stamp
                .disagreement(&read.program_text, "pre", &["book"]),
            None
        );
        // Not a build: not a zip; a zip with no stamp.
        let r = read_build(b"not a workbook at all").expect_err("not a zip");
        assert_eq!(r.id, "rebuild-not-a-build");
        assert!(r.text.contains("not a zip archive"));
        let plain =
            zip::write_stored(&[("xl/workbook.xml".to_string(), b"<workbook/>".to_vec())]).unwrap();
        let r = read_build(&plain).expect_err("no stamp");
        assert_eq!(r.id, "rebuild-not-a-build");
        assert!(r.text.contains("no Frazaro.Build stamp"), "{}", r.text);
        // The answer's one line.
        let yes = Rebuilt {
            sentences: 9,
            built_by: "0.7.1".to_string(),
            matches: true,
            why: String::new(),
            partial: false,
        };
        assert_eq!(
            yes.line(),
            "This workbook was built from these 9 sentences by Frazaro 0.7.1: yes."
        );
        let no = Rebuilt {
            why: "the prelude given is not the one the stamp names".to_string(),
            matches: false,
            ..yes
        };
        assert_eq!(
            no.line(),
            "This workbook was built from these 9 sentences by Frazaro 0.7.1: no. Why: the prelude given is not the one the stamp names."
        );
    }

    #[test]
    fn rebuild_says_yes_to_its_own_build_and_no_to_a_changed_one() {
        let r = crate::api::english_rebuild_xlsx(GOLDEN, PRELUDE, &[ENGLISH])
            .unwrap_or_else(|r| panic!("the golden did not read back: {}", r.refusal));
        assert!(r.matches, "{}", r.why);
        assert_eq!(r.sentences, 9);
        assert_eq!(r.built_by, crate::VERSION);
        let mut changed = GOLDEN.to_vec();
        changed[100] ^= 1; // inside [Content_Types].xml, the first part
        let r = crate::api::english_rebuild_xlsx(&changed, PRELUDE, &[ENGLISH]).unwrap();
        assert!(!r.matches);
        assert!(r.why.contains("not what this core builds"), "{}", r.why);
        let r = crate::api::english_rebuild_xlsx(GOLDEN, "", &[ENGLISH]).unwrap();
        assert!(!r.matches);
        assert_eq!(r.why, "the prelude given is not the one the stamp names");
    }

    #[test]
    fn a_build_into_a_model_leaves_the_model_alone() {
        use crate::sheet::merge::test_model;
        // Writes to Output (new) and Checks (new) land; the model's Model
        // and Notes may be gone to but never written into.
        let vla = "(sub main ()\n  (at-line 1\n  (set! (range \"b1\") 5))\n  (at-line 2\n  (begin (vlaensuresheet \"checks\") (. (worksheets \"checks\") activate)))\n  (at-line 3\n  (set! (. (range \"a1\") formula) \"=IFS(Model!B3>0,\\\"profit\\\",TRUE,\\\"loss\\\")\"))\n  (at-line 4\n  (begin (vlaensuresheet \"notes\") (. (worksheets \"notes\") activate))))";
        let program = "Put 5 into cell B1.\nWork on sheet Checks.\nPut formula \"=IFS(...)\" into cell A1.\nWork on sheet Notes.\n";
        let out =
            build_xlsx_into(program, vla, "", &["book"], test_model(None), "model.xlsx").unwrap();
        let read = read_build(&out).expect("the output reads back as a build");
        assert_eq!(read.host_sheets, ["Model", "Notes"]);
        assert_eq!(read.sentences, 4);
        let into = read.stamp.into.clone().expect("an into stamp");
        assert_eq!(into.style_base, 3);
        assert_eq!(into.cm, 1);
        assert_eq!(into.model_hex, crate::sha256::sha256_hex(&test_model(None)));
        let names: Vec<String> = zip::entries(&out)
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&"xl/worksheets/frazaro_1.xml".to_string()));
        assert!(names.contains(&"xl/worksheets/frazaro_3.xml".to_string()));
        assert!(names.contains(&"xl/metadata.xml".to_string()));
        // A write into the model's own sheet is refused with its line.
        let bad = "(sub main ()\n  (at-line 1\n  (. (worksheets \"model\") activate))\n  (at-line 2\n  (set! (range \"a5\") 7)))";
        let r = build_xlsx_into(
            "Go to sheet Model.\nPut 7 into cell A5.\n",
            bad,
            "",
            &[],
            test_model(None),
            "model.xlsx",
        )
        .expect_err("a write into the model");
        assert_eq!(r.id, "build-into-model-sheet");
        assert!(
            r.text.contains("Line 2 writes into sheet Model"),
            "{}",
            r.text
        );
        // So is a cross-sheet put into it.
        let bad2 =
            "(sub main ()\n  (at-line 1\n  (set! (. (worksheets \"notes\") range \"a1\") 7)))";
        let r = build_xlsx_into(
            "Put 7 into cell A1 of sheet Notes.\n",
            bad2,
            "",
            &[],
            test_model(None),
            "model.xlsx",
        )
        .expect_err("a put into the model");
        assert_eq!(r.id, "build-into-model-sheet");
        assert!(r.text.contains("sheet Notes"), "{}", r.text);
        // A model that already has a Frazaro sheet cannot take another.
        let taken = String::from_utf8(test_model(None)).unwrap_or_default();
        let _ = taken;
        let with_frazaro = {
            let bytes = test_model(None);
            let m = Model::read(bytes, "m.xlsx").unwrap();
            let host = HostInfo {
                sheet_names: vec!["Model".to_string(), "FRAZARO".to_string()],
                ..m.host_info()
            };
            build_workbook_with(
                "Put 1 into cell A1.\n",
                "(sub main ()\n  (at-line 1\n  (set! (range \"a1\") 1)))",
                "",
                &[],
                Some(&host),
            )
        };
        let r = with_frazaro.expect_err("the name is taken");
        assert_eq!(r.id, "build-into-sheet-name-taken");
        assert!(
            r.text.contains("already has a sheet named FRAZARO"),
            "{}",
            r.text
        );
        // Not a model at all.
        let r = build_xlsx_into("", "(sub main ())", "", &[], b"nope".to_vec(), "x.xlsx")
            .expect_err("not a zip");
        assert_eq!(r.id, "build-into-not-a-workbook");
    }

    #[test]
    fn the_into_stamp_round_trips() {
        let into = IntoStamp {
            model_hex: "AB".repeat(32),
            style_base: 7,
            cm: 2,
        };
        let stamp = Stamp::of("x", "p", &["b"], Some(into.clone()));
        let text = stamp.text();
        assert!(text.contains(&format!(
            "; into sha256:{} with 7 cell formats and metadata 2; sentences ",
            "AB".repeat(32)
        )));
        assert_eq!(Stamp::parse(&text), Some(stamp));
        assert_eq!(Stamp::parse(&text.replace(" with 7 ", " with x ")), None);
        let partial = Rebuilt {
            sentences: 6,
            built_by: "0.7.1".to_string(),
            matches: true,
            why: String::new(),
            partial: true,
        };
        assert_eq!(
            partial.line(),
            "This workbook's Frazaro sheets were built from these 6 sentences by Frazaro 0.7.1, into a workbook whose own sheets are not checked: yes."
        );
    }

    /// KERNEL.20, the values folded at build time: a fresh build's file holds,
    /// for every formula the view computes, the value the view prints, read
    /// back by the reader, and nothing for a formula the view does not
    /// compute; `calc` over the file finds every computed value agreeing
    /// with the one it holds; `rebuild` still says yes.
    #[test]
    fn a_fresh_build_holds_each_value_its_view_computes() {
        let program = "Put 5 into cell B2.\n\
            Put formula \"=B2*2\" into cell B3.\n\
            Put formula \"=B2>3\" into cell C1.\n\
            Put formula \"=1/0\" into cell C2.\n\
            Put formula \"=\"\"a & <b> \"\"&B2\" into cell C3.\n\
            Put formula \"=VLOOKUP(1,B2:B3,1)\" into cell C4.\n\
            Put formula \"=C4+1\" into cell C5.\n\
            Put formula \"=0.1+0.2\" into cell C6.\n\
            Put formula \"=B9\" into cell C7.\n\
            Put formula \"=IFS(B2>3,\"\"big\"\",TRUE,\"\"small\"\")\" into cell D2.\n";
        let bytes = crate::api::english_build_xlsx(program, PRELUDE, &[ENGLISH])
            .unwrap_or_else(|r| panic!("the program did not build: {}", r.refusal));
        let relations = crate::api::reflect_relations(&bytes, "built").unwrap();
        let view = crate::api::english_view(program, PRELUDE, &[ENGLISH], "Output", None)
            .unwrap_or_else(|r| panic!("the program did not view: {}", r.refusal));
        let mut computed = 0;
        let mut not = 0;
        for line in view.lines().filter(|l| l.starts_with("(value ")) {
            // `"Output" "C3"`, then the datum.
            let rest = &line["(value ".len()..line.len() - 1];
            let address_end = rest.match_indices('"').nth(3).unwrap().0;
            let (cell, value) = (&rest[..=address_end], rest[address_end + 1..].trim_start());
            if value.starts_with("(not-computed") {
                not += 1;
                assert!(
                    !relations.contains(&format!("(cell {cell} ")),
                    "{cell} is not computed, yet the file holds a value for it:\n{relations}"
                );
            } else {
                computed += 1;
                let row = format!("(cell {cell} {value})");
                assert!(
                    relations.lines().any(|l| l == row),
                    "the file does not hold {row}:\n{relations}"
                );
            }
        }
        assert_eq!((computed, not), (7, 2));
        assert!(relations.contains("(cell \"Output\" \"C1\" true)"));
        assert!(relations.contains("(cell \"Output\" \"C2\" (error \"#DIV/0!\"))"));
        assert!(relations.contains("(cell \"Output\" \"C3\" \"a & <b> 5\")"));
        assert!(relations.contains("(cell \"Output\" \"C6\" 0.30000000000000004)"));
        assert!(relations.contains("(cell \"Output\" \"D2\" \"big\")"));
        for row in crate::api::calc_rows(&bytes, "built").unwrap().lines() {
            if row.contains("(not-computed ") {
                assert!(row.ends_with(" none unchecked)"), "{row}");
            } else {
                assert!(row.ends_with(" agree)"), "{row}");
            }
        }
        let again = crate::api::english_rebuild_xlsx(&bytes, PRELUDE, &[ENGLISH]).unwrap();
        assert!(again.matches, "{}", again.line());
    }

    /// The build golden: the fixture, built with the prelude and english.vla,
    /// is `scripts/build/fixture_golden.xlsx` byte for byte. When this fails
    /// the writer changed: regenerate with `frazaro build
    /// scripts/build/fixture.txt --prelude scripts/prelude.vla --phrasebook
    /// scripts/polyglotta/english.vla --out scripts/build/fixture_golden.xlsx
    /// --replace`, open it in Excel (the owner's live pass), and raise
    /// tools/check_build_golden.ps1's floor if it grew.
    #[test]
    fn the_build_golden_is_reproduced() {
        let got = crate::api::english_build_xlsx(FIXTURE, PRELUDE, &[ENGLISH])
            .unwrap_or_else(|r| panic!("the fixture did not build: {}", r.refusal));
        same_bytes(&got, GOLDEN, "scripts/build/fixture_golden.xlsx");
    }

    /// A build and its golden byte for byte, the first difference named by
    /// its part and its offset.
    fn same_bytes(got: &[u8], golden: &[u8], path: &str) {
        if got != golden {
            let at = got
                .iter()
                .zip(golden.iter())
                .position(|(a, b)| a != b)
                .unwrap_or(got.len().min(golden.len()));
            let part = zip::entries(golden)
                .unwrap_or_default()
                .into_iter()
                .find(|e| at >= e.data_offset && at < e.data_offset + e.size as usize)
                .map(|e| format!("{} at offset {}", e.name, at - e.data_offset))
                .unwrap_or_else(|| "a header".to_string());
            panic!(
                "the build differs from {path} at byte {at} of {} ({part}); got {} bytes",
                golden.len(),
                got.len()
            );
        }
    }

    const SHEETS: &str = include_str!("../../scripts/build/sheets.txt");
    const SHEETS_GOLDEN: &[u8] = include_bytes!("../../scripts/build/sheets_golden.xlsx");

    /// PORT.13: fills that read another sheet are written one formula a cell,
    /// as Excel writes them, and the fill on its own sheet stays shared; the
    /// golden is regenerated as the fixture's is, with sheets.txt and
    /// sheets_golden.xlsx, and opened in Excel.
    #[test]
    fn the_sheets_golden_is_reproduced() {
        let got = crate::api::english_build_xlsx(SHEETS, PRELUDE, &[ENGLISH])
            .unwrap_or_else(|r| panic!("sheets.txt did not build: {}", r.refusal));
        same_bytes(&got, SHEETS_GOLDEN, "scripts/build/sheets_golden.xlsx");
        let entries = zip::entries(&got).unwrap();
        let output = entries
            .iter()
            .find(|e| e.name == "xl/worksheets/frazaro_3.xml")
            .unwrap();
        let part = String::from_utf8(zip::stored_data(&got, output).unwrap().to_vec()).unwrap();
        assert!(
            part.contains("<c r=\"B2\" s=\"0\"><f>Data!A2*10</f><v>30</v></c>"),
            "{part}"
        );
        assert!(
            part.contains("<f>SUM(Data!$A$1:$A$3)+C3</f><v>61</v>"),
            "{part}"
        );
        assert!(
            part.contains("<f t=\"shared\" ref=\"C1:C3\" si=\"0\">B1+1</f>"),
            "{part}"
        );
        assert_eq!(part.matches("t=\"shared\"").count(), 3, "{part}");
        let r = crate::api::english_rebuild_xlsx(&got, PRELUDE, &[ENGLISH])
            .unwrap_or_else(|r| panic!("the golden did not read back: {}", r.refusal));
        assert!(r.matches, "{}", r.why);
    }
}