cinrs-core 0.2.0

The C front end behind the cinrs crate: lexer, preprocessor, parser, semantic analysis, code generation
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
//! The C99 abstract syntax tree.
//!
//! Three design points matter for the milestones that follow:
//!
//! * **Every node carries a [`SourceRange`]**, so a diagnostic raised by sema
//!   (M0b) or a token emitted by codegen can be attributed to the exact piece
//!   of C it came from.
//!
//! * **Declarators are resolved into a type tree while parsing.** The parser
//!   never hands out a raw declarator chain; `int (*fp[3])(void)` arrives as
//!   `array of 3 pointer to function(void) returning int`. Sema therefore only
//!   ever has to walk [`Type`], which is also the shape codegen needs.
//!
//! * **The body of a tag specifier is stored once.** Resolving declarators
//!   eagerly means one specifier is named by several types — `struct S { … } a,
//!   b;` is the declaration's specifiers plus the type of each declarator — so
//!   the member list lives in [`TranslationUnit::records`] and the types carry
//!   a [`RecordSpecId`]. Copying it instead would double the tree at every
//!   level of a nested `struct`.

use crate::capture::SourceRange;
use crate::lex::{CharLit, FloatLit, IntLit, StrLit};

/// A value paired with the source range it came from.
#[derive(Clone, Debug, PartialEq)]
pub struct Spanned<T> {
    /// The value.
    pub node: T,
    /// Where it was written.
    pub range: SourceRange,
}

impl<T> Spanned<T> {
    /// Pairs `node` with `range`.
    pub fn new(node: T, range: SourceRange) -> Self {
        Self { node, range }
    }
}

/// An identifier occurrence.
#[derive(Clone, Debug, PartialEq)]
pub struct Ident {
    /// The spelling.
    pub name: String,
    /// Where it was written.
    pub range: SourceRange,
}

// ---------------------------------------------------------------------------
// types
// ---------------------------------------------------------------------------

/// `const` / `volatile` / `restrict`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TypeQualifiers {
    /// `const`
    pub is_const: bool,
    /// `volatile`
    pub is_volatile: bool,
    /// `restrict`
    pub is_restrict: bool,
    /// `_Atomic`, written without a parenthesised type name — C11 6.7.3 makes
    /// it a qualifier there and a type *specifier* in `_Atomic(T)`.
    ///
    /// Unlike the other three it changes the type: `_Atomic int` resolves to
    /// [`crate::ir::Ty::Atomic`], which is a different type from `int` and has
    /// its own alignment. That is why it is not part of [`TypeQualifiers::any`],
    /// which asks about the qualifiers a type *name* carries beside its type.
    pub is_atomic: bool,
}

impl TypeQualifiers {
    /// No qualifiers at all.
    pub const NONE: Self = Self {
        is_const: false,
        is_volatile: false,
        is_restrict: false,
        is_atomic: false,
    };

    /// Whether any of the three qualifiers that leave the type alone is set.
    pub fn any(self) -> bool {
        self.is_const || self.is_volatile || self.is_restrict
    }

    /// The union of two qualifier sets.
    pub fn merge(self, other: Self) -> Self {
        Self {
            is_const: self.is_const || other.is_const,
            is_volatile: self.is_volatile || other.is_volatile,
            is_restrict: self.is_restrict || other.is_restrict,
            is_atomic: self.is_atomic || other.is_atomic,
        }
    }
}

/// Signedness of an integer type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sign {
    /// `signed` (explicitly or by default).
    Signed,
    /// `unsigned`.
    Unsigned,
}

/// Rank of a standard integer type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IntSize {
    /// `short`
    Short,
    /// `int`
    Int,
    /// `long`
    Long,
    /// `long long`
    LongLong,
    /// GNU's `__int128`.
    Int128,
}

/// Rank of a standard floating type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FloatSize {
    /// `float`
    Float,
    /// `double`
    Double,
    /// `long double`
    LongDouble,
    /// TS 18661-3's `_Float32`, which is `float`.
    Float32,
    /// `_Float64`, which is `double`.
    Float64,
    /// `_Float32x`, which is `double`.
    Float32x,
    /// `_Float64x`, which is whatever `long double` is.
    Float64x,
    /// `_Float128` (and GCC's `__float128`): binary128, which has no Rust type.
    /// It may be named — in a prototype, a `typedef`, a pointer — but sema
    /// refuses every value of it.
    Float128,
}

impl FloatSize {
    /// The type as C spells it.
    pub fn as_str(self) -> &'static str {
        match self {
            FloatSize::Float => "float",
            FloatSize::Double => "double",
            FloatSize::LongDouble => "long double",
            FloatSize::Float32 => "_Float32",
            FloatSize::Float64 => "_Float64",
            FloatSize::Float32x => "_Float32x",
            FloatSize::Float64x => "_Float64x",
            FloatSize::Float128 => "_Float128",
        }
    }

    /// Whether this is one of the `_FloatN` spellings, which GCC makes types
    /// distinct from `float`, `double` and `long double` even where they have
    /// the same format; see `_Generic` in sema.
    pub fn is_floatn(self) -> bool {
        !matches!(
            self,
            FloatSize::Float | FloatSize::Double | FloatSize::LongDouble
        )
    }
}

/// `struct` or `union`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordKind {
    /// `struct`
    Struct,
    /// `union`
    Union,
}

impl RecordKind {
    /// The keyword that introduces this kind of record.
    pub fn as_str(self) -> &'static str {
        match self {
            RecordKind::Struct => "struct",
            RecordKind::Union => "union",
        }
    }
}

/// The size of an array derivation.
#[derive(Clone, Debug, PartialEq)]
pub enum ArraySize {
    /// `[]` — an incomplete array type.
    Unspecified,
    /// `[*]` — a variable length array of unspecified size, only valid in a
    /// function prototype.
    Star,
    /// `[expr]`. Whether this is a constant array bound or a VLA is decided by
    /// constant evaluation in sema.
    Expr(Box<Expr>),
}

/// A C type, as produced by resolving declaration specifiers and a declarator.
#[derive(Clone, Debug, PartialEq)]
pub struct Type {
    /// What kind of type this is.
    pub kind: TypeKind,
    /// Qualifiers applied to *this* type (not to what it points at).
    pub qualifiers: TypeQualifiers,
    /// The source range of the construct that produced this type.
    pub range: SourceRange,
}

impl Type {
    /// Builds a type.
    pub fn new(kind: TypeKind, qualifiers: TypeQualifiers, range: SourceRange) -> Self {
        Self {
            kind,
            qualifiers,
            range,
        }
    }

    /// Builds an unqualified type.
    pub fn plain(kind: TypeKind, range: SourceRange) -> Self {
        Self::new(kind, TypeQualifiers::NONE, range)
    }

    /// Whether this is the placeholder produced by error recovery.
    pub fn is_error(&self) -> bool {
        matches!(self.kind, TypeKind::Error)
    }
}

/// The shape of a [`Type`].
#[derive(Clone, Debug, PartialEq)]
pub enum TypeKind {
    /// `void`
    Void,
    /// `_Bool`
    Bool,
    /// `char`, `signed char` or `unsigned char`. `None` means plain `char`,
    /// which is a distinct type from both of the others.
    Char(Option<Sign>),
    /// `short`, `int`, `long`, `long long`, signed or unsigned.
    Int {
        /// Signedness.
        sign: Sign,
        /// Rank.
        size: IntSize,
    },
    /// `float`, `double`, `long double`.
    Float(FloatSize),
    /// `float _Complex` and friends.
    Complex(FloatSize),
    /// `float _Imaginary` and friends.
    Imaginary(FloatSize),
    /// Pointer to the given type.
    Pointer(Box<Type>),
    /// Array derivation.
    Array {
        /// Element type.
        elem: Box<Type>,
        /// The bound.
        size: ArraySize,
        /// Qualifiers written inside the brackets (`int p[const 4]`); only
        /// meaningful on a parameter.
        qualifiers: TypeQualifiers,
        /// Whether `static` was written inside the brackets.
        is_static: bool,
    },
    /// Function derivation.
    Function(Box<FunctionType>),
    /// A `struct`/`union` specifier, with or without a body.
    ///
    /// The specifier itself lives in [`TranslationUnit::records`]; see
    /// [`RecordSpecId`] for why it is an id rather than the body.
    Record(RecordSpecId),
    /// An `enum` specifier, with or without a body.
    Enum(EnumSpecId),
    /// A name introduced by `typedef`, not yet resolved.
    Typedef(Ident),
    /// `typeof(…)` / `typeof_unqual(…)` — C23.
    ///
    /// The operand lives in [`TranslationUnit::typeofs`]; see [`TypeofId`].
    Typeof {
        /// Which operand.
        id: TypeofId,
        /// Whether this is `typeof_unqual`, which takes the *unqualified*
        /// type of its operand (C23 6.7.2.5p3).
        ///
        /// Only one qualifier is part of a [`crate::ir::Ty`] at all —
        /// `_Atomic`, which changes the size, the alignment and what an access
        /// to the object does — so that is the one this strips.
        unqual: bool,
    },
    /// The type `auto x = e;` infers from the initialiser — C23.
    Auto,
    /// Produced by error recovery; sema must not report further errors on it.
    Error,
}

/// Identifies one `typeof` operand in [`TranslationUnit::typeofs`].
///
/// Stored apart for the reason a [`RecordSpecId`] is: a type name holds both
/// the specifiers it was written with and the type its declarator produced, so
/// a `typeof` written inside another one would otherwise be copied twice per
/// level.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TypeofId(pub u32);

impl TypeofId {
    /// The index into [`TranslationUnit::typeofs`].
    pub fn index(self) -> usize {
        self.0 as usize
    }
}

/// What `typeof` was applied to.
//
// The AST is built once per macro invocation and then walked; boxing the type
// name to even the variants out would only make sema noisier to write.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum TypeofOperand {
    /// `typeof(expr)`, whose operand is not evaluated.
    Expr(Expr),
    /// `typeof(type-name)`.
    Type(TypeName),
}

/// A function type derivation.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionType {
    /// The return type.
    pub ret: Type,
    /// The declared parameters (empty for `f(void)` and for `f()`).
    pub params: Vec<ParamDecl>,
    /// Whether the parameter list ended with `, ...`.
    pub variadic: bool,
    /// Where the `...` was written, which is where a diagnostic about it
    /// belongs.
    pub ellipsis: Option<SourceRange>,
    /// Whether a prototype was given at all. `int f()` and `int f(a, b)` have
    /// no prototype; `int f(void)` and `int f(int)` do.
    pub has_prototype: bool,
    /// The identifier list of an old-style (K&R) declarator, e.g. `f(a, b)`.
    pub kr_names: Vec<Ident>,
    /// Whether [`FunctionType::params`] came from an identifier list and the
    /// declaration list of an old-style definition rather than from a
    /// prototype.
    ///
    /// Sema builds that list — see `Sema::old_style_params` — so the rest of
    /// the front end sees ordinary parameters; the flag is what remembers that
    /// the *type* still has no prototype and that the generated item takes the
    /// promoted types (C99 6.9.1p7).
    pub old_style: bool,
}

/// One parameter of a function prototype.
#[derive(Clone, Debug, PartialEq)]
pub struct ParamDecl {
    /// The parameter's declaration specifiers.
    pub specifiers: DeclSpecifiers,
    /// The parameter name, absent in an abstract declarator.
    pub name: Option<Ident>,
    /// The parameter's type after applying its declarator.
    pub ty: Type,
    /// Where the parameter was written.
    pub range: SourceRange,
}

/// Identifies one `struct`/`union` specifier in [`TranslationUnit::records`].
///
/// A declarator is resolved into a [`Type`] as it is parsed, so the specifier
/// of `struct S { … } a, b;` is named by the type of every declarator that
/// shares it *and* by the declaration's own specifiers. Storing the member
/// list once and handing out an index keeps that from copying the body — which,
/// for a record nested inside a record, would double the data at every level.
///
/// An index rather than an `Rc` because the tree crosses the thread boundary
/// [`crate::analyze`] puts the deep passes behind, and has to stay [`Send`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RecordSpecId(pub u32);

impl RecordSpecId {
    /// The index into [`TranslationUnit::records`].
    pub fn index(self) -> usize {
        self.0 as usize
    }
}

/// Identifies one `enum` specifier in [`TranslationUnit::enums`].
///
/// See [`RecordSpecId`], which this is the enumeration's counterpart of.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EnumSpecId(pub u32);

impl EnumSpecId {
    /// The index into [`TranslationUnit::enums`].
    pub fn index(self) -> usize {
        self.0 as usize
    }
}

/// A `struct` or `union` specifier, as written.
///
/// One of these lives in [`TranslationUnit::records`] per specifier in the
/// source, and [`TypeKind::Record`] names it by [`RecordSpecId`].
#[derive(Clone, Debug, PartialEq)]
pub struct RecordSpec {
    /// `struct` or `union`.
    pub kind: RecordKind,
    /// The tag, if one was written.
    pub name: Option<Ident>,
    /// The member list; `None` for a reference such as `struct S *p`.
    pub fields: Option<Vec<FieldDecl>>,
    /// The `_Static_assert` declarations written among the members (C11).
    ///
    /// They are kept apart from the members because they declare nothing: a
    /// member list with one in it lays out exactly as it would without.
    pub asserts: Vec<StaticAssert>,
    /// What `__attribute__((packed))` and friends asked of the whole record.
    pub attrs: Attributes,
    /// The member alignment `#pragma pack(N)` was asking for where the
    /// specifier was written, if any.
    pub pack: Option<u32>,
    /// Where the specifier was written.
    pub range: SourceRange,
}

/// `_Static_assert(expr, "message");` — C11 6.7.10, whose message C23 makes
/// optional.
#[derive(Clone, Debug, PartialEq)]
pub struct StaticAssert {
    /// The constant expression that must be non-zero.
    pub cond: Expr,
    /// The message, as written (quotes included), if one was given.
    pub message: Option<String>,
    /// Where the whole declaration was written.
    pub range: SourceRange,
}

/// One member of a `struct` or `union`.
#[derive(Clone, Debug, PartialEq)]
pub struct FieldDecl {
    /// The member's declaration specifiers.
    pub specifiers: DeclSpecifiers,
    /// The member name; absent for an anonymous bit-field or an anonymous
    /// struct/union member.
    pub name: Option<Ident>,
    /// The member's type.
    pub ty: Type,
    /// The bit-field width, if any.
    pub bit_width: Option<Expr>,
    /// What `__attribute__((…))` on this member asked for.
    pub attrs: Attributes,
    /// Where the member was written.
    pub range: SourceRange,
}

/// An `enum` specifier, as written.
///
/// Stored in [`TranslationUnit::enums`] and named by [`EnumSpecId`], for the
/// same reason a [`RecordSpec`] is.
#[derive(Clone, Debug, PartialEq)]
pub struct EnumSpec {
    /// The tag, if one was written.
    pub name: Option<Ident>,
    /// The enumerator list; `None` for a reference such as `enum E e`.
    pub enumerators: Option<Vec<Enumerator>>,
    /// The fixed underlying type (`enum E : unsigned char { … }`), C23.
    pub underlying: Option<Type>,
    /// Where the specifier was written.
    pub range: SourceRange,
}

/// One `enum` constant.
#[derive(Clone, Debug, PartialEq)]
pub struct Enumerator {
    /// The constant's name.
    pub name: Ident,
    /// Its explicit value, if given.
    pub value: Option<Expr>,
    /// Where it was written.
    pub range: SourceRange,
}

// ---------------------------------------------------------------------------
// declarations
// ---------------------------------------------------------------------------

/// A storage-class specifier.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StorageClass {
    /// `typedef`
    Typedef,
    /// `extern`
    Extern,
    /// `static`
    Static,
    /// `auto`
    Auto,
    /// `register`
    Register,
    /// `constexpr` — C23.
    Constexpr,
}

impl StorageClass {
    /// The keyword spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            StorageClass::Typedef => "typedef",
            StorageClass::Extern => "extern",
            StorageClass::Static => "static",
            StorageClass::Auto => "auto",
            StorageClass::Register => "register",
            StorageClass::Constexpr => "constexpr",
        }
    }
}

/// An `_Alignas` / `alignas` specifier (C11 6.7.5).
#[derive(Clone, Debug, PartialEq)]
pub struct Alignment {
    /// What was written inside the parentheses.
    pub kind: AlignmentKind,
    /// Whether this came from `__attribute__((aligned(N)))` rather than from an
    /// `_Alignas` specifier.
    ///
    /// The two ask for the same thing and are folded into one list, but they
    /// differ on one point: an `_Alignas` weaker than the type's own alignment
    /// is a constraint violation (C11 6.7.5p4), while GCC's `aligned` "can only
    /// increase alignment" and a weaker one is simply not applied.
    pub from_attribute: bool,
    /// Where the specifier was written.
    pub range: SourceRange,
}

/// The operand of an [`Alignment`].
#[derive(Clone, Debug, PartialEq)]
pub enum AlignmentKind {
    /// `_Alignas(16)` — a constant expression.
    Expr(Expr),
    /// `_Alignas(double)` — the alignment of a type.
    Type(Box<TypeName>),
}

/// What an attribute specifier sequence asked for.
///
/// Both spellings — GNU's `__attribute__((…))` and C23's `[[…]]` — produce
/// this, because they say the same things. Everything the front end does not
/// act on is dropped while it is parsed, which C23 6.7.13.1p3 explicitly
/// allows and which GCC does with a warning this crate has no way to raise.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Attributes {
    /// `noreturn` / `[[noreturn]]`, which says exactly what `_Noreturn` says.
    pub noreturn: Option<SourceRange>,
    /// `always_inline`.
    pub always_inline: Option<SourceRange>,
    /// `noinline`.
    pub noinline: Option<SourceRange>,
    /// `cold`; `hot` clears it again, as GCC's do.
    pub cold: Option<SourceRange>,
    /// `deprecated`, with the message it was given.
    pub deprecated: Option<Spanned<Option<String>>>,
    /// `packed`, on a record or on one member.
    pub packed: Option<SourceRange>,
    /// `aligned(N)`, which is the same request `_Alignas(N)` makes.
    pub aligned: Option<Alignment>,
    /// `section("…")`.
    pub section: Option<Spanned<String>>,
    /// `target("avx2")`, `target("sse4.2,popcnt")`, `target("avx2", "fma")`:
    /// the instruction sets the function is compiled for, one entry per name,
    /// in GCC's spelling and with the range of the attribute that wrote it.
    ///
    /// Also what `#pragma GCC target` leaves behind for the functions after
    /// it; the parser puts the pragma's list here when the declaration writes
    /// no attribute of its own.
    pub target: Vec<Spanned<String>>,
    /// `constructor`, whose priority is parsed and ignored.
    pub constructor: Option<SourceRange>,
    /// `destructor`, likewise.
    pub destructor: Option<SourceRange>,
    /// `cleanup(f)`, on a variable with automatic storage duration.
    pub cleanup: Option<Cleanup>,
    /// `mode(M)`, which replaces the declared type with the one the machine
    /// mode names, keeping its signedness.
    pub mode: Option<Spanned<String>>,
    /// `[[cinrs::safe]]` / `__attribute__((cinrs_safe))`: generate the function
    /// without `unsafe`, so that `rustc` checks its body.
    ///
    /// This crate's own attribute rather than one of GCC's, which is why it is
    /// spelled in this crate's namespace both ways.
    pub safe: Option<SourceRange>,
    /// `weak`, which only sema can answer: it is refused on a definition and
    /// accepted on a declaration.
    pub weak: Option<SourceRange>,
}

/// `__attribute__((cleanup(f)))`: `f(&x)` runs when `x` goes out of scope.
#[derive(Clone, Debug, PartialEq)]
pub struct Cleanup {
    /// The function named, or `None` when the argument was not an identifier
    /// at all — which GCC refuses with "cleanup argument not an identifier".
    pub func: Option<Ident>,
    /// Where the attribute was written.
    pub range: SourceRange,
}

impl Attributes {
    /// Whether nothing was asked for.
    pub fn is_empty(&self) -> bool {
        *self == Attributes::default()
    }

    /// Everything either sequence asked for.
    ///
    /// GCC lets the attributes of one declaration be spread over the
    /// specifiers, the declarator and the definition, and takes the union.
    pub fn merge(&mut self, other: Attributes) {
        self.noreturn = self.noreturn.or(other.noreturn);
        self.always_inline = self.always_inline.or(other.always_inline);
        self.noinline = self.noinline.or(other.noinline);
        self.cold = self.cold.or(other.cold);
        self.deprecated = self.deprecated.take().or(other.deprecated);
        self.packed = self.packed.or(other.packed);
        self.aligned = self.aligned.take().or(other.aligned);
        self.section = self.section.take().or(other.section);
        // Two `target` attributes on one declaration add up, exactly as two
        // `-m` switches do: `__attribute__((target("avx2"))) __attribute__
        // ((target("fma"))) void f(void)` asks for both.
        self.target.extend(other.target);
        self.constructor = self.constructor.or(other.constructor);
        self.destructor = self.destructor.or(other.destructor);
        self.cleanup = self.cleanup.take().or(other.cleanup);
        self.mode = self.mode.take().or(other.mode);
        self.safe = self.safe.or(other.safe);
        self.weak = self.weak.or(other.weak);
    }
}

/// The declaration specifiers shared by all declarators of one declaration.
#[derive(Clone, Debug, PartialEq)]
pub struct DeclSpecifiers {
    /// The storage class, if one was written.
    pub storage: Option<Spanned<StorageClass>>,
    /// Where `_Thread_local`, C23's `thread_local` or GNU's `__thread` was
    /// written, if it was.
    ///
    /// It is not a [`StorageClass`], because C11 6.7.1p2 lets it appear
    /// *beside* one: `static _Thread_local int x;` names a thread-local object
    /// with internal linkage, and at block scope one of `static` or `extern`
    /// is required (6.7.1p3).
    pub thread_local: Option<SourceRange>,
    /// Whether `inline` was written.
    pub inline: bool,
    /// Whether the declaration was marked `_Noreturn`, `[[noreturn]]` or
    /// `__cinrs_noreturn`.
    pub noreturn: Option<SourceRange>,
    /// The alignment specifiers written among these declaration specifiers, in
    /// the order they were written.
    ///
    /// C11 6.7.5p6 allows several and makes the strictest of them the one that
    /// holds, so they are all kept; `__attribute__((aligned(N)))` written here
    /// asks for the same thing and is folded in, with
    /// [`Alignment::from_attribute`] saying which spelling each one came from.
    pub alignas: Vec<Alignment>,
    /// What `__attribute__((…))` and `[[…]]` asked for.
    pub attrs: Attributes,
    /// The base type built from the type specifiers and qualifiers.
    pub base: Type,
    /// Where the specifiers were written.
    pub range: SourceRange,
}

impl DeclSpecifiers {
    /// Whether this declaration introduces `typedef` names.
    pub fn is_typedef(&self) -> bool {
        matches!(
            self.storage,
            Some(Spanned {
                node: StorageClass::Typedef,
                ..
            })
        )
    }
}

/// A declaration: specifiers plus zero or more declarators.
#[derive(Clone, Debug, PartialEq)]
pub struct Decl {
    /// The shared specifiers.
    pub specifiers: DeclSpecifiers,
    /// The declared entities.
    pub declarators: Vec<InitDeclarator>,
    /// Where the declaration was written, including its `;`.
    pub range: SourceRange,
}

/// One declarator of a [`Decl`], with its optional initialiser.
#[derive(Clone, Debug, PartialEq)]
pub struct InitDeclarator {
    /// The declared name; absent only after error recovery.
    pub name: Option<Ident>,
    /// The fully resolved type.
    pub ty: Type,
    /// The initialiser, if any.
    pub init: Option<Initializer>,
    /// What `__attribute__((…))` written on *this* declarator asked for.
    pub attrs: Attributes,
    /// The symbol `__asm__("name")` renamed this declaration to.
    pub asm_label: Option<Spanned<String>>,
    /// Where the declarator was written.
    pub range: SourceRange,
}

/// An initialiser.
#[derive(Clone, Debug, PartialEq)]
pub struct Initializer {
    /// What kind of initialiser this is.
    pub kind: InitializerKind,
    /// Where it was written.
    pub range: SourceRange,
}

/// The shape of an [`Initializer`].
#[derive(Clone, Debug, PartialEq)]
pub enum InitializerKind {
    /// `= expr`
    Expr(Expr),
    /// `= { … }`
    List(Vec<InitItem>),
}

/// One element of a braced initialiser list.
#[derive(Clone, Debug, PartialEq)]
pub struct InitItem {
    /// Designators written before `=`, e.g. `.x` or `[3]`.
    pub designators: Vec<Designator>,
    /// The value.
    pub init: Initializer,
    /// Where the element was written.
    pub range: SourceRange,
}

/// A C99 designator.
#[derive(Clone, Debug, PartialEq)]
pub enum Designator {
    /// `.name`, and the pre-C99 `name:` GNU still accepts.
    Field(Ident),
    /// `[expr]`
    Index(Expr),
    /// `[low ... high]` — GNU's range designator, which fills every element of
    /// the range with the same value.
    Range(Expr, Expr),
}

/// A type name, as written in a cast, `sizeof(T)` or a compound literal.
#[derive(Clone, Debug, PartialEq)]
pub struct TypeName {
    /// The specifier-qualifier list.
    pub specifiers: DeclSpecifiers,
    /// The type after applying the abstract declarator.
    pub ty: Type,
    /// Where it was written.
    pub range: SourceRange,
}

// ---------------------------------------------------------------------------
// statements
// ---------------------------------------------------------------------------

/// A compound statement.
#[derive(Clone, Debug, PartialEq)]
pub struct Block {
    /// Declarations and statements, in source order (C99 allows mixing).
    pub items: Vec<BlockItem>,
    /// The labels `__label__ a, b;` declared local to this block.
    ///
    /// C gives every label function scope, and so does this crate, so the
    /// declaration is accepted and the labels behave as they would without it.
    pub local_labels: Vec<Ident>,
    /// Where the block was written, including its braces.
    pub range: SourceRange,
}

/// An element of a [`Block`].
//
// The AST is built once per macro invocation and then walked; boxing every
// large field to even out the variants would only make sema and codegen
// noisier to write.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum BlockItem {
    /// A declaration.
    Decl(Decl),
    /// A statement.
    Stmt(Stmt),
    /// `_Static_assert(…);` — C11.
    StaticAssert(StaticAssert),
    /// GNU's nested function definition, `int f(void) { int g(int x) { … } }`.
    ///
    /// It is a block *item* rather than a declaration or a statement: it
    /// declares a name in the enclosing block, contributes no statement to it,
    /// and its body is checked in a scope of its own. Semantic analysis lifts
    /// it to a file-scope item with a hidden environment; see
    /// `Sema::nested_function_def`.
    NestedFunction(FunctionDef),
}

/// A statement.
#[derive(Clone, Debug, PartialEq)]
pub struct Stmt {
    /// What kind of statement this is.
    pub kind: StmtKind,
    /// Where it was written.
    pub range: SourceRange,
}

/// The shape of a [`Stmt`].
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum StmtKind {
    /// `label: stmt`
    Labeled {
        /// The label.
        label: Ident,
        /// The labelled statement.
        body: Box<Stmt>,
    },
    /// `case expr: stmt`, and GNU's `case low ... high: stmt`.
    Case {
        /// The case value, or the low end of a range.
        value: Expr,
        /// The high end of a `case low ... high:` range.
        upper: Option<Expr>,
        /// The labelled statement.
        body: Box<Stmt>,
    },
    /// `default: stmt`
    Default {
        /// The labelled statement.
        body: Box<Stmt>,
    },
    /// `{ … }`
    Compound(Block),
    /// `expr;` or the null statement `;`.
    Expr(Option<Expr>),
    /// `if (cond) then else otherwise`
    If {
        /// The controlling expression.
        cond: Expr,
        /// The `then` branch.
        then_branch: Box<Stmt>,
        /// The `else` branch, if any.
        else_branch: Option<Box<Stmt>>,
    },
    /// `switch (cond) body`
    Switch {
        /// The controlling expression.
        cond: Expr,
        /// The switch body.
        body: Box<Stmt>,
    },
    /// `while (cond) body`
    While {
        /// The controlling expression.
        cond: Expr,
        /// The loop body.
        body: Box<Stmt>,
    },
    /// `do body while (cond);`
    DoWhile {
        /// The loop body.
        body: Box<Stmt>,
        /// The controlling expression.
        cond: Expr,
    },
    /// `for (init; cond; step) body`
    For {
        /// The init clause.
        init: ForInit,
        /// The controlling expression, if any.
        cond: Option<Expr>,
        /// The iteration expression, if any.
        step: Option<Expr>,
        /// The loop body.
        body: Box<Stmt>,
    },
    /// `goto label;`
    Goto(Ident),
    /// GNU's computed `goto *expr;`, whose operand is a label address.
    GotoPtr(Expr),
    /// `continue;`
    Continue,
    /// `break;`
    Break,
    /// `return expr;`
    Return(Option<Expr>),
    /// GNU's inline assembly statement, basic or extended; see [`AsmStmt`].
    Asm(Box<AsmStmt>),
    /// Produced by error recovery.
    Error,
}

/// `asm [volatile] [inline] [goto] ( template [: outputs [: inputs [:
/// clobbers [: labels]]]] ) ;` — GNU inline assembly.
///
/// The parser records what was written and nothing more: the template and
/// the constraints are opaque strings here (adjacent string literals already
/// concatenated), and deciding what they mean — and what of it `asm!` can
/// express — is sema's business.
#[derive(Clone, Debug, PartialEq)]
pub struct AsmStmt {
    /// `volatile` or `__volatile__` was written.
    pub volatile: bool,
    /// `inline` or `__inline__` was written.
    pub inline: bool,
    /// `goto` was written: the statement may jump to one of [`labels`].
    ///
    /// [`labels`]: AsmStmt::labels
    pub goto: bool,
    /// The assembler template.
    pub template: Spanned<String>,
    /// Whether any colon section was written, which is what makes this
    /// *extended* asm: GCC treats `%` in a basic asm template literally, and
    /// `asm("" :)` as extended asm with no operands.
    pub extended: bool,
    /// The output operands, in order.
    pub outputs: Vec<AsmOperand>,
    /// The input operands, in order; GCC numbers them after the outputs.
    pub inputs: Vec<AsmOperand>,
    /// The clobber list: register names, `"memory"`, `"cc"`.
    pub clobbers: Vec<Spanned<String>>,
    /// The labels of an `asm goto`.
    pub labels: Vec<Ident>,
}

/// One operand of an extended [`AsmStmt`]: `[name] "constraint" (expr)`.
#[derive(Clone, Debug, PartialEq)]
pub struct AsmOperand {
    /// The symbolic name `%[name]` refers to it by, if any.
    pub name: Option<Ident>,
    /// The constraint string, modifiers (`=`, `+`, `&`) included.
    pub constraint: Spanned<String>,
    /// The operand: an lvalue for an output, any expression for an input.
    pub expr: Expr,
}

/// The init clause of a `for` statement.
#[derive(Clone, Debug, PartialEq)]
pub enum ForInit {
    /// `for (; …)`
    None,
    /// `for (expr; …)`
    Expr(Expr),
    /// `for (int i = 0; …)` — C99.
    Decl(Box<Decl>),
    /// `for (_Static_assert(1, "…"); …)`.
    ///
    /// A static assertion is a *declaration*, so the grammar puts it here,
    /// and C11 6.8.5p3 then forbids it — the clause may only declare objects
    /// with automatic or register storage duration, and this declares nothing
    /// at all. GCC and Clang both accept it anyway (Clang's `C11/n1330.c`
    /// says so in as many words), it asserts exactly what it would one line
    /// higher up, and refusing it would be refusing something both compilers
    /// this crate follows take.
    StaticAssert(StaticAssert),
}

// ---------------------------------------------------------------------------
// expressions
// ---------------------------------------------------------------------------

/// A prefix or unary operator.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnaryOp {
    /// `+x`
    Plus,
    /// `-x`
    Minus,
    /// `!x`
    LogNot,
    /// `~x`
    BitNot,
    /// `*p`
    Deref,
    /// `&x`
    AddrOf,
}

impl UnaryOp {
    /// The operator's spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            UnaryOp::Plus => "+",
            UnaryOp::Minus => "-",
            UnaryOp::LogNot => "!",
            UnaryOp::BitNot => "~",
            UnaryOp::Deref => "*",
            UnaryOp::AddrOf => "&",
        }
    }
}

/// A binary operator.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum BinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    Shl,
    Shr,
    Lt,
    Gt,
    Le,
    Ge,
    Eq,
    Ne,
    BitAnd,
    BitXor,
    BitOr,
    LogAnd,
    LogOr,
}

impl BinaryOp {
    /// The operator's spelling.
    pub fn as_str(self) -> &'static str {
        use BinaryOp::*;
        match self {
            Add => "+",
            Sub => "-",
            Mul => "*",
            Div => "/",
            Rem => "%",
            Shl => "<<",
            Shr => ">>",
            Lt => "<",
            Gt => ">",
            Le => "<=",
            Ge => ">=",
            Eq => "==",
            Ne => "!=",
            BitAnd => "&",
            BitXor => "^",
            BitOr => "|",
            LogAnd => "&&",
            LogOr => "||",
        }
    }
}

/// `++` or `--`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IncDec {
    /// `++`
    Inc,
    /// `--`
    Dec,
}

impl IncDec {
    /// The operator's spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            IncDec::Inc => "++",
            IncDec::Dec => "--",
        }
    }
}

/// An expression.
#[derive(Clone, Debug, PartialEq)]
pub struct Expr {
    /// What kind of expression this is.
    pub kind: ExprKind,
    /// Where it was written.
    pub range: SourceRange,
}

/// The shape of an [`Expr`].
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
    /// An identifier reference.
    Ident(Ident),
    /// An integer constant.
    Int(IntLit),
    /// A floating constant.
    Float(FloatLit),
    /// A character constant.
    Char(CharLit),
    /// A string literal, after adjacent-literal concatenation.
    Str(StrLit),
    /// A unary operator application.
    Unary {
        /// The operator.
        op: UnaryOp,
        /// The operand.
        operand: Box<Expr>,
    },
    /// A binary operator application.
    Binary {
        /// The operator.
        op: BinaryOp,
        /// Left operand.
        lhs: Box<Expr>,
        /// Right operand.
        rhs: Box<Expr>,
    },
    /// An assignment; `op` is `None` for `=` and `Some(op)` for `op=`.
    Assign {
        /// The compound operator, if any.
        op: Option<BinaryOp>,
        /// The assigned-to operand.
        lhs: Box<Expr>,
        /// The assigned value.
        rhs: Box<Expr>,
    },
    /// `cond ? then_expr : else_expr`, and GNU's `cond ?: else_expr`.
    Conditional {
        /// The condition.
        cond: Box<Expr>,
        /// The value when the condition holds; `None` for `a ?: b`, where it
        /// is the condition's own value and the condition is evaluated once.
        then_expr: Option<Box<Expr>>,
        /// The value otherwise.
        else_expr: Box<Expr>,
    },
    /// `lhs, rhs`
    Comma {
        /// Evaluated and discarded.
        lhs: Box<Expr>,
        /// The result.
        rhs: Box<Expr>,
    },
    /// `callee(args…)`
    Call {
        /// The called expression.
        callee: Box<Expr>,
        /// The arguments.
        args: Vec<Expr>,
    },
    /// `base.field` or `base->field`
    Member {
        /// The object or pointer.
        base: Box<Expr>,
        /// Whether `->` was used.
        arrow: bool,
        /// The member name.
        field: Ident,
    },
    /// `base[index]`
    Index {
        /// The array or pointer.
        base: Box<Expr>,
        /// The subscript.
        index: Box<Expr>,
    },
    /// `x++` / `x--`
    PostIncDec {
        /// Which operator.
        op: IncDec,
        /// The operand.
        operand: Box<Expr>,
    },
    /// `++x` / `--x`
    PreIncDec {
        /// Which operator.
        op: IncDec,
        /// The operand.
        operand: Box<Expr>,
    },
    /// `(T)expr`
    Cast {
        /// The target type.
        ty: Box<TypeName>,
        /// The operand.
        expr: Box<Expr>,
    },
    /// GNU's `&&label`: the address of a label of the enclosing function, of
    /// type `void *`, which `goto *` jumps to.
    LabelAddr(Ident),
    /// `sizeof expr`
    SizeofExpr(Box<Expr>),
    /// `sizeof(T)`
    SizeofType(Box<TypeName>),
    /// `_Alignof expr` — a GNU extension C never standardised.
    AlignofExpr(Box<Expr>),
    /// `_Alignof(T)` / `alignof(T)` — C11.
    AlignofType(Box<TypeName>),
    /// `_Generic(controlling, T: value, …)` — C11.
    Generic {
        /// The controlling expression, which is never evaluated.
        controlling: Box<Expr>,
        /// The associations, in the order written.
        assocs: Vec<GenericAssoc>,
    },
    /// `true` / `false` — C23.
    Bool(bool),
    /// `nullptr` — C23.
    Nullptr,
    /// `va_arg(ap, T)`.
    ///
    /// It looks like a call but takes a type name, so — like `sizeof` — the
    /// parser has to know about it.
    VaArg {
        /// The argument list read from.
        ap: Box<Expr>,
        /// The type of the argument being read.
        ty: Box<TypeName>,
    },
    /// `__builtin_offsetof(T, member)`, which `<stddef.h>`'s `offsetof` is.
    ///
    /// Another one that takes a type name where an expression would go.
    OffsetOf {
        /// The `struct` or `union` type.
        ty: Box<TypeName>,
        /// The first step of the member designator, which C requires to be a
        /// member name.
        member: Ident,
        /// The steps after it — `offsetof(struct S, a.b)` and
        /// `offsetof(struct S, a[2].b)` are both member designators
        /// (C99 7.17p3). A [`Designator::Range`] never appears here.
        path: Vec<Designator>,
    },
    /// `(T){ … }` — a C99 compound literal.
    CompoundLiteral {
        /// The literal's type.
        ty: Box<TypeName>,
        /// The initialiser elements.
        init: Vec<InitItem>,
    },
    /// `({ … })` — GNU's statement expression, whose value is the value of the
    /// last expression statement in the block.
    StmtExpr(Box<Block>),
    /// `__builtin_types_compatible_p(T1, T2)`, an integer constant.
    TypesCompatible {
        /// The first type.
        lhs: Box<TypeName>,
        /// The second type.
        rhs: Box<TypeName>,
    },
    /// `__builtin_choose_expr(c, a, b)`.
    ///
    /// Only the operand the constant condition picks is type checked, which is
    /// the whole point of the builtin.
    ChooseExpr {
        /// The controlling constant expression.
        cond: Box<Expr>,
        /// Chosen when it is non-zero.
        then_expr: Box<Expr>,
        /// Chosen otherwise.
        else_expr: Box<Expr>,
    },
    /// `__real__ e` / `__imag__ e`, which need complex arithmetic.
    ComplexPart {
        /// Whether this is `__real__`.
        real: bool,
        /// The operand.
        operand: Box<Expr>,
    },
    /// Produced by error recovery.
    Error,
}

/// One association of a `_Generic` selection.
#[derive(Clone, Debug, PartialEq)]
pub struct GenericAssoc {
    /// The type this association is chosen for; `None` for `default:`.
    pub ty: Option<TypeName>,
    /// The value the selection has when this association is chosen.
    pub value: Expr,
    /// Where the association was written.
    pub range: SourceRange,
}

// ---------------------------------------------------------------------------
// top level
// ---------------------------------------------------------------------------

/// A function definition.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionDef {
    /// The declaration specifiers.
    pub specifiers: DeclSpecifiers,
    /// The function's name.
    pub name: Ident,
    /// The function's type; always [`TypeKind::Function`] unless recovery
    /// kicked in.
    pub ty: Type,
    /// Old-style parameter declarations (`int f(a) int a; { … }`). Empty for a
    /// prototype-style definition; sema decides whether to accept them.
    pub kr_decls: Vec<Decl>,
    /// What `__attribute__((…))` written after the declarator asked for.
    pub attrs: Attributes,
    /// The symbol `__asm__("name")` renamed the definition to.
    pub asm_label: Option<Spanned<String>>,
    /// The body.
    pub body: Block,
    /// Whether the body takes the address of a label — GNU's `&&label`.
    ///
    /// Such a function is lowered through a [control-flow
    /// graph](crate::cfg), where a computed `goto` is a `switch` over the
    /// labels whose address is taken. The parser records it because `&&label` is an
    /// *expression* and may sit anywhere one may — an initialiser, an
    /// argument, a block-scope `static`'s table — while the rest of the
    /// decision is read off the statements; see
    /// [`Parser::label_addrs`](crate::parse). A nested function's own
    /// `&&label` is its own business and does not set this.
    pub uses_label_addrs: bool,
    /// Where the definition was written.
    pub range: SourceRange,
}

/// A top-level item.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum ExternalDecl {
    /// A function definition.
    Function(FunctionDef),
    /// A declaration.
    Decl(Decl),
    /// `_Static_assert(…);` — C11.
    StaticAssert(StaticAssert),
}

/// A whole translation unit — the contents of one `c99!` invocation.
#[derive(Clone, Debug, PartialEq)]
pub struct TranslationUnit {
    /// The top-level items.
    pub items: Vec<ExternalDecl>,
    /// Every `struct`/`union` specifier written in the unit, in source order.
    ///
    /// [`TypeKind::Record`] indexes this; see [`RecordSpecId`].
    pub records: Vec<RecordSpec>,
    /// Every `enum` specifier written in the unit, in source order.
    pub enums: Vec<EnumSpec>,
    /// Every `typeof` operand written in the unit, in source order.
    pub typeofs: Vec<TypeofOperand>,
    /// The range covering the whole input.
    pub range: SourceRange,
}

impl TranslationUnit {
    /// The `struct`/`union` specifier `id` names.
    pub fn record(&self, id: RecordSpecId) -> &RecordSpec {
        &self.records[id.index()]
    }

    /// The `enum` specifier `id` names.
    pub fn enum_spec(&self, id: EnumSpecId) -> &EnumSpec {
        &self.enums[id.index()]
    }

    /// The `typeof` operand `id` names.
    pub fn typeof_operand(&self, id: TypeofId) -> &TypeofOperand {
        &self.typeofs[id.index()]
    }
}