rucc_types/types.rs
1//! The type table: interning, canonicalisation, and the nominal declarations.
2//!
3//! Design: `spec/07-types-and-semantics.md` section 7.1.
4//!
5//! There is one [`Types`] per translation unit and every [`TypeId`] belongs to it. Interning
6//! is what makes type identity an integer comparison, which is the single most frequent
7//! question the compiler asks, and it is also what makes the canonical form free to look up:
8//! each entry stores the id of its own canonical type, so stripping a stack of typedefs is one
9//! array read rather than a walk.
10
11use std::collections::HashMap;
12use std::num::NonZeroU32;
13
14use rucc_base::{Idx, Symbol};
15
16use crate::kind::{
17 ArrayLen, EnumId, FloatKind, FunctionId, FunctionType, IntKind, Qualifiers, RecordId,
18 RecordKind, Type, TypeKind,
19};
20use crate::layout::Layout;
21use crate::record::{Field, RecordLayout, VariableLayout};
22
23/// The identity of a type.
24///
25/// Four bytes, `Copy`, and equal exactly when the two types are the same type. Ids from two
26/// different [`Types`] tables are not comparable, which is not a restriction in practice
27/// because there is one table per translation unit.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct TypeId(Idx<Entry>);
30
31impl std::fmt::Debug for TypeId {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 write!(f, "TypeId#{}", self.0.raw())
34 }
35}
36
37/// One row of the table.
38///
39/// The canonical id is stored rather than computed because almost every read of a type wants
40/// it, and computing it means walking a chain whose length is however many typedefs the header
41/// author felt like writing.
42#[derive(Debug, Clone, Copy)]
43struct Entry {
44 ty: Type,
45 canonical: TypeId,
46}
47
48/// What is known about one `struct` or `union` declaration.
49#[derive(Debug, Clone)]
50pub struct RecordInfo {
51 /// Whether it is a `struct` or a `union`.
52 pub kind: RecordKind,
53 /// The tag, absent for an anonymous one.
54 pub tag: Option<Symbol>,
55 /// The layout, absent until the members have been seen and laid out.
56 ///
57 /// This is also what says whether the type is complete. A record is incomplete from the
58 /// point its tag is first mentioned until its closing brace, and code in between may
59 /// declare pointers to it and nothing else.
60 ///
61 /// For a record with a member of no fixed size the alignment here is the right one and the
62 /// size is zero, since an alignment never depends on a length. [`RecordInfo::variable`] is
63 /// what holds the size in that case and what says the size here means nothing.
64 pub layout: Option<Layout>,
65 /// How long the record is and where its members sit, where those are not numbers.
66 ///
67 /// Present on exactly the records C calls variably modified, meaning a variable length array
68 /// is somewhere among the members, which may only be written inside a function.
69 pub variable: Option<VariableLayout>,
70 /// The members, placed, and empty until the record is complete.
71 ///
72 /// One entry per member the program wrote, in that order, so a caller that kept the
73 /// declarations can index the two together.
74 pub fields: Vec<Field>,
75 /// Whether `__attribute__((transparent_union))` was written on it and held up.
76 ///
77 /// Only ever true of a union, and only of one whose first member is the size and the
78 /// alignment of the whole of it, which is what makes passing the union and passing that
79 /// member the same thing at a call. What it buys is two rules: a parameter of this type is
80 /// compatible with a parameter of any member's type, and a value assigned to it is put into
81 /// whichever member it fits. Both are in `spec/13-gnu-compat.md`.
82 pub transparent: bool,
83 /// Whether the scalars in it are stored in the byte order the target does not have.
84 ///
85 /// What `__attribute__((scalar_storage_order("big-endian")))` on a little-endian target asks
86 /// for, and what the same attribute written with the target's own order does not. It changes
87 /// nothing about where the members sit: the record is the size and the alignment it would
88 /// otherwise be and every member is at the offset it would otherwise be at. What it changes
89 /// is the order of the bytes inside each scalar, which is a byte swap on every load and
90 /// store, and the end of a storage unit a bit-field is allocated from. Both are in
91 /// `spec/13-gnu-compat.md`.
92 pub reverse: bool,
93}
94
95/// What is known about one `enum` declaration.
96#[derive(Debug, Clone)]
97pub struct EnumInfo {
98 /// The tag, absent for an anonymous one.
99 pub tag: Option<Symbol>,
100 /// The type the enumerators are represented in, absent until it is decided.
101 ///
102 /// C23 lets the program write it, and before that it is chosen once every enumerator has
103 /// been seen. Either way it is a fact about the declaration rather than about the type
104 /// system, so it is recorded here and not derived twice.
105 pub underlying: Option<TypeId>,
106 /// Whether the underlying type was written by the program rather than chosen.
107 ///
108 /// It changes the answer to what an enumerator's own type is, and it decides whether an
109 /// enumerator that does not fit is an error or a reason to widen.
110 pub fixed: bool,
111 /// The enumerators in the order the program wrote them, empty until the enumeration is
112 /// complete.
113 ///
114 /// Nothing the type system itself asks about, since an enumerator is a name in a scope and
115 /// what has the type is the enumeration rather than the list. It is here because the
116 /// declaration is the only place the list ever exists, the scope it is declared into throws
117 /// away the order and the tie to the enumeration, and a reader that wants the list later has
118 /// nowhere else to ask. Debug information is that reader: without this a debugger prints the
119 /// number where the program wrote the name.
120 pub enumerators: Vec<Enumerator>,
121}
122
123/// One enumerator of an enumeration.
124#[derive(Debug, Clone)]
125pub struct Enumerator {
126 /// The name the program wrote.
127 pub name: Symbol,
128 /// Its value, in the enumeration's underlying type.
129 ///
130 /// Held as an [`i128`] because the value is worked out before the underlying type is chosen,
131 /// and because the widest enumeration a target has still has to fit in something wider than
132 /// itself while the list is being read.
133 pub value: i128,
134}
135
136/// A typedef name the program wrote, and what it stands for.
137#[derive(Debug, Clone, Copy)]
138pub struct Alias {
139 /// The name.
140 pub name: Symbol,
141 /// The type it was written for, which is the same type the name resolves to rather than a
142 /// type of its own.
143 pub of: TypeId,
144}
145
146/// Every type in one translation unit.
147#[derive(Debug)]
148pub struct Types {
149 entries: Vec<Entry>,
150 map: HashMap<Type, TypeId>,
151 functions: Vec<FunctionType>,
152 function_map: HashMap<FunctionType, FunctionId>,
153 records: Vec<RecordInfo>,
154 enums: Vec<EnumInfo>,
155 aliases: Vec<Alias>,
156 void: TypeId,
157 boolean: TypeId,
158 ints: [TypeId; 13],
159 floats: [TypeId; 9],
160}
161
162impl Default for Types {
163 fn default() -> Types {
164 Types::new()
165 }
166}
167
168impl Types {
169 /// A table holding the basic types and nothing else.
170 ///
171 /// The basic types are interned here rather than on first use so that asking for `int` is
172 /// an array read. They are the ones asked for by far the most often, because every
173 /// integer promotion produces one.
174 #[must_use]
175 pub fn new() -> Types {
176 let mut types = Types {
177 entries: Vec::new(),
178 map: HashMap::new(),
179 functions: Vec::new(),
180 function_map: HashMap::new(),
181 records: Vec::new(),
182 enums: Vec::new(),
183 aliases: Vec::new(),
184 // Fixed up immediately below. There is no id to put here before the table exists,
185 // and an `Option` on each of them would be paid for on every read for the sake of
186 // four lines of construction.
187 void: TypeId(Idx::new(0)),
188 boolean: TypeId(Idx::new(0)),
189 ints: [TypeId(Idx::new(0)); 13],
190 floats: [TypeId(Idx::new(0)); 9],
191 };
192 types.void = types.intern(Type::new(TypeKind::Void));
193 types.boolean = types.intern(Type::new(TypeKind::Bool));
194 for kind in IntKind::ALL {
195 types.ints[kind.index()] = types.intern(Type::new(TypeKind::Int(kind)));
196 }
197 for kind in FloatKind::ALL {
198 types.floats[kind.index()] = types.intern(Type::new(TypeKind::Float(kind)));
199 }
200 types
201 }
202
203 /// How many distinct types there are.
204 #[must_use]
205 pub fn len(&self) -> usize {
206 self.entries.len()
207 }
208
209 /// Whether the table is empty, which it never is once [`Types::new`] has run.
210 #[must_use]
211 pub fn is_empty(&self) -> bool {
212 self.entries.is_empty()
213 }
214
215 /// The type `id` stands for, with its qualifiers.
216 ///
217 /// # Panics
218 ///
219 /// Panics if `id` came from a different table.
220 #[must_use]
221 pub fn get(&self, id: TypeId) -> Type {
222 self.entries[id.0.index()].ty
223 }
224
225 /// What `id` is, ignoring its qualifiers.
226 ///
227 /// # Panics
228 ///
229 /// Panics if `id` came from a different table.
230 #[must_use]
231 pub fn kind(&self, id: TypeId) -> TypeKind {
232 self.get(id).kind
233 }
234
235 /// What `id` is qualified with.
236 ///
237 /// # Panics
238 ///
239 /// Panics if `id` came from a different table.
240 #[must_use]
241 pub fn quals(&self, id: TypeId) -> Qualifiers {
242 self.get(id).quals
243 }
244
245 /// The canonical form of `id`, with every typedef resolved at every depth.
246 ///
247 /// This is what every semantic rule reads. `id` itself is what every diagnostic prints.
248 ///
249 /// # Panics
250 ///
251 /// Panics if `id` came from a different table.
252 #[must_use]
253 pub fn canonical(&self, id: TypeId) -> TypeId {
254 self.entries[id.0.index()].canonical
255 }
256
257 /// Whether `id` is written with a typedef name somewhere inside it.
258 ///
259 /// # Panics
260 ///
261 /// Panics if `id` came from a different table.
262 #[must_use]
263 pub fn is_sugar(&self, id: TypeId) -> bool {
264 self.canonical(id) != id
265 }
266
267 /// `void`.
268 #[must_use]
269 pub fn void(&self) -> TypeId {
270 self.void
271 }
272
273 /// `bool`, which is `_Bool` in the older spellings.
274 ///
275 /// Named this way because `bool` is a Rust keyword and `r#bool` at every call site would
276 /// be a worse trade than one unusual name here.
277 #[must_use]
278 pub fn boolean(&self) -> TypeId {
279 self.boolean
280 }
281
282 /// One of the standard integer types.
283 #[must_use]
284 pub fn int(&self, kind: IntKind) -> TypeId {
285 self.ints[kind.index()]
286 }
287
288 /// One of the real floating types.
289 #[must_use]
290 pub fn float(&self, kind: FloatKind) -> TypeId {
291 self.floats[kind.index()]
292 }
293
294 /// `_Complex T` for the real type `T`, which is one of the halves.
295 pub fn complex(&mut self, part: TypeId) -> TypeId {
296 self.intern(Type::new(TypeKind::Complex(part)))
297 }
298
299 /// `_Complex T` for a real floating `T`, which is the spelling C has.
300 pub fn complex_float(&mut self, kind: FloatKind) -> TypeId {
301 let part = self.float(kind);
302 self.complex(part)
303 }
304
305 /// `_BitInt(width)`, signed or not.
306 ///
307 /// The width is not checked against the target's maximum here. That check belongs where
308 /// there is a span to point at, and building the type anyway means the rest of the
309 /// declaration still gets checked instead of collapsing into a cascade.
310 pub fn bit_int(&mut self, signed: bool, width: u32) -> TypeId {
311 self.intern(Type::new(TypeKind::BitInt { signed, width }))
312 }
313
314 /// A pointer to `pointee`.
315 pub fn pointer(&mut self, pointee: TypeId) -> TypeId {
316 self.intern(Type::new(TypeKind::Pointer(pointee)))
317 }
318
319 /// `_Atomic(inner)`.
320 pub fn atomic(&mut self, inner: TypeId) -> TypeId {
321 self.intern(Type::new(TypeKind::Atomic(inner)))
322 }
323
324 /// An array of `elem`.
325 pub fn array(&mut self, elem: TypeId, len: ArrayLen) -> TypeId {
326 self.intern(Type::new(TypeKind::Array { elem, len }))
327 }
328
329 /// A GNU vector of `len` elements of `elem`.
330 pub fn vector(&mut self, elem: TypeId, len: u32) -> TypeId {
331 self.intern(Type::new(TypeKind::Vector { elem, len }))
332 }
333
334 /// A function type, deduplicated by content.
335 ///
336 /// # Panics
337 ///
338 /// Panics past four billion distinct function types in one translation unit. The
339 /// alternative to panicking is handing back an id that means a different type, so the
340 /// limit is stated rather than worked around.
341 pub fn function(&mut self, signature: FunctionType) -> TypeId {
342 let id = match self.function_map.get(&signature) {
343 Some(&id) => id,
344 None => {
345 let id = FunctionId(u32::try_from(self.functions.len()).expect("too many types"));
346 self.functions.push(signature.clone());
347 self.function_map.insert(signature, id);
348 id
349 }
350 };
351 self.intern(Type::new(TypeKind::Function(id)))
352 }
353
354 /// The signature behind a function type.
355 ///
356 /// # Panics
357 ///
358 /// Panics if `id` came from a different table.
359 #[must_use]
360 pub fn signature(&self, id: FunctionId) -> &FunctionType {
361 &self.functions[id.0 as usize]
362 }
363
364 /// Declares a `struct` or `union` that has been named but not yet laid out.
365 ///
366 /// Each call makes a new type even for the same tag, because a record type in C is its
367 /// declaration. Redeclaring a tag in an inner scope makes a different type, and the two
368 /// being distinct is what the scope rules mean.
369 ///
370 /// # Panics
371 ///
372 /// Panics past four billion record declarations in one translation unit.
373 pub fn declare_record(&mut self, kind: RecordKind, tag: Option<Symbol>) -> RecordId {
374 let id = RecordId(u32::try_from(self.records.len()).expect("too many types"));
375 self.records.push(RecordInfo {
376 kind,
377 tag,
378 layout: None,
379 variable: None,
380 fields: Vec::new(),
381 transparent: false,
382 reverse: false,
383 });
384 id
385 }
386
387 /// Records that a union was declared transparent, which is a decision made elsewhere.
388 ///
389 /// Whether the attribute holds up is a question about the members and their layout, so it is
390 /// answered where the members are read rather than here, and this only writes the answer down.
391 /// It is a fact about the declaration and not about one spelling of it, which is why the whole
392 /// record is marked rather than a variant of the type: every name for the union is the same
393 /// union and a parameter written with any of them takes the same values.
394 ///
395 /// # Panics
396 ///
397 /// Panics if `id` came from a different table.
398 pub fn make_transparent(&mut self, id: RecordId) {
399 self.records[id.0 as usize].transparent = true;
400 }
401
402 /// Records that a record holds its scalars in the byte order the target does not have.
403 ///
404 /// Which order the attribute asked for and which one the target has are both known where the
405 /// attribute is read, so what arrives here is the answer to the one question the rest of the
406 /// compiler asks. It is a fact about the declaration rather than about one spelling of it, for
407 /// the reason [`Types::make_transparent`] gives, and it is set after the members are laid out
408 /// because it changes nothing about the layout.
409 ///
410 /// # Panics
411 ///
412 /// Panics if `id` came from a different table.
413 pub fn make_reverse_order(&mut self, id: RecordId) {
414 self.records[id.0 as usize].reverse = true;
415 }
416
417 /// The type of a declared record.
418 pub fn record(&mut self, id: RecordId) -> TypeId {
419 self.intern(Type::new(TypeKind::Record(id)))
420 }
421
422 /// What is known about a declared record.
423 ///
424 /// # Panics
425 ///
426 /// Panics if `id` came from a different table.
427 #[must_use]
428 pub fn record_info(&self, id: RecordId) -> &RecordInfo {
429 &self.records[id.0 as usize]
430 }
431
432 /// Every record declared so far, in declaration order.
433 ///
434 /// For whoever wants to say something about all of them rather than about one, which so
435 /// far is [`measure_all`](crate::measure_all), measuring how their bytes fall into granules.
436 ///
437 /// # Panics
438 ///
439 /// Panics if more than `u32::MAX` records have been declared, which every other index into
440 /// this table would already have panicked on.
441 pub fn records(&self) -> impl Iterator<Item = (RecordId, &RecordInfo)> {
442 self.records
443 .iter()
444 .enumerate()
445 .map(|(index, info)| (RecordId(u32::try_from(index).expect("a declared record")), info))
446 }
447
448 /// Completes a record by recording what [`layout_record`](crate::layout_record) produced.
449 ///
450 /// # Panics
451 ///
452 /// Panics if `id` came from a different table.
453 pub fn complete_record(&mut self, id: RecordId, laid_out: RecordLayout) {
454 let info = &mut self.records[id.0 as usize];
455 info.layout = Some(laid_out.layout);
456 info.variable = laid_out.variable;
457 info.fields = laid_out.fields;
458 }
459
460 /// The member of a record with the given name.
461 ///
462 /// Direct members only. Reaching into an anonymous member is a name lookup with a path to
463 /// build rather than a search, so it belongs to whoever is resolving the expression.
464 ///
465 /// # Panics
466 ///
467 /// Panics if `id` came from a different table.
468 #[must_use]
469 pub fn field(&self, id: RecordId, name: Symbol) -> Option<&Field> {
470 self.records[id.0 as usize].fields.iter().find(|field| field.name == Some(name))
471 }
472
473 /// Declares an `enum` whose underlying type is not decided yet.
474 ///
475 /// # Panics
476 ///
477 /// Panics past four billion enumeration declarations in one translation unit.
478 pub fn declare_enum(&mut self, tag: Option<Symbol>) -> EnumId {
479 let id = EnumId(u32::try_from(self.enums.len()).expect("too many types"));
480 self.enums.push(EnumInfo { tag, underlying: None, fixed: false, enumerators: Vec::new() });
481 id
482 }
483
484 /// The type of a declared enumeration.
485 pub fn enumeration(&mut self, id: EnumId) -> TypeId {
486 self.intern(Type::new(TypeKind::Enum(id)))
487 }
488
489 /// What is known about a declared enumeration.
490 ///
491 /// # Panics
492 ///
493 /// Panics if `id` came from a different table.
494 #[must_use]
495 pub fn enum_info(&self, id: EnumId) -> &EnumInfo {
496 &self.enums[id.0 as usize]
497 }
498
499 /// Records what an enumeration is represented in, and whether the program said so.
500 ///
501 /// # Panics
502 ///
503 /// Panics if `id` came from a different table.
504 pub fn complete_enum(&mut self, id: EnumId, underlying: TypeId, fixed: bool) {
505 let info = &mut self.enums[id.0 as usize];
506 info.underlying = Some(underlying);
507 info.fixed = fixed;
508 }
509
510 /// Records what an enumeration's enumerators are.
511 ///
512 /// Apart from [`Types::complete_enum`] because it is a different fact with a different reader.
513 /// What an enumeration is represented in decides what its values do in arithmetic and is asked
514 /// by the rest of the compiler; the list of names is asked by nothing but the debug
515 /// information, and an enumeration that reaches completion without one, which is what a C23
516 /// declaration that writes an underlying type and no body does, is complete all the same.
517 ///
518 /// # Panics
519 ///
520 /// Panics if `id` came from a different table.
521 pub fn list_enumerators(&mut self, id: EnumId, enumerators: Vec<Enumerator>) {
522 self.enums[id.0 as usize].enumerators = enumerators;
523 }
524
525 /// Records that the program wrote `name` as a typedef name for `of`.
526 ///
527 /// Beside the table rather than in it, and that is the decision this is. A typedef name is a
528 /// second name for a type and not a type of its own, so an ordinary typedef interns nothing
529 /// and the name is written nowhere the types can be asked for it. Making it a type of its own
530 /// would mean two names for one type are two ids, and then the equality of two [`TypeId`]s
531 /// stops meaning the two are the same type, which is the question this table is built to
532 /// answer in one comparison. So the names go in a list that changes nothing about what a type
533 /// is.
534 ///
535 /// What the list cannot answer is which of two names a particular declaration was written
536 /// with, since that is a fact about the declaration and this is a fact about the type. A
537 /// reader gets the names the program wrote and what each one stands for, and no more.
538 pub fn alias(&mut self, name: Symbol, of: TypeId) {
539 if self.aliases.iter().any(|had| had.name == name && had.of == of) {
540 return;
541 }
542 self.aliases.push(Alias { name, of });
543 }
544
545 /// Every typedef name the program wrote, in the order it wrote them.
546 #[must_use]
547 pub fn aliases(&self) -> &[Alias] {
548 &self.aliases
549 }
550
551 /// A typedef name standing for `underlying`.
552 pub fn typedef(&mut self, name: Symbol, underlying: TypeId) -> TypeId {
553 self.intern(Type::new(TypeKind::Typedef { name, underlying, align: None }))
554 }
555
556 /// The same, for a typedef that said what an object of it is aligned to.
557 ///
558 /// `align` is in bytes and is what the type is aligned to rather than a floor on it, which
559 /// is what `__attribute__((aligned(n)))` means in this one position. See
560 /// [`TypeKind::Typedef`].
561 pub fn aligned_typedef(
562 &mut self,
563 name: Symbol,
564 underlying: TypeId,
565 align: NonZeroU32,
566 ) -> TypeId {
567 self.intern(Type::new(TypeKind::Typedef { name, underlying, align: Some(align) }))
568 }
569
570 /// What a typedef in `id`'s sugar asked an object of it to be aligned to, and [`None`] when
571 /// none of them asked for anything.
572 ///
573 /// The nearest one wins, because `typedef L M __attribute__((aligned(8)))` over an `L` that
574 /// asked for two is an eight and not a two: the outer typedef is the one the declaration was
575 /// written with. Below the sugar there is nothing to find, since only a typedef can carry one
576 /// of these, so the walk stops at the first node that is not one.
577 ///
578 /// # Panics
579 ///
580 /// Panics if `id` came from a different table.
581 #[must_use]
582 pub fn align_override(&self, id: TypeId) -> Option<NonZeroU32> {
583 let mut id = id;
584 loop {
585 let TypeKind::Typedef { underlying, align, .. } = self.kind(id) else { return None };
586 if align.is_some() {
587 return align;
588 }
589 id = underlying;
590 }
591 }
592
593 /// `id` with `quals` added to whatever it already carries.
594 ///
595 /// Qualifying an array qualifies its element type and leaves the array itself unqualified,
596 /// which is 6.7.3p10 and is not a shortcut. An array type has no qualifiers of its own,
597 /// and if it did then `const` on an array parameter would mean nothing at all.
598 pub fn qualified(&mut self, id: TypeId, quals: Qualifiers) -> TypeId {
599 if quals.is_none() {
600 return id;
601 }
602 let ty = self.get(id);
603 if let TypeKind::Array { elem, len } = ty.kind {
604 let elem = self.qualified(elem, quals);
605 return self.intern(Type { kind: TypeKind::Array { elem, len }, quals: ty.quals });
606 }
607 self.intern(Type { kind: ty.kind, quals: ty.quals.with(quals) })
608 }
609
610 /// `id` with every qualifier removed from its outermost node.
611 ///
612 /// Only the outermost, because that is what the standard means by the unqualified version
613 /// of a type. The pointee of a `const char *` stays `const`.
614 pub fn unqualified(&mut self, id: TypeId) -> TypeId {
615 let ty = self.get(id);
616 if ty.quals.is_none() {
617 return id;
618 }
619 self.intern(Type::new(ty.kind))
620 }
621
622 /// The qualifiers an object of `id` carries, which for an array are its element's.
623 ///
624 /// [`Self::quals`] answers what the node holds, and [`Self::qualified`] has just put an array's
625 /// qualifiers on its element rather than on the array, so the node holds nothing and an object
626 /// of the type is still `const`. That gap is only visible in one place, which is a pointer to an
627 /// array: `const int (*)[4]` points at something nobody may write to and asking the array node
628 /// says otherwise.
629 #[must_use]
630 pub fn object_quals(&self, id: TypeId) -> Qualifiers {
631 let ty = self.get(id);
632 match ty.kind {
633 TypeKind::Array { elem, .. } => ty.quals.with(self.object_quals(elem)),
634 _ => ty.quals,
635 }
636 }
637
638 /// `id` with the qualifiers of an object of it removed, which for an array are its element's.
639 ///
640 /// [`Self::unqualified`] taken through an array for the same reason [`Self::object_quals`] is,
641 /// so that the two agree about where an array keeps its qualifiers. What it is for is the
642 /// comparison in a pointer assignment: C's own compatibility says `const int [4]` and `int [4]`
643 /// are different types, because the element types are, so `const int (*)[4] = p` would be an
644 /// incompatible pointer rather than a qualifier being added. Every compiler takes it, C23 says
645 /// so outright, and taking the qualifiers off both sides before comparing is what makes the
646 /// assignment rule read the array the way it reads everything else.
647 pub fn unqualified_object(&mut self, id: TypeId) -> TypeId {
648 let ty = self.get(id);
649 if let TypeKind::Array { elem, len } = ty.kind {
650 let elem = self.unqualified_object(elem);
651 return self.intern(Type::new(TypeKind::Array { elem, len }));
652 }
653 self.unqualified(id)
654 }
655
656 /// The id for `ty`, making one if this is the first time it has been asked for.
657 fn intern(&mut self, ty: Type) -> TypeId {
658 if let Some(&id) = self.map.get(&ty) {
659 return id;
660 }
661 // Canonicalising can intern other types, which means `self.entries` may have grown by
662 // the time this returns and the id below has to be taken afterwards. It cannot have
663 // interned `ty` itself, because a canonical type differs from the sugar it came from,
664 // but the second lookup is one hash of a cold path against a duplicate entry that
665 // would quietly break the promise that equal ids mean equal types.
666 let canonical = self.canonicalise(&ty);
667 if let Some(&id) = self.map.get(&ty) {
668 return id;
669 }
670 let id = TypeId(Idx::from_usize(self.entries.len()));
671 self.entries.push(Entry { ty, canonical: canonical.unwrap_or(id) });
672 self.map.insert(ty, id);
673 id
674 }
675
676 /// The canonical form of `ty`, or `None` when `ty` is already canonical.
677 ///
678 /// A typedef is not the only place sugar hides. `T *` is sugar when `T` is, and so is an
679 /// array of one, and so is a function that returns one, so this rebuilds the type around
680 /// whatever its parts canonicalise to rather than only looking at the outermost node.
681 fn canonicalise(&mut self, ty: &Type) -> Option<TypeId> {
682 match ty.kind {
683 TypeKind::Typedef { underlying, .. } => {
684 let base = self.canonical(underlying);
685 Some(self.qualified(base, ty.quals))
686 }
687 TypeKind::Pointer(inner) => self.rebuild(ty, inner, TypeKind::Pointer),
688 TypeKind::Atomic(inner) => self.rebuild(ty, inner, TypeKind::Atomic),
689 TypeKind::Complex(part) => self.rebuild(ty, part, TypeKind::Complex),
690 TypeKind::Array { elem, len } => {
691 self.rebuild(ty, elem, |elem| TypeKind::Array { elem, len })
692 }
693 TypeKind::Vector { elem, len } => {
694 self.rebuild(ty, elem, |elem| TypeKind::Vector { elem, len })
695 }
696 TypeKind::Function(id) => self.canonicalise_function(ty, id),
697 TypeKind::Void
698 | TypeKind::Bool
699 | TypeKind::Int(_)
700 | TypeKind::Float(_)
701 | TypeKind::BitInt { .. }
702 | TypeKind::Record(_)
703 | TypeKind::Enum(_) => None,
704 }
705 }
706
707 /// The canonical form of a type built out of one other type.
708 fn rebuild(
709 &mut self,
710 ty: &Type,
711 inner: TypeId,
712 make: impl FnOnce(TypeId) -> TypeKind,
713 ) -> Option<TypeId> {
714 let canonical = self.canonical(inner);
715 if canonical == inner {
716 return None;
717 }
718 Some(self.intern(Type { kind: make(canonical), quals: ty.quals }))
719 }
720
721 /// The canonical form of a function type, which is sugar when any part of its signature is.
722 fn canonicalise_function(&mut self, ty: &Type, id: FunctionId) -> Option<TypeId> {
723 let signature = self.signature(id).clone();
724 let ret = self.canonical(signature.ret);
725 let params: Vec<TypeId> =
726 signature.params.iter().map(|¶m| self.canonical(param)).collect();
727 if ret == signature.ret && params == signature.params {
728 return None;
729 }
730 let canonical = FunctionType { ret, params, ..signature };
731 let id = self.function(canonical);
732 Some(self.qualified(id, ty.quals))
733 }
734}