1 //! Type inference, i.e. the process of walking through the code and determining
2 //! the type of each expression and pattern.
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.
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.
17 use std::iter::repeat;
22 use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
23 use rustc_hash::FxHashMap;
25 use ra_arena::map::ArenaMap;
27 use test_utils::tested_by;
30 autoderef, lower, method_resolution, op, primitive,
31 traits::{Guidance, Obligation, ProjectionPredicate, Solution},
32 ApplicationTy, CallableDef, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef,
33 Ty, TypableDef, TypeCtor,
37 code_model::{ModuleDef::Trait, TypeAlias},
38 diagnostics::DiagnosticSink,
40 self, Array, BinaryOp, BindingAnnotation, Body, Expr, ExprId, FieldPat, Literal, Pat,
41 PatId, Statement, UnaryOp,
43 generics::{GenericParams, HasGenericParams},
45 nameres::{Namespace, PerNs},
46 path::{GenericArg, GenericArgs, PathKind, PathSegment},
48 Resolution::{self, Def},
51 ty::infer::diagnostics::InferenceDiagnostic,
52 type_ref::{Mutability, TypeRef},
53 AdtDef, ConstData, DefWithBody, FnData, Function, HirDatabase, ImplItem, ModuleDef, Name, Path,
59 /// The entry point of type inference.
60 pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> {
61 let _p = profile("infer_query");
62 let body = def.body(db);
63 let resolver = def.resolver(db);
64 let mut ctx = InferenceContext::new(db, body, resolver);
67 DefWithBody::Const(ref c) => ctx.collect_const(&c.data(db)),
68 DefWithBody::Function(ref f) => ctx.collect_fn(&f.data(db)),
69 DefWithBody::Static(ref s) => ctx.collect_const(&s.data(db)),
74 Arc::new(ctx.resolve_all())
77 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
83 impl_froms!(ExprOrPatId: ExprId, PatId);
85 /// Binding modes inferred for patterns.
86 /// https://doc.rust-lang.org/reference/patterns.html#binding-modes
87 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
94 pub fn convert(annotation: BindingAnnotation) -> BindingMode {
96 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
97 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared),
98 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
103 impl Default for BindingMode {
104 fn default() -> Self {
109 /// The result of type inference: A mapping from expressions and patterns to types.
110 #[derive(Clone, PartialEq, Eq, Debug, Default)]
111 pub struct InferenceResult {
112 /// For each method call expr, records the function it resolves to.
113 method_resolutions: FxHashMap<ExprId, Function>,
114 /// For each field access expr, records the field it resolves to.
115 field_resolutions: FxHashMap<ExprId, StructField>,
116 /// For each struct literal, records the variant it resolves to.
117 variant_resolutions: FxHashMap<ExprOrPatId, VariantDef>,
118 /// For each associated item record what it resolves to
119 assoc_resolutions: FxHashMap<ExprOrPatId, ImplItem>,
120 diagnostics: Vec<InferenceDiagnostic>,
121 pub(super) type_of_expr: ArenaMap<ExprId, Ty>,
122 pub(super) type_of_pat: ArenaMap<PatId, Ty>,
125 impl InferenceResult {
126 pub fn method_resolution(&self, expr: ExprId) -> Option<Function> {
127 self.method_resolutions.get(&expr).copied()
129 pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> {
130 self.field_resolutions.get(&expr).copied()
132 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantDef> {
133 self.variant_resolutions.get(&id.into()).copied()
135 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantDef> {
136 self.variant_resolutions.get(&id.into()).copied()
138 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<ImplItem> {
139 self.assoc_resolutions.get(&id.into()).copied()
141 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<ImplItem> {
142 self.assoc_resolutions.get(&id.into()).copied()
144 pub(crate) fn add_diagnostics(
146 db: &impl HirDatabase,
148 sink: &mut DiagnosticSink,
150 self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink))
154 impl Index<ExprId> for InferenceResult {
157 fn index(&self, expr: ExprId) -> &Ty {
158 self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown)
162 impl Index<PatId> for InferenceResult {
165 fn index(&self, pat: PatId) -> &Ty {
166 self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown)
170 /// The inference context contains all information needed during type inference.
171 #[derive(Clone, Debug)]
172 struct InferenceContext<'a, D: HirDatabase> {
176 var_unification_table: InPlaceUnificationTable<TypeVarId>,
177 trait_env: Arc<TraitEnvironment>,
178 obligations: Vec<Obligation>,
179 result: InferenceResult,
180 /// The return type of the function being inferred.
184 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
185 fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self {
187 result: InferenceResult::default(),
188 var_unification_table: InPlaceUnificationTable::new(),
189 obligations: Vec::default(),
190 return_ty: Ty::Unknown, // set in collect_fn_signature
191 trait_env: lower::trait_env(db, &resolver),
198 fn resolve_all(mut self) -> InferenceResult {
199 // FIXME resolve obligations as well (use Guidance if necessary)
200 let mut result = mem::replace(&mut self.result, InferenceResult::default());
201 let mut tv_stack = Vec::new();
202 for ty in result.type_of_expr.values_mut() {
203 let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown));
206 for ty in result.type_of_pat.values_mut() {
207 let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown));
213 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
214 self.result.type_of_expr.insert(expr, ty);
217 fn write_method_resolution(&mut self, expr: ExprId, func: Function) {
218 self.result.method_resolutions.insert(expr, func);
221 fn write_field_resolution(&mut self, expr: ExprId, field: StructField) {
222 self.result.field_resolutions.insert(expr, field);
225 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantDef) {
226 self.result.variant_resolutions.insert(id, variant);
229 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: ImplItem) {
230 self.result.assoc_resolutions.insert(id, item);
233 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
234 self.result.type_of_pat.insert(pat, ty);
237 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
238 self.result.diagnostics.push(diagnostic);
241 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
242 let ty = Ty::from_hir(
244 // FIXME use right resolver for block
248 self.insert_type_vars(ty)
251 fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool {
252 substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth))
255 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
256 self.unify_inner(ty1, ty2, 0)
259 fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool {
261 // prevent stackoverflows
262 panic!("infinite recursion in unification");
267 // try to resolve type vars first
268 let ty1 = self.resolve_ty_shallow(ty1);
269 let ty2 = self.resolve_ty_shallow(ty2);
270 match (&*ty1, &*ty2) {
271 (Ty::Unknown, ..) => true,
272 (.., Ty::Unknown) => true,
273 (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => {
274 self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1)
276 (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2)))
277 | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2)))
278 | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) => {
279 // both type vars are unknown since we tried to resolve them
280 self.var_unification_table.union(*tv1, *tv2);
283 (Ty::Infer(InferTy::TypeVar(tv)), other)
284 | (other, Ty::Infer(InferTy::TypeVar(tv)))
285 | (Ty::Infer(InferTy::IntVar(tv)), other)
286 | (other, Ty::Infer(InferTy::IntVar(tv)))
287 | (Ty::Infer(InferTy::FloatVar(tv)), other)
288 | (other, Ty::Infer(InferTy::FloatVar(tv))) => {
289 // the type var is unknown since we tried to resolve it
290 self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone()));
297 fn new_type_var(&mut self) -> Ty {
298 Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
301 fn new_integer_var(&mut self) -> Ty {
302 Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
305 fn new_float_var(&mut self) -> Ty {
306 Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
309 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
310 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
312 Ty::Unknown => self.new_type_var(),
313 Ty::Apply(ApplicationTy {
314 ctor: TypeCtor::Int(primitive::UncertainIntTy::Unknown),
316 }) => self.new_integer_var(),
317 Ty::Apply(ApplicationTy {
318 ctor: TypeCtor::Float(primitive::UncertainFloatTy::Unknown),
320 }) => self.new_float_var(),
325 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
326 ty.fold(&mut |ty| self.insert_type_vars_shallow(ty))
329 fn resolve_obligations_as_possible(&mut self) {
330 let obligations = mem::replace(&mut self.obligations, Vec::new());
331 for obligation in obligations {
332 let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone());
333 let canonicalized = self.canonicalizer().canonicalize_obligation(in_env);
335 self.db.trait_solve(self.resolver.krate().unwrap(), canonicalized.value.clone());
338 Some(Solution::Unique(substs)) => {
339 canonicalized.apply_solution(self, substs.0);
341 Some(Solution::Ambig(Guidance::Definite(substs))) => {
342 canonicalized.apply_solution(self, substs.0);
343 self.obligations.push(obligation);
346 // FIXME use this when trying to resolve everything at the end
347 self.obligations.push(obligation);
350 // FIXME obligation cannot be fulfilled => diagnostic
356 /// Resolves the type as far as currently possible, replacing type variables
357 /// by their known types. All types returned by the infer_* functions should
358 /// be resolved as far as possible, i.e. contain no type variables with
360 fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
361 self.resolve_obligations_as_possible();
363 ty.fold(&mut |ty| match ty {
365 let inner = tv.to_inner();
366 if tv_stack.contains(&inner) {
367 tested_by!(type_var_cycles_resolve_as_possible);
369 return tv.fallback_value();
371 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() {
372 // known_ty may contain other variables that are known by now
373 tv_stack.push(inner);
374 let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone());
385 /// If `ty` is a type variable with known type, returns that type;
386 /// otherwise, return ty.
387 fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> {
388 let mut ty = Cow::Borrowed(ty);
389 // The type variable could resolve to a int/float variable. Hence try
390 // resolving up to three times; each type of variable shouldn't occur
394 tested_by!(type_var_resolves_to_int_var);
398 let inner = tv.to_inner();
399 match self.var_unification_table.probe_value(inner).known() {
401 // The known_ty can't be a type var itself
402 ty = Cow::Owned(known_ty.clone());
410 log::error!("Inference variable still not resolved: {:?}", ty);
414 /// Resolves the type completely; type variables without known type are
415 /// replaced by Ty::Unknown.
416 fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
417 ty.fold(&mut |ty| match ty {
419 let inner = tv.to_inner();
420 if tv_stack.contains(&inner) {
421 tested_by!(type_var_cycles_resolve_completely);
423 return tv.fallback_value();
425 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() {
426 // known_ty may contain other variables that are known by now
427 tv_stack.push(inner);
428 let result = self.resolve_ty_completely(tv_stack, known_ty.clone());
439 fn infer_path_expr(&mut self, resolver: &Resolver, path: &Path, id: ExprOrPatId) -> Option<Ty> {
440 let resolved = resolver.resolve_path_segments(self.db, &path);
442 let (def, remaining_index) = resolved.into_inner();
445 "path {:?} resolved to {:?} with remaining index {:?}",
451 // if the remaining_index is None, we expect the path
452 // to be fully resolved, in this case we continue with
453 // the default by attempting to `take_values´ from the resolution.
454 // Otherwise the path was partially resolved, which means
455 // we might have resolved into a type for which
456 // we may find some associated item starting at the
457 // path.segment pointed to by `remaining_index´
459 if remaining_index.is_none() { def.take_values()? } else { def.take_types()? };
461 let remaining_index = remaining_index.unwrap_or_else(|| path.segments.len());
462 let mut actual_def_ty: Option<Ty> = None;
464 let krate = resolver.krate()?;
465 // resolve intermediate segments
466 for (i, segment) in path.segments[remaining_index..].iter().enumerate() {
467 let ty = match resolved {
468 Resolution::Def(def) => {
469 // FIXME resolve associated items from traits as well
470 let typable: Option<TypableDef> = def.into();
471 let typable = typable?;
473 let ty = self.db.type_for_def(typable, Namespace::Types);
475 // For example, this substs will take `Gen::*<u32>*::make`
476 assert!(remaining_index > 0);
477 let substs = Ty::substs_from_path_segment(
480 &path.segments[remaining_index + i - 1],
486 Resolution::LocalBinding(_) => {
487 // can't have a local binding in an associated item path
490 Resolution::GenericParam(..) => {
491 // FIXME associated item of generic param
494 Resolution::SelfType(_) => {
495 // FIXME associated item of self type
500 // Attempt to find an impl_item for the type which has a name matching
501 // the current segment
502 log::debug!("looking for path segment: {:?}", segment);
504 actual_def_ty = Some(ty.clone());
506 let item: crate::ModuleDef = ty.iterate_impl_items(self.db, krate, |item| {
507 let matching_def: Option<crate::ModuleDef> = match item {
508 crate::ImplItem::Method(func) => {
509 if segment.name == func.name(self.db) {
516 crate::ImplItem::Const(konst) => {
517 let data = konst.data(self.db);
518 if segment.name == *data.name() {
525 // FIXME: Resolve associated types
526 crate::ImplItem::TypeAlias(_) => None,
530 self.write_assoc_resolution(id, item);
537 resolved = Resolution::Def(item);
541 Resolution::Def(def) => {
542 let typable: Option<TypableDef> = def.into();
543 let typable = typable?;
544 let mut ty = self.db.type_for_def(typable, Namespace::Values);
545 if let Some(sts) = self.find_self_types(&def, actual_def_ty) {
549 let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable);
550 let ty = ty.subst(&substs);
551 let ty = self.insert_type_vars(ty);
554 Resolution::LocalBinding(pat) => {
555 let ty = self.result.type_of_pat.get(pat)?.clone();
556 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
559 Resolution::GenericParam(..) => {
560 // generic params can't refer to values... yet
563 Resolution::SelfType(_) => {
564 log::error!("path expr {:?} resolved to Self type in values ns", path);
570 fn find_self_types(&self, def: &ModuleDef, actual_def_ty: Option<Ty>) -> Option<Substs> {
571 let actual_def_ty = actual_def_ty?;
573 if let crate::ModuleDef::Function(func) = def {
574 // We only do the infer if parent has generic params
575 let gen = func.generic_params(self.db);
576 if gen.count_parent_params() == 0 {
580 let impl_block = func.impl_block(self.db)?.target_ty(self.db);
581 let impl_block_substs = impl_block.substs()?;
582 let actual_substs = actual_def_ty.substs()?;
584 let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()];
586 // The following code *link up* the function actual parma type
587 // and impl_block type param index
588 impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| {
589 if let Ty::Param { idx, .. } = param {
590 if let Some(s) = new_substs.get_mut(*idx as usize) {
596 Some(Substs(new_substs.into()))
602 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantDef>) {
603 let path = match path {
605 None => return (Ty::Unknown, None),
607 let resolver = &self.resolver;
608 let typable: Option<TypableDef> =
609 // FIXME: this should resolve assoc items as well, see this example:
610 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
611 match resolver.resolve_path_without_assoc_items(self.db, &path).take_types() {
612 Some(Resolution::Def(def)) => def.into(),
613 Some(Resolution::LocalBinding(..)) => {
614 // this cannot happen
615 log::error!("path resolved to local binding in type ns");
616 return (Ty::Unknown, None);
618 Some(Resolution::GenericParam(..)) => {
619 // generic params can't be used in struct literals
620 return (Ty::Unknown, None);
622 Some(Resolution::SelfType(..)) => {
623 // FIXME this is allowed in an impl for a struct, handle this
624 return (Ty::Unknown, None);
626 None => return (Ty::Unknown, None),
628 let def = match typable {
629 None => return (Ty::Unknown, None),
632 // FIXME remove the duplication between here and `Ty::from_path`?
633 let substs = Ty::substs_from_path(self.db, resolver, path, def);
635 TypableDef::Struct(s) => {
636 let ty = s.ty(self.db);
637 let ty = self.insert_type_vars(ty.apply_substs(substs));
640 TypableDef::EnumVariant(var) => {
641 let ty = var.parent_enum(self.db).ty(self.db);
642 let ty = self.insert_type_vars(ty.apply_substs(substs));
643 (ty, Some(var.into()))
646 | TypableDef::TypeAlias(_)
647 | TypableDef::Function(_)
648 | TypableDef::Enum(_)
649 | TypableDef::Const(_)
650 | TypableDef::Static(_)
651 | TypableDef::BuiltinType(_) => (Ty::Unknown, None),
655 fn infer_tuple_struct_pat(
660 default_bm: BindingMode,
662 let (ty, def) = self.resolve_variant(path);
664 self.unify(&ty, expected);
666 let substs = ty.substs().unwrap_or_else(Substs::empty);
668 for (i, &subpat) in subpats.iter().enumerate() {
669 let expected_ty = def
670 .and_then(|d| d.field(self.db, &Name::tuple_field_name(i)))
671 .map_or(Ty::Unknown, |field| field.ty(self.db))
673 self.infer_pat(subpat, &expected_ty, default_bm);
682 subpats: &[FieldPat],
684 default_bm: BindingMode,
687 let (ty, def) = self.resolve_variant(path);
688 if let Some(variant) = def {
689 self.write_variant_resolution(id.into(), variant);
692 self.unify(&ty, expected);
694 let substs = ty.substs().unwrap_or_else(Substs::empty);
696 for subpat in subpats {
697 let matching_field = def.and_then(|it| it.field(self.db, &subpat.name));
699 matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs);
700 self.infer_pat(subpat.pat, &expected_ty, default_bm);
706 fn infer_pat(&mut self, pat: PatId, mut expected: &Ty, mut default_bm: BindingMode) -> Ty {
707 let body = Arc::clone(&self.body); // avoid borrow checker problem
709 let is_non_ref_pat = match &body[pat] {
711 | Pat::TupleStruct { .. }
714 | Pat::Slice { .. } => true,
715 // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented.
716 Pat::Path(..) | Pat::Lit(..) => true,
717 Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false,
720 while let Some((inner, mutability)) = expected.as_reference() {
722 default_bm = match default_bm {
723 BindingMode::Move => BindingMode::Ref(mutability),
724 BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared),
725 BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability),
728 } else if let Pat::Ref { .. } = &body[pat] {
729 tested_by!(match_ergonomics_ref);
730 // When you encounter a `&pat` pattern, reset to Move.
731 // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
732 default_bm = BindingMode::Move;
736 let default_bm = default_bm;
737 let expected = expected;
739 let ty = match &body[pat] {
740 Pat::Tuple(ref args) => {
741 let expectations = match expected.as_tuple() {
742 Some(parameters) => &*parameters.0,
745 let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown));
747 let inner_tys: Substs = args
749 .zip(expectations_iter)
750 .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm))
754 Ty::apply(TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, inner_tys)
756 Pat::Ref { pat, mutability } => {
757 let expectation = match expected.as_reference() {
758 Some((inner_ty, exp_mut)) => {
759 if *mutability != exp_mut {
760 // FIXME: emit type error?
766 let subty = self.infer_pat(*pat, expectation, default_bm);
767 Ty::apply_one(TypeCtor::Ref(*mutability), subty)
769 Pat::TupleStruct { path: ref p, args: ref subpats } => {
770 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm)
772 Pat::Struct { path: ref p, args: ref fields } => {
773 self.infer_struct_pat(p.as_ref(), fields, expected, default_bm, pat)
776 // FIXME use correct resolver for the surrounding expression
777 let resolver = self.resolver.clone();
778 self.infer_path_expr(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown)
780 Pat::Bind { mode, name: _name, subpat } => {
781 let mode = if mode == &BindingAnnotation::Unannotated {
784 BindingMode::convert(*mode)
786 let inner_ty = if let Some(subpat) = subpat {
787 self.infer_pat(*subpat, expected, default_bm)
791 let inner_ty = self.insert_type_vars_shallow(inner_ty);
793 let bound_ty = match mode {
794 BindingMode::Ref(mutability) => {
795 Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone())
797 BindingMode::Move => inner_ty.clone(),
799 let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty);
800 self.write_pat_ty(pat, bound_ty);
805 // use a new type variable if we got Ty::Unknown here
806 let ty = self.insert_type_vars_shallow(ty);
807 self.unify(&ty, expected);
808 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
809 self.write_pat_ty(pat, ty.clone());
813 fn substs_for_method_call(
815 def_generics: Option<Arc<GenericParams>>,
816 generic_args: Option<&GenericArgs>,
819 let (parent_param_count, param_count) =
820 def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len()));
821 let mut substs = Vec::with_capacity(parent_param_count + param_count);
822 // Parent arguments are unknown, except for the receiver type
823 if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) {
824 for param in &parent_generics.params {
825 if param.name == name::SELF_TYPE {
826 substs.push(receiver_ty.clone());
828 substs.push(Ty::Unknown);
832 // handle provided type arguments
833 if let Some(generic_args) = generic_args {
834 // if args are provided, it should be all of them, but we can't rely on that
835 for arg in generic_args.args.iter().take(param_count) {
837 GenericArg::Type(type_ref) => {
838 let ty = self.make_ty(type_ref);
844 let supplied_params = substs.len();
845 for _ in supplied_params..parent_param_count + param_count {
846 substs.push(Ty::Unknown);
848 assert_eq!(substs.len(), parent_param_count + param_count);
849 Substs(substs.into())
852 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
853 if let Ty::Apply(a_ty) = callable_ty {
854 if let TypeCtor::FnDef(def) = a_ty.ctor {
855 let generic_predicates = self.db.generic_predicates(def.into());
856 for predicate in generic_predicates.iter() {
857 let predicate = predicate.clone().subst(&a_ty.parameters);
858 if let Some(obligation) = Obligation::from_predicate(predicate) {
859 self.obligations.push(obligation);
862 // add obligation for trait implementation, if this is a trait method
864 CallableDef::Function(f) => {
865 if let Some(trait_) = f.parent_trait(self.db) {
866 // construct a TraitDef
867 let substs = a_ty.parameters.prefix(
868 trait_.generic_params(self.db).count_params_including_parent(),
870 self.obligations.push(Obligation::Trait(TraitRef { trait_, substs }));
873 CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {}
879 fn infer_method_call(
885 generic_args: Option<&GenericArgs>,
887 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
888 let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone());
889 let resolved = method_resolution::lookup_method(
890 &canonicalized_receiver.value,
895 let (derefed_receiver_ty, method_ty, def_generics) = match resolved {
896 Some((ty, func)) => {
897 let ty = canonicalized_receiver.decanonicalize_ty(ty);
898 self.write_method_resolution(tgt_expr, func);
901 self.db.type_for_def(func.into(), Namespace::Values),
902 Some(func.generic_params(self.db)),
905 None => (receiver_ty, Ty::Unknown, None),
907 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty);
908 let method_ty = method_ty.apply_substs(substs);
909 let method_ty = self.insert_type_vars(method_ty);
910 self.register_obligations_for_call(&method_ty);
911 let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
913 if !sig.params().is_empty() {
914 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
916 (Ty::Unknown, Vec::new(), sig.ret().clone())
919 None => (Ty::Unknown, Vec::new(), Ty::Unknown),
921 // Apply autoref so the below unification works correctly
922 // FIXME: return correct autorefs from lookup_method
923 let actual_receiver_ty = match expected_receiver_ty.as_reference() {
924 Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty),
925 _ => derefed_receiver_ty,
927 self.unify(&expected_receiver_ty, &actual_receiver_ty);
929 let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown));
930 for (arg, param) in args.iter().zip(param_iter) {
931 self.infer_expr(*arg, &Expectation::has_type(param));
936 fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
937 let body = Arc::clone(&self.body); // avoid borrow checker problem
938 let ty = match &body[tgt_expr] {
939 Expr::Missing => Ty::Unknown,
940 Expr::If { condition, then_branch, else_branch } => {
941 // if let is desugared to match, so this is always simple if
942 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool)));
943 let then_ty = self.infer_expr(*then_branch, expected);
945 Some(else_branch) => {
946 self.infer_expr(*else_branch, expected);
949 // no else branch -> unit
950 self.unify(&then_ty, &Ty::unit()); // actually coerce
955 Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected),
956 Expr::TryBlock { body } => {
957 let _inner = self.infer_expr(*body, expected);
958 // FIXME should be std::result::Result<{inner}, _>
961 Expr::Loop { body } => {
962 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
963 // FIXME handle break with value
964 Ty::simple(TypeCtor::Never)
966 Expr::While { condition, body } => {
967 // while let is desugared to a match loop, so this is always simple while
968 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool)));
969 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
972 Expr::For { iterable, body, pat } => {
973 let iterable_ty = self.infer_expr(*iterable, &Expectation::none());
975 let pat_ty = match self.resolve_into_iter_item() {
976 Some(into_iter_item_alias) => {
977 let pat_ty = self.new_type_var();
978 let projection = ProjectionPredicate {
980 projection_ty: ProjectionTy {
981 associated_ty: into_iter_item_alias,
982 parameters: vec![iterable_ty].into(),
985 self.obligations.push(Obligation::Projection(projection));
986 self.resolve_ty_as_possible(&mut vec![], pat_ty)
991 self.infer_pat(*pat, &pat_ty, BindingMode::default());
992 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
995 Expr::Lambda { body, args, arg_types } => {
996 assert_eq!(args.len(), arg_types.len());
998 for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) {
999 let expected = if let Some(type_ref) = arg_type {
1000 self.make_ty(type_ref)
1004 self.infer_pat(*arg_pat, &expected, BindingMode::default());
1007 // FIXME: infer lambda type etc.
1008 let _body_ty = self.infer_expr(*body, &Expectation::none());
1011 Expr::Call { callee, args } => {
1012 let callee_ty = self.infer_expr(*callee, &Expectation::none());
1013 let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) {
1014 Some(sig) => (sig.params().to_vec(), sig.ret().clone()),
1017 // FIXME: report an error
1018 (Vec::new(), Ty::Unknown)
1021 self.register_obligations_for_call(&callee_ty);
1022 let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown));
1023 for (arg, param) in args.iter().zip(param_iter) {
1024 self.infer_expr(*arg, &Expectation::has_type(param));
1028 Expr::MethodCall { receiver, args, method_name, generic_args } => self
1029 .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()),
1030 Expr::Match { expr, arms } => {
1031 let expected = if expected.ty == Ty::Unknown {
1032 Expectation::has_type(self.new_type_var())
1036 let input_ty = self.infer_expr(*expr, &Expectation::none());
1039 for &pat in &arm.pats {
1040 let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default());
1042 if let Some(guard_expr) = arm.guard {
1045 &Expectation::has_type(Ty::simple(TypeCtor::Bool)),
1048 self.infer_expr(arm.expr, &expected);
1054 // FIXME this could be more efficient...
1055 let resolver = expr::resolver_for_expr(self.body.clone(), self.db, tgt_expr);
1056 self.infer_path_expr(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown)
1058 Expr::Continue => Ty::simple(TypeCtor::Never),
1059 Expr::Break { expr } => {
1060 if let Some(expr) = expr {
1061 // FIXME handle break with value
1062 self.infer_expr(*expr, &Expectation::none());
1064 Ty::simple(TypeCtor::Never)
1066 Expr::Return { expr } => {
1067 if let Some(expr) = expr {
1068 self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone()));
1070 Ty::simple(TypeCtor::Never)
1072 Expr::StructLit { path, fields, spread } => {
1073 let (ty, def_id) = self.resolve_variant(path.as_ref());
1074 if let Some(variant) = def_id {
1075 self.write_variant_resolution(tgt_expr.into(), variant);
1078 let substs = ty.substs().unwrap_or_else(Substs::empty);
1079 for (field_idx, field) in fields.iter().enumerate() {
1080 let field_ty = def_id
1081 .and_then(|it| match it.field(self.db, &field.name) {
1082 Some(field) => Some(field),
1084 self.push_diagnostic(InferenceDiagnostic::NoSuchField {
1091 .map_or(Ty::Unknown, |field| field.ty(self.db))
1093 self.infer_expr(field.expr, &Expectation::has_type(field_ty));
1095 if let Some(expr) = spread {
1096 self.infer_expr(*expr, &Expectation::has_type(ty.clone()));
1100 Expr::Field { expr, name } => {
1101 let receiver_ty = self.infer_expr(*expr, &Expectation::none());
1102 let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty);
1103 let ty = autoderef::autoderef(
1105 &self.resolver.clone(),
1106 canonicalized.value.clone(),
1108 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) {
1109 Ty::Apply(a_ty) => match a_ty.ctor {
1110 TypeCtor::Tuple { .. } => {
1111 let i = name.to_string().parse::<usize>().ok();
1112 i.and_then(|i| a_ty.parameters.0.get(i).cloned())
1114 TypeCtor::Adt(AdtDef::Struct(s)) => s.field(self.db, name).map(|field| {
1115 self.write_field_resolution(tgt_expr, field);
1116 field.ty(self.db).subst(&a_ty.parameters)
1122 .unwrap_or(Ty::Unknown);
1123 self.insert_type_vars(ty)
1125 Expr::Await { expr } => {
1126 let inner_ty = self.infer_expr(*expr, &Expectation::none());
1127 let ty = match self.resolve_future_future_output() {
1128 Some(future_future_output_alias) => {
1129 let ty = self.new_type_var();
1130 let projection = ProjectionPredicate {
1132 projection_ty: ProjectionTy {
1133 associated_ty: future_future_output_alias,
1134 parameters: vec![inner_ty].into(),
1137 self.obligations.push(Obligation::Projection(projection));
1138 self.resolve_ty_as_possible(&mut vec![], ty)
1140 None => Ty::Unknown,
1144 Expr::Try { expr } => {
1145 let inner_ty = self.infer_expr(*expr, &Expectation::none());
1146 let ty = match self.resolve_ops_try_ok() {
1147 Some(ops_try_ok_alias) => {
1148 let ty = self.new_type_var();
1149 let projection = ProjectionPredicate {
1151 projection_ty: ProjectionTy {
1152 associated_ty: ops_try_ok_alias,
1153 parameters: vec![inner_ty].into(),
1156 self.obligations.push(Obligation::Projection(projection));
1157 self.resolve_ty_as_possible(&mut vec![], ty)
1159 None => Ty::Unknown,
1163 Expr::Cast { expr, type_ref } => {
1164 let _inner_ty = self.infer_expr(*expr, &Expectation::none());
1165 let cast_ty = self.make_ty(type_ref);
1166 // FIXME check the cast...
1169 Expr::Ref { expr, mutability } => {
1171 if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() {
1172 if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared {
1173 // FIXME: throw type error - expected mut reference but found shared ref,
1174 // which cannot be coerced
1176 Expectation::has_type(Ty::clone(exp_inner))
1180 // FIXME reference coercions etc.
1181 let inner_ty = self.infer_expr(*expr, &expectation);
1182 Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty)
1184 Expr::UnaryOp { expr, op } => {
1185 let inner_ty = self.infer_expr(*expr, &Expectation::none());
1188 let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty);
1189 if let Some(derefed_ty) =
1190 autoderef::deref(self.db, &self.resolver, &canonicalized.value)
1192 canonicalized.decanonicalize_ty(derefed_ty.value)
1199 Ty::Apply(a_ty) => match a_ty.ctor {
1200 TypeCtor::Int(primitive::UncertainIntTy::Unknown)
1201 | TypeCtor::Int(primitive::UncertainIntTy::Known(
1203 signedness: primitive::Signedness::Signed,
1207 | TypeCtor::Float(..) => inner_ty,
1210 Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => {
1213 // FIXME: resolve ops::Neg trait
1219 Ty::Apply(a_ty) => match a_ty.ctor {
1220 TypeCtor::Bool | TypeCtor::Int(_) => inner_ty,
1223 Ty::Infer(InferTy::IntVar(..)) => inner_ty,
1224 // FIXME: resolve ops::Not trait for inner_ty
1230 Expr::BinaryOp { lhs, rhs, op } => match op {
1232 let lhs_expectation = match op {
1233 BinaryOp::BooleanAnd | BinaryOp::BooleanOr => {
1234 Expectation::has_type(Ty::simple(TypeCtor::Bool))
1236 _ => Expectation::none(),
1238 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
1239 // FIXME: find implementation of trait corresponding to operation
1240 // symbol and resolve associated `Output` type
1241 let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty);
1242 let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation));
1244 // FIXME: similar as above, return ty is often associated trait type
1245 op::binary_op_return_ty(*op, rhs_ty)
1249 Expr::Tuple { exprs } => {
1250 let mut ty_vec = Vec::with_capacity(exprs.len());
1251 for arg in exprs.iter() {
1252 ty_vec.push(self.infer_expr(*arg, &Expectation::none()));
1256 TypeCtor::Tuple { cardinality: ty_vec.len() as u16 },
1257 Substs(ty_vec.into()),
1260 Expr::Array(array) => {
1261 let elem_ty = match &expected.ty {
1262 Ty::Apply(a_ty) => match a_ty.ctor {
1263 TypeCtor::Slice | TypeCtor::Array => {
1264 Ty::clone(&a_ty.parameters.as_single())
1266 _ => self.new_type_var(),
1268 _ => self.new_type_var(),
1272 Array::ElementList(items) => {
1273 for expr in items.iter() {
1274 self.infer_expr(*expr, &Expectation::has_type(elem_ty.clone()));
1277 Array::Repeat { initializer, repeat } => {
1278 self.infer_expr(*initializer, &Expectation::has_type(elem_ty.clone()));
1281 &Expectation::has_type(Ty::simple(TypeCtor::Int(
1282 primitive::UncertainIntTy::Known(primitive::IntTy::usize()),
1288 Ty::apply_one(TypeCtor::Array, elem_ty)
1290 Expr::Literal(lit) => match lit {
1291 Literal::Bool(..) => Ty::simple(TypeCtor::Bool),
1292 Literal::String(..) => {
1293 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str))
1295 Literal::ByteString(..) => {
1296 let byte_type = Ty::simple(TypeCtor::Int(primitive::UncertainIntTy::Known(
1297 primitive::IntTy::u8(),
1299 let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type);
1300 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type)
1302 Literal::Char(..) => Ty::simple(TypeCtor::Char),
1303 Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int(*ty)),
1304 Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float(*ty)),
1307 // use a new type variable if we got Ty::Unknown here
1308 let ty = self.insert_type_vars_shallow(ty);
1309 self.unify(&ty, &expected.ty);
1310 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
1311 self.write_expr_ty(tgt_expr, ty.clone());
1317 statements: &[Statement],
1318 tail: Option<ExprId>,
1319 expected: &Expectation,
1321 for stmt in statements {
1323 Statement::Let { pat, type_ref, initializer } => {
1325 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown);
1326 let decl_ty = self.insert_type_vars(decl_ty);
1327 let ty = if let Some(expr) = initializer {
1328 let expr_ty = self.infer_expr(*expr, &Expectation::has_type(decl_ty));
1334 self.infer_pat(*pat, &ty, BindingMode::default());
1336 Statement::Expr(expr) => {
1337 self.infer_expr(*expr, &Expectation::none());
1341 let ty = if let Some(expr) = tail { self.infer_expr(expr, expected) } else { Ty::unit() };
1345 fn collect_const(&mut self, data: &ConstData) {
1346 self.return_ty = self.make_ty(data.type_ref());
1349 fn collect_fn(&mut self, data: &FnData) {
1350 let body = Arc::clone(&self.body); // avoid borrow checker problem
1351 for (type_ref, pat) in data.params().iter().zip(body.params()) {
1352 let ty = self.make_ty(type_ref);
1354 self.infer_pat(*pat, &ty, BindingMode::default());
1356 self.return_ty = self.make_ty(data.ret_type());
1359 fn infer_body(&mut self) {
1360 self.infer_expr(self.body.body_expr(), &Expectation::has_type(self.return_ty.clone()));
1363 fn resolve_into_iter_item(&self) -> Option<TypeAlias> {
1364 let into_iter_path = Path {
1365 kind: PathKind::Abs,
1367 PathSegment { name: name::STD, args_and_bindings: None },
1368 PathSegment { name: name::ITER, args_and_bindings: None },
1369 PathSegment { name: name::INTO_ITERATOR, args_and_bindings: None },
1373 match self.resolver.resolve_path_segments(self.db, &into_iter_path).into_fully_resolved() {
1374 PerNs { types: Some(Def(Trait(trait_))), .. } => {
1375 Some(trait_.associated_type_by_name(self.db, name::ITEM)?)
1381 fn resolve_ops_try_ok(&self) -> Option<TypeAlias> {
1382 let ops_try_path = Path {
1383 kind: PathKind::Abs,
1385 PathSegment { name: name::STD, args_and_bindings: None },
1386 PathSegment { name: name::OPS, args_and_bindings: None },
1387 PathSegment { name: name::TRY, args_and_bindings: None },
1391 match self.resolver.resolve_path_segments(self.db, &ops_try_path).into_fully_resolved() {
1392 PerNs { types: Some(Def(Trait(trait_))), .. } => {
1393 Some(trait_.associated_type_by_name(self.db, name::OK)?)
1399 fn resolve_future_future_output(&self) -> Option<TypeAlias> {
1400 let future_future_path = Path {
1401 kind: PathKind::Abs,
1403 PathSegment { name: name::STD, args_and_bindings: None },
1404 PathSegment { name: name::FUTURE_MOD, args_and_bindings: None },
1405 PathSegment { name: name::FUTURE_TYPE, args_and_bindings: None },
1411 .resolve_path_segments(self.db, &future_future_path)
1412 .into_fully_resolved()
1414 PerNs { types: Some(Def(Trait(trait_))), .. } => {
1415 Some(trait_.associated_type_by_name(self.db, name::OUTPUT)?)
1422 /// The ID of a type variable.
1423 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
1424 pub struct TypeVarId(pub(super) u32);
1426 impl UnifyKey for TypeVarId {
1427 type Value = TypeVarValue;
1429 fn index(&self) -> u32 {
1433 fn from_index(i: u32) -> Self {
1437 fn tag() -> &'static str {
1442 /// The value of a type variable: either we already know the type, or we don't
1444 #[derive(Clone, PartialEq, Eq, Debug)]
1445 pub enum TypeVarValue {
1451 fn known(&self) -> Option<&Ty> {
1453 TypeVarValue::Known(ty) => Some(ty),
1454 TypeVarValue::Unknown => None,
1459 impl UnifyValue for TypeVarValue {
1460 type Error = NoError;
1462 fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> {
1463 match (value1, value2) {
1464 // We should never equate two type variables, both of which have
1465 // known types. Instead, we recursively equate those types.
1466 (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!(
1467 "equating two type variables, both of which have known types: {:?} and {:?}",
1471 // If one side is known, prefer that one.
1472 (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()),
1473 (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()),
1475 (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown),
1480 /// The kinds of placeholders we need during type inference. There's separate
1481 /// values for general types, and for integer and float variables. The latter
1482 /// two are used for inference of literal values (e.g. `100` could be one of
1483 /// several integer types).
1484 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1488 FloatVar(TypeVarId),
1492 fn to_inner(self) -> TypeVarId {
1494 InferTy::TypeVar(ty) | InferTy::IntVar(ty) | InferTy::FloatVar(ty) => ty,
1498 fn fallback_value(self) -> Ty {
1500 InferTy::TypeVar(..) => Ty::Unknown,
1501 InferTy::IntVar(..) => {
1502 Ty::simple(TypeCtor::Int(primitive::UncertainIntTy::Known(primitive::IntTy::i32())))
1504 InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(
1505 primitive::UncertainFloatTy::Known(primitive::FloatTy::f64()),
1511 /// When inferring an expression, we propagate downward whatever type hint we
1512 /// are able in the form of an `Expectation`.
1513 #[derive(Clone, PartialEq, Eq, Debug)]
1514 struct Expectation {
1516 // FIXME: In some cases, we need to be aware whether the expectation is that
1517 // the type match exactly what we passed, or whether it just needs to be
1518 // coercible to the expected type. See Expectation::rvalue_hint in rustc.
1522 /// The expectation that the type of the expression needs to equal the given
1524 fn has_type(ty: Ty) -> Self {
1528 /// This expresses no expectation on the type.
1530 Expectation { ty: Ty::Unknown }
1536 diagnostics::{DiagnosticSink, NoSuchField},
1538 Function, HasSource, HirDatabase,
1541 #[derive(Debug, PartialEq, Eq, Clone)]
1542 pub(super) enum InferenceDiagnostic {
1543 NoSuchField { expr: ExprId, field: usize },
1546 impl InferenceDiagnostic {
1547 pub(super) fn add_to(
1549 db: &impl HirDatabase,
1551 sink: &mut DiagnosticSink,
1554 InferenceDiagnostic::NoSuchField { expr, field } => {
1555 let file = owner.source(db).file_id;
1556 let field = owner.body_source_map(db).field_syntax(*expr, *field);
1557 sink.push(NoSuchField { file, field })