]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir_ty/src/infer.rs
bbbc391c4f561bbb148e2be1fcb0cd6dcd2e0c39
[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 builder = Substs::build_for_def(self.db, res_assoc_ty)
379                     .push(inner_ty)
380                     .fill(params.iter().cloned());
381                 let projection = ProjectionPredicate {
382                     ty: ty.clone(),
383                     projection_ty: ProjectionTy {
384                         associated_ty: res_assoc_ty,
385                         parameters: builder.build(),
386                     },
387                 };
388                 self.obligations.push(Obligation::Projection(projection));
389                 self.resolve_ty_as_possible(ty)
390             }
391             None => Ty::Unknown,
392         }
393     }
394
395     /// Recurses through the given type, normalizing associated types mentioned
396     /// in it by replacing them by type variables and registering obligations to
397     /// resolve later. This should be done once for every type we get from some
398     /// type annotation (e.g. from a let type annotation, field type or function
399     /// call). `make_ty` handles this already, but e.g. for field types we need
400     /// to do it as well.
401     fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
402         let ty = self.resolve_ty_as_possible(ty);
403         ty.fold(&mut |ty| match ty {
404             Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty),
405             _ => ty,
406         })
407     }
408
409     fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty {
410         let var = self.table.new_type_var();
411         let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() };
412         let obligation = Obligation::Projection(predicate);
413         self.obligations.push(obligation);
414         var
415     }
416
417     fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
418         let path = match path {
419             Some(path) => path,
420             None => return (Ty::Unknown, None),
421         };
422         let resolver = &self.resolver;
423         // FIXME: this should resolve assoc items as well, see this example:
424         // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
425         match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
426             Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
427                 let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into());
428                 let ty = self.db.ty(strukt.into());
429                 let ty = self.insert_type_vars(ty.apply_substs(substs));
430                 (ty, Some(strukt.into()))
431             }
432             Some(TypeNs::EnumVariantId(var)) => {
433                 let substs = Ty::substs_from_path(self.db, resolver, path, var.into());
434                 let ty = self.db.ty(var.parent.into());
435                 let ty = self.insert_type_vars(ty.apply_substs(substs));
436                 (ty, Some(var.into()))
437             }
438             Some(_) | None => (Ty::Unknown, None),
439         }
440     }
441
442     fn collect_const(&mut self, data: &ConstData) {
443         self.return_ty = self.make_ty(&data.type_ref);
444     }
445
446     fn collect_fn(&mut self, data: &FunctionData) {
447         let body = Arc::clone(&self.body); // avoid borrow checker problem
448         for (type_ref, pat) in data.params.iter().zip(body.params.iter()) {
449             let ty = self.make_ty(type_ref);
450
451             self.infer_pat(*pat, &ty, BindingMode::default());
452         }
453         let return_ty = self.make_ty(&data.ret_type);
454         self.return_ty = self.insert_vars_for_impl_trait(return_ty);
455     }
456
457     fn infer_body(&mut self) {
458         self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
459     }
460
461     fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
462         let path = path![std::iter::IntoIterator];
463         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
464         self.db.trait_data(trait_).associated_type_by_name(&name![Item])
465     }
466
467     fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
468         let path = path![std::ops::Try];
469         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
470         self.db.trait_data(trait_).associated_type_by_name(&name![Ok])
471     }
472
473     fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
474         let path = path![std::ops::Neg];
475         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
476         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
477     }
478
479     fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
480         let path = path![std::ops::Not];
481         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
482         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
483     }
484
485     fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
486         let path = path![std::future::Future];
487         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
488         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
489     }
490
491     fn resolve_boxed_box(&self) -> Option<AdtId> {
492         let path = path![std::boxed::Box];
493         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
494         Some(struct_.into())
495     }
496
497     fn resolve_range_full(&self) -> Option<AdtId> {
498         let path = path![std::ops::RangeFull];
499         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
500         Some(struct_.into())
501     }
502
503     fn resolve_range(&self) -> Option<AdtId> {
504         let path = path![std::ops::Range];
505         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
506         Some(struct_.into())
507     }
508
509     fn resolve_range_inclusive(&self) -> Option<AdtId> {
510         let path = path![std::ops::RangeInclusive];
511         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
512         Some(struct_.into())
513     }
514
515     fn resolve_range_from(&self) -> Option<AdtId> {
516         let path = path![std::ops::RangeFrom];
517         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
518         Some(struct_.into())
519     }
520
521     fn resolve_range_to(&self) -> Option<AdtId> {
522         let path = path![std::ops::RangeTo];
523         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
524         Some(struct_.into())
525     }
526
527     fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
528         let path = path![std::ops::RangeToInclusive];
529         let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
530         Some(struct_.into())
531     }
532
533     fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
534         let path = path![std::ops::Index];
535         let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
536         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
537     }
538 }
539
540 /// The kinds of placeholders we need during type inference. There's separate
541 /// values for general types, and for integer and float variables. The latter
542 /// two are used for inference of literal values (e.g. `100` could be one of
543 /// several integer types).
544 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
545 pub enum InferTy {
546     TypeVar(unify::TypeVarId),
547     IntVar(unify::TypeVarId),
548     FloatVar(unify::TypeVarId),
549     MaybeNeverTypeVar(unify::TypeVarId),
550 }
551
552 impl InferTy {
553     fn to_inner(self) -> unify::TypeVarId {
554         match self {
555             InferTy::TypeVar(ty)
556             | InferTy::IntVar(ty)
557             | InferTy::FloatVar(ty)
558             | InferTy::MaybeNeverTypeVar(ty) => ty,
559         }
560     }
561
562     fn fallback_value(self) -> Ty {
563         match self {
564             InferTy::TypeVar(..) => Ty::Unknown,
565             InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))),
566             InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))),
567             InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never),
568         }
569     }
570 }
571
572 /// When inferring an expression, we propagate downward whatever type hint we
573 /// are able in the form of an `Expectation`.
574 #[derive(Clone, PartialEq, Eq, Debug)]
575 struct Expectation {
576     ty: Ty,
577     // FIXME: In some cases, we need to be aware whether the expectation is that
578     // the type match exactly what we passed, or whether it just needs to be
579     // coercible to the expected type. See Expectation::rvalue_hint in rustc.
580 }
581
582 impl Expectation {
583     /// The expectation that the type of the expression needs to equal the given
584     /// type.
585     fn has_type(ty: Ty) -> Self {
586         Expectation { ty }
587     }
588
589     /// This expresses no expectation on the type.
590     fn none() -> Self {
591         Expectation { ty: Ty::Unknown }
592     }
593 }
594
595 mod diagnostics {
596     use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup};
597     use hir_expand::diagnostics::DiagnosticSink;
598
599     use crate::{db::HirDatabase, diagnostics::NoSuchField};
600
601     #[derive(Debug, PartialEq, Eq, Clone)]
602     pub(super) enum InferenceDiagnostic {
603         NoSuchField { expr: ExprId, field: usize },
604     }
605
606     impl InferenceDiagnostic {
607         pub(super) fn add_to(
608             &self,
609             db: &impl HirDatabase,
610             owner: FunctionId,
611             sink: &mut DiagnosticSink,
612         ) {
613             match self {
614                 InferenceDiagnostic::NoSuchField { expr, field } => {
615                     let file = owner.lookup(db).source(db).file_id;
616                     let (_, source_map) = db.body_with_source_map(owner.into());
617                     let field = source_map.field_syntax(*expr, *field);
618                     sink.push(NoSuchField { file, field })
619                 }
620             }
621         }
622     }
623 }