ironwork-compile 0.9.0

ironwork for COBOL: the compiler that checks a parsed program and lays out its storage as IBM does
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
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
//! ironwork for COBOL, the compiler: a parsed program checked against IBM's rules, with its
//! WORKING-STORAGE laid out as IBM lays it out, ready for the interpreter or for lowering.

pub mod any_length;
pub mod arith;
pub mod cics_bind;
mod crt_status;
mod classes;
pub mod constructs;
pub mod collating;
mod corresponding;
pub use corresponding::is_alphabetic;
pub use operands::as_characters;
pub mod declaratives;
pub mod facts;
pub mod function;
mod initcheck;
pub mod layout;
pub mod linage;
pub mod lower;
pub mod markup;
pub mod numcheck;
mod omitted;
pub mod oo;
mod operands;
pub mod picture;
pub mod printer;
pub mod report;
mod registers;
mod reserved;
mod scope;
mod screens;
pub mod sort;
pub mod sql;
pub mod statements;
mod switches;
pub mod values;

use layout::Layout;
use numeric::{Options, Vlr};
use rt::lir::{CompileTime, TimeSource};
use rt::storage::literal_fixed;
use syntax::ast::*;
use syntax::messages::{IWC0003, IWC0004, Message};
use syntax::{Error, Pos, Severity};

pub struct Compiled {
    pub program: Program,
    /// FUNCTION WHEN-COMPILED's time.
    pub when_compiled: CompileTime,
    pub layout: Layout,
    pub options: Options,
    pub ssrange: bool,
    pub report_writer: report::Writer,
    /// The PROGRAM COLLATING SEQUENCE, or EBCDIC.
    pub collating: collating::Sequence,
    /// Each file's printer control character, when it is a print file.
    pub carriage: Vec<Option<printer::Carriage>>,
    /// The messages of a program that compiled, none of them severe enough to stop its object code.
    pub diagnostics: Vec<Error>,
    /// The program's ENTRY statements, in source order.
    pub entries: Vec<EntryPoint>,
    /// Where each EXCEPTION/ERROR and debugging procedure runs.
    pub declaratives: declaratives::Table,
    /// The user-defined functions the program may invoke.
    pub functions: Vec<function::Udf>,
}

/// An alternate entry point: a CALL of `name` begins at statement `statement` of paragraph
/// `paragraph`, the one after the ENTRY statement, with `using` addressing LINKAGE.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntryPoint {
    pub name: String,
    pub paragraph: usize,
    pub statement: usize,
    pub using: Vec<Param>,
    pub pos: Pos,
}

/// The ENTRY statements of a program, each a sentence of its own paragraph's.
pub fn entry_points(program: &Program) -> Vec<EntryPoint> {
    let mut out = Vec::new();
    for (paragraph, p) in program.paragraphs.iter().enumerate() {
        for (k, s) in p.statements.iter().enumerate() {
            if let Stmt::Entry { name, using, pos } = s {
                out.push(EntryPoint { name: name.clone(), paragraph, statement: k + 1, using: using.clone(), pos: *pos });
            }
        }
    }
    out
}

/// Whether file k's records vary in length: RECORDING MODE V, RECORD IS VARYING, a RECORD clause
/// with two bounds, or, with neither RECORDING MODE nor RECORD, level-01 records of different
/// lengths or with an OCCURS DEPENDING ON table, an SD's as well (Language Reference SC27-8713-03,
/// p. 191; Programming Guide SC27-8714-03, pp. 227-228).
pub fn variable_records(file: &FileDecl, layout: &Layout, k: usize) -> bool {
    let undeclared = file.recording.is_none() && file.record_min.is_none() && file.record_max.is_none() && !file.record_varying;
    file.recording == Some('V') || file.record_varying || file.record_min != file.record_max || undeclared && layout.record_lengths[k].is_some_and(|(shortest, longest)| shortest != longest)
}

/// The shortest and longest variable-length record a READ of file k takes without a record length
/// conflict: under VLR(STANDARD) its level-01 records', under VLR(COMPAT) its RECORD IS VARYING
/// clause's, where a bound the clause leaves out is the level-01 records' (Programming Guide
/// SC27-8714-03, pp. 422-424; Language Reference SC27-8713-03, pp. 187, 300, 431). See
/// [`numeric::assumptions::VLR_WITHOUT_VARYING`] and [`numeric::assumptions::VLR_RECORDS_CHECKED`].
pub fn read_lengths(file: &FileDecl, layout: &Layout, k: usize, vlr: Vlr) -> (u32, u32) {
    match vlr {
        Vlr::Compat if file.record_varying => varying_lengths(file, layout, k),
        _ => record_lengths(layout, k),
    }
}

/// The shortest and longest record RECORD IS VARYING allows file k, a bound it leaves out being the
/// level-01 records' (Language Reference SC27-8713-03, p. 187).
pub fn varying_lengths(file: &FileDecl, layout: &Layout, k: usize) -> (u32, u32) {
    let (shortest, longest) = record_lengths(layout, k);
    (file.record_min.unwrap_or(shortest), file.record_max.unwrap_or(longest))
}

fn record_lengths(layout: &Layout, k: usize) -> (u32, u32) {
    layout.record_lengths[k].unwrap_or((0, layout.file_areas[k].1))
}

const FUNCTIONS: &[&str] = rt::intrinsic::FIRST;

pub const NUMERIC_FUNCTION_MOVED: &str = "an integer or numeric function as a MOVE's sender (GnuCOBOL; Enterprise COBOL takes one only where an arithmetic expression can be)";
pub const INTO_WITHOUT_COLON: &str = "an INTO name written without its colon (Db2 13 for z/OS requires the colon before every host variable)";

/// Checks and lays out a parsed program. `flags` are this compiler's own, such as `-silent`. A
/// program is refused, with every message, when one stops its object code: under IBM's default
/// NOCOMPILE(S) one that is S or U, from W under `-warnings-block`, or as a CBL or PROCESS card's
/// COMPILE or NOCOMPILE says; otherwise its messages are [`Compiled::diagnostics`].
pub fn compile(program: Program, flags: &[String]) -> Result<Compiled, Vec<Error>> {
    let at = compile_time().map_err(|message| vec![syntax::messages::IWO0004.at(Pos::default(), message)])?;
    compile_at(program, flags, at)
}

/// Compiles as [`compile`] does, WHEN-COMPILED giving `at`.
pub fn compile_at(program: Program, flags: &[String], at: CompileTime) -> Result<Compiled, Vec<Error>> {
    if program.oo.as_ref().is_some_and(|o| o.class().is_some()) {
        return oo::compile_class_definition(program, flags, at);
    }
    compile_program(program, flags, true, at)
}

/// When a compile happens: SOURCE_DATE_EPOCH's seconds when the build sets it, the
/// reproducible-builds convention, and the clock otherwise.
pub fn compile_time() -> Result<CompileTime, String> {
    let clock = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
    compile_time_from(std::env::var_os("SOURCE_DATE_EPOCH").as_deref(), clock)
}

fn compile_time_from(epoch: Option<&std::ffi::OsStr>, clock: std::time::Duration) -> Result<CompileTime, String> {
    let Some(epoch) = epoch else {
        return Ok(CompileTime { seconds: clock.as_secs() as i64, hundredths: clock.subsec_millis() / 10, source: TimeSource::Clock });
    };
    let text = epoch.to_string_lossy();
    match text.parse::<i64>() {
        Ok(seconds) if text.bytes().all(|b| b.is_ascii_digit()) && seconds <= CompileTime::LATEST => Ok(CompileTime { seconds, hundredths: 0, source: TimeSource::SourceDateEpoch }),
        _ => Err(format!("SOURCE_DATE_EPOCH={text}: not a whole number of seconds from 0 to {}", CompileTime::LATEST)),
    }
}

/// `whole` is false for the parts a class definition is compiled into, which IBM's rules for
/// compiler options do not apply to one by one.
pub(crate) fn compile_program(mut program: Program, flags: &[String], whole: bool, when_compiled: CompileTime) -> Result<Compiled, Vec<Error>> {
    let mut errors = std::mem::take(&mut program.messages);
    reserved::check(&program, &mut errors);
    let mut declared = program.working_storage.len();
    let mut program = declaratives::with_debug_item(markup::with_special_registers(sort::with_special_registers(registers::with_when_compiled(program, when_compiled))));
    switches::declare(&mut program, &mut errors);
    qualify_in_own_section(&mut program);
    let mut options = Options::default();
    let mut ssrange = false;
    // The flags first, as the compiler's invocation, then the cards, which outrank it (Programming
    // Guide SC27-8714-03, p. 273).
    for flag in flags {
        if let Err(e) = options.apply_flag(flag) {
            errors.push(syntax::messages::IWO0005.at(Pos::default(), e.to_string()));
        }
    }
    for option in &program.options {
        if let Some(on) = numeric::options::switch(option, "SSRANGE") {
            ssrange = on;
        }
        if let Err(e) = options.apply(option) {
            errors.push(syntax::messages::IWO0001.at(Pos::default(), format!("CBL {option}: {e}")).graded(option_severity(&e)));
        }
    }
    if options.compliance == numeric::Compliance::Extended {
        let inserted = top_level_tables(&mut program.working_storage, &mut errors);
        declared += inserted.iter().filter(|&&at| at < declared).count();
        top_level_tables(&mut program.local_storage, &mut errors);
        let Program { working_storage, local_storage, linkage, files, .. } = &mut program;
        for entries in [working_storage, local_storage, linkage].into_iter().chain(files.iter_mut().map(|f| &mut f.records)) {
            renames_inside_records(entries, &mut errors);
        }
        declared = based_items(&mut program, declared, &mut errors);
    }
    screens::expand(&mut program, options.compliance == numeric::Compliance::Extended, &mut errors);
    let page = options.code_page();
    if let Err((message, m)) = syntax::parser::decode_currency(&mut program.environment, |bytes| page.decode(bytes)) {
        errors.push(message.at(Pos::default(), m));
    }
    default_currency(&mut program, &mut options, &mut errors);
    national_symbols(&mut program, &mut options, &mut errors);
    if options.intdate == numeric::IntDate::Lilian {
        program.paragraphs.iter_mut().for_each(|p| ceecbldy_to_ceedays(&mut p.statements, &mut errors));
    }
    for (name, alphabet) in &program.environment.alphabets {
        if program.environment.collating_sequence.as_ref() != Some(name)
            && let Err((message, m)) = collating::Sequence::of(alphabet, options.code_page(), options.quote)
        {
            errors.push(message.at(Pos::default(), format!("ALPHABET {name}: {m}")));
        }
    }
    let collating = collating::Sequence::program(&program.environment, options.code_page(), options.quote).unwrap_or_else(|(message, m)| {
        errors.push(message.at(Pos::default(), m));
        let mut native = collating::Sequence::native();
        native.quote = options.quote;
        native
    });
    digit_limits(&program, options.arith, &mut errors);
    binary_chars(&program, &options, &mut errors);
    forever_names(&program, &mut errors);
    micro_focus_binaries(&program, &options, &mut errors);
    let drafts = report::prepare(&mut program, options.adv, options.qualify, &mut errors);
    let linage_counters = linage::add_counters(&mut program, options.qualify);
    if whole {
        oo::option_rules(&program, &options, &mut errors);
    }
    options.initial &= !options.thread;
    if whole && program.oo.as_deref().and_then(Oo::method).is_none() {
        program.initial |= options.initial;
    }
    scope::rules(&program, &mut errors);
    if whole {
        program_names(&program, &options, &mut errors);
    }
    let inherited = scope::inherit(&mut program);
    let own_linkage = scope::own_linkage(&program);
    omitted::rewrite(&mut program, &inherited.entries, options.compliance == numeric::Compliance::Extended, &mut errors);
    any_length::rewrite(&mut program, &mut errors);
    if options.compliance == numeric::Compliance::Extended {
        crt_status::rewrite(&mut program, &inherited.entries);
    }
    declare_assign_items(&mut program, &inherited.entries);
    let linkage: Vec<DataEntry> = program.linkage.iter().chain(&inherited.entries).cloned().collect();
    let files: Vec<(&[DataEntry], Option<u32>)> = program.files.iter().map(|f| (f.records.as_slice(), f.record_max)).collect();
    let shared = layout::record_area_owners(&program.files, &program.environment).unwrap_or_else(|e| {
        errors.push(e);
        (0..files.len()).collect()
    });
    let mut layout = match layout::build(&program.working_storage, &files, &shared, &linkage, program.linkage.len(), &program.local_storage, crate::picture::Notation::of(&program.environment), options.qualify, options.parmcheck.map(|p| (declared, p.bytes.into()))) {
        Ok(l) => l,
        Err(e) => {
            errors.push(e);
            return Err(errors.into_iter().map(|e| e.in_files(&program.sources)).collect());
        }
    };
    scope::bind(&mut layout, own_linkage, inherited, &program.files);
    layout.classes = classes::sets(&program.environment.classes, page, &mut errors);
    let counter_item = |entry: usize| program.working_storage[..entry].iter().filter(|e| e.level != 88).count();
    layout.name_files(&program.files, linage_counters.iter().map(|c| c.map(counter_item)).collect());
    assign_items(&mut program, &layout, &options, &mut errors);
    corresponding::expand(&mut program, &layout, &mut errors);
    condition_subjects(&mut program, &layout);
    dbcs_values(&layout, &mut errors);
    numeric_values(&layout, &mut errors);
    edited_values(&layout, options.compliance, &mut errors);
    for item in &layout.items {
        if let Some(object) = &item.depending_on {
            match layout.resolve(&object.name, &object.qualifiers, object.pos) {
                Ok(layout::Resolved::Item(i)) if !layout.items[i].moved_by.is_empty() => errors.push(syntax::messages::IWC0048.at(
                    object.pos,
                    format!("OCCURS DEPENDING ON {}: the object cannot follow an OCCURS DEPENDING ON table in its record", object.name),
                )),
                Ok(layout::Resolved::Item(i)) if layout.items[i].kind.is_numeric() => {}
                Ok(_) => errors.push(syntax::messages::IWC0049.at(object.pos, format!("OCCURS DEPENDING ON {}: not a numeric data item", object.name))),
                Err(e) => errors.push(e),
            }
        }
    }
    let is_record = |name: &str| layout.linkage_roots.iter().enumerate().any(|(o, &i)| layout.is_argument(o) && layout.items[i].name.as_deref() == Some(name));
    for param in &program.using {
        if !is_record(&param.name) {
            errors.push(syntax::messages::IWC0050.at(Pos::default(), format!("PROCEDURE DIVISION USING {}: not an 01 or 77 item of the LINKAGE SECTION", param.name)));
        }
    }
    // Language Reference SC27-8713-03, pp. 262-263; a method's and a function's are checked with their signatures.
    if let Some(name) = &program.returning
        && program.function.is_none()
        && program.oo.as_deref().and_then(Oo::method).is_none()
        && !is_record(name)
    {
        errors.push(syntax::messages::IWC0051.at(Pos::default(), format!("PROCEDURE DIVISION RETURNING {name}: not an 01 or 77 item of the LINKAGE SECTION")));
    }
    let report_writer = report::resolve(&program, &layout, drafts, &mut errors);
    let carriage = printer::carriages(&program, &layout, options.adv);
    let declaratives = declaratives::resolve(&program, &layout, &options, &mut errors);
    let debugging = declaratives::debugging_sections(&program);
    let functions = function::functions(&program, options.qualify, &mut errors);
    let alphabetic: Vec<Pos> = [&program.working_storage, &program.local_storage, &program.linkage]
        .into_iter()
        .flatten()
        .chain(program.files.iter().flat_map(|f| &f.records))
        .filter(|e| e.picture.as_deref().is_some_and(is_alphabetic))
        .map(|e| e.pos)
        .collect();
    let mut check = Check {
        layout: &layout,
        program: &program,
        errors: &mut errors,
        debugging: false,
        max_digits: options.arith.max_picture_digits(),
        inline_performs: 0,
        functions: Some(&functions),
        alphabetic: &alphabetic,
        at: Pos::default(),
        paragraph: 0,
        extended: options.compliance == numeric::Compliance::Extended,
        environment_named: None,
    };
    for k in 0..program.files.len() {
        check.file_keys(k);
        check.record_depending(k);
        check.label_records(k);
        check.recording_mode(k);
        check.passwords(k);
        linage::check_file(check.program, check.layout, k, check.errors);
    }
    for block in &program.exec_declarations {
        check.exec_block(block);
    }
    for (i, p) in program.paragraphs.iter().enumerate() {
        check.debugging = debugging.iter().any(|&(first, last)| (first..=last).contains(&i));
        check.paragraph = i;
        check.statements(&p.statements);
    }
    let entries = entry_points(&program);
    procedure_rules(&program, &layout, &entries, &options, &mut errors);
    if whole && !program.oo.as_deref().is_some_and(|o| o.method().is_some()) && !program.is_prototype() {
        program_end(&program, &options, &mut errors);
    }
    oo::check(&layout, &program, &mut errors);
    if let Some(mode) = options.initcheck {
        errors.extend(initcheck::check(&program, &layout, declared, mode));
    }
    scope::check(&program, &layout, &mut errors);
    layout.numcheck = numcheck::facts(&program, &layout, declared, &options, &collating, &mut errors);
    let errors: Vec<Error> = errors.into_iter().map(|e| e.in_files(&program.sources)).collect();
    if refused(&errors, &options) {
        Err(errors)
    } else {
        Ok(Compiled { program, when_compiled, layout, options, ssrange, report_writer, collating, carriage, diagnostics: errors, entries, declaratives, functions })
    }
}

/// Which files take their name from a data item at each OPEN. Under `--compliance extended` an
/// ASSIGN name that is an alphanumeric or group item's is one, with IWX0007-W, and DYNAMIC or
/// USING must name one; under strict a name stays the DD name it is in Enterprise COBOL and
/// DYNAMIC and USING are refused (C361). A file SORT or MERGE reads or writes is refused one, as
/// the sort opens its files by their DD names.
/// Micro Focus's ASSIGN TO DISK name where neither the program nor a program containing it declares
/// the name: a 4,095-byte alphanumeric item of WORKING-STORAGE, as cobc 3.2 declares it under
/// `-std=mf` (assumption C482).
fn declare_assign_items(program: &mut Program, inherited: &[DataEntry]) {
    let mut missing: Vec<(String, Pos)> = Vec::new();
    for a in program.files.iter().filter_map(|f| f.assign_item.as_ref()).filter(|a| a.declared_if_missing) {
        let name = &a.reference.name;
        let declared = program.working_storage.iter().chain(&program.local_storage).chain(&program.linkage).chain(inherited).chain(program.files.iter().flat_map(|f| &f.records)).any(|e| e.name.as_ref() == Some(name));
        if !declared && !missing.iter().any(|(m, _)| m == name) {
            missing.push((name.clone(), a.reference.pos));
        }
    }
    for (name, pos) in missing {
        program.working_storage.push(report::entry(1, Some(name), Some("X(4095)".into()), None, pos));
    }
}

fn assign_items(program: &mut Program, layout: &layout::Layout, options: &Options, errors: &mut Vec<Error>) {
    let extended = options.compliance == numeric::Compliance::Extended;
    let mut all = Vec::new();
    program.paragraphs.iter().for_each(|p| inner_statements(&p.statements, &mut all));
    let sorted: Vec<&str> = all
        .iter()
        .filter_map(|s| match s {
            Stmt::Sorting(sorting) => match sorting.as_ref() {
                Sorting::Sort(s) => Some(s),
                _ => None,
            },
            _ => None,
        })
        .flat_map(|s| [&s.input, &s.output])
        .filter_map(|io| if let Some(SortIo::Files(names)) = io { Some(names) } else { None })
        .flatten()
        .map(String::as_str)
        .collect();
    let mut kept = Vec::new();
    for (k, f) in program.files.iter().enumerate() {
        let Some(a) = &f.assign_item else { continue };
        let (name, pos) = (&a.reference.name, a.reference.pos);
        if !extended {
            if a.explicit {
                errors.push(syntax::messages::IWC0052.at(pos, format!("ASSIGN USING or DYNAMIC {name}: a Micro Focus and GnuCOBOL form; --compliance extended reads it")));
            }
            continue;
        }
        let item = match layout.resolve(name, &a.reference.qualifiers, pos) {
            Ok(layout::Resolved::Item(i)) => i,
            Ok(layout::Resolved::Condition(_)) | Err(_) if a.explicit => {
                errors.push(syntax::messages::IWC0053.at(pos, format!("ASSIGN {name}: not a data item")));
                continue;
            }
            _ => continue,
        };
        if !matches!(layout.items[item].kind, rt::storage::Kind::Group | rt::storage::Kind::Alnum { .. }) {
            errors.push(syntax::messages::IWC0054.at(pos, format!("ASSIGN {name}: the item holding the file's name must be alphanumeric or a group")));
        } else if f.sort || sorted.contains(&f.name.as_str()) {
            errors.push(syntax::messages::IWR0022.at(pos, format!("ASSIGN {name}: a file SORT or MERGE reads, writes or describes taking its name from a data item is not supported yet")));
        } else {
            errors.push(syntax::messages::IWX0007.at(pos, format!("{}: each OPEN of {} takes its DD name from {name}", syntax::extended::ASSIGN_ITEM, f.name)));
            kept.push(k);
        }
    }
    for (k, f) in program.files.iter_mut().enumerate() {
        if !kept.contains(&k) {
            f.assign_item = None;
        }
    }
}

/// How severe IBM's message for a card's option is: an invalid suboption is an error and the option
/// is discarded, and a removed option a warning or informational message (assumptions
/// [`numeric::assumptions::INVALID_OPTION_DISCARDED`], [`numeric::assumptions::NUMPROC_MIG_WARNS`]
/// and [`numeric::assumptions::OPTIONS_WITHOUT_EFFECT`]). A code page ironwork does not carry
/// stops the compile, as ironwork cannot read the program in it.
fn option_severity(e: &numeric::options::OptionError) -> Severity {
    use numeric::options::OptionError;
    match e {
        OptionError::BadSuboption { .. } => Severity::Error,
        OptionError::Removed { .. } | OptionError::NoEffect { warning: true, .. } => Severity::Warning,
        OptionError::NoEffect { warning: false, .. } => Severity::Informational,
        OptionError::UnsupportedCodePage(_) | OptionError::UnknownFlag(_) => Severity::Severe,
    }
}

/// CURRENCY(literal) makes its character the currency symbol, standing for itself, of a program
/// with no CURRENCY SIGN clause, in place of $; a program with one ignores the option
/// (Programming Guide SC27-8714-03, p. 358). A hexadecimal literal whose character the option may
/// not name is discarded with an error, as an invalid suboption is (assumption
/// [`numeric::assumptions::CURRENCY_OPTION`]).
fn default_currency(program: &mut Program, options: &mut Options, errors: &mut Vec<Error>) {
    match options.currency_symbol() {
        Some(Ok(symbol)) if program.environment.currency.is_empty() => program.environment.currency.push(CurrencySign { value: symbol.to_string(), symbol, hex: None }),
        Some(Err(c)) => {
            errors.push(syntax::messages::IWO0002.at(Pos::default(), format!("CBL CURRENCY: code page {} reads its byte as {c:?}, which cannot be a currency symbol", options.codepage)).graded(Severity::Error));
            options.currency = None;
        }
        _ => {}
    }
}

/// NSYMBOL(DBCS) makes a PICTURE of N, with or without B, and no USAGE, its own or a group's,
/// USAGE DISPLAY-1 (Programming Guide SC27-8714-03, p. 388). NSYMBOL(NATIONAL) with NODBCS on the
/// cards is IBM's conflict: DBCS in effect, with a warning (p. 344; assumption
/// [`numeric::assumptions::NSYMBOL_DBCS`]).
fn national_symbols(program: &mut Program, options: &mut Options, errors: &mut Vec<Error>) {
    if options.nsymbol == numeric::Nsymbol::National {
        if !options.dbcs && program.options.iter().any(|o| numeric::options::switch(o, "NSYMBOL").is_some()) {
            errors.push(syntax::messages::IWO0003.at(Pos::default(), "CBL NODBCS: NSYMBOL(NATIONAL) requires DBCS, which is in effect"));
            options.dbcs = true;
        }
        return;
    }
    let only_n = |p: &str| p.chars().any(|c| c.eq_ignore_ascii_case(&'N')) && p.chars().all(|c| c.eq_ignore_ascii_case(&'N') || c.eq_ignore_ascii_case(&'B') || c.is_ascii_digit() || matches!(c, '(' | ')'));
    let lists = [&mut program.working_storage, &mut program.local_storage, &mut program.linkage].into_iter().chain(program.files.iter_mut().map(|f| &mut f.records));
    for entries in lists {
        let mut groups: Vec<(u8, bool)> = Vec::new();
        for e in entries.iter_mut().filter(|e| !matches!(e.level, 66 | 88)) {
            let level = if e.level == 77 { 1 } else { e.level };
            while groups.last().is_some_and(|&(l, _)| l >= level) {
                groups.pop();
            }
            let usage = e.usage.is_some() || groups.iter().any(|&(_, u)| u);
            groups.push((level, e.usage.is_some()));
            if !usage && e.picture.as_deref().is_some_and(only_n) {
                e.usage = Some(Usage::Dbcs);
            }
        }
    }
}

/// IBM's warning for a program with no STOP RUN, GOBACK or EXIT PROGRAM, which may run past its
/// end; one that leaves by EXEC CICS RETURN or XCTL gets what `--cics-return-warning` says
/// (assumption [`numeric::assumptions::NO_PROGRAM_END`]).
fn program_end(program: &Program, options: &Options, errors: &mut Vec<Error>) {
    use numeric::CicsReturnWarning;
    let mut all = Vec::new();
    program.paragraphs.iter().for_each(|p| inner_statements(&p.statements, &mut all));
    if all.iter().any(|s| matches!(s, Stmt::StopRun { .. } | Stmt::Goback { .. } | Stmt::ExitProgram { .. })) {
        return;
    }
    let cics_end = all.iter().find_map(|s| match s {
        Stmt::Exec(b) if b.kind == ExecKind::Cics && matches!(b.command.as_str(), "RETURN" | "XCTL") => Some(b.command.as_str()),
        _ => None,
    });
    match (cics_end, options.cics_return_warning) {
        (Some(_), CicsReturnWarning::Never) => {}
        (Some(command), CicsReturnWarning::Once) => errors.push(syntax::messages::IWP0002.at(Pos::default(), format!(
            "IGYPS2091-W not given: the program ends with EXEC CICS {command}, which the CICS translator turns into a CALL; --cics-return-warning=always gives the warning, =never drops this note"
        )).graded(Severity::Informational)),
        (None, _) | (Some(_), CicsReturnWarning::Always) => {
            errors.push(syntax::messages::IWC0055.at(Pos::default(), "no STOP RUN, GOBACK or EXIT PROGRAM in the program: check that it ends"));
        }
    }
}

/// Under INTDATE(LILIAN) a CALL of the literal 'CEECBLDY', whose ANSI integer date neither the date
/// functions nor the callable services could then read, is diagnosed and calls CEEDAYS
/// (Programming Guide SC27-8714-03, p. 375; assumption
/// [`numeric::assumptions::CEECBLDY_UNDER_LILIAN`]).
fn ceecbldy_to_ceedays(stmts: &mut [Stmt], errors: &mut Vec<Error>) {
    for s in stmts {
        if let Stmt::Call(c) = s
            && let Operand::Literal(Literal::Alnum(name)) = &mut c.target
            && name.trim().eq_ignore_ascii_case("CEECBLDY")
        {
            *name = "CEEDAYS".into();
            errors.push(syntax::messages::IWC0056.at(c.pos, "CALL 'CEECBLDY' under INTDATE(LILIAN): CEECBLDY gives an ANSI integer date, which nothing can use under LILIAN, so the CALL is to CEEDAYS"));
        }
        for body in oo::bodies_mut(s) {
            ceecbldy_to_ceedays(body, errors);
        }
    }
}

/// Whether messages keep a program from running: the COMPILE option in force stops its object code,
/// or, as IGYWCLG bypasses its GO step, the return code is above 8. See
/// [`numeric::assumptions::REFUSED_FROM_S`] and [`numeric::assumptions::NOCOMPILE`].
pub fn refused(messages: &[Error], options: &Options) -> bool {
    let stops_at = options.object_code().stops_at().min(12);
    stops_at == 0 || messages.iter().any(|m| m.severity.return_code() >= stops_at)
}

/// The rules of the ENTRY statement (Language Reference SC27-8713-03, pp. 339-340), and of ALTER
/// and the GO TO it alters (pp. 318, 346-348).
fn procedure_rules(program: &Program, layout: &Layout, entries: &[EntryPoint], options: &Options, errors: &mut Vec<Error>) {
    let method = program.oo.as_ref().is_some_and(|o| matches!(o.unit, OoUnit::Method(_)));
    for (k, e) in entries.iter().enumerate() {
        if program.returning.is_some() {
            errors.push(syntax::messages::IWC0057.at(e.pos, format!("ENTRY '{}': a program with PROCEDURE DIVISION RETURNING cannot have ENTRY statements", e.name)));
        }
        if e.name.eq_ignore_ascii_case(&program.id) || entries[..k].iter().any(|f| f.name == e.name) {
            errors.push(syntax::messages::IWC0058.at(e.pos, format!("ENTRY '{}': the name is already the program's or another ENTRY's", e.name)));
        }
        for param in &e.using {
            if !layout.linkage_roots.iter().enumerate().any(|(o, &i)| layout.is_argument(o) && layout.items[i].name.as_deref() == Some(param.name.as_str())) {
                errors.push(syntax::messages::IWC0059.at(e.pos, format!("ENTRY '{}' USING {}: not an 01 or 77 item of the LINKAGE SECTION", e.name, param.name)));
            }
        }
    }
    let why_no_alter = if program.recursive {
        Some("a RECURSIVE program")
    } else if options.thread {
        Some("a program compiled with THREAD")
    } else {
        method.then_some("a method")
    };
    for p in &program.paragraphs {
        for s in &p.statements {
            let mut inner = Vec::new();
            oo::bodies(s).into_iter().for_each(|body| inner_statements(body, &mut inner));
            for (t, nested) in std::iter::once((s, false)).chain(inner.into_iter().map(|t| (t, true))) {
                match t {
                    Stmt::Entry { name, pos, .. } if nested => {
                        errors.push(syntax::messages::IWC0060.at(*pos, format!("ENTRY '{name}' must be a sentence of its own, not inside another statement")));
                    }
                    Stmt::GoTo { target: None, pos } => {
                        if let Some(why) = why_no_alter {
                            errors.push(syntax::messages::IWC0061.at(*pos, format!("a GO TO with no procedure-name cannot be used in {why}")));
                        }
                        if nested || !lone_go_to(p) {
                            errors.push(syntax::messages::IWC0062.at(*pos, "a GO TO with no procedure-name must be its paragraph's only sentence"));
                        }
                    }
                    Stmt::Alter { pairs, pos } => {
                        if let Some(why) = why_no_alter {
                            errors.push(syntax::messages::IWC0063.at(*pos, format!("ALTER cannot be used in {why}")));
                        }
                        for (from, to) in pairs {
                            altered_paragraph(program, from, *pos, errors);
                            if let Err(m) = procedure(program, to) {
                                errors.push(m.at(*pos));
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}

/// Enterprise COBOL's rules for the programs of a compilation (Language Reference, Conventions for
/// program-names): under strict scope two of them may not share a name, and under
/// `--unresolved-calls=fail` a static CALL must name one of them that it reaches, or a Language
/// Environment service, as IBM's binder must resolve it.
fn program_names(program: &Program, options: &Options, errors: &mut Vec<Error>) {
    let strict = options.program_scope == numeric::ProgramScope::Strict;
    if strict {
        for (name, pos) in &program.duplicates {
            let text = format!("{name}: two programs of {} have this name, and the programs of a separately compiled program each need their own (--program-scope=flexible allows it)", program.id);
            errors.push(syntax::messages::IWC0295.at(*pos, text));
        }
    }
    if options.unresolved_calls != numeric::UnresolvedCalls::Fail || options.dynam {
        return;
    }
    let reached = |name: &str| {
        let contained = program.callable.iter().chain(program.hidden.iter().filter(|_| !strict));
        program.linked.iter().chain(contained).any(|n| n.eq_ignore_ascii_case(name)) || rt::le::provides(&name.to_ascii_uppercase())
    };
    let mut all = Vec::new();
    program.paragraphs.iter().for_each(|p| inner_statements(&p.statements, &mut all));
    for s in all {
        if let Stmt::Call(c) = s
            && let Operand::Literal(Literal::Alnum(name)) = &c.target
            && !reached(name.trim_end())
        {
            let text = format!("CALL '{}': no program of the compilation has this name, and --unresolved-calls=fail refuses a static CALL the binder could not resolve", name.trim_end());
            errors.push(syntax::messages::IWC0296.at(c.pos, text));
        }
    }
}

/// Every statement inside `stmts`, at any depth.
fn inner_statements<'s>(stmts: &'s [Stmt], out: &mut Vec<&'s Stmt>) {
    for s in stmts {
        out.push(s);
        oo::bodies(s).into_iter().for_each(|body| inner_statements(body, out));
    }
}

/// A paragraph ALTER can name: one sentence, a GO TO without DEPENDING ON.
fn altered_paragraph(program: &Program, name: &ProcName, pos: Pos, errors: &mut Vec<Error>) {
    match procedure(program, name) {
        Err(m) => errors.push(m.at(pos)),
        Ok((i, _)) if program.paragraphs[i].is_section => errors.push(syntax::messages::IWC0064.at(pos, format!("ALTER {}: a section, where ALTER names a paragraph", name.name))),
        Ok((i, _)) if !lone_go_to(&program.paragraphs[i]) => {
            errors.push(syntax::messages::IWC0065.at(pos, format!("ALTER {}: the paragraph must hold one sentence, a GO TO without DEPENDING ON", name.name)));
        }
        Ok(_) => {}
    }
}

fn lone_go_to(p: &Paragraph) -> bool {
    matches!(p.statements.as_slice(), [Stmt::GoTo { .. }] | [Stmt::GoTo { .. }, Stmt::SentenceEnd])
}

/// The last paragraph of the section that paragraph `i` is in, or `i` when there are no sections.
/// END DECLARATIVES ends a section as a section header does.
pub fn section_end(program: &Program, i: usize) -> usize {
    let paragraphs = &program.paragraphs;
    let declaratives = program.report_writer.procedure_start;
    let (floor, ceiling) = if i < declaratives { (0, declaratives) } else { (declaratives, paragraphs.len()) };
    let Some(header) = (floor..=i).rev().find(|&j| paragraphs[j].is_section) else { return i };
    (header + 1..ceiling).take_while(|&j| !paragraphs[j].is_section).last().unwrap_or(header)
}

/// Qualifies each unqualified paragraph-name that more than one section holds with the section it
/// is written in, when that section holds it: within its own section a paragraph-name needs no
/// qualifier, so every later lookup must find that paragraph (assumption C151).
fn qualify_in_own_section(program: &mut Program) {
    for i in 0..program.paragraphs.len() {
        let Some(section) = program.paragraphs[i].section.clone() else { continue };
        let mut statements = std::mem::take(&mut program.paragraphs[i].statements);
        oo::each_mut(&mut statements, &mut |s| {
            for name in procedure_names_mut(s) {
                if name.section.is_none() && names_own_paragraph(&program.paragraphs, &name.name, &section) {
                    name.section = Some(section.clone());
                }
            }
        });
        program.paragraphs[i].statements = statements;
    }
}

/// Whether an unqualified `name` written in `section` names that section's own paragraph: more than
/// one procedure has the name, and `section` holds a paragraph of it.
fn names_own_paragraph(paragraphs: &[Paragraph], name: &str, section: &str) -> bool {
    paragraphs.iter().filter(|p| p.name == name).count() > 1 && paragraphs.iter().any(|p| p.name == name && !p.is_section && p.section.as_deref() == Some(section))
}

/// `procedure` for a name written in paragraph `from` that no statement holds as a procedure-name,
/// such as a WHENEVER or HANDLE label or a USE FOR DEBUGGING operand, qualified with `from`'s
/// section as `qualify_in_own_section` qualifies a statement's.
pub fn procedure_from(program: &Program, p: &ProcName, from: usize) -> Result<(usize, usize), Unnamed> {
    match program.paragraphs.get(from).and_then(|q| q.section.as_deref()) {
        Some(section) if p.section.is_none() && names_own_paragraph(&program.paragraphs, &p.name, section) => {
            procedure(program, &ProcName { name: p.name.clone(), section: Some(section.to_owned()) })
        }
        _ => procedure(program, p),
    }
}

/// An EVALUATE subject that is a condition-name is a condition, and so are its WHEN objects
/// written as names, which the parser could not tell from values.
/// A DBCS item's VALUE, and a condition-name's of a DBCS item, is a DBCS literal no longer than the
/// item, SPACE, or ALL with a DBCS literal; a DBCS literal is the VALUE of a DBCS item only
/// (Language Reference SC27-8713-03, pp. 248-249).
fn dbcs_values(layout: &Layout, errors: &mut Vec<Error>) {
    let dbcs = |i: usize| matches!(layout.items[i].kind, rt::storage::Kind::Dbcs { .. });
    let is_dbcs = |l: &Literal| matches!(l, Literal::Dbcs(_)) || matches!(l, Literal::All(inner) if matches!(**inner, Literal::Dbcs(_)));
    let fits = |l: &Literal, i: usize| match l {
        Literal::Dbcs(s) => s.chars().count() <= layout.items[i].size as usize / 2,
        Literal::Figurative(syntax::ast::Figurative::Space) => true,
        l => is_dbcs(l),
    };
    let values = layout.items.iter().enumerate().filter_map(|(i, it)| it.value.as_ref().map(|v| (i, v, it.pos)));
    let conditions = layout.conditions.iter().flat_map(|c| c.values.iter().flat_map(|(low, high)| std::iter::once(low).chain(high)).chain(&c.false_value).map(move |v| (c.item, v, layout.items[c.item].pos)));
    for (i, value, pos) in values.chain(conditions) {
        let name = layout.items[i].name.as_deref().unwrap_or("FILLER");
        if dbcs(i) && !fits(value, i) {
            errors.push(syntax::messages::IWC0066.at(pos, format!("{name}: a DBCS item's VALUE is a DBCS literal of at most {} characters, SPACE or ALL with a DBCS literal", layout.items[i].size / 2)));
        } else if !dbcs(i) && is_dbcs(value) {
            errors.push(syntax::messages::IWC0067.at(pos, format!("{name}: a DBCS literal can be the VALUE of a DBCS item only")));
        }
    }
}

/// The environment-names DISPLAY UPON takes, directly or by a mnemonic-name (Language Reference
/// SC27-8713-03, pp. 126, 334).
const DISPLAY_DEVICES: &[&str] = &["SYSOUT", "SYSLIST", "SYSLST", "SYSPUNCH", "SYSPCH", "CONSOLE"];

/// A numeric item's VALUE literal must be numeric (Language Reference SC27-8713-03, p. 246); a
/// figurative constant stands for a literal as its own rules allow (p. 17).
fn numeric_values(layout: &Layout, errors: &mut Vec<Error>) {
    for item in layout.items.iter().filter(|i| i.children.is_empty() && i.kind.is_numeric()) {
        let what = match item.value {
            Some(Literal::Alnum(_) | Literal::Hex(_)) => "an alphanumeric literal",
            Some(Literal::National(_)) => "a national literal",
            _ => continue,
        };
        let name = item.name.as_deref().unwrap_or("FILLER");
        errors.push(syntax::messages::IWC0068.at(item.pos, format!("VALUE of {name}: {what}, where a numeric item's VALUE literal must be numeric")));
    }
}

/// A numeric-edited item's VALUE is an alphanumeric literal, a national one under USAGE NATIONAL,
/// or a figurative constant, in edited form (Language Reference SC27-8713-03, pp. 246-247;
/// IGYGR1080-S). Micro Focus and GnuCOBOL also take a numeric literal, edited as a MOVE edits it.
fn edited_values(layout: &Layout, compliance: numeric::Compliance, errors: &mut Vec<Error>) {
    for item in layout.items.iter().filter(|i| matches!(i.kind, rt::storage::Kind::NumericEdited { .. }) && matches!(i.value, Some(Literal::Number(_)))) {
        let name = item.name.as_deref().unwrap_or("FILLER");
        errors.push(if compliance == numeric::Compliance::Extended {
            syntax::messages::IWX0012.at(item.pos, format!("a numeric literal as a numeric-edited item's VALUE (Micro Focus and GnuCOBOL; Enterprise COBOL takes an alphanumeric literal in edited form): {name} starts as the literal moved to it"))
        } else {
            syntax::messages::IWC0292.at(item.pos, format!("VALUE of {name}: a numeric literal, where a numeric-edited item's VALUE is an alphanumeric literal or a figurative constant written in edited form; --compliance extended edits the number into it"))
        });
    }
}

fn condition_subjects(program: &mut Program, layout: &Layout) {
    let is_condition = |r: &Ref| matches!(layout.resolve(&r.name, &r.qualifiers, r.pos), Ok(layout::Resolved::Condition(_)));
    for p in &mut program.paragraphs {
        oo::each_mut(&mut p.statements, &mut |s| {
            let Stmt::Evaluate { subjects, whens, .. } = s else { return };
            for (k, subject) in subjects.iter_mut().enumerate() {
                let Subject::Expr(Expr::Operand(Operand::Ref(r))) = subject else { continue };
                if !is_condition(r) {
                    continue;
                }
                *subject = Subject::Cond(Cond::Name(r.clone()));
                for alternative in whens.iter_mut().flat_map(|w| w.alternatives.iter_mut()) {
                    let cond = match alternative.get(k) {
                        Some(Object::Value { not, from: Expr::Operand(Operand::Ref(o)), thru: None }) => {
                            let c = Cond::Name(o.clone());
                            if *not { Cond::Not(Box::new(c)) } else { c }
                        }
                        _ => continue,
                    };
                    alternative[k] = Object::Cond(cond);
                }
            }
        });
    }
}

/// The procedure-names statement `s` itself names, not those of the statements it holds.
fn procedure_names_mut(s: &mut Stmt) -> Vec<&mut ProcName> {
    match s {
        Stmt::PerformProc { from, thru, .. } => std::iter::once(from).chain(thru.as_mut()).collect(),
        Stmt::GoTo { target, .. } => target.iter_mut().collect(),
        Stmt::GoToDepending { targets, .. } => targets.iter_mut().collect(),
        Stmt::Alter { pairs, .. } => pairs.iter_mut().flat_map(|(from, to)| [from, to]).collect(),
        Stmt::XmlParse(x) => std::iter::once(&mut x.procedure).chain(x.thru.as_mut()).collect(),
        Stmt::Sorting(so) => match &mut **so {
            Sorting::Sort(st) => [st.input.as_mut(), st.output.as_mut()]
                .into_iter()
                .flatten()
                .flat_map(|io| match io {
                    SortIo::Procedure { from, thru } => std::iter::once(from).chain(thru.as_mut()).collect(),
                    SortIo::Files(_) => Vec::new(),
                })
                .collect(),
            _ => Vec::new(),
        },
        _ => Vec::new(),
    }
}

/// Why a procedure-name names no one procedure: the catalogue's message and its text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unnamed {
    pub message: Message,
    pub text: String,
}

impl Unnamed {
    pub fn at(self, pos: Pos) -> Error {
        self.message.at(pos, self.text)
    }
}

impl std::fmt::Display for Unnamed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text)
    }
}

impl From<Unnamed> for String {
    fn from(u: Unnamed) -> Self {
        u.text
    }
}

/// The first and last paragraph a procedure name covers: one paragraph, or a whole section.
pub fn procedure(program: &Program, p: &ProcName) -> Result<(usize, usize), Unnamed> {
    let found: Vec<usize> = program
        .paragraphs
        .iter()
        .enumerate()
        .filter(|(_, q)| q.name == p.name && (p.section.is_none() || (q.section == p.section && !q.is_section)))
        .map(|(i, _)| i)
        .collect();
    match found.as_slice() {
        [i] if program.paragraphs[*i].is_section => Ok((*i, section_end(program, *i))),
        [i] => Ok((*i, *i)),
        [] => Err(Unnamed { message: IWC0003, text: format!("no paragraph or section named {}", p.name) }),
        _ => Err(Unnamed { message: IWC0004, text: format!("{} names more than one paragraph; qualify it with OF and its section", p.name) }),
    }
}

/// An 01 or 77 entry with OCCURS, which Micro Focus and GnuCOBOL take and Enterprise COBOL does not,
/// read under `--compliance extended` as an unnamed 01 group holding the table one level down, its
/// subordinate entries a level lower too, with IWX0019-W. An entry REDEFINES, EXTERNAL or GLOBAL
/// names, or one with a level-49 entry under it, is left for the layout to refuse (IWC0027).
/// Assumption C461.
/// Returns where each record was inserted, counted in the entries as they were before.
fn top_level_tables(entries: &mut Vec<DataEntry>, errors: &mut Vec<Error>) -> Vec<usize> {
    let mut inserted = Vec::new();
    let mut at = 0;
    while at < entries.len() {
        let e = &entries[at];
        let end = at + 1 + entries[at + 1..].iter().take_while(|d| (2..=49).contains(&d.level) || d.level == 88).count();
        let movable = matches!(e.level, 1 | 77) && e.occurs.is_some() && e.redefines.is_none() && !e.external && !e.global && entries[at + 1..end].iter().all(|d| d.level != 49);
        if !movable {
            at = end.max(at + 1);
            continue;
        }
        let name = e.name.clone().unwrap_or_else(|| "FILLER".into());
        errors.push(syntax::messages::IWX0019.at(e.pos, format!("OCCURS at level {:02} (Micro Focus and GnuCOBOL; Enterprise COBOL takes OCCURS only at levels 02 to 49): {name} is read as a table in a record of its own", e.level)));
        let record = DataEntry { level: 1, name: None, spelled: None, picture: None, usage: None, value: None, redefines: None, occurs: None, occurs_min: None, depending_on: None, sign: None, justified: false, sync: false, blank_when_zero: false, indexed_by: Vec::new(), keys: Vec::new(), condition_values: Vec::new(), false_value: None, renames: None, object_class: None, external: false, global: false, any_length: false, based: false, pos: e.pos };
        for d in &mut entries[at..end] {
            if d.level != 88 {
                d.level = if d.level == 77 { 2 } else { d.level + 1 };
            }
        }
        entries.insert(at, record);
        inserted.push(at - inserted.len());
        at = end + 1;
    }
    inserted
}

/// Level-66 entries followed by an entry of levels 02 to 49 of the same record, which cobc 3.2
/// takes under its IBM and Micro Focus dialects, moved under `--compliance extended` to follow the
/// record's last entry, with IWX0032-W. A RENAMES names what it renames, so where it stands changes
/// no storage. One followed by a level-88 entry is left for the layout to refuse (IWC0028).
/// Assumption C471.
fn renames_inside_records(entries: &mut [DataEntry], errors: &mut Vec<Error>) {
    let mut at = 0;
    while at < entries.len() {
        if entries[at].level != 66 {
            at += 1;
            continue;
        }
        let run = entries[at..].iter().take_while(|e| e.level == 66).count();
        let next = at + run;
        if !entries.get(next).is_some_and(|e| (2..=49).contains(&e.level)) {
            at = next;
            continue;
        }
        let record = entries[..at].iter().rev().find(|e| e.level == 1).and_then(|e| e.name.clone()).unwrap_or_else(|| "FILLER".into());
        let end = next + entries[next..].iter().take_while(|e| !matches!(e.level, 1 | 66 | 77)).count();
        for e in &entries[at..next] {
            let name = e.name.as_deref().unwrap_or("FILLER");
            errors.push(syntax::messages::IWX0032.at(e.pos, format!("a level-66 entry before the end of its record (GnuCOBOL's IBM and Micro Focus dialects; Enterprise COBOL writes a record's RENAMES entries after its last entry): {name} is read as following {record}'s last entry")));
        }
        entries[at..end].rotate_left(run);
        at = end - run;
    }
}

/// A paragraph or section named FOREVER where PERFORM FOREVER is read as the endless loop
/// (`--compliance extended`): Enterprise COBOL would perform it.
fn forever_names(program: &Program, errors: &mut Vec<Error>) {
    let mut endless = false;
    for p in &program.paragraphs {
        oo::each(&p.statements, &mut |s| endless |= matches!(s, Stmt::PerformInline { repeat: Loop::Forever, .. } | Stmt::PerformProc { repeat: Loop::Forever, .. }));
    }
    if !endless {
        return;
    }
    for p in program.paragraphs.iter().filter(|p| p.name == "FOREVER") {
        let what = if p.is_section { "SECTION" } else { "paragraph" };
        errors.push(syntax::messages::IWC0304.at(p.pos, format!("{what} FOREVER: under --compliance extended PERFORM FOREVER is Micro Focus's and GnuCOBOL's endless loop, not a PERFORM of it; compile the program under strict")));
    }
}

/// BASED records of WORKING-STORAGE and LOCAL-STORAGE, GnuCOBOL's and Micro Focus's items with no
/// storage until SET ADDRESS OF gives them some, moved with what is subordinate to them to the
/// LINKAGE SECTION, where Enterprise COBOL describes such items, with IWX0046-W (assumption C486).
/// Gives `declared`, the count of WORKING-STORAGE entries the source declares, less those moved.
fn based_items(program: &mut Program, declared: usize, errors: &mut Vec<Error>) -> usize {
    let mut moved = Vec::new();
    let mut declared_left = declared;
    for (entries, storage) in [(&mut program.working_storage, true), (&mut program.local_storage, false)] {
        let mut kept = Vec::with_capacity(entries.len());
        let mut taking = false;
        for (k, e) in std::mem::take(entries).into_iter().enumerate() {
            if e.based && !matches!(e.level, 1 | 77) {
                errors.push(syntax::messages::IWR0077.at(e.pos, format!("BASED on {}: ironwork reads BASED on an 01 or 77 entry", e.name.as_deref().unwrap_or("FILLER"))));
            }
            if matches!(e.level, 1 | 77) {
                taking = e.based;
                if taking {
                    let name = e.name.as_deref().unwrap_or("FILLER");
                    errors.push(syntax::messages::IWX0046.at(e.pos, format!("BASED (GnuCOBOL and Micro Focus; Enterprise COBOL describes such an item in the LINKAGE SECTION): {name} has no storage until SET ADDRESS OF gives it some")));
                }
            }
            if taking {
                declared_left -= usize::from(storage && k < declared);
                moved.push(e);
            } else {
                kept.push(e);
            }
        }
        *entries = kept;
    }
    program.linkage.extend(moved);
    declared_left
}

/// BINARY-CHAR, Micro Focus's and GnuCOBOL's one-byte binary: a warning naming its range under
/// `--compliance extended` (assumption C460), refused under strict.
fn binary_chars(program: &Program, options: &Options, errors: &mut Vec<Error>) {
    let entries = program.working_storage.iter().chain(&program.local_storage).chain(&program.linkage).chain(program.files.iter().flat_map(|f| &f.records));
    for e in entries {
        let Some(Usage::BinaryChar { signed }) = e.usage else { continue };
        if options.compliance == numeric::Compliance::Strict {
            errors.push(syntax::messages::IWC0293.at(e.pos, "BINARY-CHAR: Micro Focus's and GnuCOBOL's one-byte binary, not Enterprise COBOL's; --compliance extended reads it"));
            continue;
        }
        let name = e.name.as_deref().unwrap_or("FILLER");
        let range = if signed { "-128 to 127" } else { "0 to 255" };
        errors.push(syntax::messages::IWX0016.at(e.pos, format!("BINARY-CHAR (Micro Focus and GnuCOBOL; Enterprise COBOL's binary items are two, four or eight bytes): {name} is one byte of binary, {range}")));
    }
}

/// COMP-X, and COMP-5 with an alphanumeric PICTURE, Micro Focus's binary of one to eight bytes: a
/// warning naming its bytes and range under `--compliance extended` (assumptions C467 and C468),
/// refused under strict. Layout refuses a PIC X(n) of more than eight bytes.
fn micro_focus_binaries(program: &Program, options: &Options, errors: &mut Vec<Error>) {
    let entries = program.working_storage.iter().chain(&program.local_storage).chain(&program.linkage).chain(program.files.iter().flat_map(|f| &f.records));
    for e in entries {
        let Some(usage @ (Usage::CompX | Usage::NativeBinary)) = e.usage else { continue };
        let Some(pic) = e.picture.as_deref().and_then(|p| picture::analyse(p).ok()) else { continue };
        let (native, digits, signed) = match (usage, pic.category) {
            (Usage::CompX, picture::Category::Numeric) if pic.digits <= 18 => (numeric::Native::CompX, pic.digits as u8, pic.signed),
            (Usage::CompX, picture::Category::Alphanumeric) if pic.size <= 8 => (numeric::Native::CompX, numeric::binary::alphanumeric_digits(pic.size), false),
            (Usage::NativeBinary, picture::Category::Alphanumeric) if pic.size <= 8 => (numeric::Native::Comp5Bytes, numeric::binary::alphanumeric_digits(pic.size), false),
            _ => continue,
        };
        if options.compliance == numeric::Compliance::Strict {
            errors.push(if native == numeric::Native::CompX {
                syntax::messages::IWC0301.at(e.pos, "COMP-X: Micro Focus's binary in the fewest bytes its digits need, not Enterprise COBOL's; --compliance extended reads it")
            } else {
                syntax::messages::IWC0302.at(e.pos, "PIC X(n) COMP-5: Micro Focus's and GnuCOBOL's binary of n bytes, where Enterprise COBOL's COMP-5 takes a numeric PICTURE; --compliance extended reads it")
            });
            continue;
        }
        let name = e.name.as_deref().unwrap_or("FILLER");
        let bytes = numeric::binary::Binary { digits, signed, native }.bytes();
        let bits = 8 * bytes as u32;
        let range = if signed { format!("-{} to {}", 1u64 << (bits - 1), (1u64 << (bits - 1)) - 1) } else { format!("0 to {}", u64::MAX >> (64 - bits)) };
        let plural = if bytes == 1 { "" } else { "s" };
        errors.push(if native == numeric::Native::CompX {
            syntax::messages::IWX0025.at(e.pos, format!("COMP-X (Micro Focus; Enterprise COBOL's binary items are two, four or eight bytes): {name} is {bytes} byte{plural} of binary, {range}, shown in {digits} digits"))
        } else {
            syntax::messages::IWX0026.at(e.pos, format!("PIC X(n) COMP-5 (Micro Focus and GnuCOBOL; Enterprise COBOL's COMP-5 takes a numeric PICTURE): {name} is {bytes} byte{plural} of binary, {range}"))
        });
    }
}

/// Under ARITH(COMPAT) a numeric or numeric-edited PICTURE, scaling positions P included, and a
/// fixed-point numeric literal hold at most 18 digits, and under ARITH(EXTEND) 31 (Language
/// Reference SC27-8713-03, pp. 45, 209, 217-218; Programming Guide SC27-8714-03, p. 349).
fn digit_limits(program: &Program, arith: numeric::options::Arith, errors: &mut Vec<Error>) {
    let max = arith.max_picture_digits();
    let option = match arith {
        numeric::options::Arith::Compat => "ARITH(COMPAT)",
        numeric::options::Arith::Extend => "ARITH(EXTEND)",
    };
    let entries = program.working_storage.iter().chain(&program.local_storage).chain(&program.linkage).chain(program.files.iter().flat_map(|f| &f.records));
    for e in entries {
        if let Some(p) = e.picture.as_deref()
            && let Ok(pic) = picture::analyse_with(p, crate::picture::Notation::of(&program.environment))
            && matches!(pic.category, picture::Category::Numeric | picture::Category::NumericEdited)
        {
            let positions = pic.digits + pic.scaling + pic.scale.saturating_sub(pic.digits);
            if positions > max {
                errors.push(syntax::messages::IWC0069.at(e.pos, format!("PICTURE {p}: {positions} digit positions, more than the {max} {option} allows")));
            }
        }
        let values = e.value.iter().chain(e.condition_values.iter().flat_map(|(low, high)| std::iter::once(low).chain(high))).chain(&e.false_value);
        for v in values {
            if let Literal::Number(t) = v
                && literal_digits(t) > max as usize
            {
                errors.push(syntax::messages::IWC0070.at(e.pos, format!("the literal {t} has more than the {max} digits {option} allows")));
            }
        }
    }
}

fn literal_digits(t: &str) -> usize {
    t.chars().filter(char::is_ascii_digit).count()
}

/// The usage of an INSPECT operand's characters.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CharUsage {
    Display,
    National,
    Dbcs,
}

impl CharUsage {
    fn of(kind: rt::storage::Kind) -> Self {
        match kind {
            rt::storage::Kind::National => Self::National,
            rt::storage::Kind::Dbcs { .. } => Self::Dbcs,
            _ => Self::Display,
        }
    }
}

impl std::fmt::Display for CharUsage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Display => "DISPLAY",
            Self::National => "national",
            Self::Dbcs => "DBCS",
        })
    }
}

/// How an INSPECT message names a literal, and its usage; None for a figurative constant, which
/// takes the inspected item's usage.
fn inspected_literal(l: &Literal) -> Option<(&'static str, CharUsage)> {
    match l {
        Literal::Figurative(_) => None,
        Literal::All(inner) => inspected_literal(inner),
        Literal::National(_) => Some(("a national literal", CharUsage::National)),
        Literal::Dbcs(_) => Some(("a DBCS literal", CharUsage::Dbcs)),
        Literal::Number(_) => Some(("a numeric literal", CharUsage::Display)),
        Literal::Alnum(_) | Literal::Hex(_) => Some(("an alphanumeric literal", CharUsage::Display)),
    }
}

/// Resolves every name before the program runs, so a misspelling is a compile error.
/// The condition-names a JSON PARSE USING phrase names.
fn flag_conditions(flag: &Flag) -> Vec<&Ref> {
    match flag {
        Flag::Condition(c) => vec![c],
        Flag::Conditions(on, off) => vec![on, off],
        Flag::Literals(..) => Vec::new(),
    }
}

struct Check<'a> {
    layout: &'a Layout,
    program: &'a Program,
    errors: &'a mut Vec<Error>,
    /// The statements are a debugging section's, which alone may reference DEBUG-ITEM.
    debugging: bool,
    /// The most digits a numeric literal has under the program's ARITH option.
    max_digits: u32,
    /// How many inline PERFORMs the statement is inside.
    inline_performs: usize,
    /// The user-defined functions the statements may invoke; None where none can be.
    functions: Option<&'a [function::Udf]>,
    /// Where each item of category alphabetic is declared.
    alphabetic: &'a [Pos],
    /// The statement whose conditions are being checked, which their messages name.
    at: Pos,
    /// The paragraph the statements are in, from which a HANDLE label is found.
    paragraph: usize,
    /// `--compliance extended` is in force.
    extended: bool,
    /// Where an ACCEPT ... FROM ENVIRONMENT's DISPLAY UPON ENVIRONMENT-NAME is, whose ACCEPT the
    /// message is given at.
    environment_named: Option<Pos>,
}

impl Check<'_> {
    fn statements(&mut self, stmts: &[Stmt]) {
        for s in stmts {
            self.statement(s);
        }
    }

    fn statement(&mut self, s: &Stmt) {
        linage::check_receivers(self.layout, s, self.errors);
        if let Stmt::If { pos, .. } | Stmt::Evaluate { pos, .. } | Stmt::PerformInline { pos, .. } | Stmt::PerformProc { pos, .. } = s {
            self.at = *pos;
        }
        if let Stmt::Search(se) = s {
            self.at = se.pos;
        }
        match s {
            Stmt::Move { from, to, .. } => {
                self.operand(from);
                if let Operand::Function(f) = from {
                    self.moved_function(f);
                }
                to.iter().for_each(|r| self.reference(r));
            }
            Stmt::Compute { targets, expr, size_error, .. } => {
                for t in targets {
                    self.reference(&t.r);
                    self.arithmetic_receiver("COMPUTE", &t.r);
                }
                self.expr(expr);
                self.size_error(size_error.as_ref());
            }
            Stmt::Arith(a) => {
                let verb = match a.verb {
                    ArithVerb::Add => "ADD",
                    ArithVerb::Subtract => "SUBTRACT",
                    ArithVerb::Multiply => "MULTIPLY",
                    ArithVerb::Divide => "DIVIDE",
                };
                for (t, e) in &a.computations {
                    self.reference(&t.r);
                    self.arithmetic_receiver(verb, &t.r);
                    self.expr(e);
                }
                if let Some((t, x, y)) = &a.remainder {
                    self.reference(&t.r);
                    self.arithmetic_receiver(verb, &t.r);
                    self.expr(x);
                    self.expr(y);
                }
                self.size_error(a.size_error.as_ref());
            }
            Stmt::If { cond, then, otherwise, .. } => {
                self.cond(cond);
                self.statements(then);
                self.statements(otherwise);
            }
            Stmt::PerformInline { body, repeat, .. } => {
                self.repeat(repeat);
                self.inline_performs += 1;
                self.statements(body);
                self.inline_performs -= 1;
            }
            Stmt::PerformProc { from, thru, repeat, pos } => {
                self.procedure(from, *pos);
                if let Some(t) = thru {
                    self.procedure(t, *pos);
                }
                self.repeat(repeat);
            }
            Stmt::Evaluate { subjects, whens, other, pos } => {
                for subject in subjects {
                    match subject {
                        Subject::Expr(e) => self.expr(e),
                        Subject::Cond(c) => self.cond(c),
                        Subject::Bool(_) => {}
                    }
                }
                for w in whens {
                    for alternative in &w.alternatives {
                        for (subject, object) in subjects.iter().zip(alternative) {
                            match object {
                                Object::Any => {}
                                Object::Bool(_) | Object::Cond(_) if matches!(subject, Subject::Expr(_)) => {
                                    self.errors.push(syntax::messages::IWC0071.at(*pos, "a condition as the WHEN object of a value subject"));
                                }
                                Object::Bool(_) => {}
                                Object::Cond(c) => self.cond(c),
                                Object::Value { .. } if !matches!(subject, Subject::Expr(_)) => {
                                    self.errors.push(syntax::messages::IWC0072.at(*pos, "a value as the WHEN object of a TRUE, FALSE or condition subject"));
                                }
                                Object::Value { from, thru, .. } => {
                                    self.expr(from);
                                    if let Some(t) = thru {
                                        self.expr(t);
                                    }
                                    if let Subject::Expr(e) = subject {
                                        std::iter::once(from).chain(thru).for_each(|o| self.comparison(e, o));
                                    }
                                }
                            }
                        }
                    }
                    self.statements(&w.body);
                }
                self.statements(other);
            }
            Stmt::Display { items, upon, screen, pos, .. } => {
                for o in items {
                    self.operand(o);
                    if let Operand::Function(f) = o {
                        self.displayed_function(f);
                    }
                }
                if let Some(screen) = screen.as_deref().filter(|s| s.screen.is_none()) {
                    self.screen("DISPLAY", screen);
                }
                if let Some(upon) = upon
                    && matches!(upon.device.as_str(), "ENVIRONMENT-NAME" | "ENVIRONMENT-VALUE")
                {
                    self.environment_display(upon, *pos);
                } else if let Some(upon) = upon
                    && upon.device == "ARGUMENT-NUMBER"
                {
                    self.argument_number(items, *pos);
                } else if let Some(upon) = upon
                    && upon.device == "SYSERR"
                    && self.extended
                {
                    self.errors.push(syntax::messages::IWX0056.at(*pos, "DISPLAY UPON SYSERR (GnuCOBOL and Micro Focus; Enterprise COBOL has no such device): the line is written to the run's standard error"));
                } else if let Some(upon) = upon
                    && !DISPLAY_DEVICES.contains(&upon.device.as_str())
                {
                    let why = if upon.name == upon.device {
                        "neither an environment-name DISPLAY writes to, SYSOUT, SYSLIST, SYSLST, SYSPUNCH, SYSPCH or CONSOLE, nor a mnemonic-name for one".to_owned()
                    } else {
                        format!("a mnemonic-name for {}, which DISPLAY does not write to", upon.device)
                    };
                    self.errors.push(syntax::messages::IWC0073.at(*pos, format!("DISPLAY UPON {}: {why}", upon.name)));
                }
            }
            Stmt::Open { files, pos } => files.iter().for_each(|(_, f)| self.file(f, *pos)),
            Stmt::DeleteFile { files, pos } => files.iter().for_each(|name| self.file(name, *pos)),
            Stmt::Close { files, pos } => {
                for (name, closing) in files {
                    self.file(name, *pos);
                    let keyed = self.program.files.iter().any(|f| f.name == *name && matches!(f.organization, Organization::Indexed | Organization::Relative));
                    if keyed && matches!(closing, Some(Closing::Volume | Closing::NoRewind)) {
                        self.errors.push(syntax::messages::IWC0074.at(*pos, format!("CLOSE {name}: REEL, UNIT and NO REWIND are not valid for an indexed or relative file")));
                    }
                }
            }
            Stmt::Read(r) => {
                self.file(&r.file, r.pos);
                if r.next {
                    self.not_random(&r.file, "READ NEXT", r.pos);
                }
                if let Some(into) = &r.into {
                    self.reference(into);
                }
                if let Some(key) = &r.key {
                    self.key_of(&r.file, key, false);
                }
                self.handlers(&r.at_end);
                self.handlers(&r.invalid);
            }
            Stmt::Write { record, from, invalid, pos, .. } | Stmt::Rewrite { record, from, invalid, pos } => {
                let verb = if matches!(s, Stmt::Write { .. }) { "WRITE" } else { "REWRITE" };
                self.reference(record);
                if let Ok(layout::Resolved::Item(i)) = self.layout.resolve(&record.name, &record.qualifiers, record.pos)
                    && self.layout.items[i].file.is_none()
                {
                    self.errors.push(syntax::messages::IWC0075.at(*pos, format!("{verb} {}: not a record of a file", record.name)));
                }
                if let Some(op) = from {
                    self.operand(op);
                }
                if let Stmt::Write { advancing, end_of_page, .. } = s {
                    if let Some(a) = advancing {
                        if let Advancing::Lines { count, .. } = a {
                            self.expr(count);
                        }
                        printer::check_write(self.program, self.layout, record, a, self.extended, *pos, self.errors);
                    }
                    linage::check_write(self.program, self.layout, record, advancing.as_ref(), end_of_page, *pos, self.errors);
                    self.handlers(end_of_page);
                }
                self.handlers(invalid);
            }
            Stmt::Delete { file, invalid, pos } => {
                self.keyed_file(file, "DELETE", *pos);
                self.handlers(invalid);
            }
            Stmt::Start { file, key, invalid, pos } => {
                self.keyed_file(file, "START", *pos);
                self.not_random(file, "START", *pos);
                if let Some((op, r)) = key {
                    if self.extended && matches!(op, RelOp::Lt | RelOp::Le) {
                        let written = if *op == RelOp::Lt { "<" } else { "NOT > or <=" };
                        self.errors.push(syntax::messages::IWX0036.at(*pos, format!("START KEY {written} (Micro Focus and GnuCOBOL; Enterprise COBOL's START takes =, >, NOT < or >=): the file is positioned at the last record whose key is {written} the value, which READ NEXT or READ PREVIOUS reads first")));
                    } else if !matches!(op, RelOp::Eq | RelOp::Gt | RelOp::Ge) {
                        self.errors.push(syntax::messages::IWC0076.at(*pos, "START KEY takes =, >, NOT < or >="));
                    }
                    self.key_of(file, r, true);
                }
                self.handlers(invalid);
            }
            Stmt::Initialize { targets, with, pos } => {
                for r in targets {
                    self.reference(r);
                    if self.item(r).is_some_and(|i| self.layout.items[i].level == 66) {
                        self.errors.push(syntax::messages::IWC0077.at(*pos, format!("INITIALIZE {}: a level-66 RENAMES item cannot be initialized", r.name)));
                    }
                    let items = &self.layout.items;
                    if self.item(r).is_some_and(|i| !items[i].moved_by.is_empty() || items[i].odo.iter().any(|&t| items[t].followed)) {
                        self.errors.push(syntax::messages::IWC0078.at(*pos, format!("INITIALIZE {}: a variably located item, or a group holding one, cannot be initialized (Language Reference p. 351)", r.name)));
                    }
                }
                if let Some(with) = with {
                    with.replacing.iter().for_each(|(_, by)| self.operand(by));
                    self.initialize_incompatible(targets, with, *pos);
                }
            }
            Stmt::GoTo { target: Some(target), pos } => self.procedure(target, *pos),
            Stmt::GoToDepending { targets, on, pos } => {
                targets.iter().for_each(|t| self.procedure(t, *pos));
                self.reference(on);
            }
            Stmt::GoTo { target: None, .. } | Stmt::Alter { .. } | Stmt::Entry { .. } => {}
            Stmt::Call(c) => {
                self.operand(&c.target);
                for arg in &c.using {
                    if let Some(op) = &arg.value {
                        self.operand(op);
                    }
                }
                if let Some(r) = &c.returning {
                    self.reference(r);
                }
                self.statements(c.on_exception.as_deref().unwrap_or_default());
                self.statements(c.not_on_exception.as_deref().unwrap_or_default());
            }
            Stmt::Cancel { targets, .. } => targets.iter().for_each(|t| self.operand(t)),
            Stmt::Set { set, .. } => match set {
                SetStmt::ConditionTrue(targets) => {
                    for r in targets {
                        self.reference_or_condition(r);
                        if let Ok(layout::Resolved::Condition(c)) = self.layout.resolve(&r.name, &r.qualifiers, r.pos)
                            && let Some(e) = switches::without_variable(self.layout, c, r)
                        {
                            self.errors.push(e);
                        }
                    }
                }
                SetStmt::ConditionFalse(targets) => {
                    for r in targets {
                        self.reference_or_condition(r);
                        if let Ok(layout::Resolved::Condition(c)) = self.layout.resolve(&r.name, &r.qualifiers, r.pos)
                            && self.layout.conditions[c].false_value.is_none()
                        {
                            self.errors.push(syntax::messages::IWC0079.at(r.pos, format!("SET {} TO FALSE: the condition-name has no WHEN SET TO FALSE value", r.name)));
                        }
                    }
                }
                SetStmt::To { targets, value } | SetStmt::Entry { targets, entry: value } => {
                    targets.iter().for_each(|r| self.reference(r));
                    self.operand(value);
                }
                SetStmt::AddressOf { targets, value } => {
                    targets.iter().for_each(|r| self.reference(r));
                    targets.iter().for_each(|r| scope::set_address(self.layout, r, self.errors));
                    self.operand(value);
                }
                SetStmt::UpDown { targets, by, .. } => {
                    targets.iter().for_each(|r| self.reference(r));
                    self.expr(by);
                }
                SetStmt::Switches(_) => {}
            },
            Stmt::Accept { target, from, exception, screen, pos } => {
                match screen {
                    Some(screen) if screen.screen.is_some() => {
                        for i in &screen.inputs {
                            self.reference(&i.field);
                            self.reference(&i.target);
                        }
                    }
                    Some(screen) => {
                        self.reference(target);
                        self.screen("ACCEPT", screen);
                    }
                    None => {
                        self.reference(target);
                        self.accept_source(*from, exception, target, *pos);
                    }
                }
                self.statements(exception.on.as_deref().unwrap_or_default());
                self.statements(exception.not_on.as_deref().unwrap_or_default());
            }
            Stmt::String(st) => {
                for (op, delimiter) in &st.sources {
                    self.operand(op);
                    if let Delimiter::By(d) = delimiter {
                        self.operand(d);
                    }
                }
                self.reference(&st.into);
                if let Some(p) = &st.pointer {
                    self.reference(p);
                }
                self.statements(st.on_overflow.as_deref().unwrap_or_default());
                self.statements(st.not_on_overflow.as_deref().unwrap_or_default());
            }
            Stmt::Unstring(u) => {
                self.reference(&u.source);
                u.delimiters.iter().for_each(|(_, d)| self.operand(d));
                for into in &u.into {
                    self.reference(&into.target);
                    into.delimiter_in.iter().chain(&into.count_in).for_each(|r| self.reference(r));
                }
                u.pointer.iter().chain(&u.tallying).for_each(|r| self.reference(r));
                self.statements(u.on_overflow.as_deref().unwrap_or_default());
                self.statements(u.not_on_overflow.as_deref().unwrap_or_default());
            }
            Stmt::Inspect(i) => {
                self.operand(&i.target);
                match &i.target {
                    Operand::Function(f) => self.inspected_function(f, i),
                    Operand::Ref(r) => self.inspected_usage(r, i),
                    _ => {}
                }
                for p in i.tallying.iter().chain(&i.replacing) {
                    p.pattern.iter().chain(&p.by).for_each(|o| self.operand(o));
                    if let Some(c) = &p.counter {
                        self.reference(c);
                    }
                    p.bounds.iter().for_each(|b| self.operand(&b.value));
                }
                if let Some((from, to, bounds)) = &i.converting {
                    self.operand(from);
                    self.operand(to);
                    bounds.iter().for_each(|b| self.operand(&b.value));
                }
            }
            Stmt::Search(se) => {
                self.reference_unsubscripted(&se.table);
                if let Some(v) = &se.varying {
                    self.reference(v);
                    self.search_varying(se, v);
                }
                self.statements(se.at_end.as_deref().unwrap_or_default());
                for (cond, body) in &se.whens {
                    self.cond(cond);
                    self.statements(body);
                }
            }
            Stmt::Exec(block) => self.exec_block(block),
            Stmt::Report(r) => report::check_statement(self.program, r, self.errors),
            Stmt::Invoke(i) => self.invoke(i),
            Stmt::XmlParse(x) => {
                self.reference(&x.document);
                if let Some(op) = &x.encoding {
                    self.operand(op);
                }
                self.procedure(&x.procedure, x.pos);
                if let Some(t) = &x.thru {
                    self.procedure(t, x.pos);
                }
                self.statements(x.on_exception.as_deref().unwrap_or_default());
                self.statements(x.not_on_exception.as_deref().unwrap_or_default());
            }
            Stmt::JsonParse(j) => {
                self.reference(&j.source);
                self.whole_table_reference(&j.into);
                let mut named: Vec<&Ref> = j.names.iter().map(|(r, _)| r).chain(&j.suppress).chain(j.ignoring.iter().flatten()).collect();
                for (item, flag, indicator) in &j.indicating {
                    named.push(item);
                    named.extend(indicator);
                    named.extend(flag_conditions(flag));
                }
                for (item, conversion) in &j.converting {
                    named.push(item);
                    if let ParseConversion::Boolean(flag) = conversion {
                        named.extend(flag_conditions(flag));
                    }
                }
                named.into_iter().for_each(|r| self.reference_unsubscripted(r));
                if let Some(Encoding::Ccsid(op)) = &j.encoding {
                    self.operand(op);
                }
                self.statements(j.on_exception.as_deref().unwrap_or_default());
                self.statements(j.not_on_exception.as_deref().unwrap_or_default());
            }
            Stmt::XmlGenerate(x) => {
                for r in [&x.receiver, &x.from].into_iter().chain(&x.count) {
                    self.reference(r);
                }
                let named = x.names.iter().map(|(r, _)| r).chain(x.types.iter().map(|(r, _)| r));
                let suppressed = x.suppress.iter().filter_map(|s| if let Suppression::Item { item, .. } = s { Some(item) } else { None });
                named.chain(suppressed).for_each(|r| self.reference_unsubscripted(r));
                for op in [&x.encoding, &x.namespace, &x.prefix].into_iter().flatten() {
                    self.operand(op);
                }
                self.statements(x.on_exception.as_deref().unwrap_or_default());
                self.statements(x.not_on_exception.as_deref().unwrap_or_default());
            }
            Stmt::JsonGenerate(g) => {
                for r in [&g.receiver].into_iter().chain(&g.count) {
                    self.reference(r);
                }
                self.whole_table_reference(&g.from);
                let mut named: Vec<&Ref> = g.names.iter().map(|(r, _)| r).collect();
                for s in &g.suppress {
                    if let Suppression::Item { item, .. } = s {
                        named.push(item);
                    }
                }
                for (item, conversion) in &g.converting {
                    named.push(item);
                    if let JsonConversion::Boolean(Marker::Condition(c)) = conversion {
                        named.push(c);
                    }
                }
                for i in &g.indicating {
                    named.push(&i.item);
                    named.extend(&i.indicator);
                    if let Marker::Condition(c) = &i.marker {
                        named.push(c);
                    }
                }
                named.into_iter().for_each(|r| self.reference_unsubscripted(r));
                if let Some(Encoding::Ccsid(op)) = &g.encoding {
                    self.operand(op);
                }
                self.statements(g.on_exception.as_deref().unwrap_or_default());
                self.statements(g.not_on_exception.as_deref().unwrap_or_default());
            }
            Stmt::Sorting(s) => self.sorting(s),
            // Language Reference SC27-8713-03, p. 344.
            Stmt::Exit { kind: kind @ (ExitKind::Perform | ExitKind::PerformCycle), pos } if self.inline_performs == 0 => {
                let exit = if *kind == ExitKind::Perform { "EXIT PERFORM" } else { "EXIT PERFORM CYCLE" };
                self.errors.push(syntax::messages::IWC0080.at(*pos, format!("{exit} must be inside an inline PERFORM")));
            }
            Stmt::Goback { .. } | Stmt::StopRun { .. } | Stmt::ExitProgram { .. } | Stmt::ExitMethod { .. } | Stmt::Continue { .. } | Stmt::Exit { .. } | Stmt::NextSentence | Stmt::SentenceEnd => {}
            Stmt::Corresponding(_) => unreachable!("CORRESPONDING is expanded before Check"),
        }
    }

    fn size_error(&mut self, se: Option<&SizeError>) {
        if let Some(se) = se {
            self.statements(&se.on);
            self.statements(&se.not_on);
        }
    }

    fn repeat(&mut self, repeat: &Loop) {
        match repeat {
            Loop::Once | Loop::Forever => {}
            Loop::Times(e) => self.expr(e),
            Loop::Until { cond, .. } => self.cond(cond),
            Loop::Varying { varying, after, .. } => {
                for v in std::iter::once(&**varying).chain(after) {
                    self.reference(&v.var);
                    self.expr(&v.from);
                    self.expr(&v.by);
                    self.cond(&v.until);
                    self.varying(v);
                }
            }
        }
    }

    /// A VARYING or AFTER variable is a numeric elementary item or an index-name, and its FROM and
    /// BY an identifier, index-name or literal (Language Reference SC27-8713-03, p. 419).
    fn varying(&mut self, v: &Varying) {
        use rt::storage::Kind;
        if let Some(i) = self.item(&v.var)
            && !matches!(self.layout.items[i].kind, Kind::Zoned { .. } | Kind::Packed { .. } | Kind::Binary { .. } | Kind::Float(_) | Kind::Index)
        {
            self.errors.push(syntax::messages::IWC0081.at(self.at, format!("PERFORM VARYING {}: not a numeric elementary item or an index-name", v.var.name)));
        }
        for (phrase, e) in [("FROM", &v.from), ("BY", &v.by)] {
            if !matches!(e, Expr::Operand(_)) {
                self.errors.push(syntax::messages::IWC0082.at(self.at, format!("PERFORM VARYING {} {phrase}: an arithmetic expression, where {phrase} takes an identifier, index-name or literal", v.var.name)));
            }
        }
    }

    fn file(&mut self, name: &str, pos: Pos) {
        if !self.program.files.iter().any(|f| f.name == name) {
            self.errors.push(syntax::messages::IWC0083.at(pos, format!("no file named {name}")));
        }
    }

    fn keyed_file(&mut self, name: &str, verb: &str, pos: Pos) {
        match self.program.files.iter().find(|f| f.name == name) {
            None => self.errors.push(syntax::messages::IWC0083.at(pos, format!("no file named {name}"))),
            Some(f) if !matches!(f.organization, Organization::Indexed | Organization::Relative) => {
                self.errors.push(syntax::messages::IWC0084.at(pos, format!("{verb} {name}: not an indexed or relative file")));
            }
            Some(_) => {}
        }
    }

    fn not_random(&mut self, name: &str, verb: &str, pos: Pos) {
        if self.program.files.iter().any(|f| f.name == name && f.access == Access::Random) {
            self.errors.push(syntax::messages::IWC0085.at(pos, format!("{verb} {name}: the file's ACCESS MODE is RANDOM")));
        }
    }

    fn handlers(&mut self, h: &Handlers) {
        self.statements(h.on.as_deref().unwrap_or_default());
        self.statements(h.not_on.as_deref().unwrap_or_default());
    }

    /// A class-name condition tests a data item of USAGE DISPLAY (Language Reference SC27-8713-03,
    /// p. 269): alphabetic, alphanumeric, edited, zoned decimal or a group.
    fn class_name_subject(&mut self, e: &Expr, name: &str) {
        let Expr::Operand(Operand::Ref(r)) = e else {
            self.errors.push(syntax::messages::IWC0086.at(self.at, format!("class-name {name} tests a data item, not an expression")));
            return;
        };
        let Some(i) = self.item(r) else { return };
        if !matches!(self.layout.items[i].kind, layout::Kind::Group | layout::Kind::Alnum { .. } | layout::Kind::AlnumEdited { .. } | layout::Kind::NumericEdited { .. } | layout::Kind::Zoned { .. }) {
            self.errors.push(syntax::messages::IWC0087.at(r.pos, format!("class-name {name} tests a data item of USAGE DISPLAY, and {} is not one", r.name)));
        }
    }

    fn item(&self, r: &Ref) -> Option<usize> {
        match self.layout.resolve(&r.name, &r.qualifiers, r.pos) {
            Ok(layout::Resolved::Item(i)) => Some(i),
            _ => None,
        }
    }

    /// The KEY of READ or START on an indexed file: a record key or alternate key of the file, or
    /// for START (`partial`) an item that starts where one does and is no longer.
    fn key_of(&mut self, file: &str, key: &Ref, partial: bool) {
        let Some(f) = self.program.files.iter().find(|f| f.name == file) else { return self.reference(key) };
        if key.qualifiers.is_empty() && f.split_key(&key.name).is_some() {
            return;
        }
        self.reference(key);
        if f.organization != Organization::Indexed {
            return;
        }
        let Some(item) = self.item(key).map(|i| &self.layout.items[i]) else { return };
        let fits = |r: &Ref| {
            self.item(r).map(|i| &self.layout.items[i]).is_some_and(|k| k.offset == item.offset && (k.size == item.size || partial && item.size < k.size))
        };
        let named = f.record_key.iter().chain(f.alternate_keys.iter().map(|(r, _)| r)).any(fits);
        if item.file.is_none() || !named {
            self.errors.push(syntax::messages::IWC0088.at(key.pos, format!("{}: not a key of {file}", key.name)));
        }
    }

    /// An indexed file's keys lie in its records; a relative file's RELATIVE KEY lies outside them.
    fn file_keys(&mut self, k: usize) {
        let f = &self.program.files[k];
        let in_records = |c: &Self, r: &Ref| c.item(r).is_some_and(|i| c.layout.items[i].file == Some(k as u16));
        match f.organization {
            Organization::Indexed => {
                if f.record_key.is_none() {
                    self.errors.push(syntax::messages::IWC0089.at(f.pos, format!("{}: an indexed file needs a RECORD KEY", f.name)));
                }
                let keys = f.record_key.iter().chain(f.alternate_keys.iter().map(|(r, _)| r));
                let items: Vec<Ref> = keys.flat_map(|r| f.split_key(&r.name).map_or_else(|| vec![r.clone()], <[Ref]>::to_vec)).collect();
                for r in &items {
                    self.reference(r);
                    if self.item(r).is_some() && !in_records(self, r) {
                        self.errors.push(syntax::messages::IWC0090.at(r.pos, format!("{}: a key of {} must be in its records", r.name, f.name)));
                    }
                }
            }
            Organization::Relative => {
                if let Some(r) = &f.relative_key {
                    self.reference(r);
                    if in_records(self, r) {
                        self.errors.push(syntax::messages::IWC0091.at(r.pos, format!("{}: the RELATIVE KEY of {} must not be in its records", r.name, f.name)));
                    }
                } else if f.access != Access::Sequential {
                    self.errors.push(syntax::messages::IWC0092.at(f.pos, format!("{}: random or dynamic access needs a RELATIVE KEY", f.name)));
                }
            }
            _ => {}
        }
    }

    /// RECORD IS VARYING's DEPENDING ON item is an elementary unsigned integer (Language Reference
    /// SC27-8713-03, p. 188).
    fn record_depending(&mut self, k: usize) {
        let f = &self.program.files[k];
        let Some(r) = &f.record_depending else { return };
        self.reference(r);
        if self.item(r).is_some() && linage::unsigned_integer(self.layout, r).is_none() {
            self.errors.push(syntax::messages::IWC0093.at(r.pos, format!("{}: the DEPENDING ON item of {} must be an elementary unsigned integer", r.name, f.name)));
        }
    }

    /// LABEL RECORD IS data-name: Enterprise COBOL reads the clause as comments and still refuses a
    /// data-name it does not know, IGYGR1174-S.
    fn label_records(&mut self, k: usize) {
        let f = &self.program.files[k];
        for r in &f.label_records {
            if self.layout.resolve(&r.name, &r.qualifiers, r.pos).is_err() {
                self.errors.push(syntax::messages::IWC0324.at(r.pos, format!("LABEL RECORDS {}: not defined as a data-name", r.name)));
            }
        }
    }

    /// RECORDING MODE F takes records of one length: not RECORD IS VARYING, not a two-bound RECORD
    /// clause, and level-01 records of one size with no OCCURS DEPENDING ON (Programming Guide
    /// SC27-8714-03, p. 227). Enterprise COBOL discards the file otherwise, IGYGR1211-S.
    fn recording_mode(&mut self, k: usize) {
        let f = &self.program.files[k];
        if f.recording != Some('F') {
            return;
        }
        let declared = (f.record_min, f.record_max);
        let lengths = match declared {
            (Some(min), Some(max)) if f.record_varying || min != max => Some((min, max)),
            _ => self.layout.record_lengths[k].filter(|(shortest, longest)| shortest != longest),
        };
        if let Some((shortest, longest)) = lengths {
            self.errors.push(syntax::messages::IWC0325.at(f.pos, format!("FD {}: RECORDING MODE F, but its records are {shortest} to {longest} bytes", f.name)));
        }
    }

    /// A PASSWORD item is a WORKING-STORAGE item of category alphabetic, alphanumeric or
    /// alphanumeric-edited (Language Reference SC27-8713-03, p. 152).
    fn passwords(&mut self, k: usize) {
        let f = &self.program.files[k];
        for r in &f.passwords {
            self.reference(r);
            let Some(i) = self.item(r) else { continue };
            let item = &self.layout.items[i];
            let working = !item.local && item.file.is_none() && item.linkage.is_none();
            if !working || !matches!(item.kind, rt::storage::Kind::Alnum { .. } | rt::storage::Kind::AlnumEdited { .. } | rt::storage::Kind::Group) {
                self.errors.push(syntax::messages::IWC0094.at(r.pos, format!("{}: the PASSWORD of {} must be an alphabetic, alphanumeric or alphanumeric-edited item of WORKING-STORAGE", r.name, f.name)));
            }
        }
    }

    fn procedure(&mut self, p: &ProcName, pos: Pos) {
        if let Err(m) = procedure(self.program, p) {
            self.errors.push(m.at(pos));
        }
    }

    /// A reference to data: an identifier names a data item or a function, and a condition-name
    /// is neither (Language Reference SC27-8713-03, p. 69).
    fn reference(&mut self, r: &Ref) {
        self.reference_or_condition(r);
        if let Ok(layout::Resolved::Condition(_)) = self.layout.resolve(&r.name, &r.qualifiers, r.pos) {
            self.errors.push(syntax::messages::IWC0095.at(r.pos, format!("{} is a condition-name, not a data item", r.name)));
        }
    }

    /// An arithmetic statement's receiving operand is numeric or numeric-edited (Language Reference
    /// SC27-8713-03, the ADD, COMPUTE, DIVIDE, MULTIPLY and SUBTRACT statements); Enterprise COBOL
    /// discards the statement otherwise, IGYPA3146-S. CORRESPONDING never comes here: it pairs
    /// numeric items of its two groups.
    fn arithmetic_receiver(&mut self, verb: &str, r: &Ref) {
        let Some(i) = self.item(r) else { return };
        let kind = self.layout.items[i].kind;
        if kind.is_numeric() || matches!(kind, rt::storage::Kind::NumericEdited { .. }) {
            return;
        }
        let class = match kind {
            rt::storage::Kind::Group => "a group",
            rt::storage::Kind::Alnum { .. } => "alphanumeric",
            rt::storage::Kind::AlnumEdited { .. } => "alphanumeric-edited",
            rt::storage::Kind::National => "national",
            rt::storage::Kind::Pointer | rt::storage::Kind::ProgramPointer => "a pointer",
            _ => "not numeric",
        };
        self.errors.push(syntax::messages::IWC0323.at(r.pos, format!("{verb} {}: a receiving operand of an arithmetic statement must be numeric or numeric-edited, and {} is {class}", r.name, r.name)));
    }

    /// A reference that may name a condition-name: a condition's, or SET TO TRUE's or FALSE's.
    fn reference_or_condition(&mut self, r: &Ref) {
        if r.name == "RETURN-CODE" && r.qualifiers.is_empty() && self.layout.resolve(&r.name, &r.qualifiers, r.pos).is_err() {
            return;
        }
        if oo::special_register(self.layout, r) || markup::xml_register(self.layout, r) {
            return;
        }
        if !self.debugging && !self.program.declaratives.debugging.is_empty() && declaratives::DEBUG_ITEM_NAMES.contains(&r.name.as_str()) {
            self.errors.push(syntax::messages::IWC0096.at(r.pos, format!("{}: only a debugging section may reference DEBUG-ITEM", r.name)));
            return;
        }
        match self.layout.resolve(&r.name, &r.qualifiers, r.pos) {
            Err(e) => self.errors.push(e),
            Ok(layout::Resolved::Item(i)) if switches::switch_of(self.layout, i).is_some() => self.errors.push(switches::mnemonic_as_data(r, self.layout, i)),
            Ok(layout::Resolved::Item(i)) if self.layout.items[i].dims.len() != r.subscripts.len() => self.errors.push(syntax::messages::IWC0097.at(
                r.pos,
                format!("{} takes {} subscripts, not {}", r.name, self.layout.items[i].dims.len(), r.subscripts.len()),
            )),
            Ok(_) => {}
        }
        r.subscripts.iter().for_each(|e| self.expr(e));
        if let Some(rm) = &r.refmod {
            self.expr(&rm.start);
            if let Some(l) = &rm.length {
                self.expr(l);
            }
        }
    }

    /// Every host variable and every CICS argument that names data must resolve.
    fn exec_block(&mut self, block: &ExecBlock) {
        if block.kind == ExecKind::Dli {
            self.dli_block(block);
        }
        if block.kind == ExecKind::Cics && matches!(block.command.as_str(), "HANDLE CONDITION" | "HANDLE AID" | "HANDLE ABEND") {
            self.handle_labels(block);
        }
        if let Some(syntax::sql::Sql { statement: syntax::sql::Statement::Malformed(why), .. }) = &block.sql {
            self.errors.push(syntax::messages::IWP0003.at(block.pos, format!("EXEC SQL {}: {why}", block.command)));
        }
        // Db2 13 requires a colon before every host variable (SQL Reference, db2z_refs2hostvars):
        // an INTO name without one is refused under strict and read as a host variable under extended.
        for r in block.sql.iter().flat_map(|sql| sql.statement.colonless_into()) {
            if self.extended {
                self.errors.push(syntax::messages::IWX0011.at(r.pos, format!("{INTO_WITHOUT_COLON}: {} is read as a host variable", r.name)));
            } else {
                self.errors.push(syntax::messages::IWP0046.at(r.pos, format!("EXEC SQL {}: {} in the INTO list has no colon, which Db2 requires before every host variable", block.command, r.name)));
            }
        }
        for r in &block.host_variables {
            if r.subscripts.is_empty() {
                self.reference_unsubscripted(r);
            } else {
                self.reference(r);
            }
        }
        for (_, arg) in &block.options {
            if let Some(ExecArg::Operand(op)) = arg {
                self.operand(op);
            }
        }
    }

    /// IBM's IGYPS2047-W: with only a REPLACING phrase, a receiver none of whose elementary items is
    /// of a category the phrase names is not initialized (Migration Guide GC27-8715-03, p. 137).
    fn initialize_incompatible(&mut self, targets: &[Ref], with: &InitializeWith, pos: Pos) {
        if !with.value.is_empty() || with.default {
            return;
        }
        for r in targets {
            let Some(i) = self.item(r) else { continue };
            let initialized = match r.refmod {
                Some(_) => with.initial_value(Some(self.layout.refmod_category(Some(i), self.layout.items[i].kind)), false).is_some(),
                None => self.layout.initialize_receivers(i, with.filler).iter().any(|&(e, _)| with.initial_value(self.layout.category(e), false).is_some()),
            };
            if !initialized {
                let categories: Vec<&str> = with.replacing.iter().map(|(c, _)| c.word()).collect();
                self.errors.push(syntax::messages::IWC0098.at(
                    pos,
                    format!("INITIALIZE {}: none of its items is of a category REPLACING names ({}), so it is not initialized", r.name, categories.join(", ")),
                ));
            }
        }
    }

    /// JSON GENERATE's and JSON PARSE's own item, which may name a whole table by leaving out its
    /// last subscript (Programming Guide SC27-8714-03, pp. 612-614, 619-620).
    fn whole_table_reference(&mut self, r: &Ref) {
        if let Ok(layout::Resolved::Item(i)) = self.layout.resolve(&r.name, &r.qualifiers, r.pos)
            && self.layout.items[i].table
            && self.layout.items[i].dims.len() == r.subscripts.len() + 1
        {
            r.subscripts.iter().for_each(|e| self.expr(e));
            return;
        }
        self.reference(r);
    }

    /// An EXEC DLI command and its options against IMS's table, and each qualification's form.
    fn dli_block(&mut self, block: &ExecBlock) {
        let Some(command) = syntax::dli::find(&block.command) else {
            self.errors.push(syntax::messages::IWP0004.at(block.pos, format!("EXEC DLI {} is not an EXEC DLI command", block.command)));
            return;
        };
        for (name, arg) in &block.options {
            if command.options.is_some_and(|options| !options.contains(&name.as_str())) {
                self.errors.push(syntax::messages::IWP0005.at(block.pos, format!("EXEC DLI {}: {name} is not one of its options", command.name)));
            } else if let (true, Some(ExecArg::Text(t))) = (name == "WHERE", arg)
                && let Err(why) = syntax::dli::qualification(t)
            {
                self.errors.push(syntax::messages::IWP0006.at(block.pos, format!("EXEC DLI {} WHERE({t}): {why}", command.name)));
            }
        }
    }

    /// A function's value can be inspected only as a character string, and only by TALLYING:
    /// REPLACING and CONVERTING store into the inspected item (Language Reference SC27-8713-03,
    /// pp. 77, 359; assumption C190).
    fn inspected_function(&mut self, f: &FunctionCall, i: &Inspect) {
        let name = f.name.as_str();
        let known = self.intrinsic(name);
        let numeric_udf = self.functions.into_iter().flatten().any(|u| u.name == name && !u.character_valued());
        if known && !rt::intrinsic::CHARACTER_VALUED.contains(&name) || numeric_udf {
            self.errors.push(syntax::messages::IWC0099.at(f.pos, format!("INSPECT FUNCTION {name}: an integer or numeric function can be used only where an arithmetic expression can, not as the inspected item")));
        }
        let stores = if !i.replacing.is_empty() {
            Some("REPLACING")
        } else {
            i.converting.as_ref().map(|_| "CONVERTING")
        };
        if let Some(phrase) = stores {
            self.errors.push(syntax::messages::IWC0100.at(f.pos, format!("INSPECT FUNCTION {name} {phrase}: {phrase} stores into the inspected item, and a function-identifier cannot be a receiving operand")));
        }
    }

    /// An integer or numeric intrinsic function, MAX and MIN among them when their arguments are
    /// numeric, can be used only where an arithmetic expression can (Language Reference
    /// SC27-8713-03, p. 499; Programming Guide SC27-8714-03, p. 56), and DISPLAY's operands are
    /// identifiers and literals (assumption C332).
    fn displayed_function(&mut self, f: &FunctionCall) {
        let name = f.name.as_str();
        let numeric = !rt::intrinsic::CHARACTER_VALUED.contains(&name) || self.numeric_max_or_min(f);
        if self.intrinsic(name) && numeric {
            self.errors.push(syntax::messages::IWC0101.at(f.pos, format!("DISPLAY FUNCTION {name}: an integer or numeric function can be used only where an arithmetic expression can, and DISPLAY takes none")));
        }
    }

    /// A DISPLAY's or ACCEPT's screen phrases, Micro Focus's and GnuCOBOL's: under `--compliance
    /// extended` a warning naming where on the screen, refused under strict.
    fn screen(&mut self, statement: &str, phrases: &ScreenPhrases) {
        let mut placed = Vec::new();
        match &phrases.at {
            Some(ScreenAt::Combined(o)) => placed.push(o),
            Some(ScreenAt::LineColumn { line, column }) => placed.extend(line.iter().chain(column)),
            None => {}
        }
        for o in placed {
            self.operand(o);
        }
        if !self.extended {
            self.errors.push(syntax::messages::IWC0298.at(phrases.pos, format!("{statement} on the screen: Micro Focus's and GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it")));
            return;
        }
        let at = match &phrases.at {
            Some(ScreenAt::Combined(_)) => "the line and column AT gives",
            Some(ScreenAt::LineColumn { line: Some(_), column: Some(_) }) => "the line and column given",
            Some(ScreenAt::LineColumn { line: Some(_), column: None }) => "column 1 of the line given",
            Some(ScreenAt::LineColumn { line: None, .. }) => "the column given on the cursor's line",
            None => "the cursor",
        };
        self.errors.push(syntax::messages::IWX0020.at(phrases.pos, format!("{statement} on the screen (Micro Focus and GnuCOBOL; Enterprise COBOL has none): at {at}")));
    }

    /// ACCEPT ... FROM COMMAND-LINE, ARGUMENT-NUMBER and ARGUMENT-VALUE are Micro Focus's and
    /// GnuCOBOL's, which `--compliance extended` reads from the job step's PARM with IWX0010-W
    /// (assumption C442); ON EXCEPTION goes with ARGUMENT-VALUE alone.
    fn accept_source(&mut self, from: AcceptFrom, exception: &Handlers, target: &Ref, pos: Pos) {
        if (exception.on.is_some() || exception.not_on.is_some()) && !matches!(from, AcceptFrom::ArgumentValue | AcceptFrom::EnvironmentValue) {
            self.errors.push(syntax::messages::IWC0256.at(pos, "ACCEPT ... ON EXCEPTION: of the ACCEPT statements, only ACCEPT ... FROM ARGUMENT-VALUE and the environment under --compliance extended have an exception"));
        }
        if from == AcceptFrom::EnvironmentValue {
            let named = self.environment_named.take() == Some(pos);
            let written = if named { "ACCEPT ... FROM ENVIRONMENT" } else { "ACCEPT ... FROM ENVIRONMENT-VALUE" };
            if self.extended {
                self.errors.push(syntax::messages::IWX0021.at(pos, format!("{written} (Micro Focus and GnuCOBOL; Enterprise COBOL reads and sets no environment variable): {} receives the value of the environment variable named, or spaces and the exception when it is not set", target.name)));
            } else if named {
                self.errors.push(syntax::messages::IWS0055.at(pos, "ACCEPT ... FROM ENVIRONMENT is GnuCOBOL's, not Enterprise COBOL's"));
            } else {
                self.errors.push(syntax::messages::IWS0060.at(pos, "ACCEPT ... FROM ENVIRONMENT-VALUE: GnuCOBOL's, not Enterprise COBOL's"));
            }
            return;
        }
        let (name, what) = match from {
            AcceptFrom::CommandLine => ("COMMAND-LINE", "the job step's PARM program arguments"),
            AcceptFrom::ArgumentNumber => ("ARGUMENT-NUMBER", "how many words the job step's PARM program arguments hold"),
            AcceptFrom::ArgumentValue => ("ARGUMENT-VALUE", "the next word of the job step's PARM program arguments"),
            _ => return,
        };
        if self.extended {
            self.errors.push(syntax::messages::IWX0010.at(pos, format!("ACCEPT ... FROM {name} (Micro Focus and GnuCOBOL; Enterprise COBOL reads no command line): {} receives {what}", target.name)));
        } else {
            self.errors.push(syntax::messages::IWC0257.at(pos, format!("ACCEPT ... FROM {name}: Micro Focus's and GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it from the job step's PARM")));
        }
    }

    /// DISPLAY UPON ENVIRONMENT-NAME or ENVIRONMENT-VALUE, written or standing for ACCEPT ... FROM
    /// ENVIRONMENT's naming or SET ENVIRONMENT, Micro Focus's and GnuCOBOL's: under `--compliance
    /// extended` a warning saying what it does, refused under strict. ACCEPT ... FROM
    /// ENVIRONMENT's message is given at its ACCEPT, and SET ENVIRONMENT's at its value.
    fn environment_display(&mut self, upon: &Upon, pos: Pos) {
        let value = upon.device == "ENVIRONMENT-VALUE";
        match upon.name.as_str() {
            "ENVIRONMENT" => self.environment_named = Some(pos),
            "SET ENVIRONMENT" if !value => {}
            "SET ENVIRONMENT" if self.extended => self.errors.push(syntax::messages::IWX0021.at(pos, "SET ENVIRONMENT (Micro Focus and GnuCOBOL; Enterprise COBOL reads and sets no environment variable): the environment variable named takes the value")),
            "SET ENVIRONMENT" => self.errors.push(syntax::messages::IWS0061.at(pos, "SET ENVIRONMENT is GnuCOBOL's, not Enterprise COBOL's")),
            _ if self.extended => {
                let what = if value { "the environment variable ENVIRONMENT-NAME last named takes the value" } else { "names the environment variable ENVIRONMENT-VALUE reads and sets next" };
                self.errors.push(syntax::messages::IWX0021.at(pos, format!("DISPLAY UPON {} (Micro Focus and GnuCOBOL; Enterprise COBOL reads and sets no environment variable): {what}", upon.device)));
            }
            _ => self.errors.push(syntax::messages::IWC0073.at(pos, format!("DISPLAY UPON {}: Micro Focus's and GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it", upon.name))),
        }
    }

    /// DISPLAY ... UPON ARGUMENT-NUMBER, Micro Focus's and GnuCOBOL's, which under `--compliance
    /// extended` makes the numeric item or literal it shows the number of the PARM word the next
    /// ACCEPT ... FROM ARGUMENT-VALUE takes, with IWX0010-W (assumption C442).
    fn argument_number(&mut self, items: &[Operand], pos: Pos) {
        if !self.extended {
            self.errors.push(syntax::messages::IWC0258.at(pos, "DISPLAY UPON ARGUMENT-NUMBER: Micro Focus's and GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it"));
            return;
        }
        let numeric = match items {
            [Operand::Literal(Literal::Number(_))] => true,
            [Operand::Ref(r)] => self.item(r).is_some_and(|i| self.layout.items[i].kind.is_numeric()),
            _ => false,
        };
        if numeric {
            self.errors.push(syntax::messages::IWX0010.at(pos, "DISPLAY ... UPON ARGUMENT-NUMBER (Micro Focus and GnuCOBOL; Enterprise COBOL reads no command line): the next ACCEPT ... FROM ARGUMENT-VALUE takes the job step's PARM word it numbers"));
        } else {
            self.errors.push(syntax::messages::IWC0259.at(pos, "DISPLAY UPON ARGUMENT-NUMBER: it shows one numeric item or literal, the number of the argument the next ACCEPT ... FROM ARGUMENT-VALUE takes"));
        }
    }

    /// An integer or numeric intrinsic function, MAX and MIN among them when their arguments are
    /// numeric, is no MOVE sender: it can be used only where an arithmetic expression can, and
    /// MOVE's sender is an identifier or literal (Language Reference SC27-8713-03, pp. 400-402, 499;
    /// Programming Guide SC27-8714-03, p. 119; assumption C394). `--compliance extended` moves its
    /// value with IWX0008-W.
    fn moved_function(&mut self, f: &FunctionCall) {
        let name = f.name.as_str();
        let numeric = !rt::intrinsic::CHARACTER_VALUED.contains(&name) || self.numeric_max_or_min(f);
        if !self.intrinsic(name) || !numeric {
            return;
        }
        if self.extended {
            self.errors.push(syntax::messages::IWX0008.at(f.pos, format!("{NUMERIC_FUNCTION_MOVED}: FUNCTION {name} is moved as its value")));
        } else {
            self.errors.push(syntax::messages::IWC0102.at(f.pos, format!("MOVE FUNCTION {name}: an integer or numeric function can be used only where an arithmetic expression can, not as a MOVE's sender")));
        }
    }

    /// INSPECT's identifiers but the count field have the inspected item's usage, and its literals
    /// are national when it is national, DBCS when it is DBCS and alphanumeric otherwise; a
    /// figurative constant is any of them (Language Reference SC27-8713-03, p. 355; assumption
    /// C231). A function-identifier's category is known only when it runs.
    fn inspected_usage(&mut self, target: &Ref, i: &Inspect) {
        let Some(t) = self.item(target) else { return };
        let usage = CharUsage::of(self.layout.items[t].kind);
        let phrases = i.tallying.iter().chain(&i.replacing).flat_map(|p| p.pattern.iter().chain(&p.by).chain(p.bounds.iter().map(|b| &b.value)));
        let converting = i.converting.iter().flat_map(|(from, to, bounds)| [from, to].into_iter().chain(bounds.iter().map(|b| &b.value)));
        for op in phrases.chain(converting) {
            let (operand, operand_usage, pos) = match op {
                Operand::Literal(l) => match inspected_literal(l) {
                    Some((what, operand_usage)) => (what.to_owned(), operand_usage, i.pos),
                    None => continue,
                },
                Operand::Ref(r) => match self.item(r) {
                    Some(k) => (r.name.clone(), CharUsage::of(self.layout.items[k].kind), r.pos),
                    None => continue,
                },
                _ => continue,
            };
            let name = &target.name;
            let why = match (usage, operand_usage) {
                (u, o) if u == o => continue,
                (CharUsage::Display, o) => format!("{name} is not {o}, and an operand can be {o} only when the inspected item is"),
                (u, _) => format!("{name} is {u} and every operand but the count field must be {u} too"),
            };
            self.errors.push(syntax::messages::IWC0103.at(pos, format!("INSPECT {name}: {operand} cannot be an operand here, since {why}")));
        }
    }

    /// A HANDLE label is a paragraph or section of the program, where control goes when the
    /// condition, attention key or abend comes (Programming Guide SC27-8714-03, p. 503).
    fn handle_labels(&mut self, block: &ExecBlock) {
        let abend = block.command == "HANDLE ABEND";
        for (option, arg) in &block.options {
            let Some(ExecArg::Text(label)) = arg else { continue };
            let label = label.trim();
            if label.is_empty() || matches!(option.as_str(), "RESP" | "RESP2" | "NOHANDLE") || abend && option != "LABEL" {
                continue;
            }
            let name = ProcName { name: label.to_ascii_uppercase(), section: None };
            if let Err(m) = procedure_from(self.program, &name, self.paragraph) {
                self.errors.push(syntax::messages::IWP0007.at(block.pos, format!("EXEC CICS {} {option}({label}): {m}", block.command)));
            }
        }
    }

    /// SEARCH VARYING names an index-name, an index data item or an elementary integer item
    /// (Language Reference SC27-8713-03, p. 437).
    fn search_varying(&mut self, se: &Search, v: &Ref) {
        use rt::storage::Kind;
        let Some(i) = self.item(v) else { return };
        if !matches!(self.layout.items[i].kind, Kind::Index | Kind::Zoned { scale: 0, .. } | Kind::Packed { scale: 0, .. } | Kind::Binary { scale: 0, .. }) {
            self.errors.push(syntax::messages::IWC0104.at(v.pos, format!("SEARCH {} VARYING {}: not an index-name, an index data item or an elementary integer item", se.table.name, v.name)));
        }
    }

    /// SEARCH names a table without a subscript.
    fn reference_unsubscripted(&mut self, r: &Ref) {
        if let Err(e) = self.layout.resolve(&r.name, &r.qualifiers, r.pos) {
            self.errors.push(e);
        }
    }

    /// Whether FUNCTION `name` invokes an intrinsic function: a user-defined function this program
    /// may invoke takes the name over.
    fn intrinsic(&self, name: &str) -> bool {
        (FUNCTIONS.contains(&name) || rt::intrinsic::FUNCTIONS.contains(&name)) && !self.functions.into_iter().flatten().any(|u| u.name == name)
    }

    fn operand(&mut self, op: &Operand) {
        match op {
            Operand::LengthOf(r) => self.reference(&self.layout.length_of_ref(r)),
            Operand::Ref(r) | Operand::AddressOf(r) => self.reference(r),
            Operand::Literal(Literal::Number(t)) if literal_fixed(t).is_none() || literal_digits(t) > self.max_digits as usize => {
                self.errors.push(syntax::messages::IWC0105.at(Pos::default(), format!("the literal {t} has more than {} digits", self.max_digits.min(31))));
            }
            Operand::Literal(_) => {}
            Operand::Function(f) => {
                if f.name == "MODULE-CALLER-ID" && self.intrinsic(&f.name) {
                    self.errors.push(if self.extended {
                        syntax::messages::IWX0031.at(f.pos, "FUNCTION MODULE-CALLER-ID (GnuCOBOL; Enterprise COBOL has no such function): the PROGRAM-ID of the program that called this one, empty in the main program")
                    } else {
                        syntax::messages::IWC0305.at(f.pos, "FUNCTION MODULE-CALLER-ID: GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it")
                    });
                }
                if f.name == "CONCATENATE" && self.intrinsic(&f.name) {
                    self.errors.push(if self.extended {
                        syntax::messages::IWX0053.at(f.pos, "FUNCTION CONCATENATE (GnuCOBOL; Enterprise COBOL has no such function): its arguments' characters joined, a number's as its digits")
                    } else {
                        syntax::messages::IWC0319.at(f.pos, "FUNCTION CONCATENATE: GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it")
                    });
                }
                if f.name == "STORED-CHAR-LENGTH" && self.intrinsic(&f.name) {
                    self.errors.push(if self.extended {
                        syntax::messages::IWX0042.at(f.pos, "FUNCTION STORED-CHAR-LENGTH (GnuCOBOL; Enterprise COBOL has no such function): the argument's length in characters without its trailing spaces")
                    } else {
                        syntax::messages::IWC0312.at(f.pos, "FUNCTION STORED-CHAR-LENGTH: GnuCOBOL's, not Enterprise COBOL's; --compliance extended reads it")
                    });
                }
                if !self.intrinsic(&f.name) {
                    match self.functions.map(|all| all.iter().find(|u| u.name == f.name)) {
                        Some(Some(udf)) => function::check_invocation(udf, f, self.layout, self.alphabetic, self.program.environment.decimal_point_comma, self.errors),
                        Some(None) => self.errors.push(syntax::messages::IWC0106.at(f.pos, format!("FUNCTION {}: neither an intrinsic function nor a user-defined function defined or prototyped before this program", f.name))),
                        None => self.errors.push(syntax::messages::IWR0075.at(f.pos, format!("FUNCTION {}: a user-defined function is not supported here yet", f.name))),
                    }
                }
                self.function_arguments(f);
                f.args.iter().for_each(|a| self.expr(a));
            }
        }
    }

    fn expr(&mut self, e: &Expr) {
        match e {
            Expr::Operand(op) => self.operand(op),
            Expr::Neg(inner) => self.expr(inner),
            Expr::Bin(a, _, b) => {
                self.expr(a);
                self.expr(b);
            }
        }
    }

    fn cond(&mut self, c: &Cond) {
        match c {
            Cond::Rel(a, _, b) => {
                self.expr(a);
                self.expr(b);
                self.comparison(a, b);
            }
            Cond::Class(e, class) => {
                self.expr(e);
                if let Class::Named(name) = class {
                    self.class_name_subject(e, name);
                }
            }
            Cond::Name(r) => self.reference_or_condition(r),
            Cond::NameOrRel { subject, name, .. } => {
                self.expr(subject);
                self.reference_or_condition(name);
                if self.item(name).is_some() {
                    self.comparison(subject, &Expr::Operand(Operand::Ref(name.clone())));
                }
            }
            Cond::Not(inner) => self.cond(inner),
            Cond::And(a, b) | Cond::Or(a, b) => {
                self.cond(a);
                self.cond(b);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsStr;
    use std::time::Duration;

    #[test]
    fn source_date_epoch_decides_the_compile_time_and_the_clock_stands_in_for_it() {
        let clock = Duration::from_millis(1_790_510_400_428);
        let from = |epoch: Option<&str>| compile_time_from(epoch.map(OsStr::new), clock);
        assert_eq!(from(None), Ok(CompileTime { seconds: 1_790_510_400, hundredths: 42, source: TimeSource::Clock }));
        assert_eq!(from(Some("315532800")), Ok(CompileTime { seconds: 315_532_800, hundredths: 0, source: TimeSource::SourceDateEpoch }));
        assert_eq!(from(Some("253402300799")).map(|t| t.seconds), Ok(CompileTime::LATEST));
        for bad in ["", "-1", "+5", "1.5", " 7", "253402300800"] {
            assert!(from(Some(bad)).unwrap_err().starts_with(&format!("SOURCE_DATE_EPOCH={bad}: ")), "{bad}");
        }
    }
}