rucc-sema 0.3.2

Type checking, conversions, initialization, constant evaluation, and the typed AST.
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
//! Statements: what happens, in what order, and where control is allowed to go instead.
//!
//! Design: `spec/07-types-and-semantics.md` section 7.14.
//!
//! An expression is checked against the types of its operands and nothing else, which is why the
//! expression checking is a walk with no state in it. A statement is not. Whether `break` is
//! allowed depends on what encloses it, what `return` may carry depends on the function it is in,
//! and a `goto` may name a label that is fifty lines further down. So this walk carries a [`Body`]
//! for as long as it is inside one, and everything a statement needs to know that is not in the
//! statement itself is in there.
//!
//! # Labels are resolved over the whole function and not in order
//!
//! A label is one namespace, scoped to the function, and a `goto` is allowed to come first. So a
//! label is created where its name is first met, whether that is the `goto` or the label itself,
//! and the statement it names is filled in later. What is left over at the end of the function is
//! the labels that were used and never defined, which is the one diagnostic here that cannot be
//! written where it is found.
//!
//! GNU's `__label__` is the exception: it declares a label local to the block, which is what lets
//! a macro that jumps to its own end be expanded twice in one function without the two colliding.
//! Those are undone when the block ends, which is what the saved bindings in the body are for.
//!
//! # Why the case table is patched
//!
//! A `switch` holds its cases as a run, so that the walk to the IR builds a jump table from a
//! table rather than by searching the body for labels. The run is not known until the body has
//! been walked, and the `case` statements in the body are built while it is being walked, so each
//! of them is written with a placeholder and given its real entry once the run exists. Collecting
//! the whole run at the end is also what keeps a nested `switch` from interleaving its cases with
//! the ones outside it, since each `switch` adds its cases in one go.
//!
//! # What is not here
//!
//! Reachability. `control reaches end of non-void function` and the unreachable code warnings are
//! questions about a control flow graph, and the answer to them is in the IR rather than in the
//! tree, so they wait for it. A label that is defined and never used is a warning gcc only gives
//! under `-Wall`, and it waits for the flag rather than for anything here.

use std::collections::{HashMap, HashSet};
use std::mem;

use rucc_ast::{self as ast, AsmQuals, ForInit, StorageClass};
use rucc_base::Symbol;
use rucc_diag::{Diagnostic, Span};
use rucc_lex::{Encoding, Remarks, StringLiteral};
use rucc_session::Std;
use rucc_types::{IntegerInfo, Qualifiers, TypeId, is_integer, is_pointer, is_record, is_void};

use crate::asm::{Asm, AsmOperand, AsmOperandList, LabelList};
use crate::check::Checker;
use crate::check::expr::Target;
use crate::decl::{DeclId, DeclList};
use crate::eval;
use crate::expr::{Category, Expr, ExprId, ExprKind};
use crate::stmt::{Case, Stmt, StmtId};
use crate::tast::{Const, Label, LabelId, StrId};

/// The spellings that stand for the name of the function they are written in. The first is the
/// one C99 added and the other two are GNU's, which are the same thing in C and differ only in
/// C++, where the pretty one spells out the signature.
pub(in crate::check) const FUNCTION_NAMES: [&str; 3] =
    ["__func__", "__FUNCTION__", "__PRETTY_FUNCTION__"];

/// What the statements of one function body are checked against.
#[derive(Debug)]
pub(in crate::check) struct Body {
    /// The return type, which every `return` in it answers to.
    ret: TypeId,
    /// Where the function was named, for the `declared here` note under a `return` that
    /// disagrees with the return type.
    at: Span,
    /// Whether the parameter list ends in `...`, which is what says whether there is anything
    /// for a `va_start` in here to start reading.
    variadic: bool,
    /// The last named parameter, which is what `va_start`'s second argument ought to name.
    last_param: Option<DeclId>,
    /// Every parameter, which is what tells an assignment to one of them from an assignment to
    /// a local: gcc says `read-only parameter` for the first and `read-only variable` for the
    /// second, and there is nothing on a declaration itself that says which it is.
    params: DeclList,
    /// The name the definition was written with, which is what `__func__` answers.
    name: Option<Symbol>,
    /// The string each of the three spellings was made into, so that every mention of one of them
    /// in a function is one object rather than one per use. They are three objects and not one,
    /// because gcc gives each spelling its own and a program is allowed to notice: comparing
    /// `__func__` with `__FUNCTION__` there is false.
    func_name: [Option<StrId>; FUNCTION_NAMES.len()],
    /// The labels of the function, by the name they were written with.
    labels: HashMap<Symbol, Labelled>,
    /// What the enclosing blocks bound the names of their `__label__` declarations to, so that a
    /// block-local label can be undone when the block ends.
    shadowed: Vec<(Symbol, Option<Labelled>)>,
    /// Where each enclosing block's run of those starts.
    blocks: Vec<usize>,
    /// The `switch` statements this one is inside, innermost last.
    switches: Vec<Switch>,
    /// How many loops it is inside, which is what `continue` asks and half of what `break` asks.
    loops: usize,
    /// The names this function has already been told about, so that a name nobody declared is
    /// reported once rather than once per use. The message says `first use in this function`
    /// and gcc means it: a typo in a loop body is one mistake however many times it is written.
    undeclared: HashSet<Symbol>,
    /// Every declaration of a variably modified type met so far, each one saying which of them
    /// it was written inside.
    modified: Vec<Modified>,
    /// The innermost of those the walk is inside. The chain out of it through the entries above
    /// is every one of them whose scope is open here.
    inside: Option<usize>,
    /// Where each label of the function is, filled in as the labels are met.
    landings: HashMap<LabelId, Landing>,
    /// Every `goto` met so far, kept until the whole function has been walked.
    jumps: Vec<Jump>,
}

/// One declaration of a variably modified type, which is one a jump may not enter the scope of.
#[derive(Debug, Clone, Copy)]
struct Modified {
    /// What it is called, absent for a declaration that names nothing.
    name: Option<Symbol>,
    /// Where it was written, for the note under the jump that skips it.
    at: Span,
    /// The one it was written inside, absent for one at the top of the function.
    outer: Option<usize>,
}

/// Where a label is, which is what says whether a jump to it is allowed.
#[derive(Debug, Clone, Copy)]
struct Landing {
    /// Where the label was written.
    at: Span,
    /// The innermost variably modified declaration whose scope it is in.
    inside: Option<usize>,
}

/// One `goto`, which is checked when the function ends rather than where it is written.
#[derive(Debug, Clone, Copy)]
struct Jump {
    /// The label it names.
    to: LabelId,
    /// Where it was written.
    at: Span,
    /// The innermost variably modified declaration whose scope it is in.
    inside: Option<usize>,
}

/// What a body is opened with, which is what the enclosing function says about itself.
#[derive(Debug, Clone, Copy)]
pub(in crate::check) struct Enclosing {
    /// The return type, which every `return` answers to.
    pub ret: TypeId,
    /// Where the function was named.
    pub at: Span,
    /// Whether the parameter list ends in `...`.
    pub variadic: bool,
    /// The last named parameter, absent when there are none.
    pub last_param: Option<DeclId>,
    /// Every parameter of the definition, empty for a body that is not one.
    pub params: DeclList,
    /// The name the function was written with, absent for a body that is not a definition.
    pub name: Option<Symbol>,
}

impl Enclosing {
    /// A function returning `ret` and saying nothing else about itself, which is what a caller
    /// that has a statement rather than a definition in its hand has.
    pub(in crate::check) fn returning(ret: TypeId) -> Enclosing {
        Enclosing {
            ret,
            at: Span::DUMMY,
            variadic: false,
            last_param: None,
            params: DeclList::EMPTY,
            name: None,
        }
    }
}

/// One label of a function.
#[derive(Debug, Clone, Copy)]
struct Labelled {
    /// The label in the typed tree, made where the name was first met.
    id: LabelId,
    /// Whether the statement it names has been seen, and where the label was written.
    defined: Option<Span>,
    /// Where the name was first met, which is what an undefined label is reported at.
    at: Span,
}

/// One `switch` being checked, and the case table it is collecting.
#[derive(Debug)]
struct Switch {
    /// The promoted type of the controlling expression, which every case value is held in.
    ty: TypeId,
    /// The shape of the type before that promotion, which is the range a case value is warned
    /// about for leaving. gcc measures against what was written rather than against what the
    /// promotion widened it to, so `case 300` on a `char` is worth saying even though 300 is a
    /// perfectly good `int`.
    range: Option<IntegerInfo>,
    /// The cases so far, in the order they were written.
    cases: Vec<Case>,
    /// Where each of them was written, for the note under a duplicate.
    spans: Vec<Span>,
    /// The statements those cases label, which are patched with their table entries once the
    /// table exists. Each one says which entry is its own, so the order here does not matter.
    labels: Vec<StmtId>,
    /// The `default`, and where it was written, once one has been seen.
    default: Option<(StmtId, Span)>,
}

impl Checker<'_> {
    /// Checks one statement, as though it were the body of a function returning `ret`.
    ///
    /// The entry for a caller that has a statement rather than a translation unit, which is what
    /// the tests here are built on. A body is opened around it and closed after, so that the
    /// labels are resolved and reported the way they are in a real function.
    pub fn check_stmt(&mut self, ret: TypeId, id: ast::StmtId) -> StmtId {
        let previous = self.open_body(Enclosing::returning(ret));
        let stmt = self.stmt(id);
        self.close_body(previous);
        stmt
    }

    /// Checks one statement and gives back the node it became.
    pub(in crate::check) fn stmt(&mut self, id: ast::StmtId) -> StmtId {
        let span = self.ast.stmt_span(id);
        let node = match self.ast[id] {
            ast::Stmt::Error => Stmt::Error,
            ast::Stmt::Empty => Stmt::Empty,
            ast::Stmt::Expr(value) => {
                let value = self.expr(value);
                Stmt::Expr(self.value(value))
            }
            ast::Stmt::Decl(decl) => {
                let decls = self.check_decl(decl);
                self.variably_modified(decls);
                Stmt::Decls(decls)
            }
            ast::Stmt::Compound(body) => Stmt::Block(self.block(body)),
            ast::Stmt::If { cond, then, otherwise } => {
                let cond = self.controlling(cond);
                let then = self.stmt(then);
                Stmt::If { cond, then, otherwise: otherwise.map(|id| self.stmt(id)) }
            }
            ast::Stmt::Switch { scrutinee, body } => self.switch(scrutinee, body),
            ast::Stmt::While { cond, body } => {
                let cond = self.controlling(cond);
                Stmt::While { cond, body: self.loop_body(body) }
            }
            ast::Stmt::DoWhile { body, cond } => {
                let body = self.loop_body(body);
                Stmt::DoWhile { body, cond: self.controlling(cond) }
            }
            ast::Stmt::For { init, cond, step, body } => self.for_loop(init, cond, step, body),
            ast::Stmt::Goto(name) => Stmt::Goto(self.jump(name, span)),
            ast::Stmt::GotoExpr(target) => self.computed_goto(target),
            ast::Stmt::Continue => self.continue_stmt(span),
            ast::Stmt::Break => self.break_stmt(span),
            ast::Stmt::Return(value) => self.return_stmt(value, span),
            ast::Stmt::Label { name, body, .. } => self.labelled(name, body, span),
            ast::Stmt::Case { lo, hi, body } => self.case(lo, hi, body, span),
            ast::Stmt::Default { body } => self.default(body, span),
            ast::Stmt::LocalLabels(names) => {
                self.local_labels(names, span);
                Stmt::Empty
            }
            ast::Stmt::Asm(asm) => self.asm(asm, span),
        };
        let stmt = self.tast.stmt(node, span);
        // The `switch` patches its cases once it has a table, and what it has to patch is the
        // node that ended up in the body rather than the one the arm above built, so the case
        // is registered here where that node exists.
        if matches!(node, Stmt::Case { .. }) {
            if let Some(switch) = self.switches() {
                switch.labels.push(stmt);
            }
        }
        stmt
    }

    /// `({ ... })`, GNU's statement expression, whose value is its last statement's.
    ///
    /// The type is the last statement's if that statement is an expression, and `void` otherwise,
    /// which is gcc's rule and which makes `({ })` and `({ int x; })` both `void`. This works
    /// because an expression statement holds the value of its expression rather than a conversion
    /// of it to `void`: the statement is what discards the value, and here is where the value is
    /// wanted instead.
    pub(in crate::check) fn stmt_expr(&mut self, id: ast::StmtId, span: Span) -> ExprId {
        let stmt = self.stmt(id);
        let ty = match self.tast[stmt] {
            Stmt::Block(body) => match self.tast[body].last() {
                Some(&last) => match self.tast[last] {
                    Stmt::Expr(value) => self.tast[value].ty,
                    _ => self.types.void(),
                },
                None => self.types.void(),
            },
            _ => self.types.void(),
        };
        self.tast.expr(Expr::new(ExprKind::StmtExpr(stmt), ty, Category::Rvalue), span)
    }

    /// `&&name`, GNU's label address, whose type is `void *` and whose target is a label.
    ///
    /// Mentioning a label here is a use of it and not a definition, so a function that takes the
    /// address of a label it never defines is reported the same way a `goto` to one is.
    pub(in crate::check) fn label_addr(&mut self, name: Symbol, span: Span) -> ExprId {
        let label = self.label(name, span);
        let ty = self.types.pointer(self.types.void());
        self.tast.expr(Expr::new(ExprKind::LabelAddr(label), ty, Category::Rvalue), span)
    }

    /// Opens a body, and gives back the one it displaced so that it can be put back.
    ///
    /// Displaced rather than asserted absent, because GNU's nested functions are a body inside a
    /// body and each has its own labels, its own return type and its own loops.
    pub(in crate::check) fn open_body(&mut self, func: Enclosing) -> Option<Body> {
        let body = Body {
            ret: func.ret,
            at: func.at,
            variadic: func.variadic,
            last_param: func.last_param,
            params: func.params,
            name: func.name,
            func_name: [None; FUNCTION_NAMES.len()],
            labels: HashMap::new(),
            shadowed: Vec::new(),
            blocks: Vec::new(),
            switches: Vec::new(),
            loops: 0,
            undeclared: HashSet::new(),
            modified: Vec::new(),
            inside: None,
            landings: HashMap::new(),
            jumps: Vec::new(),
        };
        self.body.replace(body)
    }

    /// Whether the function being checked takes arguments past its named ones.
    ///
    /// False outside a function, where `va_start` is as wrong as it is in one with a fixed
    /// parameter list and is reported in the same words.
    pub(in crate::check) fn in_variadic_function(&self) -> bool {
        self.body.as_ref().is_some_and(|body| body.variadic)
    }

    /// The last named parameter of the function being checked, which is what `va_start`'s
    /// second argument ought to name.
    pub(in crate::check) fn last_named_parameter(&self) -> Option<DeclId> {
        self.body.as_ref().and_then(|body| body.last_param)
    }

    /// The string the `which`th spelling stands for in the function being checked, made on first
    /// use.
    ///
    /// `None` outside a function, where the name is not declared at all. gcc gives it the empty
    /// string there and warns, which is a warning nothing here can select yet, so a use outside
    /// a function is left to the ordinary undeclared-name error.
    pub(in crate::check) fn function_name_string(&mut self, which: usize) -> Option<StrId> {
        let name = self.body.as_ref()?.name?;
        if let Some(id) = self.body.as_ref().and_then(|body| body.func_name[which]) {
            return Some(id);
        }
        let elements = self.text(name).chars().map(|c| c as u32).collect();
        let literal =
            StringLiteral { elements, encoding: Encoding::Plain, remarks: Remarks::default() };
        let id = self.tast.add_string(literal);
        if let Some(body) = &mut self.body {
            body.func_name[which] = Some(id);
        }
        Some(id)
    }

    /// Whether a declaration is one of the parameters of the function being checked.
    ///
    /// False outside a function body, where every name in sight belongs to something else.
    pub(in crate::check) fn is_parameter(&self, decl: DeclId) -> bool {
        self.body.as_ref().is_some_and(|body| self.tast[body.params].contains(&decl))
    }

    /// Whether this is the first time the function being checked has used the undeclared name
    /// `name`, and records it either way.
    ///
    /// Always true outside a function body, where there is nothing to remember it in and where
    /// each declaration is its own context anyway.
    pub(in crate::check) fn first_undeclared_use(&mut self, name: Symbol) -> bool {
        match &mut self.body {
            Some(body) => body.undeclared.insert(name),
            None => true,
        }
    }

    /// Closes a body, reporting the labels that were used and never defined.
    pub(in crate::check) fn close_body(&mut self, previous: Option<Body>) {
        let Some(body) = mem::replace(&mut self.body, previous) else {
            return;
        };
        // Sorted, because a map has no order and a compiler whose diagnostics come out in a
        // different order on two runs of the same input is one nobody can write a test against.
        let mut undefined: Vec<Labelled> =
            body.labels.into_values().filter(|label| label.defined.is_none()).collect();
        undefined.sort_by_key(|label| label.at.lo);
        for label in undefined {
            self.undefined_label(label);
        }

        // Where each `goto` lands, which is the one thing about one that cannot be answered
        // where it is written, since the label it names may be fifty lines further down.
        for jump in &body.jumps {
            let Some(landing) = body.landings.get(&jump.to) else { continue };
            let Some(entered) = landing.inside else { continue };
            if open_at(&body.modified, jump.inside, entered) {
                continue;
            }
            self.jumped_into_scope(*jump, *landing, body.modified[entered]);
        }
    }

    /// The diagnostic for a `goto` that jumps into the scope of a variably modified declaration.
    ///
    /// The wording is gcc's, and so are the two notes, which are what make it readable: the
    /// label says where control lands and the declaration says what is not there when it does.
    fn jumped_into_scope(&mut self, jump: Jump, landing: Landing, entered: Modified) {
        let label = self.text(self.tast[jump.to].name).to_owned();
        let mut diag =
            Diagnostic::error("jump into scope of identifier with variably modified type", jump.at)
                .with_code("E0684")
                .note(format!("label '{label}' defined here"), landing.at);
        if let Some(name) = entered.name {
            let spelled = self.text(name).to_owned();
            diag = diag.note(format!("'{spelled}' declared here"), entered.at);
        }
        self.report(diag);
    }

    /// The body of a function definition, walked in the scope its parameters are already in.
    ///
    /// A function body is one scope with the parameters, which is why this exists rather than
    /// the caller reaching [`Checker::stmt`]: that would open a second scope and make
    /// `void f(int a) { int a; }` two declarations of `a` that never meet.
    pub(in crate::check) fn body_block(&mut self, body: ast::StmtId) -> StmtId {
        let span = self.ast.stmt_span(body);
        let ast::Stmt::Compound(list) = self.ast[body] else {
            return self.stmt(body);
        };
        let list = self.statements(list);
        self.tast.stmt(Stmt::Block(list), span)
    }

    /// A block, which is a scope.
    fn block(&mut self, body: ast::StmtList) -> crate::stmt::StmtList {
        self.scopes.push();
        let outer = self.open_scope();
        let list = self.statements(body);
        self.close_scope(outer);
        self.scopes.pop();
        list
    }

    /// What the walk is inside as a scope opens, so that what the scope declares is out of scope
    /// again when it ends.
    ///
    /// Every scope a jump can leave has to do this, which is a block and a `for` clause. The
    /// function body is not one of them: nothing in it is outside it.
    fn open_scope(&self) -> Option<usize> {
        self.body.as_ref().and_then(|state| state.inside)
    }

    /// Puts that back.
    fn close_scope(&mut self, outer: Option<usize>) {
        if let Some(state) = self.body.as_mut() {
            state.inside = outer;
        }
    }

    /// Records what a declaration declares that is variably modified.
    ///
    /// C11 6.8.6.1p1 says a jump may not enter the scope of one of these, and the reason is that
    /// the size is a value the program worked out where the declaration is: a jump that lands
    /// past the declaration without going through it lands somewhere that value was never
    /// computed. What is recorded here is what a jump is checked against at the end.
    fn variably_modified(&mut self, decls: DeclList) {
        let ids = self.tast[decls].to_vec();
        for decl in ids {
            if !self.is_variably_modified(self.tast[decl].ty) {
                continue;
            }
            let name = self.tast[decl].name;
            let at = self.tast.decl_span(decl);
            if let Some(state) = self.body.as_mut() {
                let outer = state.inside;
                state.modified.push(Modified { name, at, outer });
                state.inside = Some(state.modified.len() - 1);
            }
        }
    }

    /// The statements of a block, with the block-local labels undone at the end of it.
    fn statements(&mut self, body: ast::StmtList) -> crate::stmt::StmtList {
        if let Some(state) = self.body.as_mut() {
            let mark = state.shadowed.len();
            state.blocks.push(mark);
        }
        let ids = self.ast[body].to_vec();
        let mut stmts = Vec::with_capacity(ids.len());
        for id in ids {
            stmts.push(self.stmt(id));
        }
        self.end_block();
        self.tast.add_stmt_refs(&stmts)
    }

    /// Undoes what `__label__` declared in the block that is ending.
    fn end_block(&mut self) {
        let Some(body) = self.body.as_mut() else {
            return;
        };
        let Some(mark) = body.blocks.pop() else {
            return;
        };
        let mut gone = Vec::new();
        while body.shadowed.len() > mark {
            let (name, previous) = body.shadowed.pop().expect("a saved binding");
            let local = match previous {
                Some(previous) => body.labels.insert(name, previous),
                None => body.labels.remove(&name),
            };
            if let Some(local) = local {
                if local.defined.is_none() {
                    gone.push(local);
                }
            }
        }
        gone.sort_by_key(|label| label.at.lo);
        for label in gone {
            self.undefined_label(label);
        }
    }

    /// The body of a loop, inside which `break` and `continue` both mean something.
    fn loop_body(&mut self, body: ast::StmtId) -> StmtId {
        if let Some(state) = self.body.as_mut() {
            state.loops += 1;
        }
        let body = self.stmt(body);
        if let Some(state) = self.body.as_mut() {
            state.loops -= 1;
        }
        body
    }

    /// `for (init; cond; step) body`, whose first clause is in a scope of its own.
    fn for_loop(
        &mut self,
        init: ForInit,
        cond: Option<ast::ExprId>,
        step: Option<ast::ExprId>,
        body: ast::StmtId,
    ) -> Stmt {
        // The scope is the loop's rather than the body's, which is what makes the `i` in
        // `for (int i = 0; ...)` visible to the condition and gone after the loop.
        self.scopes.push();
        let outer = self.open_scope();
        let init = match init {
            ForInit::None => None,
            ForInit::Expr(value) => {
                let span = self.ast.expr_span(value);
                let value = self.expr(value);
                let value = self.value(value);
                Some(self.tast.stmt(Stmt::Expr(value), span))
            }
            ForInit::Decl(decl) => {
                let span = self.ast.decl_span(decl);
                let decls = self.check_decl(decl);
                self.variably_modified(decls);
                self.check_loop_declaration(decl);
                Some(self.tast.stmt(Stmt::Decls(decls), span))
            }
        };
        let cond = cond.map(|cond| self.controlling(cond));
        let step = step.map(|step| {
            let step = self.expr(step);
            self.value(step)
        });
        let body = self.loop_body(body);
        self.close_scope(outer);
        self.scopes.pop();
        Stmt::For { init, cond, step, body }
    }

    /// What a `for` loop's first clause is not allowed to declare.
    ///
    /// C99 6.8.5p3 says the declaration there declares objects with automatic storage and nothing
    /// else, which rules out a `static`, an `extern` and a `typedef`. The point of the rule is
    /// that the clause scopes to the loop, and a name that outlives the loop has no business
    /// being written where it looks like it does not.
    ///
    /// gcc accepts all three without a word unless `-pedantic` is on, and enough code declares a
    /// `static` counter there that following the letter of the rule by default would reject
    /// programs everyone else builds.
    fn check_loop_declaration(&mut self, decl: ast::DeclId) {
        if !self.cx.pedantic {
            return;
        }
        let ast::Decl::Var { specs, declarators } = self.ast[decl] else {
            return;
        };
        let specs = self.ast[specs];
        let word = match specs.storage {
            _ if specs.is_typedef() => "non-variable",
            Some(StorageClass::Static) => "static variable",
            Some(StorageClass::Extern) => "'extern' variable",
            _ => return,
        };
        let ast = self.ast;
        for &item in &ast[declarators] {
            let node = ast[item.declarator];
            let Some(name) = node.name else { continue };
            let spelled = self.text(name).to_owned();
            self.report(
                Diagnostic::warning(
                    format!("declaration of {word} '{spelled}' in 'for' loop initial declaration"),
                    node.name_span,
                )
                .with_code("E0619"),
            );
        }
    }

    /// `switch (cond) body`, with the case table collected while the body is walked.
    fn switch(&mut self, scrutinee: ast::ExprId, body: ast::StmtId) -> Stmt {
        let at = self.ast.expr_span(scrutinee);
        let cond = self.expr(scrutinee);
        let cond = self.value(cond);
        // Read before the promotion and not after it, because the range a case value is measured
        // against is the one that was written. `switch (c)` on a `char` and `case 300` is worth
        // saying, and by the time the promotion has run there is nothing left to say it about.
        let range = eval::int_shape(&self.types, self.tast[cond].ty, self.cx.target);
        let cond = self.conv().promote(cond);
        let ty = self.tast[cond].ty;
        let cond = if self.is_poisoned(cond) || is_integer(&self.types, ty) {
            cond
        } else {
            self.report(Diagnostic::error("switch quantity not an integer", at).with_code("E0620"));
            self.poison(at)
        };
        // The controlling type is the promoted one even where it was not an integer, so that the
        // cases in the body are still folded and checked against each other rather than being
        // reported a second time for something the `switch` itself already answered for.
        let ty = if is_integer(&self.types, ty) { ty } else { self.int() };
        if let Some(state) = self.body.as_mut() {
            state.switches.push(Switch {
                ty,
                range,
                cases: Vec::new(),
                spans: Vec::new(),
                labels: Vec::new(),
                default: None,
            });
        }
        let body = self.stmt(body);
        let Some(switch) = self.body.as_mut().and_then(|state| state.switches.pop()) else {
            return Stmt::Error;
        };
        let cases = self.tast.add_cases(&switch.cases);
        for &labelled in &switch.labels {
            let Stmt::Case { case: entry, body } = self.tast[labelled] else {
                continue;
            };
            // The node is holding the place its label took in the table, which is where the
            // label was written. It is not where the node was checked: two labels on one
            // statement are checked inside out.
            let case = cases.iter().nth(entry.index()).expect("a case for every label");
            self.tast.set_stmt(labelled, Stmt::Case { case, body });
        }
        Stmt::Switch { cond, body, cases, default: switch.default.map(|(stmt, _)| stmt) }
    }

    /// `case lo:`, or GNU's `case lo ... hi:`.
    fn case(
        &mut self,
        lo: ast::ExprId,
        hi: Option<ast::ExprId>,
        body: Option<ast::StmtId>,
        span: Span,
    ) -> Stmt {
        // The label joins the table before the statement it labels is checked, so that the
        // table comes out in the order the labels were written. `case 1: case 2: s;` is one
        // labelled statement nested inside another, and checking inside out would leave the
        // table holding 2 before 1.
        let entry = self.enter_case(lo, hi, span);
        let body = self.labelled_body(body, span);
        let Some(entry) = entry else {
            return Stmt::Error;
        };
        self.switches().expect("a switch").cases[entry].body = body;
        // The node holds its place in the table until the `switch` knows where the table went,
        // which is what the walk over its body ends with. The node this becomes is registered
        // by [`Checker::stmt`], since that is where it is written into the arena and only the
        // node that ends up in the body is worth patching.
        Stmt::Case { case: rucc_base::Idx::from_usize(entry), body }
    }

    /// The place in the enclosing switch's table that this label takes, with a body for
    /// [`Checker::case`] to fill in, or `None` for a label the switch cannot have.
    fn enter_case(
        &mut self,
        lo: ast::ExprId,
        hi: Option<ast::ExprId>,
        span: Span,
    ) -> Option<usize> {
        if self.body.as_ref().is_none_or(|state| state.switches.is_empty()) {
            self.report(
                Diagnostic::error("case label not within a switch statement", span)
                    .with_code("E0621"),
            );
            return None;
        }
        let low = self.case_value(lo, span)?;
        let high = match hi {
            Some(hi) => self.case_value(hi, span)?,
            None => low,
        };
        if high < low {
            self.report(Diagnostic::warning("empty range specified", span).with_code("E0622"));
            return None;
        }
        if let Some(at) = self.overlapping_case(low, high) {
            self.report(
                Diagnostic::error("duplicate case value", span)
                    .with_code("E0623")
                    .note("previously used here".to_owned(), at),
            );
            return None;
        }
        let switch = self.switches().expect("a switch");
        let entry = switch.cases.len();
        // The body is filled in by the caller once it has been checked. Nothing reads it in
        // between: the table is only looked at for overlap, which is a question about values.
        switch.cases.push(Case { low, high, body: rucc_base::Idx::from_usize(0) });
        switch.spans.push(span);
        Some(entry)
    }

    /// The value of one case label, folded and converted to the controlling type.
    fn case_value(&mut self, value: ast::ExprId, span: Span) -> Option<i128> {
        let at = self.ast.expr_span(value);
        let value = self.expr(value);
        let value = self.value(value);
        let folded = match self.eval_integer(value) {
            Ok(folded) => folded,
            Err(failed) => {
                if !failed.poisoned {
                    self.report(
                        Diagnostic::error("case label does not reduce to an integer constant", at)
                            .with_code("E0624"),
                    );
                }
                return None;
            }
        };
        let switch = self.switches()?;
        let (ty, range) = (switch.ty, switch.range);
        if let Some(range) = range {
            if eval::overflows(Const::Int(folded), range) {
                self.report(
                    Diagnostic::warning("case label value exceeds maximum value for type", span)
                        .with_code("E0625"),
                );
            }
        }
        let info = eval::int_shape(&self.types, ty, self.cx.target)?;
        Some(eval::narrowed(Const::Int(folded), info))
    }

    /// Where a case that already covers part of this range was written, if there is one.
    fn overlapping_case(&mut self, low: i128, high: i128) -> Option<Span> {
        let switch = self.switches()?;
        switch
            .cases
            .iter()
            .position(|case| case.low <= high && low <= case.high)
            .map(|index| switch.spans[index])
    }

    /// `default:`.
    fn default(&mut self, body: Option<ast::StmtId>, span: Span) -> Stmt {
        let body = self.labelled_body(body, span);
        if self.body.as_ref().is_none_or(|state| state.switches.is_empty()) {
            self.report(
                Diagnostic::error("'default' label not within a switch statement", span)
                    .with_code("E0626"),
            );
            return Stmt::Error;
        }
        if let Some((_, at)) = self.switches().expect("a switch").default {
            self.report(
                Diagnostic::error("multiple default labels in one switch", span)
                    .with_code("E0627")
                    .note("this is the first default label".to_owned(), at),
            );
            return Stmt::Error;
        }
        self.switches().expect("a switch").default = Some((body, span));
        Stmt::Default { body }
    }

    /// `name: body`, which defines a label.
    fn labelled(&mut self, name: Symbol, body: Option<ast::StmtId>, span: Span) -> Stmt {
        // Where control lands, taken before the labelled statement is walked, because a C23
        // label on a declaration is a label outside the scope of what that declaration declares.
        let inside = self.open_scope();
        let body = self.labelled_body(body, span);
        let label = self.label(name, span);
        let defined = self.body.as_ref().and_then(|state| state.labels[&name].defined);
        if let Some(at) = defined {
            let spelled = self.text(name).to_owned();
            self.report(
                Diagnostic::error(format!("duplicate label '{spelled}'"), span)
                    .with_code("E0628")
                    .note(format!("previous definition of '{spelled}' with type 'void'"), at),
            );
            return Stmt::Error;
        }
        if let Some(state) = self.body.as_mut() {
            state.labels.entry(name).and_modify(|known| known.defined = Some(span));
            state.landings.insert(label, Landing { at: span, inside });
        }
        self.tast.define_label(label, body);
        Stmt::Label { label, body }
    }

    /// The statement a label labels, which C23 allows to be absent at the end of a block.
    fn labelled_body(&mut self, body: Option<ast::StmtId>, span: Span) -> StmtId {
        match body {
            Some(body) => self.stmt(body),
            None => self.tast.stmt(Stmt::Empty, span),
        }
    }

    /// `__label__ a, b;`, which declares labels local to the block it is written in.
    fn local_labels(&mut self, names: ast::SymbolList, span: Span) {
        let ast = self.ast;
        for &name in &ast[names] {
            let id = self.tast.add_label(Label { name, stmt: None });
            let local = Labelled { id, defined: None, at: span };
            if let Some(state) = self.body.as_mut() {
                let previous = state.labels.insert(name, local);
                state.shadowed.push((name, previous));
            }
        }
    }

    /// `goto name;`, which is a use of the label and a jump to be looked at once every label of
    /// the function is known.
    fn jump(&mut self, name: Symbol, span: Span) -> LabelId {
        let to = self.label(name, span);
        if let Some(state) = self.body.as_mut() {
            state.jumps.push(Jump { to, at: span, inside: state.inside });
        }
        to
    }

    /// The label of a name, made where the name is first met.
    fn label(&mut self, name: Symbol, span: Span) -> LabelId {
        if let Some(known) = self.body.as_ref().and_then(|state| state.labels.get(&name)) {
            return known.id;
        }
        let id = self.tast.add_label(Label { name, stmt: None });
        if let Some(state) = self.body.as_mut() {
            state.labels.insert(name, Labelled { id, defined: None, at: span });
        }
        id
    }

    /// The diagnostic for a label that something jumped to and nothing defined.
    ///
    /// gcc points at the function rather than at the jump, which is a choice about a message
    /// written at the end of a function and not about which one is the mistake. This points at
    /// the jump, since that is what has to be changed and since a `__label__` is reported at the
    /// end of a block that a function has no way to name.
    fn undefined_label(&mut self, label: Labelled) {
        let name = self.tast[label.id].name;
        let spelled = self.text(name).to_owned();
        self.report(
            Diagnostic::error(format!("label '{spelled}' used but not defined"), label.at)
                .with_code("E0629"),
        );
    }

    /// `goto *expr;`, GNU's computed goto.
    fn computed_goto(&mut self, target: ast::ExprId) -> Stmt {
        let at = self.ast.expr_span(target);
        let target = self.expr(target);
        let target = self.value(target);
        if self.is_poisoned(target) {
            return Stmt::Error;
        }
        let ty = self.tast[target].ty;
        // An integer is allowed through because a null pointer constant is one, and `goto *0;`
        // is what a macro expands to where the target is decided elsewhere.
        if !is_pointer(&self.types, ty) && !is_integer(&self.types, ty) {
            self.report(
                Diagnostic::error("computed goto must be pointer type", at).with_code("E0630"),
            );
            return Stmt::Error;
        }
        let void = self.types.pointer(self.types.void());
        let target = self.conv().to_type(target, void);
        Stmt::IndirectGoto(target)
    }

    /// `asm(...)`, GNU's inline assembly.
    ///
    /// Nothing here reads a constraint the way a target will. What is checked is the part that
    /// belongs to the language rather than to the machine: an output has to be something the
    /// program is allowed to assign to, an output constraint has to say it is one with `=` or
    /// `+`, an input constraint has to not say it, and the labels of an `asm goto` are labels of
    /// the function it is in. Whether the target has a register that fits a `"r"` is a question
    /// for the backend, which is the only place a wrong answer to it can be given.
    ///
    /// The operands keep the order they were written in, because the template names them by
    /// position: the outputs are numbered from zero and the inputs carry on from there, which is
    /// the numbering `%0` counts in.
    fn asm(&mut self, id: ast::AsmId, span: Span) -> Stmt {
        let node = self.ast[id];
        let outputs = self.asm_operands(node.outputs, 0, true);
        let first_input = self.ast[node.outputs].len();
        let inputs = self.asm_operands(node.inputs, first_input, false);

        let mut clobbers = Vec::with_capacity(self.ast[node.clobbers].len());
        for index in 0..self.ast[node.clobbers].len() {
            let clobber = self.ast[node.clobbers][index];
            clobbers.push(self.asm_string(clobber, span));
        }
        let clobbers = self.tast.add_str_refs(&clobbers);

        let mut labels = Vec::with_capacity(self.ast[node.labels].len());
        for index in 0..self.ast[node.labels].len() {
            let name = self.ast[node.labels][index];
            labels.push(self.label(name, span));
        }
        let labels = self.tast.add_label_refs(&labels);
        let template = self.asm_template(node.template, outputs, inputs, labels, span);

        // A statement with no outputs is `volatile` whether it said so or not, since one whose
        // results nothing reads is otherwise one that may be dropped, and an `asm goto` is
        // volatile for the same reason: what it does is jump, and no output records that.
        let mut quals = node.quals;
        if self.ast[node.outputs].is_empty() || quals.has(AsmQuals::GOTO) {
            quals = quals.with(AsmQuals::VOLATILE);
        }
        Stmt::Asm(self.tast.add_asm(Asm { template, outputs, inputs, clobbers, labels, quals }))
    }

    /// One section of operands, numbered from `first` for the messages that count them.
    fn asm_operands(
        &mut self,
        list: ast::AsmOperandList,
        first: usize,
        output: bool,
    ) -> AsmOperandList {
        let mut operands = Vec::with_capacity(self.ast[list].len());
        for index in 0..self.ast[list].len() {
            let operand = self.ast[list][index];
            let operand = self.asm_operand(operand, first + index, output);
            operands.push(operand);
        }
        self.tast.add_asm_operands(&operands)
    }

    /// One operand, checked against what its constraint says it is.
    fn asm_operand(&mut self, operand: ast::AsmOperand, number: usize, output: bool) -> AsmOperand {
        let span = operand.span;
        let constraint = self.asm_string(operand.constraint, span);
        let text = spelling(&self.tast[constraint]);
        let value = self.expr(operand.value);
        let ty = self.tast[value].ty;
        let lvalue = matches!(self.tast[value].category, Category::Lvalue | Category::Bitfield);

        // A structure has no register to sit in, so it travels the only way it can whatever the
        // constraint says, and a constraint that does not allow memory is turned down rather
        // than lowered to an address the backend has no reason to expect.
        let record = is_record(&self.types, ty);
        let memory = memory_only(&text) || record;
        if record && !memory_only(&text) {
            self.statement_unsupported("a structure or a union in a register constraint", span);
        }

        if output {
            if !text.starts_with(['=', '+']) {
                self.report(
                    Diagnostic::error("output operand constraint lacks '='", span)
                        .with_code("E0653"),
                );
            }
            if !lvalue {
                self.report(
                    Diagnostic::error("lvalue required in 'asm' statement", span)
                        .with_code("E0654"),
                );
            } else if self.types.quals(ty).has(Qualifiers::CONST) {
                let what = self.read_only(value);
                self.report(
                    Diagnostic::error(format!("read-only {what} used as 'asm' output"), span)
                        .with_code("E0655"),
                );
            }
        } else {
            if let Some(sign) = text.chars().find(|&ch| ch == '=' || ch == '+') {
                self.report(
                    Diagnostic::error(format!("input operand constraint contains '{sign}'"), span)
                        .with_code("E0656"),
                );
            }
            if memory && !lvalue {
                self.report(
                    Diagnostic::error(
                        format!("memory input {number} is not directly addressable"),
                        span,
                    )
                    .with_code("E0657"),
                );
            }
        }

        // An output is written through, and an operand in memory is addressed, so both of those
        // stay the object they name. Everything else is read, which is what turns an array into
        // a pointer and a variable into its value.
        let value = if output || memory { value } else { self.value(value) };
        AsmOperand { name: operand.name, constraint, value, memory }
    }

    /// One of the strings of an assembly statement, copied into the typed tree.
    fn asm_string(&mut self, id: ast::StrId, span: Span) -> StrId {
        let literal = self.ast[id].clone();
        self.asm_narrow(&literal, span);
        self.tast.add_string(literal)
    }

    /// Reports a string of an assembly statement that is not one an assembler can be handed.
    fn asm_narrow(&mut self, literal: &StringLiteral, span: Span) {
        if !matches!(literal.encoding, Encoding::Plain) {
            self.report(Diagnostic::error("wide string literal in 'asm'", span).with_code("E0658"));
        }
    }

    /// The template, with every name in it replaced by the number of the thing it names.
    ///
    /// gcc numbers the operands and the labels in one sequence, the outputs first and the labels
    /// last, and `%[name]` is a way of writing one of those numbers without having to count. So
    /// the numbers are what is kept here: the template that reaches an assembler refers to its
    /// operands by position, which is what a position is for, and nothing downstream has to
    /// carry the names around in order to be able to read one.
    fn asm_template(
        &mut self,
        id: ast::StrId,
        outputs: AsmOperandList,
        inputs: AsmOperandList,
        labels: LabelList,
        span: Span,
    ) -> StrId {
        let mut names: Vec<(String, usize)> = Vec::new();
        let mut number = 0;
        for list in [outputs, inputs] {
            for index in 0..self.tast[list].len() {
                if let Some(name) = self.tast[list][index].name {
                    names.push((self.text(name).to_owned(), number));
                }
                number += 1;
            }
        }
        for index in 0..self.tast[labels].len() {
            let label = self.tast[labels][index];
            let name = self.tast[label].name;
            names.push((self.text(name).to_owned(), number));
            number += 1;
        }
        for at in 1..names.len() {
            if names[..at].iter().any(|(earlier, _)| *earlier == names[at].0) {
                let name = names[at].0.clone();
                self.report(
                    Diagnostic::error(format!("duplicate asm operand name '{name}'"), span)
                        .with_code("E0659"),
                );
            }
        }

        let literal = self.ast[id].clone();
        self.asm_narrow(&literal, span);
        let text = self.asm_numbers(spelling(&literal), &names, span);
        let elements = text.chars().map(|ch| ch as u32).collect();
        self.tast.add_string(StringLiteral { elements, ..literal })
    }

    /// One template, with the names in it resolved.
    ///
    /// A name comes straight after the `%` or after one modifier letter, which is what makes
    /// `%[x]`, `%w[x]` and `%l[x]` all one reference and the letter in the middle none of this
    /// walk's business. `%%` is a percent sign and is stepped over whole, so the brackets in
    /// `%%[x]` are two characters of assembly and not a name.
    fn asm_numbers(&mut self, text: String, names: &[(String, usize)], span: Span) -> String {
        let chars: Vec<char> = text.chars().collect();
        let mut out = String::with_capacity(text.len());
        let mut index = 0;
        while index < chars.len() {
            let ch = chars[index];
            out.push(ch);
            index += 1;
            if ch != '%' {
                continue;
            }
            let letter = chars.get(index).copied();
            let open = match letter {
                Some('[') => index,
                Some(modifier)
                    if modifier.is_ascii_alphabetic() && chars.get(index + 1) == Some(&'[') =>
                {
                    out.push(modifier);
                    index += 1;
                    index
                }
                // `%%` is the one escape that hides what comes after it.
                Some('%') => {
                    out.push('%');
                    index += 1;
                    continue;
                }
                _ => continue,
            };
            let Some(close) = chars[open..].iter().position(|&ch| ch == ']').map(|at| open + at)
            else {
                continue;
            };
            let name: String = chars[open + 1..close].iter().collect();
            index = close + 1;
            match names.iter().find(|(known, _)| *known == name) {
                Some(&(_, number)) => out.push_str(&number.to_string()),
                None => {
                    self.report(
                        Diagnostic::error(format!("undefined named operand '{name}'"), span)
                            .with_code("E0660"),
                    );
                    out.push_str(&chars[open..=close].iter().collect::<String>());
                }
            }
        }
        out
    }

    /// `break;`, which needs a loop or a `switch` around it.
    fn break_stmt(&mut self, span: Span) -> Stmt {
        let inside =
            self.body.as_ref().is_some_and(|state| state.loops > 0 || !state.switches.is_empty());
        if inside {
            return Stmt::Break;
        }
        self.report(
            Diagnostic::error("break statement not within loop or switch", span).with_code("E0631"),
        );
        Stmt::Error
    }

    /// `continue;`, which needs a loop and is not satisfied by a `switch`.
    fn continue_stmt(&mut self, span: Span) -> Stmt {
        if self.body.as_ref().is_some_and(|state| state.loops > 0) {
            return Stmt::Continue;
        }
        self.report(
            Diagnostic::error("continue statement not within a loop", span).with_code("E0632"),
        );
        Stmt::Error
    }

    /// `return;` or `return expr;`, checked against the return type.
    ///
    /// Both mismatches are errors. They were warnings for as long as C has had prototypes, and
    /// gcc 14 turned them into errors along with the rest of `-Wreturn-mismatch`, because a
    /// function that returns nothing where a value was promised hands its caller whatever was in
    /// the return register.
    fn return_stmt(&mut self, value: Option<ast::ExprId>, span: Span) -> Stmt {
        let Some((ret, at)) = self.body.as_ref().map(|state| (state.ret, state.at)) else {
            return Stmt::Return(None);
        };
        let void = is_void(&self.types, ret);
        // C89 let a function return without the value it promised and let one return a value it
        // had no way to give back, and gcc still takes both at that dialect: the first silently
        // and the second with a warning. C99 removed them and gcc has made them errors.
        let old = self.cx.std < Std::C99;
        let Some(value) = value else {
            if !void && !old {
                self.report(
                    Diagnostic::error(
                        "'return' with no value, in function returning non-void",
                        span,
                    )
                    .with_code("E0633")
                    .note("declared here".to_owned(), at),
                );
            }
            return Stmt::Return(None);
        };
        let where_from = self.ast.expr_span(value);
        let value = self.expr(value);
        let value = self.value(value);
        if !void {
            return Stmt::Return(Some(self.assign_to(ret, value, where_from, Target::Return)));
        }
        // C23 6.8.6.4 lets a function returning `void` say `return f();` where `f` returns
        // `void`, which is what a wrapper does and what gcc has always accepted.
        if !is_void(&self.types, self.tast[value].ty) && !self.is_poisoned(value) {
            let said = "'return' with a value, in function returning void";
            let diagnostic = if old {
                Diagnostic::warning(said, where_from)
            } else {
                Diagnostic::error(said, where_from)
            };
            self.report(diagnostic.with_code("E0634").note("declared here".to_owned(), at));
        }
        let value = self.conv().to_void(value);
        Stmt::Return(Some(value))
    }

    /// The controlling expression of an `if`, a `while`, a `do` or a `for`.
    fn controlling(&mut self, cond: ast::ExprId) -> ExprId {
        let span = self.ast.expr_span(cond);
        let cond = self.expr(cond);
        self.condition(cond, span)
    }

    /// The innermost `switch` being checked.
    fn switches(&mut self) -> Option<&mut Switch> {
        self.body.as_mut()?.switches.last_mut()
    }

    /// A statement form that is recognised and not checked yet.
    fn statement_unsupported(&mut self, what: &str, span: Span) {
        self.report(
            Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
        );
    }
}

/// Whether the scope of one variably modified declaration is open somewhere.
///
/// The chain from `at` outwards through the declarations it was written inside is every one of
/// them whose scope is open there, so this is a walk up that chain looking for the one asked
/// about. A jump is allowed when everything the label is inside is something the jump is inside
/// as well, and since these nest, asking it of the innermost is asking it of all of them.
fn open_at(modified: &[Modified], at: Option<usize>, entered: usize) -> bool {
    let mut at = at;
    while let Some(index) = at {
        if index == entered {
            return true;
        }
        at = modified[index].outer;
    }
    false
}

/// The text of one of the strings of an assembly statement.
///
/// The elements of a narrow literal are its bytes, which is what the assembler is handed. One
/// that is not narrow was reported where it was read, and reading it here as characters rather
/// than refusing to read it keeps one mistake from becoming two messages.
fn spelling(literal: &StringLiteral) -> String {
    literal.elements.iter().filter_map(|&element| char::from_u32(element)).collect()
}

/// Whether a constraint allows memory and allows nothing else.
///
/// The letters that mean memory are the machine independent ones, `m`, `o` and `V`, and the two
/// that mean an address the instruction modifies. Everything else is a register class, a
/// constant, a matching operand or a letter the target invented, and each of those is a value.
/// A constraint that allows either, `"rm"`, is a value here, which is the answer gcc reaches for
/// as well and which is free to give: a value the target cannot hold in a register is a question
/// the backend gets to ask about a machine it knows.
fn memory_only(constraint: &str) -> bool {
    let letters: Vec<char> =
        constraint.chars().filter(|ch| !"=+&%#*!?, \t".contains(*ch)).collect();
    !letters.is_empty() && letters.iter().all(|ch| "moV<>".contains(*ch))
}

#[cfg(test)]
mod tests {
    use rucc_ast::{
        ArraySize, AttrList, Builtin, BuiltinSet, DeclSpecs, DeclSpecsId, Declarator, DeclaratorId,
        Derived, Quals, TypeSpec,
    };
    use rucc_base::Interner;
    use rucc_lex::{IntConstant, IntConstantType, Remarks};
    use rucc_session::Std;
    use rucc_target::{TargetInfo, Triple};
    use rucc_types::IntKind;

    use super::*;
    use crate::check::Context;
    use crate::print::Printer;

    /// The untyped tree a test checks, built by hand.
    ///
    /// The same shape as the fixtures next door and for the same reason: the checker borrows the
    /// interner for as long as it lives, so everything a test needs to name is named before the
    /// checker exists.
    struct Fixture {
        ast: rucc_ast::Ast,
        names: Interner,
        target: TargetInfo,
    }

    impl Fixture {
        fn new() -> Fixture {
            let target =
                TargetInfo::new("x86_64-unknown-linux-gnu".parse::<Triple>().expect("a triple"));
            Fixture { ast: rucc_ast::Ast::new(), names: Interner::new(), target }
        }

        fn name(&mut self, text: &str) -> Symbol {
            self.names.intern(text)
        }

        fn int(&mut self, value: u128) -> ast::ExprId {
            let ty = IntConstantType::Standard(IntKind::Int);
            let id = self.ast.add_int(IntConstant { value, ty, remarks: Remarks::default() });
            self.ast.expr(ast::Expr::Int(id), Span::DUMMY)
        }

        fn use_name(&mut self, text: &str) -> ast::ExprId {
            let name = self.name(text);
            self.ast.expr(ast::Expr::Name(name), Span::DUMMY)
        }

        /// A specifier list naming a built-in type, as the keywords that were written.
        fn keywords(&mut self, written: &[BuiltinSet]) -> DeclSpecsId {
            let mut builtin = Builtin::NONE;
            for &keyword in written {
                builtin = builtin.add(keyword).expect("a keyword written once");
            }
            let mut specs = DeclSpecs::empty(Span::DUMMY);
            specs.ty = TypeSpec::Builtin(builtin);
            self.ast.add_specs(specs)
        }

        /// `int`, which is what most of these declarations are made of.
        fn int_specs(&mut self) -> DeclSpecsId {
            self.keywords(&[BuiltinSet::INT])
        }

        fn declarator(&mut self, name: Option<&str>, derived: &[Derived]) -> DeclaratorId {
            let name = name.map(|text| self.name(text));
            let derived = self.ast.add_derived_list(derived);
            self.ast.add_declarator(Declarator {
                name,
                name_span: Span::DUMMY,
                derived,
                span: Span::DUMMY,
            })
        }

        /// `int x;` and the like, as a statement.
        fn local(&mut self, specs: DeclSpecsId, name: &str) -> ast::DeclId {
            let declarator = self.declarator(Some(name), &[]);
            let item = ast::InitDeclarator {
                declarator,
                init: None,
                asm_label: None,
                attrs: AttrList::EMPTY,
                span: Span::DUMMY,
            };
            let declarators = self.ast.add_init_declarator_list(&[item]);
            self.ast.decl(ast::Decl::Var { specs, declarators }, Span::DUMMY)
        }

        /// `int name[size];`, which is a variable length array when the size is not a constant.
        fn array(&mut self, specs: DeclSpecsId, name: &str, size: ast::ExprId) -> ast::DeclId {
            let derived = [Derived::Array {
                size: ArraySize::Expr(size),
                quals: Quals::NONE,
                has_static: false,
            }];
            let declarator = self.declarator(Some(name), &derived);
            let item = ast::InitDeclarator {
                declarator,
                init: None,
                asm_label: None,
                attrs: AttrList::EMPTY,
                span: Span::DUMMY,
            };
            let declarators = self.ast.add_init_declarator_list(&[item]);
            self.ast.decl(ast::Decl::Var { specs, declarators }, Span::DUMMY)
        }

        /// `(ty)value`, which is how these tests write an expression of a type they choose.
        fn cast(&mut self, specs: DeclSpecsId, value: ast::ExprId) -> ast::ExprId {
            let declarator = self.declarator(None, &[]);
            let ty = self.ast.add_type_name(ast::TypeName { specs, declarator, span: Span::DUMMY });
            self.ast.expr(ast::Expr::Cast { ty, operand: value }, Span::DUMMY)
        }

        fn stmt(&mut self, stmt: ast::Stmt) -> ast::StmtId {
            self.ast.stmt(stmt, Span::DUMMY)
        }

        /// `{ ... }`, from the statements it holds.
        fn block(&mut self, body: &[ast::StmtId]) -> ast::StmtId {
            let body = self.ast.add_stmt_list(body);
            self.stmt(ast::Stmt::Compound(body))
        }

        /// `value;`.
        fn expr_stmt(&mut self, value: ast::ExprId) -> ast::StmtId {
            self.stmt(ast::Stmt::Expr(value))
        }

        /// `name: body`.
        fn labelled(&mut self, text: &str, body: Option<ast::StmtId>) -> ast::StmtId {
            let name = self.name(text);
            self.stmt(ast::Stmt::Label { name, body, attrs: AttrList::EMPTY })
        }

        /// `goto name;`.
        fn goto(&mut self, text: &str) -> ast::StmtId {
            let name = self.name(text);
            self.stmt(ast::Stmt::Goto(name))
        }

        /// `__label__ a, b;`.
        fn local_labels(&mut self, names: &[&str]) -> ast::StmtId {
            let names: Vec<Symbol> = names.iter().map(|text| self.name(text)).collect();
            let names = self.ast.add_symbol_list(&names);
            self.stmt(ast::Stmt::LocalLabels(names))
        }

        /// `case lo: body`, or GNU's `case lo ... hi: body`.
        fn case(&mut self, lo: u128, hi: Option<u128>, body: Option<ast::StmtId>) -> ast::StmtId {
            let lo = self.int(lo);
            let hi = hi.map(|hi| self.int(hi));
            self.stmt(ast::Stmt::Case { lo, hi, body })
        }

        /// `switch (scrutinee) { ... }`.
        fn switch(&mut self, scrutinee: ast::ExprId, body: &[ast::StmtId]) -> ast::StmtId {
            let body = self.block(body);
            self.stmt(ast::Stmt::Switch { scrutinee, body })
        }

        fn checker(&self) -> Checker<'_> {
            Checker::new(&self.ast, Context::new(&self.names, &self.target, Std::C23))
        }
    }

    /// The tree under one statement, which is what most assertions here are about.
    fn dump(checker: &Checker<'_>, id: StmtId) -> String {
        let mut printer = Printer::new(&checker.tast, &checker.types, checker.cx.names);
        printer.stmt(id);
        printer.finish()
    }

    /// What was reported, as the messages alone, notes included.
    fn messages(checker: &Checker<'_>) -> Vec<String> {
        checker
            .errors
            .diagnostics()
            .iter()
            .flat_map(|d| {
                std::iter::once(d.message.clone())
                    .chain(d.children.iter().map(|n| n.message.clone()))
            })
            .collect()
    }

    /// The one message that was reported, which is what most of these tests expect.
    fn message(checker: &Checker<'_>) -> String {
        let mut reported = messages(checker);
        assert_eq!(reported.len(), 1, "expected exactly one diagnostic, got {reported:?}");
        reported.pop().expect("one message")
    }

    /// What was reported, as the severity and the message of each, so that a test can say which
    /// of the two a diagnostic is. gcc 14 turned several of these from warnings into errors and
    /// the difference is the whole point of some of the tests below.
    fn reported(checker: &Checker<'_>) -> Vec<String> {
        checker
            .errors
            .diagnostics()
            .iter()
            .map(|d| format!("{}: {}", d.severity.as_str(), d.message))
            .collect()
    }

    #[test]
    fn a_block_is_a_scope_and_a_name_declared_in_one_is_gone_after_it() {
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let declared = f.local(specs, "x");
        let declared = f.stmt(ast::Stmt::Decl(declared));
        let inner = f.block(&[declared]);
        let use_x = f.use_name("x");
        let after = f.expr_stmt(use_x);
        let outer = f.block(&[inner, after]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, outer);

        assert_eq!(message(&c), "'x' undeclared (first use in this function)");
    }

    #[test]
    fn a_name_nobody_declared_is_reported_once_per_function_and_not_once_per_use() {
        // The wording promises it: `first use in this function` said three times is a sentence
        // arguing with itself. A misspelled name written in a loop body is one mistake, and one
        // message is what makes the next mistake in the file visible.
        let mut f = Fixture::new();
        let first = f.use_name("nope");
        let first = f.expr_stmt(first);
        let second = f.use_name("nope");
        let second = f.expr_stmt(second);
        let body = f.block(&[first, second]);

        let mut c = f.checker();
        let void = c.types.void();
        let previous = c.open_body(Enclosing::returning(void));
        c.check_stmt(void, body);
        c.close_body(previous);

        assert_eq!(message(&c), "'nope' undeclared (first use in this function)");
    }

    #[test]
    fn an_expression_statement_holds_the_value_and_not_a_conversion_of_it_to_void() {
        let mut f = Fixture::new();
        let one = f.int(1);
        let stmt = f.expr_stmt(one);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, stmt);

        assert_eq!(dump(&c, id), "expr\n  const 1 : int\n");
        assert!(c.errors.is_empty());
    }

    #[test]
    fn a_statement_expression_has_the_type_of_its_last_statement() {
        let mut f = Fixture::new();
        let one = f.int(1);
        let inner = f.expr_stmt(one);
        let body = f.block(&[inner]);
        let value = f.ast.expr(ast::Expr::StmtExpr(body), Span::DUMMY);
        let stmt = f.expr_stmt(value);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, stmt);

        assert_eq!(
            dump(&c, id),
            "expr\n  stmt-expr : int\n    block\n      expr\n        const 1 : int\n"
        );
        assert!(c.errors.is_empty());
    }

    #[test]
    fn a_statement_expression_that_ends_in_something_else_is_void() {
        let mut f = Fixture::new();
        let body = f.block(&[]);
        let value = f.ast.expr(ast::Expr::StmtExpr(body), Span::DUMMY);
        let stmt = f.expr_stmt(value);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, stmt);

        assert_eq!(dump(&c, id), "expr\n  stmt-expr : void\n    block\n");
        assert!(c.errors.is_empty());
    }

    #[test]
    fn the_declaration_in_a_for_clause_scopes_to_the_loop_and_not_to_what_follows() {
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let declared = f.local(specs, "i");
        let empty = f.stmt(ast::Stmt::Empty);
        let loop_stmt = f.stmt(ast::Stmt::For {
            init: ForInit::Decl(declared),
            cond: None,
            step: None,
            body: empty,
        });
        let use_i = f.use_name("i");
        let after = f.expr_stmt(use_i);
        let outer = f.block(&[loop_stmt, after]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, outer);

        assert_eq!(message(&c), "'i' undeclared (first use in this function)");
    }

    #[test]
    fn a_static_in_a_for_clause_is_accepted_and_only_pedantic_says_anything_about_it() {
        let mut f = Fixture::new();
        let mut specs = DeclSpecs::empty(Span::DUMMY);
        let builtin = Builtin::NONE.add(BuiltinSet::INT).expect("a keyword written once");
        specs.ty = TypeSpec::Builtin(builtin);
        specs.storage = Some(StorageClass::Static);
        let specs = f.ast.add_specs(specs);
        let declared = f.local(specs, "i");
        let empty = f.stmt(ast::Stmt::Empty);
        let loop_stmt = f.stmt(ast::Stmt::For {
            init: ForInit::Decl(declared),
            cond: None,
            step: None,
            body: empty,
        });

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, loop_stmt);
        assert!(c.errors.is_empty(), "got {:?}", messages(&c));

        let mut c = f.checker();
        c.cx.pedantic = true;
        let void = c.types.void();
        c.check_stmt(void, loop_stmt);
        assert_eq!(
            reported(&c),
            ["warning: declaration of static variable 'i' in 'for' loop initial declaration"]
        );
    }

    #[test]
    fn continue_needs_a_loop_and_is_not_satisfied_by_a_switch() {
        let mut f = Fixture::new();
        let one = f.int(1);
        let go_on = f.stmt(ast::Stmt::Continue);
        let case = f.stmt(ast::Stmt::Case { lo: one, hi: None, body: Some(go_on) });
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[case]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(message(&c), "continue statement not within a loop");
    }

    #[test]
    fn break_is_satisfied_by_a_switch_and_reported_where_there_is_neither() {
        let mut f = Fixture::new();
        let stop = f.stmt(ast::Stmt::Break);
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[stop]);
        let loose = f.stmt(ast::Stmt::Break);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);
        assert!(c.errors.is_empty(), "got {:?}", messages(&c));

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, loose);
        assert_eq!(message(&c), "break statement not within loop or switch");
    }

    #[test]
    fn a_goto_resolves_to_a_label_the_function_defines_further_down() {
        let mut f = Fixture::new();
        let jump = f.goto("done");
        let empty = f.stmt(ast::Stmt::Empty);
        let target = f.labelled("done", Some(empty));
        let body = f.block(&[jump, target]);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, body);

        assert_eq!(dump(&c, id), "block\n  goto #0 done\n  label #0 done\n    empty\n");
        assert!(c.errors.is_empty());
    }

    #[test]
    fn a_label_that_is_jumped_to_and_never_defined_is_reported_at_the_jump() {
        let mut f = Fixture::new();
        let jump = f.goto("away");
        let body = f.block(&[jump]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(message(&c), "label 'away' used but not defined");
    }

    #[test]
    fn the_address_of_a_label_is_a_use_of_it_and_not_a_definition() {
        let mut f = Fixture::new();
        let away = f.name("away");
        let value = f.ast.expr(ast::Expr::LabelAddr(away), Span::DUMMY);
        let stmt = f.expr_stmt(value);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, stmt);

        assert_eq!(dump(&c, id), "expr\n  label-addr #0 away : void *\n");
        assert_eq!(message(&c), "label 'away' used but not defined");
    }

    #[test]
    fn a_goto_into_the_scope_of_a_variable_length_array_is_reported() {
        // `int n; goto done; { int a[n]; done: ; }`, which lands in a block where `a` is
        // supposed to exist without having gone past the line that makes it.
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let length = f.local(specs, "n");
        let length = f.stmt(ast::Stmt::Decl(length));
        let jump = f.goto("done");
        let size = f.use_name("n");
        let array = f.array(specs, "a", size);
        let array = f.stmt(ast::Stmt::Decl(array));
        let empty = f.stmt(ast::Stmt::Empty);
        let target = f.labelled("done", Some(empty));
        let inner = f.block(&[array, target]);
        let body = f.block(&[length, jump, inner]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(
            messages(&c),
            [
                "jump into scope of identifier with variably modified type",
                "label 'done' defined here",
                "'a' declared here",
            ]
        );
    }

    #[test]
    fn a_goto_out_of_the_scope_of_a_variable_length_array_is_allowed() {
        // `int n; { int a[n]; goto done; } done: ;`, which is the direction C permits: the
        // array stops existing rather than starting to.
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let length = f.local(specs, "n");
        let length = f.stmt(ast::Stmt::Decl(length));
        let size = f.use_name("n");
        let array = f.array(specs, "a", size);
        let array = f.stmt(ast::Stmt::Decl(array));
        let jump = f.goto("done");
        let inner = f.block(&[array, jump]);
        let empty = f.stmt(ast::Stmt::Empty);
        let target = f.labelled("done", Some(empty));
        let body = f.block(&[length, inner, target]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
    }

    #[test]
    fn a_goto_into_the_scope_of_an_array_whose_length_is_a_constant_is_allowed() {
        // The same shape as the one that is reported, with a length nobody has to work out.
        // Nothing about `a` is decided where the declaration is, so there is nothing to skip.
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let jump = f.goto("done");
        let size = f.int(4);
        let array = f.array(specs, "a", size);
        let array = f.stmt(ast::Stmt::Decl(array));
        let empty = f.stmt(ast::Stmt::Empty);
        let target = f.labelled("done", Some(empty));
        let inner = f.block(&[array, target]);
        let body = f.block(&[jump, inner]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
    }

    #[test]
    fn one_label_defined_twice_is_an_error_that_points_at_the_first() {
        let mut f = Fixture::new();
        let first = f.labelled("here", None);
        let second = f.labelled("here", None);
        let body = f.block(&[first, second]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(
            messages(&c),
            ["duplicate label 'here'", "previous definition of 'here' with type 'void'",]
        );
    }

    #[test]
    fn a_local_label_is_undone_when_its_block_ends_so_two_blocks_may_declare_one_name() {
        let mut f = Fixture::new();
        let sibling = |f: &mut Fixture| {
            let declared = f.local_labels(&["done"]);
            let jump = f.goto("done");
            let target = f.labelled("done", None);
            f.block(&[declared, jump, target])
        };
        let first = sibling(&mut f);
        let second = sibling(&mut f);
        let body = f.block(&[first, second]);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, body);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
        assert_eq!(
            dump(&c, id),
            "block\n  block\n    empty\n    goto #0 done\n    label #0 done\n      empty\n  \
             block\n    empty\n    goto #1 done\n    label #1 done\n      empty\n"
        );
    }

    #[test]
    fn a_local_label_that_nothing_defines_is_reported_when_its_block_ends() {
        let mut f = Fixture::new();
        let declared = f.local_labels(&["done"]);
        let jump = f.goto("done");
        let inner = f.block(&[declared, jump]);
        let target = f.labelled("done", None);
        let body = f.block(&[inner, target]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(message(&c), "label 'done' used but not defined");
    }

    #[test]
    fn a_computed_goto_wants_something_that_could_be_an_address() {
        let mut f = Fixture::new();
        let specs = f.keywords(&[BuiltinSet::DOUBLE]);
        let zero = f.int(0);
        let target = f.cast(specs, zero);
        let stmt = f.stmt(ast::Stmt::GotoExpr(target));

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, stmt);

        assert_eq!(message(&c), "computed goto must be pointer type");
    }

    #[test]
    fn a_switch_on_something_that_is_not_an_integer_is_an_error() {
        let mut f = Fixture::new();
        let specs = f.keywords(&[BuiltinSet::DOUBLE]);
        let zero = f.int(0);
        let scrutinee = f.cast(specs, zero);
        let switch = f.switch(scrutinee, &[]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(message(&c), "switch quantity not an integer");
    }

    #[test]
    fn the_cases_of_a_switch_are_one_table_in_the_order_they_were_written() {
        let mut f = Fixture::new();
        let first = f.case(1, None, None);
        let second = f.case(4, Some(6), None);
        let default = f.stmt(ast::Stmt::Default { body: None });
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[first, second, default]);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, switch);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
        assert_eq!(
            dump(&c, id),
            "switch\n  cond\n    const 0 : int\n  cases\n    case #0 1\n    case #1 4 ... 6\n    \
             default\n  body\n    block\n      case #0\n        empty\n      case #1\n        \
             empty\n      default\n        empty\n"
        );
    }

    #[test]
    fn two_labels_on_one_statement_are_in_the_table_the_way_round_they_were_written() {
        // `case 1: case 2: ;` is one labelled statement inside another, so the checking runs
        // inside out. The table is a record of what the user wrote and does not follow it.
        let mut f = Fixture::new();
        let inner = f.case(2, None, None);
        let outer = f.case(1, None, Some(inner));
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[outer]);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, switch);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
        assert_eq!(
            dump(&c, id),
            "switch\n  cond\n    const 0 : int\n  cases\n    case #0 1\n    case #1 2\n  body\n    \
             block\n      case #0\n        case #1\n          empty\n"
        );
    }

    #[test]
    fn a_case_that_covers_a_value_an_earlier_one_covers_is_a_duplicate() {
        let mut f = Fixture::new();
        let first = f.case(1, Some(3), None);
        let second = f.case(2, None, None);
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[first, second]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(messages(&c), ["duplicate case value", "previously used here"]);
    }

    #[test]
    fn a_case_outside_a_switch_is_an_error_and_so_is_a_default() {
        let mut f = Fixture::new();
        let case = f.case(1, None, None);
        let default = f.stmt(ast::Stmt::Default { body: None });
        let body = f.block(&[case, default]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(
            messages(&c),
            [
                "case label not within a switch statement",
                "'default' label not within a switch statement",
            ]
        );
    }

    #[test]
    fn a_case_label_that_is_not_a_constant_is_an_error() {
        let mut f = Fixture::new();
        let specs = f.int_specs();
        let declared = f.local(specs, "n");
        let declared = f.stmt(ast::Stmt::Decl(declared));
        let use_n = f.use_name("n");
        let case = f.stmt(ast::Stmt::Case { lo: use_n, hi: None, body: None });
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[case]);
        let body = f.block(&[declared, switch]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, body);

        assert_eq!(message(&c), "case label does not reduce to an integer constant");
    }

    #[test]
    fn a_case_range_that_runs_backwards_is_empty() {
        let mut f = Fixture::new();
        let case = f.case(6, Some(4), None);
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[case]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(reported(&c), ["warning: empty range specified"]);
    }

    #[test]
    fn a_case_is_measured_against_the_type_that_was_written_and_not_the_promoted_one() {
        let mut f = Fixture::new();
        let specs = f.keywords(&[BuiltinSet::CHAR]);
        let zero = f.int(0);
        let scrutinee = f.cast(specs, zero);
        let case = f.case(300, None, None);
        let switch = f.switch(scrutinee, &[case]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(reported(&c), ["warning: case label value exceeds maximum value for type"]);
    }

    #[test]
    fn two_defaults_in_one_switch_are_an_error_that_points_at_the_first() {
        let mut f = Fixture::new();
        let first = f.stmt(ast::Stmt::Default { body: None });
        let second = f.stmt(ast::Stmt::Default { body: None });
        let scrutinee = f.int(0);
        let switch = f.switch(scrutinee, &[first, second]);

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, switch);

        assert_eq!(
            messages(&c),
            ["multiple default labels in one switch", "this is the first default label"]
        );
    }

    #[test]
    fn a_nested_switch_keeps_its_cases_to_itself() {
        let mut f = Fixture::new();
        let inner_case = f.case(1, None, None);
        let inner_scrutinee = f.int(0);
        let inner = f.switch(inner_scrutinee, &[inner_case]);
        let outer_case = f.case(1, None, Some(inner));
        let outer_scrutinee = f.int(0);
        let outer = f.switch(outer_scrutinee, &[outer_case]);

        let mut c = f.checker();
        let void = c.types.void();
        let id = c.check_stmt(void, outer);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
        assert_eq!(
            dump(&c, id),
            "switch\n  cond\n    const 0 : int\n  cases\n    case #1 1\n  body\n    block\n      \
             case #1\n        switch\n          cond\n            const 0 : int\n          \
             cases\n            case #0 1\n          body\n            block\n              case \
             #0\n                empty\n"
        );
    }

    #[test]
    fn a_bare_return_from_a_function_that_promised_a_value_is_an_error() {
        let mut f = Fixture::new();
        let stmt = f.stmt(ast::Stmt::Return(None));

        let mut c = f.checker();
        let int = c.int();
        c.check_stmt(int, stmt);

        assert_eq!(reported(&c), ["error: 'return' with no value, in function returning non-void"]);
        assert_eq!(messages(&c).len(), 2, "the note is attached to it");
    }

    #[test]
    fn a_value_returned_from_a_function_returning_void_is_an_error() {
        let mut f = Fixture::new();
        let one = f.int(1);
        let stmt = f.stmt(ast::Stmt::Return(Some(one)));

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, stmt);

        assert_eq!(reported(&c), ["error: 'return' with a value, in function returning void"]);
    }

    #[test]
    fn a_void_value_returned_from_a_function_returning_void_is_what_a_wrapper_writes() {
        let mut f = Fixture::new();
        let specs = f.keywords(&[BuiltinSet::VOID]);
        let one = f.int(1);
        let value = f.cast(specs, one);
        let stmt = f.stmt(ast::Stmt::Return(Some(value)));

        let mut c = f.checker();
        let void = c.types.void();
        c.check_stmt(void, stmt);

        assert!(c.errors.is_empty(), "got {:?}", messages(&c));
    }

    #[test]
    fn a_returned_value_is_converted_to_the_return_type() {
        let mut f = Fixture::new();
        let one = f.int(1);
        let stmt = f.stmt(ast::Stmt::Return(Some(one)));

        let mut c = f.checker();
        let long = c.types.int(IntKind::Long);
        let id = c.check_stmt(long, stmt);

        assert_eq!(dump(&c, id), "return\n  convert arithmetic : long\n    const 1 : int\n");
        assert!(c.errors.is_empty());
    }
}