Skip to main content

lisette_syntax/program/
checked.rs

1use rustc_hash::{FxHashMap, FxHashSet};
2use std::collections::hash_map::Entry;
3use std::fmt::{self, Debug};
4use std::hash::Hash;
5use std::mem;
6
7use super::{
8    CalleeName, ConformanceWitness, InterfaceRequirement, NativeOperation, NativeTypeKind,
9    ReceiverCoercion,
10};
11use crate::EcoString;
12use crate::ast::{Expression, ExpressionId, Span};
13use crate::types::{IterableKind, RangeKind, SubstitutionMap, Symbol, Type, substitute};
14
15/// Names one value use: the occurrence that produces the value, and its role.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct ValueUseKey {
18    expression: ExpressionId,
19    role: ValueUseRole,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23enum ValueUseRole {
24    Value,
25    PropagatedError,
26    CastOperand,
27}
28
29impl ValueUseKey {
30    /// The value of `expression` where it goes into its slot.
31    pub fn value(expression: &Expression) -> Self {
32        Self::value_id(expression.id())
33    }
34
35    pub fn value_id(expression: ExpressionId) -> Self {
36        Self {
37            expression,
38            role: ValueUseRole::Value,
39        }
40    }
41
42    /// The error that the `?` applied to `operand` returns from its function or `try` block.
43    pub fn propagated_error(operand: &Expression) -> Self {
44        Self {
45            expression: operand.id(),
46            role: ValueUseRole::PropagatedError,
47        }
48    }
49
50    /// The occurrence that produces the value.
51    pub fn expression(&self) -> ExpressionId {
52        self.expression
53    }
54
55    /// The operand of the cast with the occurrence `cast`, converted to the cast type.
56    pub fn cast_operand(cast: ExpressionId) -> Self {
57        Self {
58            expression: cast,
59            role: ValueUseRole::CastOperand,
60        }
61    }
62}
63
64/// How a value of its source type becomes a value of its slot type.
65#[derive(Debug, Clone)]
66pub enum Adaptation {
67    Identity,
68    /// The children that produce the value adapt it to the slot type.
69    Delegated {
70        /// Whether a child that produces the value changes its type.
71        converts: bool,
72    },
73    Interface(Box<InterfaceConversion>),
74    /// A Go interface value where an `Option` is expected.
75    ImplicitSome {
76        payload: Box<Adaptation>,
77    },
78    Newtype,
79    Tuple(Vec<Adaptation>),
80    Array(Box<Adaptation>),
81    /// A method receiver that takes its address or reads through its reference.
82    Receiver(ReceiverCoercion),
83}
84
85impl Adaptation {
86    /// Whether the adapted value has another type than the value before adaptation.
87    pub fn converts(&self) -> bool {
88        match self {
89            Self::Identity => false,
90            Self::Delegated { converts } => *converts,
91            Self::Interface(_)
92            | Self::Newtype
93            | Self::ImplicitSome { .. }
94            | Self::Tuple(_)
95            | Self::Array(_)
96            | Self::Receiver(_) => true,
97        }
98    }
99}
100
101/// A value converted to an interface type, with the conformance the checker selected.
102#[derive(Debug, Clone)]
103pub struct InterfaceConversion {
104    pub source: Type,
105    pub target: Type,
106    pub source_shape: Type,
107    pub target_interface: Option<Type>,
108    /// Absent when the target requires no method, or when the source is no named type or type parameter.
109    pub witness: Option<ConformanceWitness>,
110}
111
112/// The slot type of one value use, and the adaptation into it.
113#[derive(Debug, Clone)]
114pub struct CheckedValueUse {
115    pub slot: Type,
116    pub adaptation: Adaptation,
117    /// Where the value is written, for diagnostics.
118    pub span: Span,
119}
120
121/// What a callee runs and with which type arguments, as the checker selected it.
122#[derive(Debug, Clone, PartialEq)]
123pub struct CheckedCallee {
124    pub operation: CallOperation,
125    /// The declaration that the callee names, with an aliased owner type replaced by its target.
126    pub name: Option<CalleeName>,
127    /// The solved type arguments of a generic callee, in the order of its type parameters.
128    pub type_arguments: SubstitutionMap,
129    /// Whether the call must write into storage that no other name sees, as slice growth must.
130    pub copies_storage: bool,
131    /// Whether the callee holds the receiver that the first parameter of its declaration takes, as `x.m(a)` does.
132    pub binds_receiver: bool,
133    pub interface_method: Option<Box<InterfaceRequirement>>,
134    /// Where the callee is written, for diagnostics.
135    pub span: Span,
136}
137
138impl CheckedCallee {
139    pub fn definition(&self) -> Option<&str> {
140        self.name
141            .as_ref()
142            .and_then(CalleeName::definition)
143            .map(Symbol::as_str)
144    }
145
146    pub fn method(&self) -> Option<&super::MethodName> {
147        self.name.as_ref().and_then(CalleeName::method)
148    }
149
150    pub fn interface_requirement(&self) -> Option<&InterfaceRequirement> {
151        match &self.operation {
152            CallOperation::BoundMethod { requirement, .. } => Some(requirement),
153            _ => self.interface_method.as_deref(),
154        }
155    }
156
157    /// The built-in method this callee runs, if any.
158    pub fn native(&self) -> Option<NativeOperation<'_>> {
159        match &self.operation {
160            CallOperation::Native { kind, method } => Some(NativeOperation::new(*kind, method)),
161            _ => None,
162        }
163    }
164
165    /// The index of the declared parameter that the first argument of the call fills.
166    pub fn receiver_offset(&self) -> usize {
167        usize::from(self.binds_receiver)
168    }
169
170    /// The type argument of a callee whose first type parameter decides its result.
171    pub fn first_type_argument(&self) -> &Type {
172        self.type_arguments
173            .types()
174            .next()
175            .expect("internal error: the checker records the type argument of this callee")
176    }
177}
178
179/// The function, method or built-in operation that a callee selects.
180#[derive(Debug, Clone, PartialEq)]
181pub enum CallOperation {
182    /// A function value, such as a local, a field, a closure or a declared function.
183    Function,
184    /// A method that lowers to a free function, called on its receiver.
185    UfcsFunction,
186    /// A receiver method called through its type, with the receiver as the first argument.
187    ReceiverMethod {
188        is_public: bool,
189    },
190    /// A method that a type parameter takes from the bound that declares it.
191    BoundMethod {
192        bound: Type,
193        requirement: Box<InterfaceRequirement>,
194    },
195    /// A method of a built-in type.
196    Native {
197        kind: NativeTypeKind,
198        method: EcoString,
199    },
200    /// A constructor of a built-in type.
201    NativeConstructor {
202        kind: NativeTypeKind,
203        method: EcoString,
204    },
205    TupleStructConstructor {
206        owner: Symbol,
207        is_newtype: bool,
208    },
209    AssertType,
210    Zero,
211    TypeConversion,
212    /// No operation, because inference rejected the call before it could select one.
213    Unavailable,
214}
215
216/// How a program tests two values of one type for equality, as the checker selected it.
217#[derive(Debug, Clone, PartialEq)]
218pub enum EqualityRecipe {
219    /// Go `==`.
220    Operator,
221    /// The `equals` method of `owner`, or of a type parameter whose bound declares it when `owner` is absent.
222    Method { owner: Option<Symbol> },
223    /// `slices.Equal`, or `slices.EqualFunc` with the equality of the elements when they need one.
224    Slice(Option<Box<ElementEquality>>),
225    /// `maps.Equal`, or `maps.EqualFunc` with the equality of the values when they need one.
226    Map(Option<Box<ElementEquality>>),
227}
228
229/// The equality of the elements of a container, which Go `==` cannot test.
230#[derive(Debug, Clone, PartialEq)]
231pub struct ElementEquality {
232    pub ty: Type,
233    pub recipe: EqualityRecipe,
234}
235
236impl EqualityRecipe {
237    /// The types whose `equals` method this equality calls, at any depth.
238    pub fn owners(&self) -> Vec<&Symbol> {
239        match self {
240            Self::Operator | Self::Method { owner: None } => Vec::new(),
241            Self::Method { owner: Some(owner) } => vec![owner],
242            Self::Slice(element) | Self::Map(element) => element
243                .as_ref()
244                .map(|element| element.recipe.owners())
245                .unwrap_or_default(),
246        }
247    }
248}
249
250#[derive(Debug, Clone, PartialEq, Eq, Hash)]
251pub enum FieldKey {
252    Access(ExpressionId),
253    Literal(ExpressionId, EcoString),
254    Pattern(Span),
255    Positional(ExpressionId, usize),
256    PatternPosition(Span, usize),
257}
258
259impl FieldKey {
260    fn file_id(&self) -> u32 {
261        match self {
262            Self::Access(expression)
263            | Self::Literal(expression, _)
264            | Self::Positional(expression, _) => expression.file_id(),
265            Self::Pattern(span) | Self::PatternPosition(span, _) => span.file_id,
266        }
267    }
268}
269
270pub enum PatternPosition<'a> {
271    Interface(&'a Type),
272    Value,
273}
274
275#[derive(Debug, Clone, Default)]
276pub struct PatternPositions {
277    interfaces: FxHashMap<Span, Type>,
278}
279
280impl PatternPositions {
281    pub fn insert_interface(&mut self, pattern: Span, interface: Type) {
282        self.interfaces.insert(pattern, interface);
283    }
284
285    pub fn merge(&mut self, other: Self) {
286        self.interfaces.extend(other.interfaces);
287    }
288
289    pub fn interfaces(&self) -> impl Iterator<Item = (&Span, &Type)> {
290        self.interfaces.iter()
291    }
292
293    pub fn position(&self, pattern: Span) -> PatternPosition<'_> {
294        match self.interfaces.get(&pattern) {
295            Some(interface) => PatternPosition::Interface(interface),
296            None => PatternPosition::Value,
297        }
298    }
299}
300
301#[derive(Debug, Clone)]
302pub struct FieldSelection {
303    pub owner: Symbol,
304    pub declared_ty: Type,
305    pub substitutions: SubstitutionMap,
306}
307
308impl FieldSelection {
309    pub fn field_ty(&self) -> Type {
310        substitute(&self.declared_ty, &self.substitutions)
311    }
312}
313
314#[derive(Debug, Clone)]
315pub struct CheckedStructLiteral {
316    pub unset_fields: Vec<(EcoString, Type)>,
317    pub via_alias: bool,
318}
319
320/// The records that the checker published for the bodies it checked, which no consumer changes.
321#[derive(Debug, Clone, Default)]
322pub struct CheckedBodies {
323    files: FxHashMap<u32, FileBodies>,
324}
325
326#[derive(Debug, Clone, Default)]
327struct FileBodies {
328    uses: FxHashMap<ValueUseKey, CheckedValueUse>,
329    callees: FxHashMap<ValueUseKey, CheckedCallee>,
330    /// Keyed by the callee of a built-in operation that compares elements, or by an `assert` of an `equals` call.
331    equalities: FxHashMap<ExpressionId, EqualityRecipe>,
332    /// The unit value of each `if let` with no `else`, keyed by the `if let`.
333    implicit_units: FxHashMap<ExpressionId, ExpressionId>,
334    struct_literals: FxHashMap<ExpressionId, CheckedStructLiteral>,
335    field_selections: FxHashMap<FieldKey, FieldSelection>,
336    iterable_kinds: FxHashMap<ExpressionId, IterableKind>,
337    range_kinds: FxHashMap<ExpressionId, RangeKind>,
338    forwarded_failures: FxHashSet<ExpressionId>,
339    receiver_generics: FxHashMap<ExpressionId, Vec<(EcoString, Vec<Type>)>>,
340}
341
342impl CheckedBodies {
343    fn file(&self, file_id: u32) -> Option<&FileBodies> {
344        self.files.get(&file_id)
345    }
346
347    fn file_mut(&mut self, file_id: u32) -> &mut FileBodies {
348        self.files.entry(file_id).or_default()
349    }
350
351    pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
352        self.file(key.expression().file_id())?.uses.get(key)
353    }
354
355    pub fn callee(&self, key: &ValueUseKey) -> Option<&CheckedCallee> {
356        self.file(key.expression().file_id())?.callees.get(key)
357    }
358
359    pub fn equality(&self, expression: ExpressionId) -> Option<&EqualityRecipe> {
360        self.file(expression.file_id())?.equalities.get(&expression)
361    }
362
363    pub fn callees(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedCallee)> {
364        self.files.values().flat_map(|file| file.callees.iter())
365    }
366
367    pub fn uses(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedValueUse)> {
368        self.files.values().flat_map(|file| file.uses.iter())
369    }
370
371    fn field_selection(&self, key: &FieldKey) -> Option<&FieldSelection> {
372        self.file(key.file_id())?.field_selections.get(key)
373    }
374
375    pub fn pattern_field(&self, name_span: Span) -> &FieldSelection {
376        self.field_selection(&FieldKey::Pattern(name_span))
377            .unwrap_or_else(|| {
378                panic!("internal error: no checked field selection for the pattern field at {name_span:?}")
379            })
380    }
381
382    pub fn variant_pattern_fields(&self, pattern_span: Span) -> Vec<&FieldSelection> {
383        (0..)
384            .map_while(|index| {
385                self.field_selection(&FieldKey::PatternPosition(pattern_span, index))
386            })
387            .collect()
388    }
389
390    /// A lookup of the records for the occurrence `expression`, which does not check that `expression` belongs to these bodies.
391    pub fn occurrence<'e>(&self, expression: &'e Expression) -> CheckedExpression<'e, '_> {
392        CheckedExpression {
393            expression,
394            bodies: self,
395        }
396    }
397
398    pub fn debug_lines(&self) -> Vec<String> {
399        fn push<K: Debug, V: Debug>(
400            lines: &mut Vec<String>,
401            label: &str,
402            entries: impl IntoIterator<Item = (K, V)>,
403        ) {
404            lines.extend(
405                entries
406                    .into_iter()
407                    .map(|(key, value)| format!("{label} {key:?} {value:?}")),
408            );
409        }
410
411        let mut lines = Vec::new();
412        for file in self.files.values() {
413            push(&mut lines, "use", &file.uses);
414            push(&mut lines, "callee", &file.callees);
415            push(&mut lines, "equality", &file.equalities);
416            push(&mut lines, "implicit_unit", &file.implicit_units);
417            push(&mut lines, "struct_literal", &file.struct_literals);
418            push(&mut lines, "field_selection", &file.field_selections);
419            push(&mut lines, "iterable_kind", &file.iterable_kinds);
420            push(&mut lines, "range_kind", &file.range_kinds);
421            push(
422                &mut lines,
423                "forwarded_failure",
424                file.forwarded_failures.iter().map(|id| (id, ())),
425            );
426            push(&mut lines, "receiver_generics", &file.receiver_generics);
427        }
428        lines
429    }
430}
431
432/// The records that the checker collects while it checks bodies, which only it changes before it publishes them.
433#[derive(Debug, Clone, Default)]
434pub struct CheckedBodiesBuilder {
435    records: CheckedBodies,
436}
437
438impl CheckedBodiesBuilder {
439    pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
440        self.records.value_use(key)
441    }
442
443    /// Record `value_use` for `key`, which no other record names.
444    pub fn insert_use(&mut self, key: ValueUseKey, value_use: CheckedValueUse) {
445        insert_unique(
446            &mut self.records.file_mut(key.expression().file_id()).uses,
447            key,
448            value_use,
449        );
450    }
451
452    /// Record `callee` for `key`, which no other callee names.
453    pub fn insert_callee(&mut self, key: ValueUseKey, callee: CheckedCallee) {
454        insert_unique(
455            &mut self.records.file_mut(key.expression().file_id()).callees,
456            key,
457            callee,
458        );
459    }
460
461    /// Record the equality that the comparison `expression` tests with.
462    pub fn insert_equality(&mut self, expression: ExpressionId, recipe: EqualityRecipe) {
463        insert_unique(
464            &mut self.records.file_mut(expression.file_id()).equalities,
465            expression,
466            recipe,
467        );
468    }
469
470    /// Record `unit` as the value that the `if let` with no `else` `if_let` produces when its pattern does not match.
471    pub fn insert_implicit_unit(&mut self, if_let: ExpressionId, unit: ExpressionId) {
472        insert_unique(
473            &mut self.records.file_mut(if_let.file_id()).implicit_units,
474            if_let,
475            unit,
476        );
477    }
478
479    pub fn insert_struct_literal(&mut self, literal: ExpressionId, record: CheckedStructLiteral) {
480        insert_unique(
481            &mut self.records.file_mut(literal.file_id()).struct_literals,
482            literal,
483            record,
484        );
485    }
486
487    pub fn insert_field_selection(&mut self, key: FieldKey, selection: FieldSelection) {
488        insert_unique(
489            &mut self.records.file_mut(key.file_id()).field_selections,
490            key,
491            selection,
492        );
493    }
494
495    pub fn insert_iterable_kind(&mut self, for_loop: ExpressionId, kind: IterableKind) {
496        insert_unique(
497            &mut self.records.file_mut(for_loop.file_id()).iterable_kinds,
498            for_loop,
499            kind,
500        );
501    }
502
503    pub fn insert_range_kind(&mut self, range: ExpressionId, kind: RangeKind) {
504        insert_unique(
505            &mut self.records.file_mut(range.file_id()).range_kinds,
506            range,
507            kind,
508        );
509    }
510
511    pub fn insert_forwarded_failure_id(&mut self, operand: ExpressionId) {
512        let inserted = self
513            .records
514            .file_mut(operand.file_id())
515            .forwarded_failures
516            .insert(operand);
517        assert!(
518            inserted,
519            "internal error: two forwarded failures share the key {operand:?}"
520        );
521    }
522
523    pub fn insert_receiver_generics(
524        &mut self,
525        impl_block: ExpressionId,
526        generics: Vec<(EcoString, Vec<Type>)>,
527    ) {
528        insert_unique(
529            &mut self
530                .records
531                .file_mut(impl_block.file_id())
532                .receiver_generics,
533            impl_block,
534            generics,
535        );
536    }
537
538    pub fn merge(&mut self, other: Self) {
539        for (file_id, file) in other.records.files {
540            match self.records.files.entry(file_id) {
541                Entry::Vacant(entry) => {
542                    entry.insert(file);
543                }
544                Entry::Occupied(mut entry) => {
545                    let existing = mem::replace(entry.get_mut(), file);
546                    self.merge_file(existing);
547                }
548            }
549        }
550    }
551
552    fn merge_file(&mut self, other: FileBodies) {
553        let FileBodies {
554            uses,
555            callees,
556            equalities,
557            implicit_units,
558            struct_literals,
559            field_selections,
560            iterable_kinds,
561            range_kinds,
562            forwarded_failures,
563            receiver_generics,
564        } = other;
565        for (key, value_use) in uses {
566            self.insert_use(key, value_use);
567        }
568        for (key, callee) in callees {
569            self.insert_callee(key, callee);
570        }
571        for (expression, recipe) in equalities {
572            self.insert_equality(expression, recipe);
573        }
574        for (if_let, unit) in implicit_units {
575            self.insert_implicit_unit(if_let, unit);
576        }
577        for (literal, record) in struct_literals {
578            self.insert_struct_literal(literal, record);
579        }
580        for (key, selection) in field_selections {
581            self.insert_field_selection(key, selection);
582        }
583        for (for_loop, kind) in iterable_kinds {
584            self.insert_iterable_kind(for_loop, kind);
585        }
586        for (range, kind) in range_kinds {
587            self.insert_range_kind(range, kind);
588        }
589        for operand in forwarded_failures {
590            self.insert_forwarded_failure_id(operand);
591        }
592        for (impl_block, generics) in receiver_generics {
593            self.insert_receiver_generics(impl_block, generics);
594        }
595    }
596
597    /// The records collected so far.
598    pub fn records(&self) -> &CheckedBodies {
599        &self.records
600    }
601
602    /// The records as consumers receive them.
603    pub fn publish(self) -> CheckedBodies {
604        self.records
605    }
606}
607
608fn insert_unique<K: Eq + Hash + Debug, V>(map: &mut FxHashMap<K, V>, key: K, value: V) {
609    match map.entry(key) {
610        Entry::Occupied(entry) => {
611            panic!(
612                "internal error: two records share the key {:?}",
613                entry.key()
614            )
615        }
616        Entry::Vacant(entry) => {
617            entry.insert(value);
618        }
619    }
620}
621
622/// One expression occurrence with a lookup of the records the checker published for it.
623#[derive(Clone, Copy)]
624pub struct CheckedExpression<'e, 'a> {
625    expression: &'e Expression,
626    bodies: &'a CheckedBodies,
627}
628
629impl<'a> CheckedExpression<'_, 'a> {
630    /// The adaptation that the checker decided for this value into its slot.
631    pub fn value_use(&self) -> &'a CheckedValueUse {
632        self.record(ValueUseKey::value(self.expression))
633    }
634
635    /// The operand of this cast, converted to the cast type.
636    pub fn cast_operand(&self) -> &'a CheckedValueUse {
637        self.record(ValueUseKey::cast_operand(self.expression.id()))
638    }
639
640    /// The error that a `?` on this operand returns, converted to the error slot of its function or `try` block.
641    pub fn propagated_error(&self) -> Option<&'a CheckedValueUse> {
642        self.bodies
643            .value_use(&ValueUseKey::propagated_error(self.expression))
644    }
645
646    /// The reference change that this method receiver takes, as the checker recorded it.
647    pub fn receiver_change(&self) -> Option<ReceiverCoercion> {
648        match self.value_use().adaptation {
649            Adaptation::Receiver(change) => Some(change),
650            _ => None,
651        }
652    }
653
654    /// The operation and type arguments that the checker selected for this callee.
655    pub fn callee(&self) -> &'a CheckedCallee {
656        self.expect(self.function_value(), format_args!("selected callee"))
657    }
658
659    /// The definition and type arguments of this function value, or None when the checker records none for it.
660    pub fn function_value(&self) -> Option<&'a CheckedCallee> {
661        self.bodies.callee(&ValueUseKey::value(self.expression))
662    }
663
664    /// The equality that this comparison tests with, as the checker selected it, or None when it selects none.
665    pub fn equality(&self) -> Option<&'a EqualityRecipe> {
666        self.bodies.equality(self.expression.id())
667    }
668
669    /// The unit value that this `if let` produces when its pattern does not match, or None when it has an `else`.
670    pub fn implicit_unit(&self) -> Option<ExpressionId> {
671        self.table()?
672            .implicit_units
673            .get(&self.expression.id())
674            .copied()
675    }
676
677    pub fn receiver_generics(&self) -> &'a [(EcoString, Vec<Type>)] {
678        self.expect(
679            self.table()
680                .and_then(|table| table.receiver_generics.get(&self.expression.id()))
681                .map(Vec::as_slice),
682            format_args!("checked receiver generics"),
683        )
684    }
685
686    pub fn range_kind(&self) -> Option<RangeKind> {
687        self.table()?
688            .range_kinds
689            .get(&self.expression.id())
690            .copied()
691    }
692
693    pub fn forwards_failure(&self) -> bool {
694        self.table()
695            .is_some_and(|table| table.forwarded_failures.contains(&self.expression.id()))
696    }
697
698    pub fn iterable_kind(&self) -> IterableKind {
699        *self.expect(
700            self.table()
701                .and_then(|table| table.iterable_kinds.get(&self.expression.id())),
702            format_args!("checked iterable kind"),
703        )
704    }
705
706    pub fn field_selection(&self) -> Option<&'a FieldSelection> {
707        self.bodies
708            .field_selection(&FieldKey::Access(self.expression.id()))
709    }
710
711    pub fn positional_field(&self, index: usize) -> &'a FieldSelection {
712        self.expect(
713            self.bodies
714                .field_selection(&FieldKey::Positional(self.expression.id(), index)),
715            format_args!("checked field selection for field {index}"),
716        )
717    }
718
719    pub fn literal_field(&self, name: &str) -> &'a FieldSelection {
720        self.expect(
721            self.bodies
722                .field_selection(&FieldKey::Literal(self.expression.id(), name.into())),
723            format_args!("checked field selection for `{name}`"),
724        )
725    }
726
727    pub fn struct_literal(&self) -> &'a CheckedStructLiteral {
728        self.expect(
729            self.table()
730                .and_then(|table| table.struct_literals.get(&self.expression.id())),
731            format_args!("checked struct literal"),
732        )
733    }
734
735    fn table(&self) -> Option<&'a FileBodies> {
736        self.bodies.file(self.expression.id().file_id())
737    }
738
739    fn record(&self, key: ValueUseKey) -> &'a CheckedValueUse {
740        self.expect(
741            self.bodies.value_use(&key),
742            format_args!("checked value use"),
743        )
744    }
745
746    fn expect<V>(&self, found: Option<V>, what: fmt::Arguments<'_>) -> V {
747        found.unwrap_or_else(|| {
748            panic!(
749                "internal error: no {what} at {:?}",
750                self.expression.get_span()
751            )
752        })
753    }
754}