rucc_types/compat.rs
1//! Type compatibility and the composite type.
2//!
3//! Design: `spec/07-types-and-semantics.md` section 7.2.
4//!
5//! Compatibility, 6.2.7, is the looser relation that identity is not. Two types are the same
6//! when they are the same id, which is what the interner is for; two types are compatible when
7//! C says a declaration of one may follow a declaration of the other. `int f(int a[3])` and
8//! `int f(int *a)` declare the same function, an `enum` is compatible with whatever it is
9//! represented in, and an array with a size is compatible with one without.
10//!
11//! The composite type, 6.2.7p3, is what a redeclaration leaves behind: the type that takes the
12//! array size from whichever declaration had one and the parameter list from whichever
13//! declaration was a prototype. `extern int a[]; int a[4];` has to end up with an array of
14//! four, and a compiler that keeps the first type instead has lost the size for good.
15//!
16//! The rules here were checked by writing each pair of declarations and seeing which ones gcc
17//! 13.3 and clang 18 refuse. They agree everywhere except one place, recorded on
18//! [`records`]: clang implements the C23 rule that an identical structure redefinition in one
19//! translation unit is the same type, and gcc 13.3 still rejects it.
20//!
21//! Nothing in here needs the target. Everything target dependent about a type has already been
22//! decided by the time it is in the table: an enumeration knows what it is represented in and
23//! an array knows how many elements it has.
24
25use crate::kind::{ArrayLen, FloatKind, FunctionType, IntKind, RecordId, TypeKind};
26use crate::types::{TypeId, Types};
27
28/// Whether a declaration of `left` and a declaration of `right` declare the same thing, 6.2.7.
29///
30/// Identity implies compatibility and is one integer comparison, so this only does any work
31/// when the two ids differ.
32#[must_use]
33pub fn compatible(types: &Types, left: TypeId, right: TypeId) -> bool {
34 let mut assumed = Vec::new();
35 same(types, left, right, &mut assumed)
36}
37
38/// The composite type of two compatible types, 6.2.7p3, and [`None`] when they are not
39/// compatible.
40///
41/// It takes whatever each side knows: the size from the declaration that had one, the parameter
42/// list from the declaration that was a prototype. This is what a caller merging two
43/// declarations of one name should store, rather than either type it was given.
44pub fn composite(types: &mut Types, left: TypeId, right: TypeId) -> Option<TypeId> {
45 if !compatible(types, left, right) {
46 return None;
47 }
48 Some(build(types, left, right))
49}
50
51/// The type a parameter declared as `id` really has, 6.7.6.3p7 and p8.
52///
53/// An array parameter is a pointer to its element and a function parameter is a pointer to the
54/// function, which is why `int f(int a[3])` and `int f(int *a)` declare the same function. The
55/// qualifiers on the outermost node go too, so `void f(const int)` and `void f(int)` do as
56/// well: a `const` there is a promise the function makes to itself and not part of its type.
57///
58/// [`FunctionType::params`] is defined to hold types this has already been applied to, so this
59/// belongs to whoever builds the type out of a declarator rather than to the comparison below.
60pub fn adjust_parameter(types: &mut Types, id: TypeId) -> TypeId {
61 let canonical = types.canonical(id);
62 match types.kind(canonical) {
63 // The element keeps its own qualifiers. The ones C99 allows inside the brackets belong
64 // to the pointer that replaces the array, and the parser is what puts them there.
65 TypeKind::Array { elem, .. } => types.pointer(elem),
66 TypeKind::Function(_) => types.pointer(canonical),
67 _ => types.unqualified(id),
68 }
69}
70
71/// Compatibility, with a stack of record pairs already assumed compatible.
72///
73/// The stack is what makes a self referential structure terminate. `struct node { struct node
74/// *next; }` compared against another declaration of itself comes back to the same pair through
75/// the pointer, and the second time it is an assumption rather than a question.
76fn same(
77 types: &Types,
78 left: TypeId,
79 right: TypeId,
80 assumed: &mut Vec<(RecordId, RecordId)>,
81) -> bool {
82 let left = types.canonical(left);
83 let right = types.canonical(right);
84 if left == right {
85 return true;
86 }
87 if types.quals(left) != types.quals(right) {
88 // The qualifiers have to match exactly, which is what keeps `const int *` and `int *`
89 // apart as parameter types.
90 return false;
91 }
92 match (types.kind(left), types.kind(right)) {
93 // Two different enumeration declarations are two different types. Each is compatible
94 // with what it is represented in, and whether a redefinition of one tag makes the same
95 // type again is a question about enumerator values, which live with the declaration
96 // rather than in this table.
97 (TypeKind::Enum(_), TypeKind::Enum(_)) => false,
98 // An enumeration is compatible with the type it is represented in. Both compilers agree,
99 // and it is visible in that a `_Generic` cannot list `enum E` and `unsigned int` both.
100 (TypeKind::Enum(id), _) => match types.enum_info(id).underlying {
101 Some(underlying) => same(types, underlying, right, assumed),
102 None => false,
103 },
104 (_, TypeKind::Enum(id)) => match types.enum_info(id).underlying {
105 Some(underlying) => same(types, left, underlying, assumed),
106 None => false,
107 },
108 (TypeKind::Pointer(a), TypeKind::Pointer(b))
109 | (TypeKind::Atomic(a), TypeKind::Atomic(b)) => same(types, a, b, assumed),
110 (TypeKind::Array { elem: a, len: x }, TypeKind::Array { elem: b, len: y }) => {
111 lengths_agree(x, y) && same(types, a, b, assumed)
112 }
113 (TypeKind::Vector { elem: a, len: x }, TypeKind::Vector { elem: b, len: y }) => {
114 x == y && same(types, a, b, assumed)
115 }
116 (TypeKind::Function(a), TypeKind::Function(b)) => {
117 functions(types, types.signature(a), types.signature(b), assumed)
118 }
119 (TypeKind::Record(a), TypeKind::Record(b)) => records(types, a, b, assumed),
120 _ => false,
121 }
122}
123
124/// Whether two array lengths are compatible.
125///
126/// Only two constant sizes can disagree. An array whose size nobody wrote is compatible with
127/// any of them, and so is a variable length one, whose size is not known until it runs.
128fn lengths_agree(left: ArrayLen, right: ArrayLen) -> bool {
129 match (left, right) {
130 (ArrayLen::Fixed(a), ArrayLen::Fixed(b)) => a == b,
131 _ => true,
132 }
133}
134
135/// Whether two function types are compatible, 6.7.6.3p15.
136fn functions(
137 types: &Types,
138 left: &FunctionType,
139 right: &FunctionType,
140 assumed: &mut Vec<(RecordId, RecordId)>,
141) -> bool {
142 if !same(types, left.ret, right.ret, assumed) {
143 return false;
144 }
145 match (left.prototyped, right.prototyped) {
146 (true, true) => {
147 left.variadic == right.variadic
148 && left.params.len() == right.params.len()
149 && left.params.iter().zip(&right.params).all(|(&a, &b)| same(types, a, b, assumed))
150 }
151 // An old style declaration says nothing about the parameters, so it is compatible with a
152 // prototype only when the call would have gone the same way regardless: no `...`, and no
153 // parameter the default argument promotions would have changed on the way in.
154 (true, false) => stands_for(types, left),
155 (false, true) => stands_for(types, right),
156 (false, false) => true,
157 }
158}
159
160/// Whether an old style declaration of a function could stand for this prototype.
161fn stands_for(types: &Types, signature: &FunctionType) -> bool {
162 !signature.variadic && signature.params.iter().all(|¶m| survives_promotion(types, param))
163}
164
165/// Whether a parameter type is one the default argument promotions leave alone.
166///
167/// The `float` case is the one that matters: an old style call passes a `double`, so a prototype
168/// taking a `float` is a different function from the same name declared without one, and both
169/// compilers refuse the pair.
170fn survives_promotion(types: &Types, id: TypeId) -> bool {
171 match types.kind(types.canonical(id)) {
172 TypeKind::Bool => false,
173 TypeKind::Int(kind) => kind.rank() >= IntKind::Int.rank(),
174 TypeKind::Float(FloatKind::Float) => false,
175 // An enumeration is compatible with what it is represented in, so it comes through
176 // whenever that type does.
177 TypeKind::Enum(id) => match types.enum_info(id).underlying {
178 Some(underlying) => survives_promotion(types, underlying),
179 None => false,
180 },
181 // Everything else, `_BitInt` included, is its own promotion.
182 _ => true,
183 }
184}
185
186/// Whether two record declarations are the same type.
187///
188/// The same declaration always is. Two different ones are in C23 when they have the same tag and
189/// the same members, which is the rule that lets a header be included twice without a guard.
190/// clang 18 implements it and gcc 13.3 still rejects the redefinition outright. In the older
191/// dialects the question does not arise, because a second definition of a tag in one scope is
192/// refused before anything asks whether the two types match.
193fn records(
194 types: &Types,
195 left: RecordId,
196 right: RecordId,
197 assumed: &mut Vec<(RecordId, RecordId)>,
198) -> bool {
199 if left == right || assumed.contains(&(left, right)) {
200 return true;
201 }
202 let a = types.record_info(left);
203 let b = types.record_info(right);
204 if a.kind != b.kind || a.tag.is_none() || a.tag != b.tag {
205 // An anonymous record is compatible with nothing but itself. There is no name by which a
206 // second declaration could be claiming to be the same type.
207 return false;
208 }
209 if a.layout.is_none() || b.layout.is_none() || a.fields.len() != b.fields.len() {
210 // An incomplete declaration has no members to compare. Two mentions of one tag in one
211 // scope are one declaration and one id, so they never reach here.
212 return false;
213 }
214 assumed.push((left, right));
215 let answer = a
216 .fields
217 .iter()
218 .zip(&b.fields)
219 .all(|(x, y)| x.name == y.name && x.bits == y.bits && same(types, x.ty, y.ty, assumed));
220 assumed.pop();
221 answer
222}
223
224/// The composite of two types already known to be compatible.
225fn build(types: &mut Types, left: TypeId, right: TypeId) -> TypeId {
226 if left == right {
227 return left;
228 }
229 let canonical = types.canonical(left);
230 match (types.kind(canonical), types.kind(types.canonical(right))) {
231 (TypeKind::Array { elem: a, len: x }, TypeKind::Array { elem: b, len: y }) => {
232 let elem = build(types, a, b);
233 // The declaration that knew the size is the one to take it from, whichever side it
234 // was. An array type carries no qualifiers of its own, they are on the element.
235 let len = if matches!(x, ArrayLen::Fixed(_)) { x } else { y };
236 types.array(elem, len)
237 }
238 (TypeKind::Pointer(a), TypeKind::Pointer(b)) => {
239 let inner = build(types, a, b);
240 let quals = types.quals(canonical);
241 let pointer = types.pointer(inner);
242 types.qualified(pointer, quals)
243 }
244 (TypeKind::Function(a), TypeKind::Function(b)) => {
245 let a = types.signature(a).clone();
246 let b = types.signature(b).clone();
247 composite_function(types, &a, &b)
248 }
249 // Everything else has nothing to combine, and the type as it was written is the better
250 // of the two answers because a diagnostic can print the name the program used.
251 _ => left,
252 }
253}
254
255/// The composite of two compatible function types.
256fn composite_function(types: &mut Types, left: &FunctionType, right: &FunctionType) -> TypeId {
257 let ret = build(types, left.ret, right.ret);
258 // The prototype wins, because it is the declaration that knows something. This is what makes
259 // `void f(); void f(int);` a function of one `int` afterwards, so that the calls written
260 // between the two declarations can still be checked against something.
261 let (params, variadic, prototyped) = match (left.prototyped, right.prototyped) {
262 (true, true) => {
263 let params =
264 left.params.iter().zip(&right.params).map(|(&a, &b)| build(types, a, b)).collect();
265 (params, left.variadic, true)
266 }
267 (true, false) => (left.params.clone(), left.variadic, true),
268 (false, true) => (right.params.clone(), right.variadic, true),
269 (false, false) => (Vec::new(), false, false),
270 };
271 types.function(FunctionType { ret, params, variadic, prototyped })
272}