Skip to main content

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 definition is the one unprototyped type that knows what its parameters
152        // are, and 6.7.6.3p15 holds it to a stricter rule than a declaration that knows nothing:
153        // the counts have to agree and each prototype parameter has to be compatible with the
154        // promoted type of the identifier facing it, which is what the list holds.
155        (true, false) if !right.params.is_empty() => defines(types, left, right, assumed),
156        (false, true) if !left.params.is_empty() => defines(types, right, left, assumed),
157        // An old style declaration says nothing about the parameters, so it is compatible with a
158        // prototype only when the call would have gone the same way regardless: no `...`, and no
159        // parameter the default argument promotions would have changed on the way in.
160        (true, false) => stands_for(types, left),
161        (false, true) => stands_for(types, right),
162        (false, false) => true,
163    }
164}
165
166/// Whether a prototype and an old style definition describe the same function, 6.7.6.3p15.
167///
168/// The rule as written is that the counts agree and each prototype parameter is compatible with
169/// the promoted type of the identifier facing it. Taken literally that makes `int f(char);` and a
170/// definition of `f` with a `char` identifier two different functions, since `char` promotes to
171/// `int`, and every compiler takes that pair because all the code written this way is written
172/// against a header. So a prototype parameter the promotions would have changed is allowed to
173/// face what it changes into, which is the one relaxation and is what makes the pair work.
174fn defines(
175    types: &Types,
176    proto: &FunctionType,
177    def: &FunctionType,
178    assumed: &mut Vec<(RecordId, RecordId)>,
179) -> bool {
180    !proto.variadic
181        && proto.params.len() == def.params.len()
182        && proto
183            .params
184            .iter()
185            .zip(&def.params)
186            .all(|(&a, &b)| same(types, a, b, assumed) || promotes_to(types, a, b))
187}
188
189/// Whether the default argument promotions turn the first type into the second.
190fn promotes_to(types: &Types, from: TypeId, to: TypeId) -> bool {
191    if survives_promotion(types, from) {
192        return false;
193    }
194    let to = types.kind(types.canonical(to));
195    match types.kind(types.canonical(from)) {
196        TypeKind::Float(FloatKind::Float) => to == TypeKind::Float(FloatKind::Double),
197        // Everything else the promotions touch is narrower than an `int` and becomes one. The
198        // target where that is not so is one where `int` is no wider than a `short`, which none
199        // of the targets here is.
200        _ => to == TypeKind::Int(IntKind::Int),
201    }
202}
203
204/// Whether an old style declaration of a function could stand for this prototype.
205fn stands_for(types: &Types, signature: &FunctionType) -> bool {
206    !signature.variadic && signature.params.iter().all(|&param| survives_promotion(types, param))
207}
208
209/// Whether a parameter type is one the default argument promotions leave alone.
210///
211/// The `float` case is the one that matters: an old style call passes a `double`, so a prototype
212/// taking a `float` is a different function from the same name declared without one, and both
213/// compilers refuse the pair.
214fn survives_promotion(types: &Types, id: TypeId) -> bool {
215    match types.kind(types.canonical(id)) {
216        TypeKind::Bool => false,
217        TypeKind::Int(kind) => kind.rank() >= IntKind::Int.rank(),
218        TypeKind::Float(FloatKind::Float) => false,
219        // An enumeration is compatible with what it is represented in, so it comes through
220        // whenever that type does.
221        TypeKind::Enum(id) => match types.enum_info(id).underlying {
222            Some(underlying) => survives_promotion(types, underlying),
223            None => false,
224        },
225        // Everything else, `_BitInt` included, is its own promotion.
226        _ => true,
227    }
228}
229
230/// Whether two record declarations are the same type.
231///
232/// The same declaration always is. Two different ones are in C23 when they have the same tag and
233/// the same members, which is the rule that lets a header be included twice without a guard.
234/// clang 18 implements it and gcc 13.3 still rejects the redefinition outright. In the older
235/// dialects the question does not arise, because a second definition of a tag in one scope is
236/// refused before anything asks whether the two types match.
237fn records(
238    types: &Types,
239    left: RecordId,
240    right: RecordId,
241    assumed: &mut Vec<(RecordId, RecordId)>,
242) -> bool {
243    if left == right || assumed.contains(&(left, right)) {
244        return true;
245    }
246    let a = types.record_info(left);
247    let b = types.record_info(right);
248    if a.kind != b.kind || a.tag.is_none() || a.tag != b.tag {
249        // An anonymous record is compatible with nothing but itself. There is no name by which a
250        // second declaration could be claiming to be the same type.
251        return false;
252    }
253    if a.layout.is_none() || b.layout.is_none() || a.fields.len() != b.fields.len() {
254        // An incomplete declaration has no members to compare. Two mentions of one tag in one
255        // scope are one declaration and one id, so they never reach here.
256        return false;
257    }
258    assumed.push((left, right));
259    let answer = a
260        .fields
261        .iter()
262        .zip(&b.fields)
263        .all(|(x, y)| x.name == y.name && x.bits == y.bits && same(types, x.ty, y.ty, assumed));
264    assumed.pop();
265    answer
266}
267
268/// The composite of two types already known to be compatible.
269fn build(types: &mut Types, left: TypeId, right: TypeId) -> TypeId {
270    if left == right {
271        return left;
272    }
273    let canonical = types.canonical(left);
274    match (types.kind(canonical), types.kind(types.canonical(right))) {
275        (TypeKind::Array { elem: a, len: x }, TypeKind::Array { elem: b, len: y }) => {
276            let elem = build(types, a, b);
277            // The declaration that knew the size is the one to take it from, whichever side it
278            // was. An array type carries no qualifiers of its own, they are on the element.
279            let len = if matches!(x, ArrayLen::Fixed(_)) { x } else { y };
280            types.array(elem, len)
281        }
282        (TypeKind::Pointer(a), TypeKind::Pointer(b)) => {
283            let inner = build(types, a, b);
284            let quals = types.quals(canonical);
285            let pointer = types.pointer(inner);
286            types.qualified(pointer, quals)
287        }
288        (TypeKind::Function(a), TypeKind::Function(b)) => {
289            let a = types.signature(a).clone();
290            let b = types.signature(b).clone();
291            composite_function(types, &a, &b)
292        }
293        // Everything else has nothing to combine, and the type as it was written is the better
294        // of the two answers because a diagnostic can print the name the program used.
295        _ => left,
296    }
297}
298
299/// The composite of two compatible function types.
300fn composite_function(types: &mut Types, left: &FunctionType, right: &FunctionType) -> TypeId {
301    let ret = build(types, left.ret, right.ret);
302    // The prototype wins, because it is the declaration that knows something. This is what makes
303    // `void f(); void f(int);` a function of one `int` afterwards, so that the calls written
304    // between the two declarations can still be checked against something.
305    let (params, variadic, prototyped) = match (left.prototyped, right.prototyped) {
306        (true, true) => {
307            let params =
308                left.params.iter().zip(&right.params).map(|(&a, &b)| build(types, a, b)).collect();
309            (params, left.variadic, true)
310        }
311        (true, false) => (left.params.clone(), left.variadic, true),
312        (false, true) => (right.params.clone(), right.variadic, true),
313        // Neither is a prototype, so neither makes a call checkable. What is still worth keeping
314        // is an old style definition's parameter list, which is the only thing an unprototyped
315        // type ever has one of and which is what its own lowering reads.
316        (false, false) => {
317            let params =
318                if left.params.is_empty() { right.params.clone() } else { left.params.clone() };
319            (params, false, false)
320        }
321    };
322    types.function(FunctionType { ret, params, variadic, prototyped })
323}