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