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 shapes(types, left, right, assumed)
93}
94
95/// The same question with the outermost qualifiers already agreed about, on two canonical ids.
96///
97/// Split out of [`same`] for the one caller that has to ask it with the qualifiers set aside,
98/// which is [`through_transparent`]: a member of glibc's socket union is a `struct sockaddr
99/// *__restrict` and the parameter it faces is a `struct sockaddr *`, and a `restrict` there is a
100/// promise the function makes to itself rather than part of the type it takes. Stripping the
101/// qualifier instead would mean interning a type, which this module has no mutable table for.
102fn shapes(
103 types: &Types,
104 left: TypeId,
105 right: TypeId,
106 assumed: &mut Vec<(RecordId, RecordId)>,
107) -> bool {
108 if left == right {
109 return true;
110 }
111 match (types.kind(left), types.kind(right)) {
112 // Two different enumeration declarations are two different types. Each is compatible
113 // with what it is represented in, and whether a redefinition of one tag makes the same
114 // type again is a question about enumerator values, which live with the declaration
115 // rather than in this table.
116 (TypeKind::Enum(_), TypeKind::Enum(_)) => false,
117 // An enumeration is compatible with the type it is represented in. Both compilers agree,
118 // and it is visible in that a `_Generic` cannot list `enum E` and `unsigned int` both.
119 (TypeKind::Enum(id), _) => match types.enum_info(id).underlying {
120 Some(underlying) => same(types, underlying, right, assumed),
121 None => false,
122 },
123 (_, TypeKind::Enum(id)) => match types.enum_info(id).underlying {
124 Some(underlying) => same(types, left, underlying, assumed),
125 None => false,
126 },
127 (TypeKind::Pointer(a), TypeKind::Pointer(b))
128 | (TypeKind::Atomic(a), TypeKind::Atomic(b)) => same(types, a, b, assumed),
129 (TypeKind::Array { elem: a, len: x }, TypeKind::Array { elem: b, len: y }) => {
130 lengths_agree(x, y) && same(types, a, b, assumed)
131 }
132 (TypeKind::Vector { elem: a, len: x }, TypeKind::Vector { elem: b, len: y }) => {
133 x == y && same(types, a, b, assumed)
134 }
135 (TypeKind::Function(a), TypeKind::Function(b)) => {
136 functions(types, types.signature(a), types.signature(b), assumed)
137 }
138 (TypeKind::Record(a), TypeKind::Record(b)) => records(types, a, b, assumed),
139 _ => false,
140 }
141}
142
143/// Whether two array lengths are compatible.
144///
145/// Only two constant sizes can disagree. An array whose size nobody wrote is compatible with
146/// any of them, and so is a variable length one, whose size is not known until it runs.
147fn lengths_agree(left: ArrayLen, right: ArrayLen) -> bool {
148 match (left, right) {
149 (ArrayLen::Fixed(a), ArrayLen::Fixed(b)) => a == b,
150 _ => true,
151 }
152}
153
154/// Whether two function types are compatible, 6.7.6.3p15.
155fn functions(
156 types: &Types,
157 left: &FunctionType,
158 right: &FunctionType,
159 assumed: &mut Vec<(RecordId, RecordId)>,
160) -> bool {
161 if !same(types, left.ret, right.ret, assumed) {
162 return false;
163 }
164 match (left.prototyped, right.prototyped) {
165 (true, true) => {
166 left.variadic == right.variadic
167 && left.params.len() == right.params.len()
168 && left.params.iter().zip(&right.params).all(|(&a, &b)| {
169 same(types, a, b, assumed) || through_transparent(types, a, b, assumed)
170 })
171 }
172 // An old style definition is the one unprototyped type that knows what its parameters
173 // are, and 6.7.6.3p15 holds it to a stricter rule than a declaration that knows nothing:
174 // the counts have to agree and each prototype parameter has to be compatible with the
175 // promoted type of the identifier facing it, which is what the list holds.
176 (true, false) if !right.params.is_empty() => defines(types, left, right, assumed),
177 (false, true) if !left.params.is_empty() => defines(types, right, left, assumed),
178 // An old style declaration says nothing about the parameters, so it is compatible with a
179 // prototype only when the call would have gone the same way regardless: no `...`, and no
180 // parameter the default argument promotions would have changed on the way in.
181 (true, false) => stands_for(types, left),
182 (false, true) => stands_for(types, right),
183 (false, false) => true,
184 }
185}
186
187/// Whether one of two parameter types is a transparent union the other is a member of.
188///
189/// This is the half of `transparent_union` that is about declarations rather than about values.
190/// `accept` takes a union of eleven socket address pointers, and a program that declares it as
191/// taking a `struct sockaddr *` has declared the same function, which is what lets gnulib assign
192/// the one to a pointer to the other and what the attribute is for. Either side may be the union,
193/// since a program may declare the function either way round and the pair has to be compatible
194/// both ways for a redeclaration to be accepted.
195///
196/// Any member counts and not only the first. The first member is what decides how the union is
197/// passed, so it is the one the attribute needs to be well defined, but every member is a type the
198/// union takes a value of and gcc accepts a declaration written with any of them.
199///
200/// A bit-field member is not one of them, since there is no value of a bit-field's type to pass
201/// and nothing could be assigned into it whole.
202fn through_transparent(
203 types: &Types,
204 left: TypeId,
205 right: TypeId,
206 assumed: &mut Vec<(RecordId, RecordId)>,
207) -> bool {
208 member_of(types, left, right, assumed) || member_of(types, right, left, assumed)
209}
210
211/// Whether the first type is a transparent union and the second is one of its members.
212fn member_of(
213 types: &Types,
214 union: TypeId,
215 other: TypeId,
216 assumed: &mut Vec<(RecordId, RecordId)>,
217) -> bool {
218 let TypeKind::Record(id) = types.kind(types.canonical(union)) else { return false };
219 let info = types.record_info(id);
220 if !info.transparent {
221 return false;
222 }
223 let other = types.canonical(other);
224 info.fields.iter().any(|field| {
225 field.bits.is_none() && shapes(types, types.canonical(field.ty), other, assumed)
226 })
227}
228
229/// Whether a prototype and an old style definition describe the same function, 6.7.6.3p15.
230///
231/// The rule as written is that the counts agree and each prototype parameter is compatible with
232/// the promoted type of the identifier facing it. Taken literally that makes `int f(char);` and a
233/// definition of `f` with a `char` identifier two different functions, since `char` promotes to
234/// `int`, and every compiler takes that pair because all the code written this way is written
235/// against a header. So a prototype parameter the promotions would have changed is allowed to
236/// face what it changes into, which is the one relaxation and is what makes the pair work.
237fn defines(
238 types: &Types,
239 proto: &FunctionType,
240 def: &FunctionType,
241 assumed: &mut Vec<(RecordId, RecordId)>,
242) -> bool {
243 !proto.variadic
244 && proto.params.len() == def.params.len()
245 && proto
246 .params
247 .iter()
248 .zip(&def.params)
249 .all(|(&a, &b)| same(types, a, b, assumed) || promotes_to(types, a, b))
250}
251
252/// Whether the default argument promotions turn the first type into the second.
253fn promotes_to(types: &Types, from: TypeId, to: TypeId) -> bool {
254 if survives_promotion(types, from) {
255 return false;
256 }
257 let to = types.kind(types.canonical(to));
258 match types.kind(types.canonical(from)) {
259 TypeKind::Float(FloatKind::Float) => to == TypeKind::Float(FloatKind::Double),
260 // Everything else the promotions touch is narrower than an `int` and becomes one. The
261 // target where that is not so is one where `int` is no wider than a `short`, which none
262 // of the targets here is.
263 _ => to == TypeKind::Int(IntKind::Int),
264 }
265}
266
267/// Whether an old style declaration of a function could stand for this prototype.
268fn stands_for(types: &Types, signature: &FunctionType) -> bool {
269 !signature.variadic && signature.params.iter().all(|¶m| survives_promotion(types, param))
270}
271
272/// Whether a parameter type is one the default argument promotions leave alone.
273///
274/// The `float` case is the one that matters: an old style call passes a `double`, so a prototype
275/// taking a `float` is a different function from the same name declared without one, and both
276/// compilers refuse the pair.
277fn survives_promotion(types: &Types, id: TypeId) -> bool {
278 match types.kind(types.canonical(id)) {
279 TypeKind::Bool => false,
280 TypeKind::Int(kind) => kind.rank() >= IntKind::Int.rank(),
281 TypeKind::Float(FloatKind::Float) => false,
282 // An enumeration is compatible with what it is represented in, so it comes through
283 // whenever that type does.
284 TypeKind::Enum(id) => match types.enum_info(id).underlying {
285 Some(underlying) => survives_promotion(types, underlying),
286 None => false,
287 },
288 // Everything else, `_BitInt` included, is its own promotion.
289 _ => true,
290 }
291}
292
293/// Whether two record declarations are the same type.
294///
295/// The same declaration always is. Two different ones are in C23 when they have the same tag and
296/// the same members, which is the rule that lets a header be included twice without a guard.
297/// clang 18 implements it and gcc 13.3 still rejects the redefinition outright. In the older
298/// dialects the question does not arise, because a second definition of a tag in one scope is
299/// refused before anything asks whether the two types match.
300fn records(
301 types: &Types,
302 left: RecordId,
303 right: RecordId,
304 assumed: &mut Vec<(RecordId, RecordId)>,
305) -> bool {
306 if left == right || assumed.contains(&(left, right)) {
307 return true;
308 }
309 let a = types.record_info(left);
310 let b = types.record_info(right);
311 if a.kind != b.kind || a.tag.is_none() || a.tag != b.tag {
312 // An anonymous record is compatible with nothing but itself. There is no name by which a
313 // second declaration could be claiming to be the same type.
314 return false;
315 }
316 if a.layout.is_none() || b.layout.is_none() || a.fields.len() != b.fields.len() {
317 // An incomplete declaration has no members to compare. Two mentions of one tag in one
318 // scope are one declaration and one id, so they never reach here.
319 return false;
320 }
321 assumed.push((left, right));
322 let answer = a
323 .fields
324 .iter()
325 .zip(&b.fields)
326 .all(|(x, y)| x.name == y.name && x.bits == y.bits && same(types, x.ty, y.ty, assumed));
327 assumed.pop();
328 answer
329}
330
331/// The composite of two types already known to be compatible.
332fn build(types: &mut Types, left: TypeId, right: TypeId) -> TypeId {
333 if left == right {
334 return left;
335 }
336 let canonical = types.canonical(left);
337 match (types.kind(canonical), types.kind(types.canonical(right))) {
338 (TypeKind::Array { elem: a, len: x }, TypeKind::Array { elem: b, len: y }) => {
339 let elem = build(types, a, b);
340 // The declaration that knew the size is the one to take it from, whichever side it
341 // was. An array type carries no qualifiers of its own, they are on the element.
342 let len = if matches!(x, ArrayLen::Fixed(_)) { x } else { y };
343 types.array(elem, len)
344 }
345 (TypeKind::Pointer(a), TypeKind::Pointer(b)) => {
346 let inner = build(types, a, b);
347 let quals = types.quals(canonical);
348 let pointer = types.pointer(inner);
349 types.qualified(pointer, quals)
350 }
351 (TypeKind::Function(a), TypeKind::Function(b)) => {
352 let a = types.signature(a).clone();
353 let b = types.signature(b).clone();
354 composite_function(types, &a, &b)
355 }
356 // Everything else has nothing to combine, and the type as it was written is the better
357 // of the two answers because a diagnostic can print the name the program used.
358 _ => left,
359 }
360}
361
362/// The composite of two compatible function types.
363fn composite_function(types: &mut Types, left: &FunctionType, right: &FunctionType) -> TypeId {
364 let ret = build(types, left.ret, right.ret);
365 // The prototype wins, because it is the declaration that knows something. This is what makes
366 // `void f(); void f(int);` a function of one `int` afterwards, so that the calls written
367 // between the two declarations can still be checked against something.
368 let (params, variadic, prototyped) = match (left.prototyped, right.prototyped) {
369 (true, true) => {
370 let params =
371 left.params.iter().zip(&right.params).map(|(&a, &b)| build(types, a, b)).collect();
372 (params, left.variadic, true)
373 }
374 (true, false) => (left.params.clone(), left.variadic, true),
375 (false, true) => (right.params.clone(), right.variadic, true),
376 // Neither is a prototype, so neither makes a call checkable. What is still worth keeping
377 // is an old style definition's parameter list, which is the only thing an unprototyped
378 // type ever has one of and which is what its own lowering reads.
379 (false, false) => {
380 let params =
381 if left.params.is_empty() { right.params.clone() } else { left.params.clone() };
382 (params, false, false)
383 }
384 };
385 types.function(FunctionType { ret, params, variadic, prototyped })
386}