Skip to main content

rucc_types/
lib.rs

1//! The C type system, interned, and layout computation.
2//!
3//! Design: `spec/07-types-and-semantics.md`. Layer rank 2, see `spec/18-package-layout.md`.
4//!
5//! There is one [`Types`] per translation unit and it owns every type in it. A [`TypeId`] is
6//! four bytes and two of them are equal exactly when they are the same type, which turns the
7//! question the compiler asks more often than any other into an integer comparison.
8//!
9//! Two ideas shape the rest of it.
10//!
11//! **Sugar is kept and never decided on.** `typedef int32_t;` gives a node that remembers the
12//! name and points at canonical `int`. Every semantic rule reads [`Types::canonical`] and sees
13//! `int`; every diagnostic reads the type as it was written and says `int32_t`. Compilers that
14//! throw the name away produce messages nobody can act on, and compilers that decide on the
15//! name produce wrong answers, and both are common. Sugar is not only at the outermost node,
16//! so `int32_t *` and `int32_t[4]` are sugar too and canonicalising rebuilds them.
17//!
18//! **`_Atomic` is a type, not a qualifier.** `const` and `volatile` and `restrict` are a
19//! bitmask in the interning key, because nothing about them changes what an object is. C lets
20//! `_Atomic` be written in the same position, but `_Atomic(T)` can have a different alignment
21//! from `T`, so it is a type constructor here and the parser is what maps the spelling onto
22//! it. Document 01 recorded a compiler that treated it as a qualifier and lost track of it,
23//! which is exactly the shortcut that makes atomics silently wrong.
24//!
25//! Layout comes out of [`TargetInfo`](rucc_target::TargetInfo) and never out of the host.
26//! `long` is four bytes on Windows and eight on Linux, and `long double` is eight bytes on
27//! Apple and sixteen on SysV x86-64, so a cross compiler that asks its own platform is wrong
28//! twice before it has read a line of C.
29//!
30//! ```
31//! use rucc_target::{TargetInfo, Triple};
32//! use rucc_types::{IntKind, Types, layout};
33//!
34//! let mut types = Types::new();
35//! let linux = TargetInfo::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
36//! let windows = TargetInfo::new("x86_64-pc-windows-msvc".parse::<Triple>().unwrap());
37//!
38//! let long = types.int(IntKind::Long);
39//! assert_eq!(layout(&types, long, &linux).unwrap().size, 8);
40//! assert_eq!(layout(&types, long, &windows).unwrap().size, 4);
41//! ```
42//!
43//! Records are laid out by [`layout_record`], which takes the members and gives back their
44//! offsets, and the result is handed to [`Types::complete_record`] so that the record then has
45//! a size like any other type. Bit-fields, `packed`, `#pragma pack`, `aligned`, zero width
46//! bit-fields and flexible array members are all in there, and every one of their rules was
47//! measured against gcc and clang rather than read off a document.
48//!
49//! [`promote`] and [`usual_arithmetic`] are 6.3.1.1 and 6.3.1.8, the rules that decide what
50//! type an arithmetic expression has. Their answers were read out of gcc and clang with
51//! `_Generic` naming the type of every interesting pair, which is also how the C23 changes were
52//! pinned down: `_BitInt` does not promote, and an enumeration promotes through whatever it is
53//! represented in.
54//!
55//! `__int128` is one of the integer kinds rather than a `_BitInt(128)` in disguise. The two are
56//! different types: `__int128` is sixteen bytes aligned to sixteen everywhere, `_BitInt(128)` is
57//! aligned to its granule, and `__int128` outranks `long long` where a `_BitInt` is ranked by
58//! width alone. It is available on every target here, because all three architectures are
59//! 64-bit and GCC has it on every 64-bit target it supports.
60//!
61//! [`compatible`] and [`composite`] are 6.2.7, the relation that decides whether two
62//! declarations of one name are talking about the same thing and the type that is left when they
63//! are. Identity is not that relation: `int f(int a[3])` and `int f(int *a)` are different types
64//! and the same function. The composite is what a caller merging two declarations should keep,
65//! because it is the only one of the three types in play that knows both the array size and the
66//! parameter list.
67//!
68//! # Status
69//!
70//! The type universe, the interner, the canonical and sugar split, the qualifier rules, layout
71//! with records included, the arithmetic conversions, compatibility with the composite type, and
72//! [`spell`], which writes a type back as the C declaration it is, are implemented.
73//!
74//! Not here yet, and named so that the gap is not mistaken for a decision: the decimal floating
75//! types.
76//!
77//! Every crate in the workspace is published, and publishing implies a promise. This one is
78//! tier 3: its Rust API is explicitly unstable and will change without a major version bump.
79//! Depend on the `rucc` binary's behaviour, not on this.
80
81#![doc(html_root_url = "https://docs.rs/rucc-types/0.6.0")]
82
83mod classify;
84mod compat;
85mod convert;
86mod kind;
87mod layout;
88mod print;
89mod record;
90mod types;
91
92pub use crate::classify::{
93    element, is_aggregate, is_arithmetic, is_array, is_atomic, is_complete, is_complex,
94    is_floating, is_function, is_integer, is_modifiable, is_object, is_pointer, is_real,
95    is_real_floating, is_record, is_scalar, is_vector, is_void, lanes, pointee,
96};
97pub use crate::compat::{adjust_parameter, compatible, composite};
98pub use crate::convert::{
99    mask_of, promote, promote_bit_field, usual_arithmetic, vectors_convertible,
100};
101pub use crate::kind::{
102    ArrayLen, EnumId, FloatKind, FunctionId, FunctionType, IntKind, Qualifiers, RecordId,
103    RecordKind, Type, TypeKind, VlaId,
104};
105pub use crate::layout::{
106    IntegerInfo, Layout, LayoutError, float_format, float_width, int_width, integer_info, layout,
107};
108pub use crate::print::{declare, spell};
109pub use crate::record::{
110    Field, FieldDecl, RecordError, RecordLayout, RecordOptions, layout_record,
111};
112pub use crate::types::{EnumInfo, RecordInfo, TypeId, Types};
113
114/// The milestone in `spec/17-milestones.md` that fills this crate in.
115pub const MILESTONE: &str = "M2";
116
117#[cfg(test)]
118mod tests {
119    use std::num::NonZeroU32;
120
121    use rucc_base::{Interner, Symbol};
122    use rucc_target::{TargetInfo, Triple};
123
124    use super::*;
125
126    fn target(triple: &str) -> TargetInfo {
127        TargetInfo::new(triple.parse::<Triple>().expect("a triple the compiler supports"))
128    }
129
130    fn linux() -> TargetInfo {
131        target("x86_64-unknown-linux-gnu")
132    }
133
134    /// Lays out a record with no attributes on it, on x86-64 Linux.
135    fn lay_out(types: &Types, kind: RecordKind, fields: &[FieldDecl]) -> RecordLayout {
136        layout_record(types, kind, fields, &RecordOptions::default(), &linux())
137            .expect("a record every member of which has a layout")
138    }
139
140    /// The offsets of the members, in bits, which is what a measurement of a real compiler
141    /// gives back once its byte offsets and its bit dumps are put together.
142    fn offsets(laid_out: &RecordLayout) -> Vec<u128> {
143        laid_out.fields.iter().map(Field::bit_offset).collect()
144    }
145
146    /// A complete record type built out of the given members.
147    fn record(types: &mut Types, kind: RecordKind, fields: &[FieldDecl]) -> TypeId {
148        let id = types.declare_record(kind, None);
149        let laid_out = lay_out(types, kind, fields);
150        types.complete_record(id, laid_out);
151        types.record(id)
152    }
153
154    /// An ordinary member of the given type, unnamed, which is all most of these tests need.
155    fn member(ty: TypeId) -> FieldDecl {
156        FieldDecl::new(None, ty)
157    }
158
159    /// A named bit-field, which is what a measurement of a real compiler has to use to be able
160    /// to read the field back.
161    fn bits(interner: &mut Interner, name: &str, ty: TypeId, width: u32) -> FieldDecl {
162        FieldDecl::bit_field(Some(interner.intern(name)), ty, width)
163    }
164
165    /// An unnamed bit-field, which occupies bits and raises nothing.
166    fn unnamed_bits(ty: TypeId, width: u32) -> FieldDecl {
167        FieldDecl::bit_field(None, ty, width)
168    }
169
170    #[test]
171    fn milestone_is_recorded() {
172        assert!(MILESTONE.starts_with('M'));
173    }
174
175    #[test]
176    fn an_integer_type_answers_with_the_width_of_its_value_and_not_of_its_object() {
177        let mut interner = Interner::new();
178        let mut types = Types::new();
179        let target = linux();
180
181        // A `bool` is one byte and holds one bit, and a `_BitInt(37)` is eight bytes and holds
182        // thirty seven. Folding a constant in the size rather than the width gets both wrong.
183        let boolean = types.boolean();
184        let bits = types.bit_int(true, 37);
185        // Through the sugar, the qualifiers and `_Atomic`, none of which is part of a value.
186        let short = types.int(IntKind::Short);
187        let alias = types.typedef(interner.intern("word"), short);
188        let unsigned_char = types.int(IntKind::UChar);
189        let atomic = types.atomic(unsigned_char);
190
191        let shape = |ty| integer_info(&types, ty, &target).expect("an integer type");
192        assert_eq!(shape(boolean), IntegerInfo::new(false, 1));
193        assert_eq!(shape(bits), IntegerInfo::new(true, 37));
194        assert_eq!(shape(types.int(IntKind::Int)), IntegerInfo::new(true, 32));
195        assert_eq!(shape(types.int(IntKind::ULong)), IntegerInfo::new(false, 64));
196        assert_eq!(shape(alias), IntegerInfo::new(true, 16));
197        assert_eq!(shape(atomic), IntegerInfo::new(false, 8));
198
199        assert_eq!(integer_info(&types, types.float(FloatKind::Double), &target), None);
200    }
201
202    #[test]
203    fn an_enumeration_answers_with_the_type_the_enumerators_are_kept_in() {
204        let mut interner = Interner::new();
205        let mut types = Types::new();
206        let target = linux();
207
208        // An enumeration that has not been completed has no underlying type yet, and the answer
209        // is that there is no answer rather than a guess at `int` that a later `: long` unsays.
210        let colour = types.declare_enum(Some(interner.intern("colour")));
211        let ty = types.enumeration(colour);
212        assert_eq!(integer_info(&types, ty, &target), None);
213
214        let underlying = types.int(IntKind::ULong);
215        types.complete_enum(colour, underlying, true);
216        assert_eq!(integer_info(&types, ty, &target), Some(IntegerInfo::new(false, 64)));
217    }
218
219    #[test]
220    fn a_value_stored_in_an_integer_type_keeps_the_bits_the_type_has_room_for() {
221        let char_type = IntegerInfo::new(true, 8);
222        assert_eq!(char_type.wrap(300), 44);
223        assert!(!char_type.holds(300));
224        assert!(char_type.holds(-128));
225
226        assert_eq!(IntegerInfo::new(false, 32).wrap(-1), 4_294_967_295);
227        assert_eq!(IntegerInfo::new(false, 8).wrap(-1), 255);
228
229        // Every pattern is a value of a hundred and twenty eight bit type, of either signedness,
230        // which is what stops the folding from inventing an overflow at the widest type there is.
231        assert!(IntegerInfo::new(false, 128).holds(i128::MIN));
232        assert!(IntegerInfo::new(true, 128).holds(i128::MIN));
233        assert_eq!(IntegerInfo::new(true, 128).wrap(i128::MAX), i128::MAX);
234    }
235
236    #[test]
237    fn a_long_double_has_a_format_the_size_does_not_give_away() {
238        let target = linux();
239        // Sixteen bytes on SysV x86-64 and eighty bits of x87 inside them. A compiler that
240        // picked the format by the size would fold every one of those constants too finely.
241        assert_eq!(float_width(FloatKind::LongDouble, &target), 128);
242        assert_eq!(
243            float_format(FloatKind::LongDouble, &target),
244            rucc_base::float::Format::X87Extended
245        );
246        assert_eq!(float_format(FloatKind::Float, &target), rucc_base::float::Format::Single);
247    }
248
249    #[test]
250    fn an_interchange_type_names_a_format_and_an_extended_one_names_the_target() {
251        use rucc_base::float::Format;
252
253        // The four `_FloatN` types are the same format everywhere, which is the point of them,
254        // so a program that wants binary128 can say so and get it or get told it cannot.
255        for target in [&linux(), &target("aarch64-apple-darwin")] {
256            assert_eq!(float_format(FloatKind::Float16, target), Format::Half);
257            assert_eq!(float_format(FloatKind::Float32, target), Format::Single);
258            assert_eq!(float_format(FloatKind::Float64, target), Format::Double);
259            assert_eq!(float_format(FloatKind::Float128, target), Format::Quad);
260            assert_eq!(float_width(FloatKind::Float16, target), 16);
261            assert_eq!(float_width(FloatKind::Float32, target), 32);
262            assert_eq!(float_width(FloatKind::Float64, target), 64);
263            assert_eq!(float_width(FloatKind::Float128, target), 128);
264            // `_Float32x` is `double` on every target this compiles for.
265            assert_eq!(float_format(FloatKind::Float32x, target), Format::Double);
266        }
267
268        // `_Float64x` is the one that moves, and it moves with the processor rather than with
269        // the operating system, so it stays eighty bits of x87 on x86-64 where `long double`
270        // is the same thing and is quad on Apple where `long double` is only a `double`.
271        let x86 = linux();
272        assert_eq!(float_format(FloatKind::Float64x, &x86), Format::X87Extended);
273        assert_eq!(float_format(FloatKind::LongDouble, &x86), Format::X87Extended);
274        let mac = target("aarch64-apple-darwin");
275        assert_eq!(float_format(FloatKind::Float64x, &mac), Format::Quad);
276        assert_eq!(float_format(FloatKind::LongDouble, &mac), Format::Double);
277        // Sixteen bytes either way, because the x87 eighty bits are stored padded, which is
278        // the same reason `long double` is sixteen bytes on x86-64 and not ten.
279        assert_eq!(float_width(FloatKind::Float64x, &x86), 128);
280        assert_eq!(float_width(FloatKind::Float64x, &mac), 128);
281    }
282
283    #[test]
284    fn every_floating_type_is_as_wide_as_the_format_it_is_stored_in() {
285        let types = Types::new();
286        let sizes = |target: &TargetInfo| -> Vec<(u64, u64)> {
287            FloatKind::ALL
288                .iter()
289                .map(|&kind| {
290                    let found = layout(&types, types.float(kind), target).expect("a complete type");
291                    (found.size, found.align)
292                })
293                .collect()
294        };
295        // Read off gcc 16 with `sizeof` and `_Alignof`, in the order of `FloatKind::ALL`. The
296        // two targets differ in one place, which is `long double`, and the eighty bit x87 value
297        // that `long double` and `_Float64x` hold on x86-64 takes sixteen bytes to store.
298        assert_eq!(
299            sizes(&linux()),
300            [(2, 2), (4, 4), (4, 4), (8, 8), (8, 8), (8, 8), (16, 16), (16, 16), (16, 16)]
301        );
302        assert_eq!(
303            sizes(&target("aarch64-apple-darwin")),
304            [(2, 2), (4, 4), (4, 4), (8, 8), (8, 8), (8, 8), (8, 8), (16, 16), (16, 16)]
305        );
306    }
307
308    #[test]
309    fn every_floating_type_has_a_slot_of_its_own_and_a_name_of_its_own() {
310        // Nine types and nine ids, which is what makes `_Float64` and `double` two types that
311        // `_Generic` can tell apart rather than one type with two spellings.
312        let types = Types::new();
313        let mut seen = Vec::new();
314        for kind in FloatKind::ALL {
315            seen.push(types.float(kind));
316        }
317        let mut sorted = seen.clone();
318        sorted.sort_unstable();
319        sorted.dedup();
320        assert_eq!(sorted.len(), seen.len(), "two floating types share an id");
321
322        let names: Vec<&str> = FloatKind::ALL.iter().map(|kind| kind.as_str()).collect();
323        assert_eq!(
324            names,
325            [
326                "_Float16",
327                "float",
328                "_Float32",
329                "double",
330                "_Float32x",
331                "_Float64",
332                "long double",
333                "_Float64x",
334                "_Float128",
335            ]
336        );
337    }
338
339    #[test]
340    fn the_same_type_asked_for_twice_is_the_same_id() {
341        let mut types = Types::new();
342        let a = types.pointer(types.int(IntKind::Int));
343        let b = types.pointer(types.int(IntKind::Int));
344        assert_eq!(a, b, "interning is what makes type identity an integer comparison");
345        let c = types.pointer(types.int(IntKind::Long));
346        assert_ne!(a, c);
347    }
348
349    #[test]
350    fn a_qualifier_makes_a_different_type_with_the_same_shape() {
351        let mut types = Types::new();
352        let int = types.int(IntKind::Int);
353        let konst = types.qualified(int, Qualifiers::CONST);
354        assert_ne!(int, konst);
355        assert_eq!(types.kind(konst), types.kind(int));
356        assert!(types.quals(konst).has(Qualifiers::CONST));
357        assert_eq!(types.unqualified(konst), int);
358    }
359
360    #[test]
361    fn qualifiers_accumulate_and_do_not_depend_on_the_order_they_were_written() {
362        let mut types = Types::new();
363        let int = types.int(IntKind::Int);
364        let a = types.qualified(int, Qualifiers::CONST);
365        let a = types.qualified(a, Qualifiers::VOLATILE);
366        let b = types.qualified(int, Qualifiers::VOLATILE);
367        let b = types.qualified(b, Qualifiers::CONST);
368        assert_eq!(a, b, "`const volatile int` and `volatile const int` are one type");
369    }
370
371    #[test]
372    fn qualifying_an_array_qualifies_its_element() {
373        // 6.7.3p10, and not a shortcut. An array type has no qualifiers of its own, so if this
374        // put the `const` on the array then `const` on an array parameter would mean nothing.
375        let mut types = Types::new();
376        let int = types.int(IntKind::Int);
377        let array = types.array(int, ArrayLen::Fixed(4));
378        let konst = types.qualified(array, Qualifiers::CONST);
379        assert!(types.quals(konst).is_none(), "the array itself is unqualified");
380        let TypeKind::Array { elem, len } = types.kind(konst) else {
381            panic!("still an array");
382        };
383        assert_eq!(len, ArrayLen::Fixed(4));
384        assert!(types.quals(elem).has(Qualifiers::CONST));
385    }
386
387    #[test]
388    fn a_typedef_is_a_different_type_that_means_the_same_thing() {
389        let mut interner = Interner::new();
390        let mut types = Types::new();
391        let int = types.int(IntKind::Int);
392        let name = types.typedef(interner.intern("int32_t"), int);
393        assert_ne!(name, int, "the sugar survives, so a diagnostic can print it");
394        assert_eq!(types.canonical(name), int, "and no rule ever sees it");
395        assert!(types.is_sugar(name));
396        assert!(!types.is_sugar(int));
397    }
398
399    #[test]
400    fn sugar_below_the_outermost_node_is_resolved_too() {
401        // The bug this is here for: canonicalising only the top node leaves `int32_t *` and
402        // `int *` as different types, and then every rule stated on pointers stops firing.
403        let mut interner = Interner::new();
404        let mut types = Types::new();
405        let int = types.int(IntKind::Int);
406        let name = types.typedef(interner.intern("int32_t"), int);
407        let sugar_pointer = types.pointer(name);
408        let plain_pointer = types.pointer(int);
409        assert_ne!(sugar_pointer, plain_pointer);
410        assert_eq!(types.canonical(sugar_pointer), plain_pointer);
411
412        let sugar_array = types.array(name, ArrayLen::Fixed(3));
413        let plain_array = types.array(int, ArrayLen::Fixed(3));
414        assert_eq!(types.canonical(sugar_array), plain_array);
415    }
416
417    #[test]
418    fn a_typedef_of_a_typedef_canonicalises_all_the_way_down() {
419        let mut interner = Interner::new();
420        let mut types = Types::new();
421        let int = types.int(IntKind::Int);
422        let mut current = int;
423        for i in 0..8 {
424            current = types.typedef(interner.intern(&format!("t{i}")), current);
425        }
426        assert_eq!(types.canonical(current), int);
427    }
428
429    #[test]
430    fn a_typedef_that_asked_for_an_alignment_says_what_it_is_and_not_what_it_is_at_least() {
431        // `__attribute__((aligned(n)))` in this one position replaces the alignment rather than
432        // raising it, which is what lets `typedef int L __attribute__((aligned(2)))` really be an
433        // `int` at a multiple of two. The size is left where it was, which is gcc's answer and the
434        // reason an array of an over aligned typedef is refused rather than padded.
435        let mut interner = Interner::new();
436        let mut types = Types::new();
437        let target = linux();
438        let int = types.int(IntKind::Int);
439        let low = types.aligned_typedef(interner.intern("L"), int, NonZeroU32::new(2).unwrap());
440        let high = types.aligned_typedef(interner.intern("H"), int, NonZeroU32::new(16).unwrap());
441
442        assert_eq!(layout(&types, low, &target), Ok(Layout::new(4, 2)));
443        assert_eq!(layout(&types, high, &target), Ok(Layout::new(4, 16)));
444        // And the type behind them is what it always was, since the alignment belongs to the name
445        // and not to the `int`.
446        assert_eq!(layout(&types, int, &target), Ok(Layout::new(4, 4)));
447
448        // Two names for one type that asked for different alignments are two types, which is why
449        // the alignment is part of what the table interns them by.
450        assert_ne!(low, high);
451
452        // The nearest one wins, because the outer typedef is the one a declaration was written
453        // with, and one that asked for nothing keeps whatever the one below it asked for.
454        let outer = types.aligned_typedef(interner.intern("M"), low, NonZeroU32::new(8).unwrap());
455        assert_eq!(types.align_override(outer), NonZeroU32::new(8));
456        let plain = types.typedef(interner.intern("N"), low);
457        assert_eq!(types.align_override(plain), NonZeroU32::new(2));
458        // Below the sugar there is nothing to find, since only a typedef can carry one of these.
459        assert_eq!(types.align_override(int), None);
460    }
461
462    #[test]
463    fn a_qualified_typedef_keeps_the_name_and_canonicalises_to_the_qualified_type() {
464        let mut interner = Interner::new();
465        let mut types = Types::new();
466        let int = types.int(IntKind::Int);
467        let name = types.typedef(interner.intern("int32_t"), int);
468        let konst = types.qualified(name, Qualifiers::CONST);
469        assert!(matches!(types.kind(konst), TypeKind::Typedef { .. }), "still prints as int32_t");
470        let want = types.qualified(int, Qualifiers::CONST);
471        assert_eq!(types.canonical(konst), want);
472    }
473
474    #[test]
475    fn a_typedef_of_an_array_pushes_a_qualifier_to_the_element_when_it_canonicalises() {
476        // `typedef int A[4]; const A x;` declares an array of `const int`, which is where the
477        // array rule and the sugar rule have to agree with each other.
478        let mut interner = Interner::new();
479        let mut types = Types::new();
480        let int = types.int(IntKind::Int);
481        let array = types.array(int, ArrayLen::Fixed(4));
482        let name = types.typedef(interner.intern("A"), array);
483        let konst = types.qualified(name, Qualifiers::CONST);
484        let konst_int = types.qualified(int, Qualifiers::CONST);
485        let want = types.array(konst_int, ArrayLen::Fixed(4));
486        assert_eq!(types.canonical(konst), want);
487    }
488
489    #[test]
490    fn a_function_type_is_deduplicated_by_its_signature() {
491        let mut types = Types::new();
492        let int = types.int(IntKind::Int);
493        let long = types.int(IntKind::Long);
494        let make = |types: &mut Types, params: Vec<TypeId>, variadic| {
495            types.function(FunctionType { ret: int, params, variadic, prototyped: true })
496        };
497        let a = make(&mut types, vec![int, long], false);
498        let b = make(&mut types, vec![int, long], false);
499        assert_eq!(a, b);
500        assert_ne!(a, make(&mut types, vec![int, long], true), "`...` is part of the type");
501        assert_ne!(a, make(&mut types, vec![long, int], false));
502    }
503
504    #[test]
505    fn a_function_type_written_with_a_typedef_canonicalises_through_its_signature() {
506        let mut interner = Interner::new();
507        let mut types = Types::new();
508        let int = types.int(IntKind::Int);
509        let name = types.typedef(interner.intern("int32_t"), int);
510        let sugar = types.function(FunctionType {
511            ret: name,
512            params: vec![name],
513            variadic: false,
514            prototyped: true,
515        });
516        let plain = types.function(FunctionType {
517            ret: int,
518            params: vec![int],
519            variadic: false,
520            prototyped: true,
521        });
522        assert_ne!(sugar, plain);
523        assert_eq!(types.canonical(sugar), plain);
524    }
525
526    #[test]
527    fn a_record_is_its_declaration_and_not_its_members() {
528        // Two structs written the same way in one translation unit are different types. The
529        // looser relation that does hold between them is compatibility, which is a separate
530        // question from identity and is answered elsewhere.
531        let mut interner = Interner::new();
532        let mut types = Types::new();
533        let tag = interner.intern("point");
534        let first = types.declare_record(RecordKind::Struct, Some(tag));
535        let second = types.declare_record(RecordKind::Struct, Some(tag));
536        assert_ne!(types.record(first), types.record(second));
537        assert_eq!(types.record(first), types.record(first));
538    }
539
540    #[test]
541    fn a_record_has_no_layout_until_it_has_been_completed() {
542        let mut types = Types::new();
543        let id = types.declare_record(RecordKind::Struct, None);
544        let ty = types.record(id);
545        assert_eq!(layout(&types, ty, &linux()), Err(LayoutError::Incomplete));
546        let long_long = types.int(IntKind::LongLong);
547        let laid_out = lay_out(&types, RecordKind::Struct, &[member(long_long); 2]);
548        types.complete_record(id, laid_out);
549        assert_eq!(layout(&types, ty, &linux()).unwrap(), Layout::new(16, 8));
550    }
551
552    #[test]
553    fn an_enum_takes_the_layout_of_its_underlying_type() {
554        let mut types = Types::new();
555        let id = types.declare_enum(None);
556        let ty = types.enumeration(id);
557        assert_eq!(layout(&types, ty, &linux()), Err(LayoutError::Incomplete));
558        let int = types.int(IntKind::Int);
559        types.complete_enum(id, int, false);
560        assert_eq!(layout(&types, ty, &linux()).unwrap(), Layout::new(4, 4));
561    }
562
563    #[test]
564    fn the_scalar_widths_come_from_the_target() {
565        let mut types = Types::new();
566        let linux = linux();
567        let windows = target("x86_64-pc-windows-msvc");
568        let darwin = target("aarch64-apple-darwin");
569
570        let long = types.int(IntKind::Long);
571        assert_eq!(layout(&types, long, &linux).unwrap(), Layout::new(8, 8));
572        assert_eq!(layout(&types, long, &windows).unwrap(), Layout::new(4, 4), "LLP64");
573
574        let ldouble = types.float(FloatKind::LongDouble);
575        assert_eq!(layout(&types, ldouble, &linux).unwrap(), Layout::new(16, 16));
576        assert_eq!(layout(&types, ldouble, &darwin).unwrap(), Layout::new(8, 8));
577
578        let pointer = types.pointer(types.void());
579        assert_eq!(layout(&types, pointer, &linux).unwrap(), Layout::new(8, 8));
580
581        let boolean = types.boolean();
582        assert_eq!(layout(&types, boolean, &linux).unwrap(), Layout::new(1, 1));
583    }
584
585    #[test]
586    fn a_complex_type_is_two_of_its_component_with_the_components_alignment() {
587        // `_Complex long double` on SysV x86-64 is thirty two bytes aligned to sixteen, which
588        // is the case that catches an implementation that aligns the pair to its own size.
589        let mut types = Types::new();
590        let linux = linux();
591        let cfloat = types.complex(FloatKind::Float);
592        assert_eq!(layout(&types, cfloat, &linux).unwrap(), Layout::new(8, 4));
593        let cdouble = types.complex(FloatKind::Double);
594        assert_eq!(layout(&types, cdouble, &linux).unwrap(), Layout::new(16, 8));
595        let cldouble = types.complex(FloatKind::LongDouble);
596        assert_eq!(layout(&types, cldouble, &linux).unwrap(), Layout::new(32, 16));
597        let darwin = target("aarch64-apple-darwin");
598        assert_eq!(layout(&types, cldouble, &darwin).unwrap(), Layout::new(16, 8));
599    }
600
601    #[test]
602    fn an_atomic_type_can_be_more_aligned_than_the_type_it_wraps() {
603        // The whole reason `_Atomic` is a type here rather than a qualifier. A sixteen byte
604        // record is aligned to eight and the atomic version of it is aligned to sixteen.
605        let mut types = Types::new();
606        let linux = linux();
607        let long_long = types.int(IntKind::LongLong);
608        let plain = record(&mut types, RecordKind::Struct, &[member(long_long); 2]);
609        let atomic = types.atomic(plain);
610        assert_eq!(layout(&types, plain, &linux).unwrap(), Layout::new(16, 8));
611        assert_eq!(layout(&types, atomic, &linux).unwrap(), Layout::new(16, 16));
612
613        // An odd size cannot be accessed atomically in one go, so nothing is raised.
614        let odd = record(&mut types, RecordKind::Struct, &[member(long_long); 3]);
615        let atomic_odd = types.atomic(odd);
616        assert_eq!(layout(&types, atomic_odd, &linux).unwrap(), Layout::new(24, 8));
617
618        let int = types.int(IntKind::Int);
619        let atomic_int = types.atomic(int);
620        assert_eq!(layout(&types, atomic_int, &linux).unwrap(), Layout::new(4, 4));
621    }
622
623    #[test]
624    fn a_bit_int_is_laid_out_like_a_standard_integer_until_it_outgrows_one() {
625        // Measured with clang 18 on x86-64 Linux and clang on AArch64 Darwin. The two disagree
626        // above sixty four bits, which is why the granule is a target fact.
627        let mut types = Types::new();
628        let linux = linux();
629        let darwin = target("aarch64-apple-darwin");
630        let cases = [(7, 1, 1), (8, 1, 1), (9, 2, 2), (17, 4, 4), (33, 8, 8), (64, 8, 8)];
631        for (width, size, align) in cases {
632            let ty = types.bit_int(true, width);
633            assert_eq!(layout(&types, ty, &linux).unwrap(), Layout::new(size, align), "{width}");
634            assert_eq!(layout(&types, ty, &darwin).unwrap(), Layout::new(size, align), "{width}");
635        }
636        for width in [65, 96, 128] {
637            let ty = types.bit_int(false, width);
638            assert_eq!(layout(&types, ty, &linux).unwrap(), Layout::new(16, 8), "{width}");
639            assert_eq!(layout(&types, ty, &darwin).unwrap(), Layout::new(16, 16), "{width}");
640        }
641        let wide = types.bit_int(true, 129);
642        assert_eq!(layout(&types, wide, &linux).unwrap(), Layout::new(24, 8));
643        assert_eq!(layout(&types, wide, &darwin).unwrap(), Layout::new(32, 16));
644    }
645
646    #[test]
647    fn an_array_is_its_element_repeated_and_keeps_its_elements_alignment() {
648        let mut types = Types::new();
649        let linux = linux();
650        let int = types.int(IntKind::Int);
651        let ty = types.array(int, ArrayLen::Fixed(10));
652        assert_eq!(layout(&types, ty, &linux).unwrap(), Layout::new(40, 4));
653        let nested = types.array(ty, ArrayLen::Fixed(3));
654        assert_eq!(layout(&types, nested, &linux).unwrap(), Layout::new(120, 4));
655    }
656
657    #[test]
658    fn an_array_without_a_size_is_incomplete_and_an_impossible_one_says_so() {
659        let mut types = Types::new();
660        let linux = linux();
661        let int = types.int(IntKind::Int);
662        for len in [ArrayLen::Unknown, ArrayLen::Star, ArrayLen::Variable(VlaId(0))] {
663            let ty = types.array(int, len);
664            assert_eq!(layout(&types, ty, &linux), Err(LayoutError::Incomplete));
665        }
666        let huge = types.array(int, ArrayLen::Fixed(u64::MAX));
667        assert_eq!(layout(&types, huge, &linux), Err(LayoutError::TooLarge));
668    }
669
670    #[test]
671    fn the_largest_array_is_the_largest_object_and_not_the_largest_number() {
672        // The limit is `PTRDIFF_MAX` rather than wherever the multiplication happens to
673        // overflow, so an array of a byte may be every byte an object may have and one more
674        // than that is refused. gcc 16 gives the same two answers.
675        let mut types = Types::new();
676        let linux = linux();
677        let max = linux.max_object_size();
678        let ch = types.int(IntKind::Char);
679        let fits = types.array(ch, ArrayLen::Fixed(max));
680        assert_eq!(layout(&types, fits, &linux), Ok(Layout::new(max, 1)));
681        let over = types.array(ch, ArrayLen::Fixed(max + 1));
682        assert_eq!(layout(&types, over, &linux), Err(LayoutError::TooLarge));
683    }
684
685    #[test]
686    fn a_record_may_be_as_large_as_an_object_may_be_and_no_larger() {
687        // The shape `991014-1.c` in the gcc.c-torture execution suite asks about: a type
688        // nothing is ever an object of is still a type `sizeof` has to answer about. Counting
689        // the record in bits made the largest one an eighth of this, with the multiply by eight
690        // overflowing rather than any rule saying so.
691        let mut types = Types::new();
692        let linux = linux();
693        let max = linux.max_object_size();
694        let ch = types.int(IntKind::Char);
695        let int = types.int(IntKind::Int);
696        let short = types.int(IntKind::Short);
697
698        let huge = types.array(short, ArrayLen::Fixed((1 << 62) - 256));
699        let members = [member(huge), member(int), member(int), member(int), member(int)];
700        let laid_out = lay_out(&types, RecordKind::Struct, &members);
701        assert_eq!(laid_out.layout, Layout::new((1 << 63) - 496, 4));
702
703        let brim = types.array(ch, ArrayLen::Fixed(max));
704        let laid_out = lay_out(&types, RecordKind::Struct, &[member(brim)]);
705        assert_eq!(laid_out.layout, Layout::new(max, 1));
706
707        let over = [member(brim), member(ch)];
708        let options = RecordOptions::default();
709        let error = layout_record(&types, RecordKind::Struct, &over, &options, &linux);
710        assert_eq!(error, Err(RecordError::TooLarge));
711    }
712
713    #[test]
714    fn a_bit_field_past_where_a_bit_count_fits_is_still_placed() {
715        // Eight times the largest object is more than a `u64` holds, so a bit-field at the end
716        // of a record that large has a bit offset no bit count can name. It is a byte offset
717        // and a bit within it here, which is what lets this be laid out at all, and gcc 16
718        // gives the same size for it.
719        let mut types = Types::new();
720        let linux = linux();
721        let ch = types.int(IntKind::Char);
722        let int = types.int(IntKind::Int);
723        let mut interner = Interner::new();
724        let buf = types.array(ch, ArrayLen::Fixed(linux.max_object_size() - 7));
725        let members = [member(buf), bits(&mut interner, "x", int, 1)];
726        let laid_out = lay_out(&types, RecordKind::Struct, &members);
727        assert_eq!(laid_out.layout, Layout::new(9_223_372_036_854_775_804, 4));
728        let last = laid_out.fields[1];
729        assert_eq!((last.offset, last.bit), (9_223_372_036_854_775_800, 0));
730        assert_eq!(last.bit_offset(), 73_786_976_294_838_206_400);
731    }
732
733    #[test]
734    fn two_variable_length_arrays_of_the_same_element_are_still_different_types() {
735        let mut types = Types::new();
736        let int = types.int(IntKind::Int);
737        let a = types.array(int, ArrayLen::Variable(VlaId(0)));
738        let b = types.array(int, ArrayLen::Variable(VlaId(1)));
739        assert_ne!(a, b);
740    }
741
742    #[test]
743    fn a_vector_is_rounded_up_to_a_power_of_two_and_aligned_to_the_whole_thing() {
744        // What GCC does with a `vector_size` that is not already one, checked against clang on
745        // AArch64 Darwin, which accepts the three element case that GCC rejects outright.
746        let mut types = Types::new();
747        let linux = linux();
748        let int = types.int(IntKind::Int);
749        let four = types.vector(int, 4);
750        assert_eq!(layout(&types, four, &linux).unwrap(), Layout::new(16, 16));
751        let three = types.vector(int, 3);
752        assert_eq!(layout(&types, three, &linux).unwrap(), Layout::new(16, 16));
753        let three_chars = types.vector(types.int(IntKind::Char), 3);
754        assert_eq!(layout(&types, three_chars, &linux).unwrap(), Layout::new(4, 4));
755    }
756
757    #[test]
758    fn the_types_without_a_size_say_which_kind_of_without_they_are() {
759        // Kept apart because GNU C gives both of them a size of one and a different warning,
760        // and because a caller that cannot tell them apart cannot write either message.
761        let mut types = Types::new();
762        let linux = linux();
763        let void = types.void();
764        assert_eq!(layout(&types, void, &linux), Err(LayoutError::Incomplete));
765        let int = types.int(IntKind::Int);
766        let function = types.function(FunctionType {
767            ret: int,
768            params: Vec::new(),
769            variadic: false,
770            prototyped: true,
771        });
772        assert_eq!(layout(&types, function, &linux), Err(LayoutError::Function));
773        let pointer_to_function = types.pointer(function);
774        assert_eq!(layout(&types, pointer_to_function, &linux).unwrap(), Layout::new(8, 8));
775    }
776
777    #[test]
778    fn a_struct_puts_each_member_at_the_next_offset_it_is_allowed_to_start_at() {
779        let types = Types::new();
780        let char_ = types.int(IntKind::Char);
781        let int = types.int(IntKind::Int);
782        let laid_out = lay_out(&types, RecordKind::Struct, &[member(char_), member(int)]);
783        assert_eq!(laid_out.layout, Layout::new(8, 4));
784        assert_eq!(offsets(&laid_out), [0, 32]);
785        assert_eq!(laid_out.fields[1].offset, 4);
786
787        // And the tail is padded, which is what makes an array of the thing work.
788        let long_long = types.int(IntKind::LongLong);
789        let laid_out = lay_out(&types, RecordKind::Struct, &[member(long_long), member(char_)]);
790        assert_eq!(laid_out.layout, Layout::new(16, 8));
791    }
792
793    #[test]
794    fn a_union_starts_every_member_at_zero_and_is_as_large_as_the_largest() {
795        let mut types = Types::new();
796        let char_ = types.int(IntKind::Char);
797        let int = types.int(IntKind::Int);
798        let laid_out = lay_out(&types, RecordKind::Union, &[member(char_), member(int)]);
799        assert_eq!(laid_out.layout, Layout::new(4, 4));
800        assert_eq!(offsets(&laid_out), [0, 0]);
801
802        // Nine bytes and a short is ten, not nine and not sixteen: the size is rounded up to
803        // the alignment rather than to the largest member.
804        let nine = types.array(char_, ArrayLen::Fixed(9));
805        let short = types.int(IntKind::Short);
806        let laid_out = lay_out(&types, RecordKind::Union, &[member(nine), member(short)]);
807        assert_eq!(laid_out.layout, Layout::new(10, 2));
808    }
809
810    #[test]
811    fn bit_fields_share_a_unit_until_one_of_them_would_span_two() {
812        // Measured with gcc 13.3 on x86-64 Linux and clang on AArch64 Darwin, including where
813        // the bits landed, by setting each field to all ones and dumping the bytes.
814        let mut interner = Interner::new();
815        let types = Types::new();
816        let char_ = types.int(IntKind::Char);
817        let int = types.int(IntKind::Int);
818        let long_long = types.int(IntKind::LongLong);
819
820        let fields = [bits(&mut interner, "a", int, 3), bits(&mut interner, "b", int, 5)];
821        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
822        assert_eq!(laid_out.layout, Layout::new(4, 4));
823        assert_eq!(offsets(&laid_out), [0, 3]);
824
825        // Thirty bits do not fit in what is left of the first int, so they start a new one.
826        let fields = [member(char_), bits(&mut interner, "b", int, 30)];
827        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
828        assert_eq!(laid_out.layout, Layout::new(8, 4));
829        assert_eq!(offsets(&laid_out), [0, 32]);
830
831        // Thirty three bits of a `long long` do fit in what is left of the first one, because
832        // the unit is eight bytes rather than four, so they stay where they are.
833        let fields = [member(char_), bits(&mut interner, "b", long_long, 33)];
834        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
835        assert_eq!(laid_out.layout, Layout::new(8, 8));
836        assert_eq!(offsets(&laid_out), [0, 8]);
837
838        // An ordinary member after a bit-field starts at the next byte it is allowed to.
839        let fields = [bits(&mut interner, "a", int, 3), member(char_)];
840        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
841        assert_eq!(offsets(&laid_out), [0, 8]);
842    }
843
844    #[test]
845    fn a_zero_width_bit_field_moves_the_next_member_on_and_nothing_else() {
846        let types = Types::new();
847        let char_ = types.int(IntKind::Char);
848        let int = types.int(IntKind::Int);
849        let fields = [member(char_), unnamed_bits(int, 0), member(char_)];
850        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
851        // Five bytes aligned to one: the zero width field pushed the second `char` to offset
852        // four without giving the record the alignment of an `int`. Both compilers report that.
853        assert_eq!(laid_out.layout, Layout::new(5, 1));
854        assert_eq!(offsets(&laid_out), [0, 32, 32]);
855        assert_eq!(laid_out.fields.len(), 3, "one field per declaration, so indices line up");
856    }
857
858    #[test]
859    fn an_unnamed_bit_field_does_not_raise_the_records_alignment_but_a_named_one_does() {
860        let mut interner = Interner::new();
861        let types = Types::new();
862        let char_ = types.int(IntKind::Char);
863        let int = types.int(IntKind::Int);
864
865        let unnamed = [member(char_), unnamed_bits(int, 20)];
866        let unnamed = lay_out(&types, RecordKind::Struct, &unnamed);
867        assert_eq!(unnamed.layout, Layout::new(4, 1));
868
869        let named = [member(char_), bits(&mut interner, "b", int, 20)];
870        let named = lay_out(&types, RecordKind::Struct, &named);
871        assert_eq!(named.layout, Layout::new(4, 4));
872        assert_eq!(offsets(&named), [0, 8], "the same place either way");
873
874        // The unit an unnamed field has to fit inside is still its own type's, so this one
875        // moves to bit thirty two and the record is eight bytes aligned to one.
876        let wider = [member(char_), unnamed_bits(int, 30)];
877        let wider = lay_out(&types, RecordKind::Struct, &wider);
878        assert_eq!(wider.layout, Layout::new(8, 1));
879        assert_eq!(offsets(&wider), [0, 32]);
880    }
881
882    #[test]
883    fn packed_drops_every_member_to_a_byte_and_bit_fields_to_the_next_free_bit() {
884        let mut interner = Interner::new();
885        let types = Types::new();
886        let char_ = types.int(IntKind::Char);
887        let int = types.int(IntKind::Int);
888        let packed = RecordOptions { packed: true, ..RecordOptions::default() };
889
890        let fields = [member(char_), member(int)];
891        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &packed, &linux())
892            .expect("a packed struct of two complete members");
893        assert_eq!(laid_out.layout, Layout::new(5, 1));
894        assert_eq!(offsets(&laid_out), [0, 8]);
895
896        let fields = [member(char_), bits(&mut interner, "b", int, 30)];
897        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &packed, &linux())
898            .expect("a packed struct with a bit-field");
899        assert_eq!(laid_out.layout, Layout::new(5, 1));
900        assert_eq!(offsets(&laid_out), [0, 8], "no boundary left to move to");
901
902        // A zero width bit-field still rounds to its own type, packed or not, which is the
903        // whole reason a program writes one inside a packed structure.
904        let fields = [member(char_), unnamed_bits(int, 0), member(char_)];
905        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &packed, &linux())
906            .expect("a packed struct with a zero width bit-field");
907        assert_eq!(laid_out.layout, Layout::new(5, 1));
908        assert_eq!(offsets(&laid_out), [0, 32, 32]);
909    }
910
911    #[test]
912    fn pragma_pack_caps_alignment_and_leaves_a_bit_field_where_it_already_is() {
913        let mut interner = Interner::new();
914        let types = Types::new();
915        let char_ = types.int(IntKind::Char);
916        let int = types.int(IntKind::Int);
917        let pack = RecordOptions { pack: Some(2), ..RecordOptions::default() };
918
919        let fields = [member(char_), member(int)];
920        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &pack, &linux())
921            .expect("a packed struct of two complete members");
922        assert_eq!(laid_out.layout, Layout::new(6, 2));
923        assert_eq!(offsets(&laid_out), [0, 16]);
924
925        // Six bytes with the field at bit eight, not at bit sixteen. Once the alignment has
926        // been capped below the type's own there is no boundary to move to, so the field stays
927        // put. Measured, because moving it is at least as plausible a reading.
928        let fields = [member(char_), bits(&mut interner, "b", int, 30)];
929        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &pack, &linux())
930            .expect("a packed struct with a bit-field");
931        assert_eq!(laid_out.layout, Layout::new(6, 2));
932        assert_eq!(offsets(&laid_out), [0, 8]);
933
934        // The same structure with the field unnamed is five bytes aligned to one, because the
935        // capped alignment reached it through the record and an unnamed field gives none back.
936        let fields = [member(char_), unnamed_bits(int, 30)];
937        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &pack, &linux())
938            .expect("a packed struct with an unnamed bit-field");
939        assert_eq!(laid_out.layout, Layout::new(5, 1));
940    }
941
942    #[test]
943    fn an_alignment_the_program_asked_for_raises_the_member_and_the_record() {
944        let types = Types::new();
945        let char_ = types.int(IntKind::Char);
946        let int = types.int(IntKind::Int);
947
948        let aligned = FieldDecl { align: Some(16), ..member(int) };
949        let laid_out = lay_out(&types, RecordKind::Struct, &[member(char_), aligned]);
950        assert_eq!(laid_out.layout, Layout::new(32, 16));
951        assert_eq!(offsets(&laid_out), [0, 128]);
952
953        // `packed, aligned(4)` together: the members pack and the record does not, which is
954        // the combination the attribute pair exists for.
955        let options = RecordOptions { packed: true, align: Some(4), pack: None };
956        let fields = [member(char_), member(int)];
957        let laid_out = layout_record(&types, RecordKind::Struct, &fields, &options, &linux())
958            .expect("a packed struct with an alignment asked for");
959        assert_eq!(laid_out.layout, Layout::new(8, 4));
960        assert_eq!(offsets(&laid_out), [0, 8]);
961    }
962
963    #[test]
964    fn a_flexible_array_member_costs_nothing_but_its_alignment() {
965        // What makes `malloc(sizeof(struct S) + n)` the idiom it is.
966        let mut types = Types::new();
967        let char_ = types.int(IntKind::Char);
968        let int = types.int(IntKind::Int);
969        let long_long = types.int(IntKind::LongLong);
970
971        let chars = types.array(char_, ArrayLen::Unknown);
972        let laid_out = lay_out(&types, RecordKind::Struct, &[member(int), member(chars)]);
973        assert_eq!(laid_out.layout, Layout::new(4, 4));
974        assert_eq!(offsets(&laid_out), [0, 32]);
975
976        // The alignment still applies, so this is eight bytes of which one is the `char`.
977        let longs = types.array(long_long, ArrayLen::Unknown);
978        let laid_out = lay_out(&types, RecordKind::Struct, &[member(char_), member(longs)]);
979        assert_eq!(laid_out.layout, Layout::new(8, 8));
980        assert_eq!(offsets(&laid_out), [0, 64]);
981
982        // Anywhere but last it is an incomplete member, and which member is part of the answer.
983        let fields = [member(chars), member(int)];
984        let error =
985            layout_record(&types, RecordKind::Struct, &fields, &RecordOptions::default(), &linux());
986        assert_eq!(error, Err(RecordError::Member { index: 0, error: LayoutError::Incomplete }));
987    }
988
989    #[test]
990    fn a_record_with_no_members_is_zero_bytes_aligned_to_one() {
991        // The GNU empty structure, which C itself does not have and which real headers do.
992        let types = Types::new();
993        let laid_out = lay_out(&types, RecordKind::Struct, &[]);
994        assert_eq!(laid_out.layout, Layout::new(0, 1));
995    }
996
997    #[test]
998    fn a_bit_field_wider_than_the_type_it_is_declared_with_is_refused() {
999        let types = Types::new();
1000        let int = types.int(IntKind::Int);
1001        let fields = [unnamed_bits(int, 33)];
1002        let error =
1003            layout_record(&types, RecordKind::Struct, &fields, &RecordOptions::default(), &linux());
1004        let want = RecordError::BitFieldTooWide { index: 0, width: 33, capacity: 32 };
1005        assert_eq!(error, Err(want));
1006    }
1007
1008    #[test]
1009    fn a_record_reports_its_members_once_it_has_been_completed() {
1010        let mut interner = Interner::new();
1011        let mut types = Types::new();
1012        let char_ = types.int(IntKind::Char);
1013        let int = types.int(IntKind::Int);
1014        let name = interner.intern("count");
1015        let fields = [member(char_), FieldDecl::new(Some(name), int)];
1016        let id = types.declare_record(RecordKind::Struct, None);
1017        let laid_out = lay_out(&types, RecordKind::Struct, &fields);
1018        types.complete_record(id, laid_out);
1019        let ty = types.record(id);
1020        assert_eq!(layout(&types, ty, &linux()).unwrap(), Layout::new(8, 4));
1021        let field = types.field(id, name).expect("the member that was declared");
1022        assert_eq!(field.offset, 4);
1023        assert!(!field.is_bit_field());
1024        assert_eq!(types.field(id, interner.intern("missing")), None);
1025    }
1026
1027    #[test]
1028    fn a_nested_record_brings_its_own_alignment_with_it() {
1029        let mut types = Types::new();
1030        let char_ = types.int(IntKind::Char);
1031        let int = types.int(IntKind::Int);
1032        let inner = record(&mut types, RecordKind::Struct, &[member(char_)]);
1033        let laid_out = lay_out(&types, RecordKind::Struct, &[member(inner), member(int)]);
1034        assert_eq!(laid_out.layout, Layout::new(8, 4));
1035        assert_eq!(offsets(&laid_out), [0, 32]);
1036
1037        // An anonymous member is an ordinary member with no name, so the same code lays it out
1038        // and the four bytes of padding after the `char` are there either way.
1039        let anonymous = record(&mut types, RecordKind::Struct, &[member(int), member(char_)]);
1040        let laid_out = lay_out(&types, RecordKind::Struct, &[member(char_), member(anonymous)]);
1041        assert_eq!(laid_out.layout, Layout::new(12, 4));
1042        assert_eq!(offsets(&laid_out), [0, 32]);
1043    }
1044
1045    #[test]
1046    fn everything_narrower_than_an_int_promotes_to_one() {
1047        // Measured by naming the type of `+x` with `_Generic` in gcc 13.3 and clang 18. Every
1048        // one of these answers `int`, including the unsigned ones, because an `int` holds every
1049        // value a sixteen bit unsigned type has.
1050        let mut types = Types::new();
1051        let linux = linux();
1052        let int = types.int(IntKind::Int);
1053        let narrow =
1054            [IntKind::Char, IntKind::SChar, IntKind::UChar, IntKind::Short, IntKind::UShort];
1055        for kind in narrow {
1056            let ty = types.int(kind);
1057            assert_eq!(promote(&mut types, ty, &linux), int, "{}", kind.as_str());
1058        }
1059        let boolean = types.boolean();
1060        assert_eq!(promote(&mut types, boolean, &linux), int, "C23 made bool a real type");
1061
1062        // From `int` up, a type is its own promotion.
1063        for kind in [IntKind::Int, IntKind::UInt, IntKind::Long, IntKind::ULongLong] {
1064            let ty = types.int(kind);
1065            assert_eq!(promote(&mut types, ty, &linux), ty, "{}", kind.as_str());
1066        }
1067    }
1068
1069    #[test]
1070    fn a_bit_int_is_not_promoted_at_all() {
1071        // C23 6.3.1.1p2, and the point of the type. `_BitInt(8) + _BitInt(8)` stays eight bits
1072        // wide where `char + char` is an `int`, which is what makes the width mean something.
1073        let mut types = Types::new();
1074        let linux = linux();
1075        let small = types.bit_int(true, 8);
1076        assert_eq!(promote(&mut types, small, &linux), small);
1077        assert_eq!(usual_arithmetic(&mut types, small, small, &linux), Some(small));
1078    }
1079
1080    #[test]
1081    fn a_bit_field_is_promoted_by_its_width_and_not_by_its_type() {
1082        let mut types = Types::new();
1083        let linux = linux();
1084        let int = types.int(IntKind::Int);
1085        let uint = types.int(IntKind::UInt);
1086        let ullong = types.int(IntKind::ULongLong);
1087
1088        // Three bits of an unsigned field all fit in an `int`, so it is signed afterwards.
1089        assert_eq!(promote_bit_field(&mut types, uint, 3, &linux), int);
1090        // Thirty two of them do not.
1091        assert_eq!(promote_bit_field(&mut types, uint, 32, &linux), uint);
1092        // Twenty bits of a signed field, which is an `int` either way.
1093        assert_eq!(promote_bit_field(&mut types, int, 20, &linux), int);
1094        // Forty bits are forty bits of value and nothing more. The C17 wording says `unsigned
1095        // int` here, which would silently drop eight of them, and C23 says the declared type,
1096        // which would silently add twenty four. Both compilers give the width instead, so
1097        // `x.b << 32` on such a field is zero rather than a value with a bit above the fortieth.
1098        let forty = types.bit_int(false, 40);
1099        assert_eq!(promote_bit_field(&mut types, ullong, 40, &linux), forty);
1100        // A field as wide as its type is that type, since there is no precision to lose.
1101        assert_eq!(promote_bit_field(&mut types, ullong, 64, &linux), ullong);
1102    }
1103
1104    #[test]
1105    fn an_enumeration_promotes_through_what_it_is_represented_in() {
1106        let mut types = Types::new();
1107        let linux = linux();
1108        let int = types.int(IntKind::Int);
1109        let short = types.int(IntKind::Short);
1110        let uint = types.int(IntKind::UInt);
1111
1112        // `enum E : short` promotes the same way a `short` does, which is to `int`.
1113        let fixed = types.declare_enum(None);
1114        types.complete_enum(fixed, short, true);
1115        let fixed = types.enumeration(fixed);
1116        assert_eq!(promote(&mut types, fixed, &linux), int);
1117
1118        // An enumeration all of whose enumerators are non-negative is represented in
1119        // `unsigned int` by both compilers, and then it promotes to itself.
1120        let unsigned = types.declare_enum(None);
1121        types.complete_enum(unsigned, uint, false);
1122        let unsigned = types.enumeration(unsigned);
1123        assert_eq!(promote(&mut types, unsigned, &linux), uint);
1124
1125        // An enumeration nobody has decided on yet answers `int`, so that an expression using
1126        // one is still checkable while the diagnostic about it is being written.
1127        let undecided = types.declare_enum(None);
1128        let undecided = types.enumeration(undecided);
1129        assert_eq!(promote(&mut types, undecided, &linux), int);
1130    }
1131
1132    #[test]
1133    fn the_qualifiers_and_the_atomic_come_off_before_anything_else() {
1134        // By the time a value is being promoted the lvalue conversion has already happened, so
1135        // `_Atomic const int` and `int` are the same operand.
1136        let mut types = Types::new();
1137        let linux = linux();
1138        let int = types.int(IntKind::Int);
1139        let konst = types.qualified(int, Qualifiers::CONST);
1140        let atomic = types.atomic(konst);
1141        assert_eq!(promote(&mut types, atomic, &linux), int);
1142        assert_eq!(usual_arithmetic(&mut types, atomic, konst, &linux), Some(int));
1143    }
1144
1145    #[test]
1146    fn the_usual_arithmetic_conversions_between_the_standard_integer_types() {
1147        // Every row measured with `_Generic` in gcc 13.3 and clang 18 on x86-64 Linux.
1148        let mut types = Types::new();
1149        let linux = linux();
1150        let cases = [
1151            (IntKind::Int, IntKind::UInt, IntKind::UInt),
1152            (IntKind::Int, IntKind::Long, IntKind::Long),
1153            (IntKind::UInt, IntKind::Long, IntKind::Long),
1154            (IntKind::UInt, IntKind::ULong, IntKind::ULong),
1155            (IntKind::Int, IntKind::LongLong, IntKind::LongLong),
1156            (IntKind::UInt, IntKind::LongLong, IntKind::LongLong),
1157            (IntKind::ULong, IntKind::LongLong, IntKind::ULongLong),
1158            (IntKind::Char, IntKind::Char, IntKind::Int),
1159            (IntKind::UChar, IntKind::UShort, IntKind::Int),
1160        ];
1161        for (left, right, want) in cases {
1162            let left = types.int(left);
1163            let right = types.int(right);
1164            let want = types.int(want);
1165            assert_eq!(usual_arithmetic(&mut types, left, right, &linux), Some(want));
1166            assert_eq!(usual_arithmetic(&mut types, right, left, &linux), Some(want), "either way");
1167        }
1168    }
1169
1170    #[test]
1171    fn int128_is_sixteen_bytes_aligned_to_sixteen_and_outranks_long_long() {
1172        // Measured on gcc 13.3 on x86-64 Linux and clang on AArch64 Darwin, both of which
1173        // report the same size, the same alignment, and an offset of sixteen for a member
1174        // after a `char`.
1175        let mut types = Types::new();
1176        let linux = linux();
1177        let signed = types.int(IntKind::Int128);
1178        let unsigned = types.int(IntKind::UInt128);
1179        for id in [signed, unsigned] {
1180            let laid_out = layout(&types, id, &linux).expect("a complete type");
1181            assert_eq!(laid_out.size, 16);
1182            assert_eq!(laid_out.align, 16);
1183        }
1184
1185        // `__int128 + unsigned long long` is `__int128`, because it wins on rank and is wide
1186        // enough to hold every value the other side had. Both compilers agree, and it is the
1187        // one pair that says the rank is above `long long` rather than beside it.
1188        let ull = types.int(IntKind::ULongLong);
1189        assert_eq!(usual_arithmetic(&mut types, signed, ull, &linux), Some(signed));
1190        // And it is its own promotion, the way every type at or above `int` is.
1191        assert_eq!(promote(&mut types, signed, &linux), signed);
1192    }
1193
1194    #[test]
1195    fn a_bit_int_of_a_hundred_and_twenty_eight_bits_is_not_int128() {
1196        // Same width, different types. The alignment is the visible difference on x86-64,
1197        // where a `_BitInt` is aligned to its sixty four bit granule and `__int128` is not.
1198        let mut types = Types::new();
1199        let linux = linux();
1200        let int128 = types.int(IntKind::Int128);
1201        let bit_int = types.bit_int(true, 128);
1202        assert_ne!(int128, bit_int);
1203        assert!(!compatible(&types, int128, bit_int));
1204        assert_eq!(layout(&types, bit_int, &linux).expect("complete").align, 8);
1205        assert_eq!(layout(&types, int128, &linux).expect("complete").align, 16);
1206    }
1207
1208    #[test]
1209    fn the_last_arm_takes_the_unsigned_type_of_the_wider_one() {
1210        // `unsigned long + long long` is `unsigned long long` on Linux: the `long long` wins on
1211        // rank and cannot hold every value of the `unsigned long`, so neither operand's own
1212        // type is the answer. This is the arm programs are surprised by.
1213        let mut types = Types::new();
1214        let linux = linux();
1215        let ulong = types.int(IntKind::ULong);
1216        let long_long = types.int(IntKind::LongLong);
1217        let want = types.int(IntKind::ULongLong);
1218        assert_eq!(usual_arithmetic(&mut types, ulong, long_long, &linux), Some(want));
1219
1220        // The same pair on Windows, where `long` is thirty two bits, comes out as `long long`,
1221        // because there it does hold every value. A host-driven implementation gets one of
1222        // these two wrong.
1223        let windows = target("x86_64-pc-windows-msvc");
1224        assert_eq!(usual_arithmetic(&mut types, ulong, long_long, &windows), Some(long_long));
1225    }
1226
1227    #[test]
1228    fn a_bit_int_is_ranked_by_its_width_against_the_standard_types() {
1229        // Measured with clang 18 on x86-64 Linux, which is the compiler that has `_BitInt`.
1230        let mut types = Types::new();
1231        let linux = linux();
1232        let b40 = types.bit_int(true, 40);
1233        let ub40 = types.bit_int(false, 40);
1234        let b8 = types.bit_int(true, 8);
1235        let b32 = types.bit_int(true, 32);
1236        let int = types.int(IntKind::Int);
1237        let uint = types.int(IntKind::UInt);
1238        let long = types.int(IntKind::Long);
1239        let char_ = types.int(IntKind::Char);
1240
1241        // Wider than an `int`, so it outranks one.
1242        assert_eq!(usual_arithmetic(&mut types, b40, int, &linux), Some(b40));
1243        // Narrower than a `long`, so it loses to one.
1244        assert_eq!(usual_arithmetic(&mut types, b40, long, &linux), Some(long));
1245        // The same width as an `int`, and a standard type wins the tie.
1246        assert_eq!(usual_arithmetic(&mut types, b32, int, &linux), Some(int));
1247        assert_eq!(usual_arithmetic(&mut types, b32, uint, &linux), Some(uint));
1248        // The other side promotes first, so a `char` next to a narrow `_BitInt` is an `int`
1249        // and the `_BitInt` loses to it.
1250        assert_eq!(usual_arithmetic(&mut types, b8, char_, &linux), Some(int));
1251        // Unsigned and higher ranked wins outright, and unsigned and lower ranked loses to a
1252        // signed type wide enough to hold it.
1253        assert_eq!(usual_arithmetic(&mut types, ub40, int, &linux), Some(ub40));
1254        assert_eq!(usual_arithmetic(&mut types, ub40, long, &linux), Some(long));
1255        // Two bit-precise types of the same width and different signedness.
1256        assert_eq!(usual_arithmetic(&mut types, b40, ub40, &linux), Some(ub40));
1257    }
1258
1259    #[test]
1260    fn a_floating_operand_decides_the_answer_whatever_the_other_side_is() {
1261        let mut types = Types::new();
1262        let linux = linux();
1263        let float = types.float(FloatKind::Float);
1264        let double = types.float(FloatKind::Double);
1265        let long_double = types.float(FloatKind::LongDouble);
1266        let ullong = types.int(IntKind::ULongLong);
1267        let int = types.int(IntKind::Int);
1268
1269        assert_eq!(usual_arithmetic(&mut types, int, float, &linux), Some(float));
1270        assert_eq!(usual_arithmetic(&mut types, float, double, &linux), Some(double));
1271        assert_eq!(usual_arithmetic(&mut types, double, long_double, &linux), Some(long_double));
1272        // Sixty four bits of unsigned integer against a `float`, which is a `float` and loses
1273        // most of them. That is the rule rather than an oversight.
1274        assert_eq!(usual_arithmetic(&mut types, ullong, float, &linux), Some(float));
1275    }
1276
1277    #[test]
1278    fn a_mask_is_the_signed_integers_of_the_lane_width() {
1279        let mut types = Types::new();
1280        let linux = linux();
1281        let int = types.int(IntKind::Int);
1282        let float = types.float(FloatKind::Float);
1283        let short = types.int(IntKind::Short);
1284
1285        // A signed lane is already its own mask, so the answer is the vector it was given.
1286        let four_ints = types.vector(int, 4);
1287        assert_eq!(mask_of(&mut types, four_ints, &linux), Some(four_ints));
1288
1289        // An unsigned lane answers as the signed type of the same width, which is what GCC
1290        // gives a comparison of two `unsigned int` vectors.
1291        let uint = types.int(IntKind::UInt);
1292        let four_uints = types.vector(uint, 4);
1293        assert_eq!(mask_of(&mut types, four_uints, &linux), Some(four_ints));
1294
1295        // A float lane answers as an integer of the same width, since the mask is bits and not
1296        // a number and there is no float that is all ones.
1297        let four_floats = types.vector(float, 4);
1298        assert_eq!(mask_of(&mut types, four_floats, &linux), Some(four_ints));
1299
1300        // The width is the lane's own and not a word, so a `short` lane keeps its two bytes.
1301        let two_shorts = types.vector(short, 2);
1302        assert_eq!(mask_of(&mut types, two_shorts, &linux), Some(two_shorts));
1303
1304        // Not a vector, so there is no mask to give.
1305        assert_eq!(mask_of(&mut types, int, &linux), None);
1306    }
1307
1308    #[test]
1309    fn two_vectors_convert_between_each_other_when_the_bytes_line_up() {
1310        let mut types = Types::new();
1311        let linux = linux();
1312        let int = types.int(IntKind::Int);
1313        let uint = types.int(IntKind::UInt);
1314        let float = types.float(FloatKind::Float);
1315        let short = types.int(IntKind::Short);
1316
1317        let four_ints = types.vector(int, 4);
1318        let four_uints = types.vector(uint, 4);
1319        let four_floats = types.vector(float, 4);
1320        let eight_shorts = types.vector(short, 8);
1321        let two_ints = types.vector(int, 2);
1322
1323        // The case the whole thing exists for: a mask assigned to the unsigned vector it came
1324        // from, which GNU C converts and the standard rules would refuse.
1325        assert!(vectors_convertible(&types, four_uints, four_ints, &linux));
1326        // Both ways round, since assignment happens in both directions.
1327        assert!(vectors_convertible(&types, four_ints, four_uints, &linux));
1328        // The same sixteen bytes cut into eight lanes rather than four, which GCC also allows.
1329        assert!(vectors_convertible(&types, four_ints, eight_shorts, &linux));
1330        // Two floats of the same width, which is the other half of the rule.
1331        assert!(vectors_convertible(&types, four_floats, four_floats, &linux));
1332
1333        // An integer lane against a float lane, which GCC refuses even at the same size,
1334        // because reading one as the other is a cast and not a conversion.
1335        assert!(!vectors_convertible(&types, four_ints, four_floats, &linux));
1336        // Different sizes, so there is nothing to reinterpret.
1337        assert!(!vectors_convertible(&types, four_ints, two_ints, &linux));
1338        // A scalar is not a vector, whichever side it is on.
1339        assert!(!vectors_convertible(&types, four_ints, int, &linux));
1340        assert!(!vectors_convertible(&types, int, four_ints, &linux));
1341    }
1342
1343    /// Insists that `a + b` and `b + a` are both `expected` on this target.
1344    ///
1345    /// Both ways round, because the operands of `+` are not ordered and an implementation that
1346    /// keeps the left one when it cannot decide would pass half of these and be wrong.
1347    fn combines(target: &TargetInfo, a: FloatKind, b: FloatKind, expected: FloatKind) {
1348        let mut types = Types::new();
1349        let left = types.float(a);
1350        let right = types.float(b);
1351        let want = types.float(expected);
1352        assert_eq!(usual_arithmetic(&mut types, left, right, target), Some(want), "{a:?} + {b:?}");
1353        assert_eq!(usual_arithmetic(&mut types, right, left, target), Some(want), "{b:?} + {a:?}");
1354    }
1355
1356    #[test]
1357    fn two_floating_types_of_the_same_format_are_still_two_types_and_one_of_them_wins() {
1358        // Every line here was read off gcc 16 with `_Generic` rather than off the standard, on
1359        // x86-64 Linux, where `long double` and `_Float64x` are both the x87 format and the
1360        // standard type is the one that comes out.
1361        let x86 = linux();
1362        combines(&x86, FloatKind::Double, FloatKind::Float64, FloatKind::Float64);
1363        combines(&x86, FloatKind::Float, FloatKind::Float32, FloatKind::Float32);
1364        combines(&x86, FloatKind::Double, FloatKind::Float32x, FloatKind::Double);
1365        combines(&x86, FloatKind::LongDouble, FloatKind::Float64x, FloatKind::LongDouble);
1366        combines(&x86, FloatKind::Float128, FloatKind::LongDouble, FloatKind::Float128);
1367        combines(&x86, FloatKind::Float64x, FloatKind::Float128, FloatKind::Float128);
1368        combines(&x86, FloatKind::Double, FloatKind::LongDouble, FloatKind::LongDouble);
1369        combines(&x86, FloatKind::Float32x, FloatKind::Float64, FloatKind::Float64);
1370        combines(&x86, FloatKind::Float64x, FloatKind::Float64, FloatKind::Float64x);
1371        combines(&x86, FloatKind::LongDouble, FloatKind::Float64, FloatKind::LongDouble);
1372    }
1373
1374    #[test]
1375    fn the_widest_floating_type_is_a_question_about_the_target_and_not_about_the_names() {
1376        // The same reading against gcc 16 on aarch64-apple-darwin, where `long double` is a
1377        // `double` and loses to the `_Float64x` it beats on x86-64. The name says nothing about
1378        // which of the two is wider, which is why the ordering is worked out from the formats.
1379        let mac = target("aarch64-apple-darwin");
1380        combines(&mac, FloatKind::LongDouble, FloatKind::Float64x, FloatKind::Float64x);
1381        combines(&mac, FloatKind::Double, FloatKind::LongDouble, FloatKind::LongDouble);
1382        combines(&mac, FloatKind::Float128, FloatKind::LongDouble, FloatKind::Float128);
1383        combines(&mac, FloatKind::Float64x, FloatKind::Float64, FloatKind::Float64x);
1384        combines(&mac, FloatKind::Float32x, FloatKind::Float32, FloatKind::Float32x);
1385        combines(&mac, FloatKind::Float32x, FloatKind::Float64, FloatKind::Float64);
1386        combines(&mac, FloatKind::Double, FloatKind::Float64, FloatKind::Float64);
1387        // `_Float16` is the narrowest type there is and does not promote on the way in, so it
1388        // survives an operation only when nothing wider is there.
1389        combines(&mac, FloatKind::Float16, FloatKind::Float, FloatKind::Float);
1390        combines(&mac, FloatKind::Float16, FloatKind::Double, FloatKind::Double);
1391        combines(&mac, FloatKind::Float16, FloatKind::Float16, FloatKind::Float16);
1392    }
1393
1394    #[test]
1395    fn a_complex_operand_makes_the_answer_complex_after_the_real_types_have_combined() {
1396        let mut types = Types::new();
1397        let linux = linux();
1398        let cfloat = types.complex(FloatKind::Float);
1399        let cdouble = types.complex(FloatKind::Double);
1400        let cldouble = types.complex(FloatKind::LongDouble);
1401        let double = types.float(FloatKind::Double);
1402        let long_double = types.float(FloatKind::LongDouble);
1403        let float = types.float(FloatKind::Float);
1404        let int = types.int(IntKind::Int);
1405
1406        assert_eq!(usual_arithmetic(&mut types, cfloat, double, &linux), Some(cdouble));
1407        assert_eq!(usual_arithmetic(&mut types, cfloat, int, &linux), Some(cfloat));
1408        assert_eq!(usual_arithmetic(&mut types, cdouble, long_double, &linux), Some(cldouble));
1409        assert_eq!(usual_arithmetic(&mut types, cfloat, float, &linux), Some(cfloat));
1410    }
1411
1412    #[test]
1413    fn an_operand_that_is_not_arithmetic_has_no_common_type() {
1414        // The caller is the one holding the span, so this says no rather than guessing.
1415        let mut types = Types::new();
1416        let linux = linux();
1417        let int = types.int(IntKind::Int);
1418        let pointer = types.pointer(int);
1419        assert_eq!(usual_arithmetic(&mut types, pointer, int, &linux), None);
1420        assert_eq!(usual_arithmetic(&mut types, pointer, pointer, &linux), None);
1421        let void = types.void();
1422        assert_eq!(usual_arithmetic(&mut types, void, int, &linux), None);
1423        // And a type that is not arithmetic is still its own promotion, so a caller may promote
1424        // first and ask questions afterwards.
1425        assert_eq!(promote(&mut types, pointer, &linux), pointer);
1426    }
1427
1428    #[test]
1429    fn the_conversions_read_through_sugar() {
1430        let mut interner = Interner::new();
1431        let mut types = Types::new();
1432        let linux = linux();
1433        let char_ = types.int(IntKind::Char);
1434        let name = types.typedef(interner.intern("byte"), char_);
1435        let int = types.int(IntKind::Int);
1436        assert_eq!(promote(&mut types, name, &linux), int);
1437    }
1438
1439    /// A prototype returning `void`.
1440    fn prototype(types: &mut Types, params: Vec<TypeId>, variadic: bool) -> TypeId {
1441        let ret = types.void();
1442        types.function(FunctionType { ret, params, variadic, prototyped: true })
1443    }
1444
1445    /// `void f()` as it means before C23: a declaration that says nothing about the parameters.
1446    fn old_style(types: &mut Types) -> TypeId {
1447        let ret = types.void();
1448        types.function(FunctionType { ret, params: Vec::new(), variadic: false, prototyped: false })
1449    }
1450
1451    /// A complete record with the given tag and members.
1452    fn tagged(types: &mut Types, tag: Symbol, fields: &[FieldDecl]) -> RecordId {
1453        let id = types.declare_record(RecordKind::Struct, Some(tag));
1454        let laid_out = lay_out(types, RecordKind::Struct, fields);
1455        types.complete_record(id, laid_out);
1456        id
1457    }
1458
1459    #[test]
1460    fn a_type_is_compatible_with_itself_however_it_was_written() {
1461        let mut interner = Interner::new();
1462        let mut types = Types::new();
1463        let int = types.int(IntKind::Int);
1464        let name = types.typedef(interner.intern("int32_t"), int);
1465        assert!(compatible(&types, name, int), "the sugar is the same type underneath");
1466        assert_eq!(composite(&mut types, name, int), Some(name), "and it keeps its name");
1467
1468        // The qualifiers have to match exactly, which is what keeps `const int *` and `int *`
1469        // apart as parameter types.
1470        let konst = types.qualified(int, Qualifiers::CONST);
1471        assert!(!compatible(&types, konst, int));
1472        let konst_pointer = types.pointer(konst);
1473        let pointer = types.pointer(int);
1474        assert!(!compatible(&types, konst_pointer, pointer));
1475        assert_eq!(composite(&mut types, konst_pointer, pointer), None);
1476
1477        // And a different type is a different type. `char` is not `signed char` even on a target
1478        // where the two have the same range, which is why they are separate kinds here.
1479        let char_ = types.int(IntKind::Char);
1480        let schar = types.int(IntKind::SChar);
1481        assert!(!compatible(&types, char_, schar));
1482        // `_Atomic int` is not `int` either, since it is a type and not a qualifier.
1483        let atomic = types.atomic(int);
1484        assert!(!compatible(&types, atomic, int));
1485    }
1486
1487    #[test]
1488    fn an_enumeration_is_compatible_with_the_type_it_is_represented_in() {
1489        // gcc 13.3 and clang 18 both represent `enum E { A, B }` in `unsigned int`, and both
1490        // accept a redeclaration that writes the representation instead of the tag.
1491        let mut types = Types::new();
1492        let uint = types.int(IntKind::UInt);
1493        let int = types.int(IntKind::Int);
1494        let id = types.declare_enum(None);
1495        types.complete_enum(id, uint, false);
1496        let e = types.enumeration(id);
1497        assert!(compatible(&types, e, uint));
1498        assert!(compatible(&types, uint, e), "and the relation is symmetric");
1499        assert!(!compatible(&types, e, int));
1500
1501        // Two enumeration declarations are two types. Each is compatible with what it is
1502        // represented in, and that does not make them compatible with each other.
1503        let other = types.declare_enum(None);
1504        types.complete_enum(other, uint, false);
1505        let other = types.enumeration(other);
1506        assert!(!compatible(&types, e, other));
1507
1508        // One nobody has decided on yet is compatible with nothing but itself, because the
1509        // answer is not known rather than no.
1510        let undecided = types.declare_enum(None);
1511        let undecided = types.enumeration(undecided);
1512        assert!(!compatible(&types, undecided, uint));
1513        assert!(compatible(&types, undecided, undecided));
1514    }
1515
1516    #[test]
1517    fn an_array_without_a_size_is_compatible_with_one_that_has_it() {
1518        // `extern int a[]; int a[4];` is a complete array of four afterwards, which gcc reports
1519        // as a `sizeof` of sixteen. A compiler that keeps the first type has lost the size.
1520        let mut types = Types::new();
1521        let int = types.int(IntKind::Int);
1522        let unknown = types.array(int, ArrayLen::Unknown);
1523        let four = types.array(int, ArrayLen::Fixed(4));
1524        let five = types.array(int, ArrayLen::Fixed(5));
1525        assert!(compatible(&types, unknown, four));
1526        assert!(!compatible(&types, four, five));
1527        assert_eq!(composite(&mut types, unknown, four), Some(four));
1528        assert_eq!(composite(&mut types, four, unknown), Some(four), "either way round");
1529        assert_eq!(composite(&mut types, four, five), None);
1530
1531        // A variable length array is compatible with both, because its size is not something a
1532        // declaration can be checked against.
1533        let vla = types.array(int, ArrayLen::Variable(VlaId(0)));
1534        assert!(compatible(&types, vla, four));
1535        assert_eq!(composite(&mut types, vla, four), Some(four));
1536
1537        // The element types have to be compatible too, and the composite reaches into them.
1538        let long = types.int(IntKind::Long);
1539        let longs = types.array(long, ArrayLen::Fixed(4));
1540        assert!(!compatible(&types, four, longs));
1541    }
1542
1543    #[test]
1544    fn a_parameter_declared_as_an_array_is_a_pointer() {
1545        // `int fn(int p[3])` and `int fn(int *p)` are one declaration and one definition, which
1546        // both compilers accept. The adjustment is part of forming the parameter type, so two
1547        // functions written either way are not merely compatible but identical.
1548        let mut types = Types::new();
1549        let int = types.int(IntKind::Int);
1550        let three = types.array(int, ArrayLen::Fixed(3));
1551        let pointer = types.pointer(int);
1552        assert_eq!(adjust_parameter(&mut types, three), pointer);
1553
1554        // A function parameter becomes a pointer to the function the same way.
1555        let function = prototype(&mut types, vec![int], false);
1556        let function_pointer = types.pointer(function);
1557        assert_eq!(adjust_parameter(&mut types, function), function_pointer);
1558
1559        // And the qualifiers on the outermost node go, so `void f(const int)` and `void f(int)`
1560        // declare the same function. The pointee of a `const int *` keeps its own.
1561        let konst = types.qualified(int, Qualifiers::CONST);
1562        assert_eq!(adjust_parameter(&mut types, konst), int);
1563        let to_konst = types.pointer(konst);
1564        assert_eq!(adjust_parameter(&mut types, to_konst), to_konst);
1565    }
1566
1567    #[test]
1568    fn an_old_style_declaration_is_compatible_with_the_prototypes_a_call_could_not_tell_from_it() {
1569        // Measured with gcc 13.3 in C17 mode, which is the compiler that still has the old
1570        // meaning of `()`. It names the rule in its own diagnostic: an argument type that has a
1571        // default promotion cannot match an empty parameter name list declaration.
1572        let mut types = Types::new();
1573        let old = old_style(&mut types);
1574        let int = types.int(IntKind::Int);
1575        let long = types.int(IntKind::Long);
1576        let char_ = types.int(IntKind::Char);
1577        let float = types.float(FloatKind::Float);
1578        let double = types.float(FloatKind::Double);
1579
1580        let takes_int = prototype(&mut types, vec![int], false);
1581        assert!(compatible(&types, old, takes_int));
1582        assert!(compatible(&types, takes_int, old), "and the relation is symmetric");
1583        // The composite is the prototype, so the calls written before it can still be checked.
1584        assert_eq!(composite(&mut types, old, takes_int), Some(takes_int));
1585
1586        let pointer = types.pointer(int);
1587        for params in [vec![long], vec![double], vec![pointer], vec![int, long]] {
1588            let ty = prototype(&mut types, params, false);
1589            assert!(compatible(&types, old, ty), "nothing here is touched by a promotion");
1590        }
1591
1592        // A `char` promotes to `int` and a `float` to `double`, so a call through the old style
1593        // declaration would have passed something else and the two conflict.
1594        for params in [vec![char_], vec![float], vec![int, char_]] {
1595            let ty = prototype(&mut types, params, false);
1596            assert!(!compatible(&types, old, ty));
1597            assert_eq!(composite(&mut types, old, ty), None);
1598        }
1599
1600        // An ellipsis conflicts too, which gcc also says in as many words.
1601        let variadic = prototype(&mut types, vec![int], true);
1602        assert!(!compatible(&types, old, variadic));
1603
1604        // An enumeration parameter comes through when what it is represented in does.
1605        let uint = types.int(IntKind::UInt);
1606        let id = types.declare_enum(None);
1607        types.complete_enum(id, uint, false);
1608        let e = types.enumeration(id);
1609        let takes_enum = prototype(&mut types, vec![e], false);
1610        assert!(compatible(&types, old, takes_enum));
1611
1612        // Two old style declarations agree about nothing and so cannot disagree.
1613        assert!(compatible(&types, old, old));
1614
1615        // The return type still has to match, which is the one part `()` does say.
1616        let returns_int = types.function(FunctionType {
1617            ret: int,
1618            params: Vec::new(),
1619            variadic: false,
1620            prototyped: false,
1621        });
1622        assert!(!compatible(&types, returns_int, takes_int));
1623    }
1624
1625    #[test]
1626    fn from_c23_an_empty_parameter_list_is_a_prototype_and_conflicts_where_it_used_to_merge() {
1627        // The dialect decides what `()` means and the parser records the decision, so the same
1628        // pair of declarations is a redeclaration in C17 and a conflict in C23. Both compilers
1629        // report exactly that.
1630        let mut types = Types::new();
1631        let int = types.int(IntKind::Int);
1632        let takes_int = prototype(&mut types, vec![int], false);
1633        let takes_nothing = prototype(&mut types, Vec::new(), false);
1634        let old = old_style(&mut types);
1635        assert!(!compatible(&types, takes_nothing, takes_int));
1636        assert!(compatible(&types, old, takes_int), "the C17 reading of the same source");
1637    }
1638
1639    #[test]
1640    fn two_prototypes_have_to_agree_about_everything() {
1641        let mut types = Types::new();
1642        let int = types.int(IntKind::Int);
1643        let long = types.int(IntKind::Long);
1644        let base = prototype(&mut types, vec![int, int], false);
1645        for other in [vec![int], vec![int, long], vec![int, int, int], Vec::new()] {
1646            let other = prototype(&mut types, other, false);
1647            assert!(!compatible(&types, base, other));
1648        }
1649        let variadic = prototype(&mut types, vec![int, int], true);
1650        assert!(!compatible(&types, base, variadic), "`...` is part of the type");
1651
1652        // The parameters are compared with the same rules as anything else, so an array size
1653        // inside a parameter's type is compared and an unknown one is not.
1654        let four = types.array(int, ArrayLen::Fixed(4));
1655        let unknown = types.array(int, ArrayLen::Unknown);
1656        let to_four = types.pointer(four);
1657        let to_unknown = types.pointer(unknown);
1658        let a = prototype(&mut types, vec![to_four], false);
1659        let b = prototype(&mut types, vec![to_unknown], false);
1660        assert!(compatible(&types, a, b));
1661        // And the composite takes the size, which is the whole reason it exists.
1662        assert_eq!(composite(&mut types, a, b), Some(a));
1663    }
1664
1665    #[test]
1666    fn a_pointer_composite_reaches_through_to_what_is_pointed_at() {
1667        let mut types = Types::new();
1668        let int = types.int(IntKind::Int);
1669        let four = types.array(int, ArrayLen::Fixed(4));
1670        let unknown = types.array(int, ArrayLen::Unknown);
1671        let to_four = types.pointer(four);
1672        let to_unknown = types.pointer(unknown);
1673        assert_eq!(composite(&mut types, to_unknown, to_four), Some(to_four));
1674
1675        // The pointer's own qualifiers survive, since a compatible pair has the same ones.
1676        let konst_to_unknown = types.qualified(to_unknown, Qualifiers::CONST);
1677        let konst_to_four = types.qualified(to_four, Qualifiers::CONST);
1678        assert_eq!(composite(&mut types, konst_to_unknown, konst_to_four), Some(konst_to_four));
1679    }
1680
1681    #[test]
1682    fn two_record_declarations_with_the_same_tag_and_the_same_members_are_compatible() {
1683        // C23 6.2.7p1, which is what lets one header be included twice. clang 18 implements it
1684        // and gcc 13.3 still rejects the redefinition, so this is a divergence rather than a
1685        // reading; in the older dialects the redefinition never gets as far as being compared.
1686        let mut interner = Interner::new();
1687        let mut types = Types::new();
1688        let tag = interner.intern("point");
1689        let x = interner.intern("x");
1690        let y = interner.intern("y");
1691        let int = types.int(IntKind::Int);
1692        let members = [FieldDecl::new(Some(x), int), FieldDecl::new(Some(y), int)];
1693
1694        let first = tagged(&mut types, tag, &members);
1695        let second = tagged(&mut types, tag, &members);
1696        let first = types.record(first);
1697        let second = types.record(second);
1698        assert_ne!(first, second, "still two declarations and two types");
1699        assert!(compatible(&types, first, second));
1700
1701        // A different member name, a different member type, a different count, a different tag
1702        // and a different keyword are each enough to make them different types.
1703        let z = interner.intern("z");
1704        let long = types.int(IntKind::Long);
1705        let renamed = [FieldDecl::new(Some(x), int), FieldDecl::new(Some(z), int)];
1706        let retyped = [FieldDecl::new(Some(x), int), FieldDecl::new(Some(y), long)];
1707        for other in [&renamed[..], &retyped[..], &members[..1]] {
1708            let other = tagged(&mut types, tag, other);
1709            let other = types.record(other);
1710            assert!(!compatible(&types, first, other));
1711        }
1712        let elsewhere = tagged(&mut types, interner.intern("pair"), &members);
1713        let elsewhere = types.record(elsewhere);
1714        assert!(!compatible(&types, first, elsewhere));
1715
1716        // An anonymous record is compatible with nothing but itself: there is no name by which
1717        // a second declaration could be claiming to be the same type.
1718        let anonymous = record(&mut types, RecordKind::Struct, &members);
1719        let also_anonymous = record(&mut types, RecordKind::Struct, &members);
1720        assert!(!compatible(&types, anonymous, also_anonymous));
1721
1722        // Nor is an incomplete declaration, which has no members to compare.
1723        let incomplete = types.declare_record(RecordKind::Struct, Some(tag));
1724        let incomplete = types.record(incomplete);
1725        assert!(!compatible(&types, first, incomplete));
1726        assert!(compatible(&types, incomplete, incomplete));
1727    }
1728
1729    #[test]
1730    fn a_self_referential_record_is_compared_without_going_round_forever() {
1731        // `struct node { int value; struct node *next; }` declared twice. Comparing the two
1732        // reaches the same pair again through the pointer, and the second time it is an
1733        // assumption rather than a question.
1734        let mut interner = Interner::new();
1735        let mut types = Types::new();
1736        let tag = interner.intern("node");
1737        let value = interner.intern("value");
1738        let next = interner.intern("next");
1739        let int = types.int(IntKind::Int);
1740
1741        let node = |types: &mut Types| {
1742            let id = types.declare_record(RecordKind::Struct, Some(tag));
1743            let ty = types.record(id);
1744            let pointer = types.pointer(ty);
1745            let members = [FieldDecl::new(Some(value), int), FieldDecl::new(Some(next), pointer)];
1746            let laid_out = lay_out(types, RecordKind::Struct, &members);
1747            types.complete_record(id, laid_out);
1748            ty
1749        };
1750        let first = node(&mut types);
1751        let second = node(&mut types);
1752        assert_ne!(first, second);
1753        assert!(compatible(&types, first, second));
1754
1755        // The guard is an assumption and not an answer, so a difference below the cycle is still
1756        // found: the same structure with the two members the other way round is a different one.
1757        let id = types.declare_record(RecordKind::Struct, Some(tag));
1758        let ty = types.record(id);
1759        let pointer = types.pointer(ty);
1760        let members = [FieldDecl::new(Some(next), pointer), FieldDecl::new(Some(value), int)];
1761        let laid_out = lay_out(&types, RecordKind::Struct, &members);
1762        types.complete_record(id, laid_out);
1763        assert!(!compatible(&types, first, ty));
1764    }
1765
1766    #[test]
1767    fn layout_reads_through_sugar() {
1768        let mut interner = Interner::new();
1769        let mut types = Types::new();
1770        let long = types.int(IntKind::Long);
1771        let name = types.typedef(interner.intern("word"), long);
1772        let array = types.array(name, ArrayLen::Fixed(4));
1773        assert_eq!(layout(&types, array, &linux()).unwrap(), Layout::new(32, 8));
1774    }
1775}