]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir_ty/src/infer.rs
98baeed6f6b874fb82a92b49b29e2740635194fa
[rust.git] / crates / ra_hir_ty / src / infer.rs
1 //! Type inference, i.e. the process of walking through the code and determining
2 //! the type of each expression and pattern.
3 //!
4 //! For type inference, compare the implementations in rustc (the various
5 //! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and
6 //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for
7 //! inference here is the `infer` function, which infers the types of all
8 //! expressions in a given function.
9 //!
10 //! During inference, types (i.e. the `Ty` struct) can contain type 'variables'
11 //! which represent currently unknown types; as we walk through the expressions,
12 //! we might determine that certain variables need to be equal to each other, or
13 //! to certain types. To record this, we use the union-find implementation from
14 //! the `ena` crate, which is extracted from rustc.
15
16 use std::borrow::Cow;
17 use std::mem;
18 use std::ops::Index;
19 use std::sync::Arc;
20
21 use rustc_hash::FxHashMap;
22
23 use hir_def::{
24     body::Body,
25     data::{ConstData, FunctionData},
26     expr::{BindingAnnotation, ExprId, PatId},
27     path::{path, Path},
28     resolver::{HasResolver, Resolver, TypeNs},
29     type_ref::{Mutability, TypeRef},
30     AdtId, AssocItemId, DefWithBodyId, FunctionId, StructFieldId, TypeAliasId, VariantId,
31 };
32 use hir_expand::{diagnostics::DiagnosticSink, name::name};
33 use ra_arena::map::ArenaMap;
34 use ra_prof::profile;
35 use test_utils::tested_by;
36
37 use super::{
38     primitive::{FloatTy, IntTy},
39     traits::{Guidance, Obligation, ProjectionPredicate, Solution},
40     ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor,
41     TypeWalk, Uncertain,
42 };
43 use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic};
44
45 pub(crate) use unify::unify;
46
47 macro_rules! ty_app {
48     ($ctor:pat, $param:pat) => {
49         crate::Ty::Apply(crate::ApplicationTy { ctor: $ctor, parameters: $param })
50     };
51     ($ctor:pat) => {
52         ty_app!($ctor, _)
53     };
54 }
55
56 mod unify;
57 mod path;
58 mod expr;
59 mod pat;
60 mod coerce;
61
62 /// The entry point of type inference.
63 pub fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
64     let _p = profile("infer_query");
65     let resolver = def.resolver(db);
66     let mut ctx = InferenceContext::new(db, def, resolver);
67
68     match def {
69         DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
70         DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
71         DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)),
72     }
73
74     ctx.infer_body();
75
76     Arc::new(ctx.resolve_all())
77 }
78
79 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
80 enum ExprOrPatId {
81     ExprId(ExprId),
82     PatId(PatId),
83 }
84
85 impl_froms!(ExprOrPatId: ExprId, PatId);
86
87 /// Binding modes inferred for patterns.
88 /// https://doc.rust-lang.org/reference/patterns.html#binding-modes
89 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
90 enum BindingMode {
91     Move,
92     Ref(Mutability),
93 }
94
95 impl BindingMode {
96     pub fn convert(annotation: BindingAnnotation) -> BindingMode {
97         match annotation {
98             BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
99             BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared),
100             BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
101         }
102     }
103 }
104
105 impl Default for BindingMode {
106     fn default() -> Self {
107         BindingMode::Move
108     }
109 }
110
111 /// A mismatch between an expected and an inferred type.
112 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
113 pub struct TypeMismatch {
114     pub expected: Ty,
115     pub actual: Ty,
116 }
117
118 /// The result of type inference: A mapping from expressions and patterns to types.
119 #[derive(Clone, PartialEq, Eq, Debug, Default)]
120 pub struct InferenceResult {
121     /// For each method call expr, records the function it resolves to.
122     method_resolutions: FxHashMap<ExprId, FunctionId>,
123     /// For each field access expr, records the field it resolves to.
124     field_resolutions: FxHashMap<ExprId, StructFieldId>,
125     /// For each field in record literal, records the field it resolves to.
126     record_field_resolutions: FxHashMap<ExprId, StructFieldId>,
127     /// For each struct literal, records the variant it resolves to.
128     variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
129     /// For each associated item record what it resolves to
130     assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
131     diagnostics: Vec<InferenceDiagnostic>,
132     pub type_of_expr: ArenaMap<ExprId, Ty>,
133     pub type_of_pat: ArenaMap<PatId, Ty>,
134     pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>,
135 }
136
137 impl InferenceResult {
138     pub fn method_resolution(&self, expr: ExprId) -> Option<FunctionId> {
139         self.method_resolutions.get(&expr).copied()
140     }
141     pub fn field_resolution(&self, expr: ExprId) -> Option<StructFieldId> {
142         self.field_resolutions.get(&expr).copied()
143     }
144     pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructFieldId> {
145         self.record_field_resolutions.get(&expr).copied()
146     }
147     pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
148         self.variant_resolutions.get(&id.into()).copied()
149     }
150     pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
151         self.variant_resolutions.get(&id.into()).copied()
152     }
153     pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
154         self.assoc_resolutions.get(&id.into()).copied()
155     }
156     pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
157         self.assoc_resolutions.get(&id.into()).copied()
158     }
159     pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
160         self.type_mismatches.get(expr)
161     }
162     pub fn add_diagnostics(
163         &self,
164         db: &impl HirDatabase,
165         owner: FunctionId,
166         sink: &mut DiagnosticSink,
167     ) {
168         self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink))
169     }
170 }
171
172 impl Index<ExprId> for InferenceResult {
173     type Output = Ty;
174
175     fn index(&self, expr: ExprId) -> &Ty {
176         self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown)
177     }
178 }
179
180 impl Index<PatId> for InferenceResult {
181     type Output = Ty;
182
183     fn index(&self, pat: PatId) -> &Ty {
184         self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown)
185     }
186 }
187
188 /// The inference context contains all information needed during type inference.
189 #[derive(Clone, Debug)]
190 struct InferenceContext<'a, D: HirDatabase> {
191     db: &'a D,
192     owner: DefWithBodyId,
193     body: Arc<Body>,
194     resolver: Resolver,
195     table: unify::InferenceTable,
196     trait_env: Arc<TraitEnvironment>,
197     obligations: Vec<Obligation>,
198     result: InferenceResult,
199     /// The return type of the function being inferred.
200     return_ty: Ty,
201
202     /// Impls of `CoerceUnsized` used in coercion.
203     /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index
204     // FIXME: Use trait solver for this.
205     // Chalk seems unable to work well with builtin impl of `Unsize` now.
206     coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>,
207 }
208
209 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
210     fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self {
211         InferenceContext {
212             result: InferenceResult::default(),
213             table: unify::InferenceTable::new(),
214             obligations: Vec::default(),
215             return_ty: Ty::Unknown, // set in collect_fn_signature
216             trait_env: TraitEnvironment::lower(db, &resolver),
217             coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver),
218             db,
219             owner,
220             body: db.body(owner.into()),
221             resolver,
222         }
223     }
224
225     fn resolve_all(mut self) -> InferenceResult {
226         // FIXME resolve obligations as well (use Guidance if necessary)
227         let mut result = mem::replace(&mut self.result, InferenceResult::default());
228         for ty in result.type_of_expr.values_mut() {
229             let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown));
230             *ty = resolved;
231         }
232         for ty in result.type_of_pat.values_mut() {
233             let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown));
234             *ty = resolved;
235         }
236         result
237     }
238
239     fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
240         self.result.type_of_expr.insert(expr, ty);
241     }
242
243     fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId) {
244         self.result.method_resolutions.insert(expr, func);
245     }
246
247     fn write_field_resolution(&mut self, expr: ExprId, field: StructFieldId) {
248         self.result.field_resolutions.insert(expr, field);
249     }
250
251     fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
252         self.result.variant_resolutions.insert(id, variant);
253     }
254
255     fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
256         self.result.assoc_resolutions.insert(id, item.into());
257     }
258
259     fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
260         self.result.type_of_pat.insert(pat, ty);
261     }
262
263     fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
264         self.result.diagnostics.push(diagnostic);
265     }
266
267     fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
268         let ty = Ty::from_hir(
269             self.db,
270             // FIXME use right resolver for block
271             &self.resolver,
272             type_ref,
273         );
274         let ty = self.insert_type_vars(ty);
275         self.normalize_associated_types_in(ty)
276     }
277
278     /// Replaces `impl Trait` in `ty` by type variables and obligations for
279     /// those variables. This is done for function arguments when calling a
280     /// function, and for return types when inside the function body, i.e. in
281     /// the cases where the `impl Trait` is 'transparent'. In other cases, `impl
282     /// Trait` is represented by `Ty::Opaque`.
283     fn insert_vars_for_impl_trait(&mut self, ty: Ty) -> Ty {
284         ty.fold(&mut |ty| match ty {
285             Ty::Opaque(preds) => {
286                 tested_by!(insert_vars_for_impl_trait);
287                 let var = self.table.new_type_var();
288                 let var_subst = Substs::builder(1).push(var.clone()).build();
289                 self.obligations.extend(
290                     preds
291                         .iter()
292                         .map(|pred| pred.clone().subst_bound_vars(&var_subst))
293                         .filter_map(Obligation::from_predicate),
294                 );
295                 var
296             }
297             _ => ty,
298         })
299     }
300
301     /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
302     fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
303         match ty {
304             Ty::Unknown => self.table.new_type_var(),
305             Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => {
306                 self.table.new_integer_var()
307             }
308             Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => {
309                 self.table.new_float_var()
310             }
311             _ => ty,
312         }
313     }
314
315     fn insert_type_vars(&mut self, ty: Ty) -> Ty {
316         ty.fold(&mut |ty| self.insert_type_vars_shallow(ty))
317     }
318
319     fn resolve_obligations_as_possible(&mut self) {
320         let obligations = mem::replace(&mut self.obligations, Vec::new());
321         for obligation in obligations {
322             let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone());
323             let canonicalized = self.canonicalizer().canonicalize_obligation(in_env);
324             let solution = self
325                 .db
326                 .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone());
327
328             match solution {
329                 Some(Solution::Unique(substs)) => {
330                     canonicalized.apply_solution(self, substs.0);
331                 }
332                 Some(Solution::Ambig(Guidance::Definite(substs))) => {
333                     canonicalized.apply_solution(self, substs.0);
334                     self.obligations.push(obligation);
335                 }
336                 Some(_) => {
337                     // FIXME use this when trying to resolve everything at the end
338                     self.obligations.push(obligation);
339                 }
340                 None => {
341                     // FIXME obligation cannot be fulfilled => diagnostic
342                 }
343             };
344         }
345     }
346
347     fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
348         self.table.unify(ty1, ty2)
349     }
350
351     /// Resolves the type as far as currently possible, replacing type variables
352     /// by their known types. All types returned by the infer_* functions should
353     /// be resolved as far as possible, i.e. contain no type variables with
354     /// known type.
355     fn resolve_ty_as_possible(&mut self, ty: Ty) -> Ty {
356         self.resolve_obligations_as_possible();
357
358         self.table.resolve_ty_as_possible(ty)
359     }
360
361     fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> {
362         self.table.resolve_ty_shallow(ty)
363     }
364
365     fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
366         self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
367     }
368
369     fn resolve_associated_type_with_params(
370         &mut self,
371         inner_ty: Ty,
372         assoc_ty: Option<TypeAliasId>,
373         params: &[Ty],
374     ) -> Ty {
375         match assoc_ty {
376             Some(res_assoc_ty) => {
377                 let ty = self.table.new_type_var();
378                 let mut builder = Substs::build_for_def(self.db, res_assoc_ty).push(inner_ty);
379                 for ty in params {
380                     builder = builder.push(ty.clone());
381                 }
382
383                 let projection = ProjectionPredicate {
384                     ty: ty.clone(),
385                     projection_ty: ProjectionTy {
386                         associated_ty: res_assoc_ty,
387                         parameters: builder.build(),
388                     },
389                 };
390                 self.obligations.push(Obligation::Projection(projection));
391                 self.resolve_ty_as_possible(ty)
392             }
393             None => Ty::Unknown,
394         }
395     }
396
397     /// Recurses through the given type, normalizing associated types mentioned
398     /// in it by replacing them by type variables and registering obligations to
399     /// resolve later. This should be done once for every type we get from some
400     /// type annotation (e.g. from a let type annotation, field type or function
401     /// call). `make_ty` handles this already, but e.g. for field types we need
402     /// to do it as well.
403     fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
404         let ty = self.resolve_ty_as_possible(ty);
405         ty.fold(&mut |ty| match ty {
406             Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty),
407             _ => ty,
408         })
409     }
410
411     fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty {
412         let var = self.table.new_type_var();
413         let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() };
414         let obligation = Obligation::Projection(predicate);
415         self.obligations.push(obligation);
416         var
417     }
418
419     fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
420         let path = match path {
421             Some(path) => path,
422             None => return (Ty::Unknown, None),
423         };
424         let resolver = &self.resolver;
425         // FIXME: this should resolve assoc items as well, see this example:
426         // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
427         match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
428             Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
429                 let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into());
430                 let ty = self.db.ty(strukt.into());
431                 let ty = self.insert_type_vars(ty.apply_substs(substs));
432                 (ty, Some(strukt.into()))
433             }
434             Some(TypeNs::EnumVariantId(var)) => {
435                 let substs = Ty::substs_from_path(self.db, resolver, path, var.into());
436                 let ty = self.db.ty(var.parent.into());
437                 let ty = self.insert_type_vars(ty.apply_substs(substs));
438                 (ty, Some(var.into()))
439             }
440             Some(_) | None => (Ty::Unknown, None),
441         }
442     }
443
444     fn collect_const(&mut self, data: &ConstData) {
445         self.return_ty = self.make_ty(&data.type_ref);
446     }
447
448     fn collect_fn(&mut self, data: &FunctionData) {
449         let body = Arc::clone(&self.body); // avoid borrow checker problem
450         for (type_ref, pat) in data.params.iter().zip(body.params.iter()) {
451             let ty = self.make_ty(type_ref);
452
453             self.infer_pat(*pat, &ty, BindingMode::default());
454         }
455         let return_ty = self.make_ty(&data.ret_type);
456         self.return_ty = self.insert_vars_for_impl_trait(return_ty);
457     }
458
459     fn infer_body(&mut self) {
460         self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
461     }
462
463     fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
464         let path = path![std::iter::IntoIterator];
465         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
466         self.db.trait_data(trait_).associated_type_by_name(&name![Item])
467     }
468
469     fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
470         let path = path![std::ops::Try];
471         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
472         self.db.trait_data(trait_).associated_type_by_name(&name![Ok])
473     }
474
475     fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
476         let path = path![std::ops::Neg];
477         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
478         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
479     }
480
481     fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
482         let path = path![std::ops::Not];
483         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
484         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
485     }
486
487     fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
488         let path = path![std::future::Future];
489         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
490         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
491     }
492
493     fn resolve_boxed_box(&self) -> Option<AdtId> {
494         let path = path![std::boxed::Box];
495         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
496         Some(struct_.into())
497     }
498
499     fn resolve_range_full(&self) -> Option<AdtId> {
500         let path = path![std::ops::RangeFull];
501         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
502         Some(struct_.into())
503     }
504
505     fn resolve_range(&self) -> Option<AdtId> {
506         let path = path![std::ops::Range];
507         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
508         Some(struct_.into())
509     }
510
511     fn resolve_range_inclusive(&self) -> Option<AdtId> {
512         let path = path![std::ops::RangeInclusive];
513         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
514         Some(struct_.into())
515     }
516
517     fn resolve_range_from(&self) -> Option<AdtId> {
518         let path = path![std::ops::RangeFrom];
519         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
520         Some(struct_.into())
521     }
522
523     fn resolve_range_to(&self) -> Option<AdtId> {
524         let path = path![std::ops::RangeTo];
525         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
526         Some(struct_.into())
527     }
528
529     fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
530         let path = path![std::ops::RangeToInclusive];
531         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
532         Some(struct_.into())
533     }
534
535     fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
536         let path = path![std::ops::Index];
537         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
538         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
539     }
540 }
541
542 /// The kinds of placeholders we need during type inference. There's separate
543 /// values for general types, and for integer and float variables. The latter
544 /// two are used for inference of literal values (e.g. `100` could be one of
545 /// several integer types).
546 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
547 pub enum InferTy {
548     TypeVar(unify::TypeVarId),
549     IntVar(unify::TypeVarId),
550     FloatVar(unify::TypeVarId),
551     MaybeNeverTypeVar(unify::TypeVarId),
552 }
553
554 impl InferTy {
555     fn to_inner(self) -> unify::TypeVarId {
556         match self {
557             InferTy::TypeVar(ty)
558             | InferTy::IntVar(ty)
559             | InferTy::FloatVar(ty)
560             | InferTy::MaybeNeverTypeVar(ty) => ty,
561         }
562     }
563
564     fn fallback_value(self) -> Ty {
565         match self {
566             InferTy::TypeVar(..) => Ty::Unknown,
567             InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))),
568             InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))),
569             InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never),
570         }
571     }
572 }
573
574 /// When inferring an expression, we propagate downward whatever type hint we
575 /// are able in the form of an `Expectation`.
576 #[derive(Clone, PartialEq, Eq, Debug)]
577 struct Expectation {
578     ty: Ty,
579     // FIXME: In some cases, we need to be aware whether the expectation is that
580     // the type match exactly what we passed, or whether it just needs to be
581     // coercible to the expected type. See Expectation::rvalue_hint in rustc.
582 }
583
584 impl Expectation {
585     /// The expectation that the type of the expression needs to equal the given
586     /// type.
587     fn has_type(ty: Ty) -> Self {
588         Expectation { ty }
589     }
590
591     /// This expresses no expectation on the type.
592     fn none() -> Self {
593         Expectation { ty: Ty::Unknown }
594     }
595 }
596
597 mod diagnostics {
598     use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup};
599     use hir_expand::diagnostics::DiagnosticSink;
600
601     use crate::{db::HirDatabase, diagnostics::NoSuchField};
602
603     #[derive(Debug, PartialEq, Eq, Clone)]
604     pub(super) enum InferenceDiagnostic {
605         NoSuchField { expr: ExprId, field: usize },
606     }
607
608     impl InferenceDiagnostic {
609         pub(super) fn add_to(
610             &self,
611             db: &impl HirDatabase,
612             owner: FunctionId,
613             sink: &mut DiagnosticSink,
614         ) {
615             match self {
616                 InferenceDiagnostic::NoSuchField { expr, field } => {
617                     let file = owner.lookup(db).source(db).file_id;
618                     let (_, source_map) = db.body_with_source_map(owner.into());
619                     let field = source_map.field_syntax(*expr, *field);
620                     sink.push(NoSuchField { file, field })
621                 }
622             }
623         }
624     }
625 }