lisette-syntax 0.13.2

Little language inspired by Rust that compiles to Go
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::hash_map::Entry;
use std::fmt::{self, Debug};
use std::hash::Hash;
use std::mem;

use super::{
    CalleeName, ConformanceWitness, InterfaceRequirement, NativeOperation, NativeTypeKind,
    ReceiverCoercion,
};
use crate::EcoString;
use crate::ast::{Expression, ExpressionId, Span};
use crate::types::{IterableKind, RangeKind, SubstitutionMap, Symbol, Type, substitute};

/// Names one value use: the occurrence that produces the value, and its role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ValueUseKey {
    expression: ExpressionId,
    role: ValueUseRole,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ValueUseRole {
    Value,
    PropagatedError,
    CastOperand,
}

impl ValueUseKey {
    /// The value of `expression` where it goes into its slot.
    pub fn value(expression: &Expression) -> Self {
        Self::value_id(expression.id())
    }

    pub fn value_id(expression: ExpressionId) -> Self {
        Self {
            expression,
            role: ValueUseRole::Value,
        }
    }

    /// The error that the `?` applied to `operand` returns from its function or `try` block.
    pub fn propagated_error(operand: &Expression) -> Self {
        Self {
            expression: operand.id(),
            role: ValueUseRole::PropagatedError,
        }
    }

    /// The occurrence that produces the value.
    pub fn expression(&self) -> ExpressionId {
        self.expression
    }

    /// The operand of the cast with the occurrence `cast`, converted to the cast type.
    pub fn cast_operand(cast: ExpressionId) -> Self {
        Self {
            expression: cast,
            role: ValueUseRole::CastOperand,
        }
    }
}

/// How a value of its source type becomes a value of its slot type.
#[derive(Debug, Clone)]
pub enum Adaptation {
    Identity,
    /// The children that produce the value adapt it to the slot type.
    Delegated {
        /// Whether a child that produces the value changes its type.
        converts: bool,
    },
    Interface(Box<InterfaceConversion>),
    /// A Go interface value where an `Option` is expected.
    ImplicitSome {
        payload: Box<Adaptation>,
    },
    Newtype,
    Tuple(Vec<Adaptation>),
    Array(Box<Adaptation>),
    /// A method receiver that takes its address or reads through its reference.
    Receiver(ReceiverCoercion),
}

impl Adaptation {
    /// Whether the adapted value has another type than the value before adaptation.
    pub fn converts(&self) -> bool {
        match self {
            Self::Identity => false,
            Self::Delegated { converts } => *converts,
            Self::Interface(_)
            | Self::Newtype
            | Self::ImplicitSome { .. }
            | Self::Tuple(_)
            | Self::Array(_)
            | Self::Receiver(_) => true,
        }
    }
}

/// A value converted to an interface type, with the conformance the checker selected.
#[derive(Debug, Clone)]
pub struct InterfaceConversion {
    pub source: Type,
    pub target: Type,
    pub source_shape: Type,
    pub target_interface: Option<Type>,
    /// Absent when the target requires no method, or when the source is no named type or type parameter.
    pub witness: Option<ConformanceWitness>,
}

/// The slot type of one value use, and the adaptation into it.
#[derive(Debug, Clone)]
pub struct CheckedValueUse {
    pub slot: Type,
    pub adaptation: Adaptation,
    /// Where the value is written, for diagnostics.
    pub span: Span,
}

/// What a callee runs and with which type arguments, as the checker selected it.
#[derive(Debug, Clone, PartialEq)]
pub struct CheckedCallee {
    pub operation: CallOperation,
    /// The declaration that the callee names, with an aliased owner type replaced by its target.
    pub name: Option<CalleeName>,
    /// The solved type arguments of a generic callee, in the order of its type parameters.
    pub type_arguments: SubstitutionMap,
    /// Whether the call must write into storage that no other name sees, as slice growth must.
    pub copies_storage: bool,
    /// Whether the callee holds the receiver that the first parameter of its declaration takes, as `x.m(a)` does.
    pub binds_receiver: bool,
    pub interface_method: Option<Box<InterfaceRequirement>>,
    /// Where the callee is written, for diagnostics.
    pub span: Span,
}

impl CheckedCallee {
    pub fn definition(&self) -> Option<&str> {
        self.name
            .as_ref()
            .and_then(CalleeName::definition)
            .map(Symbol::as_str)
    }

    pub fn method(&self) -> Option<&super::MethodName> {
        self.name.as_ref().and_then(CalleeName::method)
    }

    pub fn interface_requirement(&self) -> Option<&InterfaceRequirement> {
        match &self.operation {
            CallOperation::BoundMethod { requirement, .. } => Some(requirement),
            _ => self.interface_method.as_deref(),
        }
    }

    /// The built-in method this callee runs, if any.
    pub fn native(&self) -> Option<NativeOperation<'_>> {
        match &self.operation {
            CallOperation::Native { kind, method } => Some(NativeOperation::new(*kind, method)),
            _ => None,
        }
    }

    /// The index of the declared parameter that the first argument of the call fills.
    pub fn receiver_offset(&self) -> usize {
        usize::from(self.binds_receiver)
    }

    /// The type argument of a callee whose first type parameter decides its result.
    pub fn first_type_argument(&self) -> &Type {
        self.type_arguments
            .types()
            .next()
            .expect("internal error: the checker records the type argument of this callee")
    }
}

/// The function, method or built-in operation that a callee selects.
#[derive(Debug, Clone, PartialEq)]
pub enum CallOperation {
    /// A function value, such as a local, a field, a closure or a declared function.
    Function,
    /// A method that lowers to a free function, called on its receiver.
    UfcsFunction,
    /// A receiver method called through its type, with the receiver as the first argument.
    ReceiverMethod {
        is_public: bool,
    },
    /// A method that a type parameter takes from the bound that declares it.
    BoundMethod {
        bound: Type,
        requirement: Box<InterfaceRequirement>,
    },
    /// A method of a built-in type.
    Native {
        kind: NativeTypeKind,
        method: EcoString,
    },
    /// A constructor of a built-in type.
    NativeConstructor {
        kind: NativeTypeKind,
        method: EcoString,
    },
    TupleStructConstructor {
        owner: Symbol,
        is_newtype: bool,
    },
    AssertType,
    Zero,
    TypeConversion,
    /// No operation, because inference rejected the call before it could select one.
    Unavailable,
}

/// How a program tests two values of one type for equality, as the checker selected it.
#[derive(Debug, Clone, PartialEq)]
pub enum EqualityRecipe {
    /// Go `==`.
    Operator,
    /// The `equals` method of `owner`, or of a type parameter whose bound declares it when `owner` is absent.
    Method { owner: Option<Symbol> },
    /// `slices.Equal`, or `slices.EqualFunc` with the equality of the elements when they need one.
    Slice(Option<Box<ElementEquality>>),
    /// `maps.Equal`, or `maps.EqualFunc` with the equality of the values when they need one.
    Map(Option<Box<ElementEquality>>),
}

/// The equality of the elements of a container, which Go `==` cannot test.
#[derive(Debug, Clone, PartialEq)]
pub struct ElementEquality {
    pub ty: Type,
    pub recipe: EqualityRecipe,
}

impl EqualityRecipe {
    /// The types whose `equals` method this equality calls, at any depth.
    pub fn owners(&self) -> Vec<&Symbol> {
        match self {
            Self::Operator | Self::Method { owner: None } => Vec::new(),
            Self::Method { owner: Some(owner) } => vec![owner],
            Self::Slice(element) | Self::Map(element) => element
                .as_ref()
                .map(|element| element.recipe.owners())
                .unwrap_or_default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FieldKey {
    Access(ExpressionId),
    Literal(ExpressionId, EcoString),
    Pattern(Span),
    Positional(ExpressionId, usize),
    PatternPosition(Span, usize),
}

impl FieldKey {
    fn file_id(&self) -> u32 {
        match self {
            Self::Access(expression)
            | Self::Literal(expression, _)
            | Self::Positional(expression, _) => expression.file_id(),
            Self::Pattern(span) | Self::PatternPosition(span, _) => span.file_id,
        }
    }
}

pub enum PatternPosition<'a> {
    Interface(&'a Type),
    Value,
}

#[derive(Debug, Clone, Default)]
pub struct PatternPositions {
    interfaces: FxHashMap<Span, Type>,
}

impl PatternPositions {
    pub fn insert_interface(&mut self, pattern: Span, interface: Type) {
        self.interfaces.insert(pattern, interface);
    }

    pub fn merge(&mut self, other: Self) {
        self.interfaces.extend(other.interfaces);
    }

    pub fn interfaces(&self) -> impl Iterator<Item = (&Span, &Type)> {
        self.interfaces.iter()
    }

    pub fn position(&self, pattern: Span) -> PatternPosition<'_> {
        match self.interfaces.get(&pattern) {
            Some(interface) => PatternPosition::Interface(interface),
            None => PatternPosition::Value,
        }
    }
}

#[derive(Debug, Clone)]
pub struct FieldSelection {
    pub owner: Symbol,
    pub declared_ty: Type,
    pub substitutions: SubstitutionMap,
}

impl FieldSelection {
    pub fn field_ty(&self) -> Type {
        substitute(&self.declared_ty, &self.substitutions)
    }
}

#[derive(Debug, Clone)]
pub struct CheckedStructLiteral {
    pub unset_fields: Vec<(EcoString, Type)>,
    pub via_alias: bool,
}

/// The records that the checker published for the bodies it checked, which no consumer changes.
#[derive(Debug, Clone, Default)]
pub struct CheckedBodies {
    files: FxHashMap<u32, FileBodies>,
}

#[derive(Debug, Clone, Default)]
struct FileBodies {
    uses: FxHashMap<ValueUseKey, CheckedValueUse>,
    callees: FxHashMap<ValueUseKey, CheckedCallee>,
    /// Keyed by the callee of a built-in operation that compares elements, or by an `assert` of an `equals` call.
    equalities: FxHashMap<ExpressionId, EqualityRecipe>,
    /// The unit value of each `if let` with no `else`, keyed by the `if let`.
    implicit_units: FxHashMap<ExpressionId, ExpressionId>,
    struct_literals: FxHashMap<ExpressionId, CheckedStructLiteral>,
    field_selections: FxHashMap<FieldKey, FieldSelection>,
    iterable_kinds: FxHashMap<ExpressionId, IterableKind>,
    range_kinds: FxHashMap<ExpressionId, RangeKind>,
    forwarded_failures: FxHashSet<ExpressionId>,
    receiver_generics: FxHashMap<ExpressionId, Vec<(EcoString, Vec<Type>)>>,
}

impl CheckedBodies {
    fn file(&self, file_id: u32) -> Option<&FileBodies> {
        self.files.get(&file_id)
    }

    fn file_mut(&mut self, file_id: u32) -> &mut FileBodies {
        self.files.entry(file_id).or_default()
    }

    pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
        self.file(key.expression().file_id())?.uses.get(key)
    }

    pub fn callee(&self, key: &ValueUseKey) -> Option<&CheckedCallee> {
        self.file(key.expression().file_id())?.callees.get(key)
    }

    pub fn equality(&self, expression: ExpressionId) -> Option<&EqualityRecipe> {
        self.file(expression.file_id())?.equalities.get(&expression)
    }

    pub fn callees(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedCallee)> {
        self.files.values().flat_map(|file| file.callees.iter())
    }

    pub fn uses(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedValueUse)> {
        self.files.values().flat_map(|file| file.uses.iter())
    }

    fn field_selection(&self, key: &FieldKey) -> Option<&FieldSelection> {
        self.file(key.file_id())?.field_selections.get(key)
    }

    pub fn pattern_field(&self, name_span: Span) -> &FieldSelection {
        self.field_selection(&FieldKey::Pattern(name_span))
            .unwrap_or_else(|| {
                panic!("internal error: no checked field selection for the pattern field at {name_span:?}")
            })
    }

    pub fn variant_pattern_fields(&self, pattern_span: Span) -> Vec<&FieldSelection> {
        (0..)
            .map_while(|index| {
                self.field_selection(&FieldKey::PatternPosition(pattern_span, index))
            })
            .collect()
    }

    /// A lookup of the records for the occurrence `expression`, which does not check that `expression` belongs to these bodies.
    pub fn occurrence<'e>(&self, expression: &'e Expression) -> CheckedExpression<'e, '_> {
        CheckedExpression {
            expression,
            bodies: self,
        }
    }

    pub fn debug_lines(&self) -> Vec<String> {
        fn push<K: Debug, V: Debug>(
            lines: &mut Vec<String>,
            label: &str,
            entries: impl IntoIterator<Item = (K, V)>,
        ) {
            lines.extend(
                entries
                    .into_iter()
                    .map(|(key, value)| format!("{label} {key:?} {value:?}")),
            );
        }

        let mut lines = Vec::new();
        for file in self.files.values() {
            push(&mut lines, "use", &file.uses);
            push(&mut lines, "callee", &file.callees);
            push(&mut lines, "equality", &file.equalities);
            push(&mut lines, "implicit_unit", &file.implicit_units);
            push(&mut lines, "struct_literal", &file.struct_literals);
            push(&mut lines, "field_selection", &file.field_selections);
            push(&mut lines, "iterable_kind", &file.iterable_kinds);
            push(&mut lines, "range_kind", &file.range_kinds);
            push(
                &mut lines,
                "forwarded_failure",
                file.forwarded_failures.iter().map(|id| (id, ())),
            );
            push(&mut lines, "receiver_generics", &file.receiver_generics);
        }
        lines
    }
}

/// The records that the checker collects while it checks bodies, which only it changes before it publishes them.
#[derive(Debug, Clone, Default)]
pub struct CheckedBodiesBuilder {
    records: CheckedBodies,
}

impl CheckedBodiesBuilder {
    pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
        self.records.value_use(key)
    }

    /// Record `value_use` for `key`, which no other record names.
    pub fn insert_use(&mut self, key: ValueUseKey, value_use: CheckedValueUse) {
        insert_unique(
            &mut self.records.file_mut(key.expression().file_id()).uses,
            key,
            value_use,
        );
    }

    /// Record `callee` for `key`, which no other callee names.
    pub fn insert_callee(&mut self, key: ValueUseKey, callee: CheckedCallee) {
        insert_unique(
            &mut self.records.file_mut(key.expression().file_id()).callees,
            key,
            callee,
        );
    }

    /// Record the equality that the comparison `expression` tests with.
    pub fn insert_equality(&mut self, expression: ExpressionId, recipe: EqualityRecipe) {
        insert_unique(
            &mut self.records.file_mut(expression.file_id()).equalities,
            expression,
            recipe,
        );
    }

    /// Record `unit` as the value that the `if let` with no `else` `if_let` produces when its pattern does not match.
    pub fn insert_implicit_unit(&mut self, if_let: ExpressionId, unit: ExpressionId) {
        insert_unique(
            &mut self.records.file_mut(if_let.file_id()).implicit_units,
            if_let,
            unit,
        );
    }

    pub fn insert_struct_literal(&mut self, literal: ExpressionId, record: CheckedStructLiteral) {
        insert_unique(
            &mut self.records.file_mut(literal.file_id()).struct_literals,
            literal,
            record,
        );
    }

    pub fn insert_field_selection(&mut self, key: FieldKey, selection: FieldSelection) {
        insert_unique(
            &mut self.records.file_mut(key.file_id()).field_selections,
            key,
            selection,
        );
    }

    pub fn insert_iterable_kind(&mut self, for_loop: ExpressionId, kind: IterableKind) {
        insert_unique(
            &mut self.records.file_mut(for_loop.file_id()).iterable_kinds,
            for_loop,
            kind,
        );
    }

    pub fn insert_range_kind(&mut self, range: ExpressionId, kind: RangeKind) {
        insert_unique(
            &mut self.records.file_mut(range.file_id()).range_kinds,
            range,
            kind,
        );
    }

    pub fn insert_forwarded_failure_id(&mut self, operand: ExpressionId) {
        let inserted = self
            .records
            .file_mut(operand.file_id())
            .forwarded_failures
            .insert(operand);
        assert!(
            inserted,
            "internal error: two forwarded failures share the key {operand:?}"
        );
    }

    pub fn insert_receiver_generics(
        &mut self,
        impl_block: ExpressionId,
        generics: Vec<(EcoString, Vec<Type>)>,
    ) {
        insert_unique(
            &mut self
                .records
                .file_mut(impl_block.file_id())
                .receiver_generics,
            impl_block,
            generics,
        );
    }

    pub fn merge(&mut self, other: Self) {
        for (file_id, file) in other.records.files {
            match self.records.files.entry(file_id) {
                Entry::Vacant(entry) => {
                    entry.insert(file);
                }
                Entry::Occupied(mut entry) => {
                    let existing = mem::replace(entry.get_mut(), file);
                    self.merge_file(existing);
                }
            }
        }
    }

    fn merge_file(&mut self, other: FileBodies) {
        let FileBodies {
            uses,
            callees,
            equalities,
            implicit_units,
            struct_literals,
            field_selections,
            iterable_kinds,
            range_kinds,
            forwarded_failures,
            receiver_generics,
        } = other;
        for (key, value_use) in uses {
            self.insert_use(key, value_use);
        }
        for (key, callee) in callees {
            self.insert_callee(key, callee);
        }
        for (expression, recipe) in equalities {
            self.insert_equality(expression, recipe);
        }
        for (if_let, unit) in implicit_units {
            self.insert_implicit_unit(if_let, unit);
        }
        for (literal, record) in struct_literals {
            self.insert_struct_literal(literal, record);
        }
        for (key, selection) in field_selections {
            self.insert_field_selection(key, selection);
        }
        for (for_loop, kind) in iterable_kinds {
            self.insert_iterable_kind(for_loop, kind);
        }
        for (range, kind) in range_kinds {
            self.insert_range_kind(range, kind);
        }
        for operand in forwarded_failures {
            self.insert_forwarded_failure_id(operand);
        }
        for (impl_block, generics) in receiver_generics {
            self.insert_receiver_generics(impl_block, generics);
        }
    }

    /// The records collected so far.
    pub fn records(&self) -> &CheckedBodies {
        &self.records
    }

    /// The records as consumers receive them.
    pub fn publish(self) -> CheckedBodies {
        self.records
    }
}

fn insert_unique<K: Eq + Hash + Debug, V>(map: &mut FxHashMap<K, V>, key: K, value: V) {
    match map.entry(key) {
        Entry::Occupied(entry) => {
            panic!(
                "internal error: two records share the key {:?}",
                entry.key()
            )
        }
        Entry::Vacant(entry) => {
            entry.insert(value);
        }
    }
}

/// One expression occurrence with a lookup of the records the checker published for it.
#[derive(Clone, Copy)]
pub struct CheckedExpression<'e, 'a> {
    expression: &'e Expression,
    bodies: &'a CheckedBodies,
}

impl<'a> CheckedExpression<'_, 'a> {
    /// The adaptation that the checker decided for this value into its slot.
    pub fn value_use(&self) -> &'a CheckedValueUse {
        self.record(ValueUseKey::value(self.expression))
    }

    /// The operand of this cast, converted to the cast type.
    pub fn cast_operand(&self) -> &'a CheckedValueUse {
        self.record(ValueUseKey::cast_operand(self.expression.id()))
    }

    /// The error that a `?` on this operand returns, converted to the error slot of its function or `try` block.
    pub fn propagated_error(&self) -> Option<&'a CheckedValueUse> {
        self.bodies
            .value_use(&ValueUseKey::propagated_error(self.expression))
    }

    /// The reference change that this method receiver takes, as the checker recorded it.
    pub fn receiver_change(&self) -> Option<ReceiverCoercion> {
        match self.value_use().adaptation {
            Adaptation::Receiver(change) => Some(change),
            _ => None,
        }
    }

    /// The operation and type arguments that the checker selected for this callee.
    pub fn callee(&self) -> &'a CheckedCallee {
        self.expect(self.function_value(), format_args!("selected callee"))
    }

    /// The definition and type arguments of this function value, or None when the checker records none for it.
    pub fn function_value(&self) -> Option<&'a CheckedCallee> {
        self.bodies.callee(&ValueUseKey::value(self.expression))
    }

    /// The equality that this comparison tests with, as the checker selected it, or None when it selects none.
    pub fn equality(&self) -> Option<&'a EqualityRecipe> {
        self.bodies.equality(self.expression.id())
    }

    /// The unit value that this `if let` produces when its pattern does not match, or None when it has an `else`.
    pub fn implicit_unit(&self) -> Option<ExpressionId> {
        self.table()?
            .implicit_units
            .get(&self.expression.id())
            .copied()
    }

    pub fn receiver_generics(&self) -> &'a [(EcoString, Vec<Type>)] {
        self.expect(
            self.table()
                .and_then(|table| table.receiver_generics.get(&self.expression.id()))
                .map(Vec::as_slice),
            format_args!("checked receiver generics"),
        )
    }

    pub fn range_kind(&self) -> Option<RangeKind> {
        self.table()?
            .range_kinds
            .get(&self.expression.id())
            .copied()
    }

    pub fn forwards_failure(&self) -> bool {
        self.table()
            .is_some_and(|table| table.forwarded_failures.contains(&self.expression.id()))
    }

    pub fn iterable_kind(&self) -> IterableKind {
        *self.expect(
            self.table()
                .and_then(|table| table.iterable_kinds.get(&self.expression.id())),
            format_args!("checked iterable kind"),
        )
    }

    pub fn field_selection(&self) -> Option<&'a FieldSelection> {
        self.bodies
            .field_selection(&FieldKey::Access(self.expression.id()))
    }

    pub fn positional_field(&self, index: usize) -> &'a FieldSelection {
        self.expect(
            self.bodies
                .field_selection(&FieldKey::Positional(self.expression.id(), index)),
            format_args!("checked field selection for field {index}"),
        )
    }

    pub fn literal_field(&self, name: &str) -> &'a FieldSelection {
        self.expect(
            self.bodies
                .field_selection(&FieldKey::Literal(self.expression.id(), name.into())),
            format_args!("checked field selection for `{name}`"),
        )
    }

    pub fn struct_literal(&self) -> &'a CheckedStructLiteral {
        self.expect(
            self.table()
                .and_then(|table| table.struct_literals.get(&self.expression.id())),
            format_args!("checked struct literal"),
        )
    }

    fn table(&self) -> Option<&'a FileBodies> {
        self.bodies.file(self.expression.id().file_id())
    }

    fn record(&self, key: ValueUseKey) -> &'a CheckedValueUse {
        self.expect(
            self.bodies.value_use(&key),
            format_args!("checked value use"),
        )
    }

    fn expect<V>(&self, found: Option<V>, what: fmt::Arguments<'_>) -> V {
        found.unwrap_or_else(|| {
            panic!(
                "internal error: no {what} at {:?}",
                self.expression.get_span()
            )
        })
    }
}