]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-ty/src/infer.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / rust-analyzer / crates / 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 rustc_hir_analysis/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::ops::Index;
17 use std::sync::Arc;
18
19 use chalk_ir::{cast::Cast, ConstValue, DebruijnIndex, Mutability, Safety, Scalar, TypeFlags};
20 use hir_def::{
21     body::Body,
22     builtin_type::BuiltinType,
23     data::{ConstData, StaticData},
24     expr::{BindingAnnotation, ExprId, PatId},
25     lang_item::LangItemTarget,
26     path::{path, Path},
27     resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
28     type_ref::TypeRef,
29     AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId, FunctionId, HasModule,
30     ItemContainerId, Lookup, TraitId, TypeAliasId, VariantId,
31 };
32 use hir_expand::name::{name, Name};
33 use itertools::Either;
34 use la_arena::ArenaMap;
35 use rustc_hash::FxHashMap;
36 use stdx::{always, impl_from};
37
38 use crate::{
39     db::HirDatabase, fold_tys, fold_tys_and_consts, infer::coerce::CoerceMany,
40     lower::ImplTraitLoweringMode, to_assoc_type_id, AliasEq, AliasTy, Const, DomainGoal,
41     GenericArg, Goal, ImplTraitId, InEnvironment, Interner, ProjectionTy, Substitution,
42     TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
43 };
44
45 // This lint has a false positive here. See the link below for details.
46 //
47 // https://github.com/rust-lang/rust/issues/57411
48 #[allow(unreachable_pub)]
49 pub use coerce::could_coerce;
50 #[allow(unreachable_pub)]
51 pub use unify::could_unify;
52
53 pub(crate) mod unify;
54 mod path;
55 mod expr;
56 mod pat;
57 mod coerce;
58 mod closure;
59
60 /// The entry point of type inference.
61 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
62     let _p = profile::span("infer_query");
63     let resolver = def.resolver(db.upcast());
64     let body = db.body(def);
65     let mut ctx = InferenceContext::new(db, def, &body, resolver);
66
67     match def {
68         DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
69         DefWithBodyId::FunctionId(f) => ctx.collect_fn(f),
70         DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
71         DefWithBodyId::VariantId(v) => {
72             ctx.return_ty = TyBuilder::builtin(match db.enum_data(v.parent).variant_body_type() {
73                 Either::Left(builtin) => BuiltinType::Int(builtin),
74                 Either::Right(builtin) => BuiltinType::Uint(builtin),
75             });
76         }
77     }
78
79     ctx.infer_body();
80
81     Arc::new(ctx.resolve_all())
82 }
83
84 /// Fully normalize all the types found within `ty` in context of `owner` body definition.
85 ///
86 /// This is appropriate to use only after type-check: it assumes
87 /// that normalization will succeed, for example.
88 pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> Ty {
89     if !ty.data(Interner).flags.intersects(TypeFlags::HAS_PROJECTION) {
90         return ty;
91     }
92     let krate = owner.module(db.upcast()).krate();
93     let trait_env = owner
94         .as_generic_def_id()
95         .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
96     let mut table = unify::InferenceTable::new(db, trait_env);
97
98     let ty_with_vars = table.normalize_associated_types_in(ty);
99     table.resolve_obligations_as_possible();
100     table.propagate_diverging_flag();
101     table.resolve_completely(ty_with_vars)
102 }
103
104 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
105 enum ExprOrPatId {
106     ExprId(ExprId),
107     PatId(PatId),
108 }
109 impl_from!(ExprId, PatId for ExprOrPatId);
110
111 /// Binding modes inferred for patterns.
112 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
113 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
114 pub enum BindingMode {
115     Move,
116     Ref(Mutability),
117 }
118
119 impl BindingMode {
120     fn convert(annotation: BindingAnnotation) -> BindingMode {
121         match annotation {
122             BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
123             BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
124             BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
125         }
126     }
127 }
128
129 impl Default for BindingMode {
130     fn default() -> Self {
131         BindingMode::Move
132     }
133 }
134
135 /// Used to generalize patterns and assignee expressions.
136 trait PatLike: Into<ExprOrPatId> + Copy {
137     type BindingMode: Copy;
138
139     fn infer(
140         this: &mut InferenceContext<'_>,
141         id: Self,
142         expected_ty: &Ty,
143         default_bm: Self::BindingMode,
144     ) -> Ty;
145 }
146
147 impl PatLike for ExprId {
148     type BindingMode = ();
149
150     fn infer(
151         this: &mut InferenceContext<'_>,
152         id: Self,
153         expected_ty: &Ty,
154         _: Self::BindingMode,
155     ) -> Ty {
156         this.infer_assignee_expr(id, expected_ty)
157     }
158 }
159
160 impl PatLike for PatId {
161     type BindingMode = BindingMode;
162
163     fn infer(
164         this: &mut InferenceContext<'_>,
165         id: Self,
166         expected_ty: &Ty,
167         default_bm: Self::BindingMode,
168     ) -> Ty {
169         this.infer_pat(id, expected_ty, default_bm)
170     }
171 }
172
173 #[derive(Debug)]
174 pub(crate) struct InferOk<T> {
175     value: T,
176     goals: Vec<InEnvironment<Goal>>,
177 }
178
179 impl<T> InferOk<T> {
180     fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
181         InferOk { value: f(self.value), goals: self.goals }
182     }
183 }
184
185 #[derive(Debug)]
186 pub(crate) struct TypeError;
187 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
188
189 #[derive(Debug, PartialEq, Eq, Clone)]
190 pub enum InferenceDiagnostic {
191     NoSuchField { expr: ExprId },
192     BreakOutsideOfLoop { expr: ExprId, is_break: bool },
193     MismatchedArgCount { call_expr: ExprId, expected: usize, found: usize },
194 }
195
196 /// A mismatch between an expected and an inferred type.
197 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
198 pub struct TypeMismatch {
199     pub expected: Ty,
200     pub actual: Ty,
201 }
202
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 struct InternedStandardTypes {
205     unknown: Ty,
206     bool_: Ty,
207     unit: Ty,
208 }
209
210 impl Default for InternedStandardTypes {
211     fn default() -> Self {
212         InternedStandardTypes {
213             unknown: TyKind::Error.intern(Interner),
214             bool_: TyKind::Scalar(Scalar::Bool).intern(Interner),
215             unit: TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner),
216         }
217     }
218 }
219 /// Represents coercing a value to a different type of value.
220 ///
221 /// We transform values by following a number of `Adjust` steps in order.
222 /// See the documentation on variants of `Adjust` for more details.
223 ///
224 /// Here are some common scenarios:
225 ///
226 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
227 ///    Here the pointer will be dereferenced N times (where a dereference can
228 ///    happen to raw or borrowed pointers or any smart pointer which implements
229 ///    Deref, including Box<_>). The types of dereferences is given by
230 ///    `autoderefs`. It can then be auto-referenced zero or one times, indicated
231 ///    by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
232 ///    `false`.
233 ///
234 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
235 ///    with a thin pointer, deref a number of times, unsize the underlying data,
236 ///    then autoref. The 'unsize' phase may change a fixed length array to a
237 ///    dynamically sized one, a concrete object to a trait object, or statically
238 ///    sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
239 ///    represented by:
240 ///
241 ///    ```
242 ///    Deref(None) -> [i32; 4],
243 ///    Borrow(AutoBorrow::Ref) -> &[i32; 4],
244 ///    Unsize -> &[i32],
245 ///    ```
246 ///
247 ///    Note that for a struct, the 'deep' unsizing of the struct is not recorded.
248 ///    E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
249 ///    The autoderef and -ref are the same as in the above example, but the type
250 ///    stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
251 ///    the underlying conversions from `[i32; 4]` to `[i32]`.
252 ///
253 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
254 ///    that case, we have the pointer we need coming in, so there are no
255 ///    autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
256 ///    At some point, of course, `Box` should move out of the compiler, in which
257 ///    case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
258 ///    Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
259 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
260 pub struct Adjustment {
261     pub kind: Adjust,
262     pub target: Ty,
263 }
264
265 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
266 pub enum Adjust {
267     /// Go from ! to any type.
268     NeverToAny,
269     /// Dereference once, producing a place.
270     Deref(Option<OverloadedDeref>),
271     /// Take the address and produce either a `&` or `*` pointer.
272     Borrow(AutoBorrow),
273     Pointer(PointerCast),
274 }
275
276 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
277 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
278 /// The target type is `U` in both cases, with the region and mutability
279 /// being those shared by both the receiver and the returned reference.
280 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
281 pub struct OverloadedDeref(pub Mutability);
282
283 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
284 pub enum AutoBorrow {
285     /// Converts from T to &T.
286     Ref(Mutability),
287     /// Converts from T to *T.
288     RawPtr(Mutability),
289 }
290
291 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
292 pub enum PointerCast {
293     /// Go from a fn-item type to a fn-pointer type.
294     ReifyFnPointer,
295
296     /// Go from a safe fn pointer to an unsafe fn pointer.
297     UnsafeFnPointer,
298
299     /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
300     /// It cannot convert a closure that requires unsafe.
301     ClosureFnPointer(Safety),
302
303     /// Go from a mut raw pointer to a const raw pointer.
304     MutToConstPointer,
305
306     #[allow(dead_code)]
307     /// Go from `*const [T; N]` to `*const T`
308     ArrayToPointer,
309
310     /// Unsize a pointer/reference value, e.g., `&[T; n]` to
311     /// `&[T]`. Note that the source could be a thin or fat pointer.
312     /// This will do things like convert thin pointers to fat
313     /// pointers, or convert structs containing thin pointers to
314     /// structs containing fat pointers, or convert between fat
315     /// pointers. We don't store the details of how the transform is
316     /// done (in fact, we don't know that, because it might depend on
317     /// the precise type parameters). We just store the target
318     /// type. Codegen backends and miri figure out what has to be done
319     /// based on the precise source/target type at hand.
320     Unsize,
321 }
322
323 /// The result of type inference: A mapping from expressions and patterns to types.
324 #[derive(Clone, PartialEq, Eq, Debug, Default)]
325 pub struct InferenceResult {
326     /// For each method call expr, records the function it resolves to.
327     method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
328     /// For each field access expr, records the field it resolves to.
329     field_resolutions: FxHashMap<ExprId, FieldId>,
330     /// For each struct literal or pattern, records the variant it resolves to.
331     variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
332     /// For each associated item record what it resolves to
333     assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
334     pub diagnostics: Vec<InferenceDiagnostic>,
335     pub type_of_expr: ArenaMap<ExprId, Ty>,
336     /// For each pattern record the type it resolves to.
337     ///
338     /// **Note**: When a pattern type is resolved it may still contain
339     /// unresolved or missing subpatterns or subpatterns of mismatched types.
340     pub type_of_pat: ArenaMap<PatId, Ty>,
341     type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
342     /// Interned common types to return references to.
343     standard_types: InternedStandardTypes,
344     /// Stores the types which were implicitly dereferenced in pattern binding modes.
345     pub pat_adjustments: FxHashMap<PatId, Vec<Ty>>,
346     pub pat_binding_modes: FxHashMap<PatId, BindingMode>,
347     pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
348 }
349
350 impl InferenceResult {
351     pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
352         self.method_resolutions.get(&expr).cloned()
353     }
354     pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
355         self.field_resolutions.get(&expr).copied()
356     }
357     pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
358         self.variant_resolutions.get(&id.into()).copied()
359     }
360     pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
361         self.variant_resolutions.get(&id.into()).copied()
362     }
363     pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
364         self.assoc_resolutions.get(&id.into()).copied()
365     }
366     pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
367         self.assoc_resolutions.get(&id.into()).copied()
368     }
369     pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
370         self.type_mismatches.get(&expr.into())
371     }
372     pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
373         self.type_mismatches.get(&pat.into())
374     }
375     pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
376         self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
377             ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
378             _ => None,
379         })
380     }
381     pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
382         self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
383             ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
384             _ => None,
385         })
386     }
387 }
388
389 impl Index<ExprId> for InferenceResult {
390     type Output = Ty;
391
392     fn index(&self, expr: ExprId) -> &Ty {
393         self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
394     }
395 }
396
397 impl Index<PatId> for InferenceResult {
398     type Output = Ty;
399
400     fn index(&self, pat: PatId) -> &Ty {
401         self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
402     }
403 }
404
405 /// The inference context contains all information needed during type inference.
406 #[derive(Clone, Debug)]
407 pub(crate) struct InferenceContext<'a> {
408     pub(crate) db: &'a dyn HirDatabase,
409     pub(crate) owner: DefWithBodyId,
410     pub(crate) body: &'a Body,
411     pub(crate) resolver: Resolver,
412     table: unify::InferenceTable<'a>,
413     trait_env: Arc<TraitEnvironment>,
414     pub(crate) result: InferenceResult,
415     /// The return type of the function being inferred, the closure or async block if we're
416     /// currently within one.
417     ///
418     /// We might consider using a nested inference context for checking
419     /// closures, but currently this is the only field that will change there,
420     /// so it doesn't make sense.
421     return_ty: Ty,
422     /// The resume type and the yield type, respectively, of the generator being inferred.
423     resume_yield_tys: Option<(Ty, Ty)>,
424     diverges: Diverges,
425     breakables: Vec<BreakableContext>,
426 }
427
428 #[derive(Clone, Debug)]
429 struct BreakableContext {
430     /// Whether this context contains at least one break expression.
431     may_break: bool,
432     /// The coercion target of the context.
433     coerce: CoerceMany,
434     /// The optional label of the context.
435     label: Option<name::Name>,
436     kind: BreakableKind,
437 }
438
439 #[derive(Clone, Debug)]
440 enum BreakableKind {
441     Block,
442     Loop,
443     /// A border is something like an async block, closure etc. Anything that prevents
444     /// breaking/continuing through
445     Border,
446 }
447
448 fn find_breakable<'c>(
449     ctxs: &'c mut [BreakableContext],
450     label: Option<&name::Name>,
451 ) -> Option<&'c mut BreakableContext> {
452     let mut ctxs = ctxs
453         .iter_mut()
454         .rev()
455         .take_while(|it| matches!(it.kind, BreakableKind::Block | BreakableKind::Loop));
456     match label {
457         Some(_) => ctxs.find(|ctx| ctx.label.as_ref() == label),
458         None => ctxs.find(|ctx| matches!(ctx.kind, BreakableKind::Loop)),
459     }
460 }
461
462 fn find_continuable<'c>(
463     ctxs: &'c mut [BreakableContext],
464     label: Option<&name::Name>,
465 ) -> Option<&'c mut BreakableContext> {
466     match label {
467         Some(_) => find_breakable(ctxs, label).filter(|it| matches!(it.kind, BreakableKind::Loop)),
468         None => find_breakable(ctxs, label),
469     }
470 }
471
472 impl<'a> InferenceContext<'a> {
473     fn new(
474         db: &'a dyn HirDatabase,
475         owner: DefWithBodyId,
476         body: &'a Body,
477         resolver: Resolver,
478     ) -> Self {
479         let krate = owner.module(db.upcast()).krate();
480         let trait_env = owner
481             .as_generic_def_id()
482             .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
483         InferenceContext {
484             result: InferenceResult::default(),
485             table: unify::InferenceTable::new(db, trait_env.clone()),
486             trait_env,
487             return_ty: TyKind::Error.intern(Interner), // set in collect_fn_signature
488             resume_yield_tys: None,
489             db,
490             owner,
491             body,
492             resolver,
493             diverges: Diverges::Maybe,
494             breakables: Vec::new(),
495         }
496     }
497
498     fn resolve_all(self) -> InferenceResult {
499         let InferenceContext { mut table, mut result, .. } = self;
500
501         // FIXME resolve obligations as well (use Guidance if necessary)
502         table.resolve_obligations_as_possible();
503
504         // make sure diverging type variables are marked as such
505         table.propagate_diverging_flag();
506         for ty in result.type_of_expr.values_mut() {
507             *ty = table.resolve_completely(ty.clone());
508         }
509         for ty in result.type_of_pat.values_mut() {
510             *ty = table.resolve_completely(ty.clone());
511         }
512         for mismatch in result.type_mismatches.values_mut() {
513             mismatch.expected = table.resolve_completely(mismatch.expected.clone());
514             mismatch.actual = table.resolve_completely(mismatch.actual.clone());
515         }
516         for (_, subst) in result.method_resolutions.values_mut() {
517             *subst = table.resolve_completely(subst.clone());
518         }
519         for adjustment in result.expr_adjustments.values_mut().flatten() {
520             adjustment.target = table.resolve_completely(adjustment.target.clone());
521         }
522         for adjustment in result.pat_adjustments.values_mut().flatten() {
523             *adjustment = table.resolve_completely(adjustment.clone());
524         }
525         result
526     }
527
528     fn collect_const(&mut self, data: &ConstData) {
529         self.return_ty = self.make_ty(&data.type_ref);
530     }
531
532     fn collect_static(&mut self, data: &StaticData) {
533         self.return_ty = self.make_ty(&data.type_ref);
534     }
535
536     fn collect_fn(&mut self, func: FunctionId) {
537         let data = self.db.function_data(func);
538         let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
539             .with_impl_trait_mode(ImplTraitLoweringMode::Param);
540         let param_tys =
541             data.params.iter().map(|(_, type_ref)| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
542         for (ty, pat) in param_tys.into_iter().zip(self.body.params.iter()) {
543             let ty = self.insert_type_vars(ty);
544             let ty = self.normalize_associated_types_in(ty);
545
546             self.infer_pat(*pat, &ty, BindingMode::default());
547         }
548         let error_ty = &TypeRef::Error;
549         let return_ty = if data.has_async_kw() {
550             data.async_ret_type.as_deref().unwrap_or(error_ty)
551         } else {
552             &*data.ret_type
553         };
554         let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Opaque);
555         self.return_ty = return_ty;
556
557         if let Some(rpits) = self.db.return_type_impl_traits(func) {
558             // RPIT opaque types use substitution of their parent function.
559             let fn_placeholders = TyBuilder::placeholder_subst(self.db, func);
560             self.return_ty = fold_tys(
561                 self.return_ty.clone(),
562                 |ty, _| {
563                     let opaque_ty_id = match ty.kind(Interner) {
564                         TyKind::OpaqueType(opaque_ty_id, _) => *opaque_ty_id,
565                         _ => return ty,
566                     };
567                     let idx = match self.db.lookup_intern_impl_trait_id(opaque_ty_id.into()) {
568                         ImplTraitId::ReturnTypeImplTrait(_, idx) => idx,
569                         _ => unreachable!(),
570                     };
571                     let bounds = (*rpits).map_ref(|rpits| {
572                         rpits.impl_traits[idx as usize].bounds.map_ref(|it| it.into_iter())
573                     });
574                     let var = self.table.new_type_var();
575                     let var_subst = Substitution::from1(Interner, var.clone());
576                     for bound in bounds {
577                         let predicate =
578                             bound.map(|it| it.cloned()).substitute(Interner, &fn_placeholders);
579                         let (var_predicate, binders) = predicate
580                             .substitute(Interner, &var_subst)
581                             .into_value_and_skipped_binders();
582                         always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
583                         self.push_obligation(var_predicate.cast(Interner));
584                     }
585                     var
586                 },
587                 DebruijnIndex::INNERMOST,
588             );
589         }
590     }
591
592     fn infer_body(&mut self) {
593         self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
594     }
595
596     fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
597         self.result.type_of_expr.insert(expr, ty);
598     }
599
600     fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
601         self.result.expr_adjustments.insert(expr, adjustments);
602     }
603
604     fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
605         self.result.method_resolutions.insert(expr, (func, subst));
606     }
607
608     fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
609         self.result.variant_resolutions.insert(id, variant);
610     }
611
612     fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
613         self.result.assoc_resolutions.insert(id, item);
614     }
615
616     fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
617         self.result.type_of_pat.insert(pat, ty);
618     }
619
620     fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
621         self.result.diagnostics.push(diagnostic);
622     }
623
624     fn make_ty_with_mode(
625         &mut self,
626         type_ref: &TypeRef,
627         impl_trait_mode: ImplTraitLoweringMode,
628     ) -> Ty {
629         // FIXME use right resolver for block
630         let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
631             .with_impl_trait_mode(impl_trait_mode);
632         let ty = ctx.lower_ty(type_ref);
633         let ty = self.insert_type_vars(ty);
634         self.normalize_associated_types_in(ty)
635     }
636
637     fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
638         self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
639     }
640
641     fn err_ty(&self) -> Ty {
642         self.result.standard_types.unknown.clone()
643     }
644
645     /// Replaces ConstScalar::Unknown by a new type var, so we can maybe still infer it.
646     fn insert_const_vars_shallow(&mut self, c: Const) -> Const {
647         let data = c.data(Interner);
648         match data.value {
649             ConstValue::Concrete(cc) => match cc.interned {
650                 hir_def::type_ref::ConstScalar::Unknown => {
651                     self.table.new_const_var(data.ty.clone())
652                 }
653                 _ => c,
654             },
655             _ => c,
656         }
657     }
658
659     /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
660     fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
661         match ty.kind(Interner) {
662             TyKind::Error => self.table.new_type_var(),
663             TyKind::InferenceVar(..) => {
664                 let ty_resolved = self.resolve_ty_shallow(&ty);
665                 if ty_resolved.is_unknown() {
666                     self.table.new_type_var()
667                 } else {
668                     ty
669                 }
670             }
671             _ => ty,
672         }
673     }
674
675     fn insert_type_vars(&mut self, ty: Ty) -> Ty {
676         fold_tys_and_consts(
677             ty,
678             |x, _| match x {
679                 Either::Left(ty) => Either::Left(self.insert_type_vars_shallow(ty)),
680                 Either::Right(c) => Either::Right(self.insert_const_vars_shallow(c)),
681             },
682             DebruijnIndex::INNERMOST,
683         )
684     }
685
686     fn push_obligation(&mut self, o: DomainGoal) {
687         self.table.register_obligation(o.cast(Interner));
688     }
689
690     fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
691         self.table.unify(ty1, ty2)
692     }
693
694     /// Recurses through the given type, normalizing associated types mentioned
695     /// in it by replacing them by type variables and registering obligations to
696     /// resolve later. This should be done once for every type we get from some
697     /// type annotation (e.g. from a let type annotation, field type or function
698     /// call). `make_ty` handles this already, but e.g. for field types we need
699     /// to do it as well.
700     fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
701         self.table.normalize_associated_types_in(ty)
702     }
703
704     fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
705         self.table.resolve_ty_shallow(ty)
706     }
707
708     fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
709         self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
710     }
711
712     fn resolve_associated_type_with_params(
713         &mut self,
714         inner_ty: Ty,
715         assoc_ty: Option<TypeAliasId>,
716         // FIXME(GATs): these are args for the trait ref, args for assoc type itself should be
717         // handled when we support them.
718         params: &[GenericArg],
719     ) -> Ty {
720         match assoc_ty {
721             Some(res_assoc_ty) => {
722                 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
723                     hir_def::ItemContainerId::TraitId(trait_) => trait_,
724                     _ => panic!("resolve_associated_type called with non-associated type"),
725                 };
726                 let ty = self.table.new_type_var();
727                 let mut param_iter = params.iter().cloned();
728                 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
729                     .push(inner_ty)
730                     .fill(|_| param_iter.next().unwrap())
731                     .build();
732                 let alias_eq = AliasEq {
733                     alias: AliasTy::Projection(ProjectionTy {
734                         associated_ty_id: to_assoc_type_id(res_assoc_ty),
735                         substitution: trait_ref.substitution.clone(),
736                     }),
737                     ty: ty.clone(),
738                 };
739                 self.push_obligation(trait_ref.cast(Interner));
740                 self.push_obligation(alias_eq.cast(Interner));
741                 ty
742             }
743             None => self.err_ty(),
744         }
745     }
746
747     fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
748         let path = match path {
749             Some(path) => path,
750             None => return (self.err_ty(), None),
751         };
752         let resolver = &self.resolver;
753         let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
754         // FIXME: this should resolve assoc items as well, see this example:
755         // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
756         let (resolution, unresolved) = if value_ns {
757             match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
758                 Some(ResolveValueResult::ValueNs(value)) => match value {
759                     ValueNs::EnumVariantId(var) => {
760                         let substs = ctx.substs_from_path(path, var.into(), true);
761                         let ty = self.db.ty(var.parent.into());
762                         let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
763                         return (ty, Some(var.into()));
764                     }
765                     ValueNs::StructId(strukt) => {
766                         let substs = ctx.substs_from_path(path, strukt.into(), true);
767                         let ty = self.db.ty(strukt.into());
768                         let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
769                         return (ty, Some(strukt.into()));
770                     }
771                     ValueNs::ImplSelf(impl_id) => (TypeNs::SelfType(impl_id), None),
772                     _ => return (self.err_ty(), None),
773                 },
774                 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
775                 None => return (self.err_ty(), None),
776             }
777         } else {
778             match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
779                 Some(it) => it,
780                 None => return (self.err_ty(), None),
781             }
782         };
783         return match resolution {
784             TypeNs::AdtId(AdtId::StructId(strukt)) => {
785                 let substs = ctx.substs_from_path(path, strukt.into(), true);
786                 let ty = self.db.ty(strukt.into());
787                 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
788                 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
789             }
790             TypeNs::AdtId(AdtId::UnionId(u)) => {
791                 let substs = ctx.substs_from_path(path, u.into(), true);
792                 let ty = self.db.ty(u.into());
793                 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
794                 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
795             }
796             TypeNs::EnumVariantId(var) => {
797                 let substs = ctx.substs_from_path(path, var.into(), true);
798                 let ty = self.db.ty(var.parent.into());
799                 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
800                 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
801             }
802             TypeNs::SelfType(impl_id) => {
803                 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
804                 let substs = generics.placeholder_subst(self.db);
805                 let ty = self.db.impl_self_ty(impl_id).substitute(Interner, &substs);
806                 self.resolve_variant_on_alias(ty, unresolved, path)
807             }
808             TypeNs::TypeAliasId(it) => {
809                 let container = it.lookup(self.db.upcast()).container;
810                 let parent_subst = match container {
811                     ItemContainerId::TraitId(id) => {
812                         let subst = TyBuilder::subst_for_def(self.db, id, None)
813                             .fill_with_inference_vars(&mut self.table)
814                             .build();
815                         Some(subst)
816                     }
817                     // Type aliases do not exist in impls.
818                     _ => None,
819                 };
820                 let ty = TyBuilder::def_ty(self.db, it.into(), parent_subst)
821                     .fill_with_inference_vars(&mut self.table)
822                     .build();
823                 self.resolve_variant_on_alias(ty, unresolved, path)
824             }
825             TypeNs::AdtSelfType(_) => {
826                 // FIXME this could happen in array size expressions, once we're checking them
827                 (self.err_ty(), None)
828             }
829             TypeNs::GenericParam(_) => {
830                 // FIXME potentially resolve assoc type
831                 (self.err_ty(), None)
832             }
833             TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
834                 // FIXME diagnostic
835                 (self.err_ty(), None)
836             }
837         };
838
839         fn forbid_unresolved_segments(
840             result: (Ty, Option<VariantId>),
841             unresolved: Option<usize>,
842         ) -> (Ty, Option<VariantId>) {
843             if unresolved.is_none() {
844                 result
845             } else {
846                 // FIXME diagnostic
847                 (TyKind::Error.intern(Interner), None)
848             }
849         }
850     }
851
852     fn resolve_variant_on_alias(
853         &mut self,
854         ty: Ty,
855         unresolved: Option<usize>,
856         path: &Path,
857     ) -> (Ty, Option<VariantId>) {
858         let remaining = unresolved.map(|x| path.segments().skip(x).len()).filter(|x| x > &0);
859         match remaining {
860             None => {
861                 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
862                     AdtId::StructId(s) => Some(VariantId::StructId(s)),
863                     AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
864                     AdtId::EnumId(_) => {
865                         // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
866                         None
867                     }
868                 });
869                 (ty, variant)
870             }
871             Some(1) => {
872                 let segment = path.mod_path().segments().last().unwrap();
873                 // this could be an enum variant or associated type
874                 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
875                     let enum_data = self.db.enum_data(enum_id);
876                     if let Some(local_id) = enum_data.variant(segment) {
877                         let variant = EnumVariantId { parent: enum_id, local_id };
878                         return (ty, Some(variant.into()));
879                     }
880                 }
881                 // FIXME potentially resolve assoc type
882                 (self.err_ty(), None)
883             }
884             Some(_) => {
885                 // FIXME diagnostic
886                 (self.err_ty(), None)
887             }
888         }
889     }
890
891     fn resolve_lang_item(&self, name: Name) -> Option<LangItemTarget> {
892         let krate = self.resolver.krate();
893         self.db.lang_item(krate, name.to_smol_str())
894     }
895
896     fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
897         let path = path![core::iter::IntoIterator];
898         let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
899         self.db.trait_data(trait_).associated_type_by_name(&name![IntoIter])
900     }
901
902     fn resolve_iterator_item(&self) -> Option<TypeAliasId> {
903         let path = path![core::iter::Iterator];
904         let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
905         self.db.trait_data(trait_).associated_type_by_name(&name![Item])
906     }
907
908     fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
909         // FIXME resolve via lang_item once try v2 is stable
910         let path = path![core::ops::Try];
911         let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
912         let trait_data = self.db.trait_data(trait_);
913         trait_data
914             // FIXME remove once try v2 is stable
915             .associated_type_by_name(&name![Ok])
916             .or_else(|| trait_data.associated_type_by_name(&name![Output]))
917     }
918
919     fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
920         let trait_ = self.resolve_lang_item(name![neg])?.as_trait()?;
921         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
922     }
923
924     fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
925         let trait_ = self.resolve_lang_item(name![not])?.as_trait()?;
926         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
927     }
928
929     fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
930         let trait_ = self
931             .resolver
932             .resolve_known_trait(self.db.upcast(), &path![core::future::IntoFuture])
933             .or_else(|| self.resolve_lang_item(name![future_trait])?.as_trait())?;
934         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
935     }
936
937     fn resolve_boxed_box(&self) -> Option<AdtId> {
938         let struct_ = self.resolve_lang_item(name![owned_box])?.as_struct()?;
939         Some(struct_.into())
940     }
941
942     fn resolve_range_full(&self) -> Option<AdtId> {
943         let path = path![core::ops::RangeFull];
944         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
945         Some(struct_.into())
946     }
947
948     fn resolve_range(&self) -> Option<AdtId> {
949         let path = path![core::ops::Range];
950         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
951         Some(struct_.into())
952     }
953
954     fn resolve_range_inclusive(&self) -> Option<AdtId> {
955         let path = path![core::ops::RangeInclusive];
956         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
957         Some(struct_.into())
958     }
959
960     fn resolve_range_from(&self) -> Option<AdtId> {
961         let path = path![core::ops::RangeFrom];
962         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
963         Some(struct_.into())
964     }
965
966     fn resolve_range_to(&self) -> Option<AdtId> {
967         let path = path![core::ops::RangeTo];
968         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
969         Some(struct_.into())
970     }
971
972     fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
973         let path = path![core::ops::RangeToInclusive];
974         let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
975         Some(struct_.into())
976     }
977
978     fn resolve_ops_index(&self) -> Option<TraitId> {
979         self.resolve_lang_item(name![index])?.as_trait()
980     }
981
982     fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
983         let trait_ = self.resolve_ops_index()?;
984         self.db.trait_data(trait_).associated_type_by_name(&name![Output])
985     }
986 }
987
988 /// When inferring an expression, we propagate downward whatever type hint we
989 /// are able in the form of an `Expectation`.
990 #[derive(Clone, PartialEq, Eq, Debug)]
991 pub(crate) enum Expectation {
992     None,
993     HasType(Ty),
994     // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
995     RValueLikeUnsized(Ty),
996 }
997
998 impl Expectation {
999     /// The expectation that the type of the expression needs to equal the given
1000     /// type.
1001     fn has_type(ty: Ty) -> Self {
1002         if ty.is_unknown() {
1003             // FIXME: get rid of this?
1004             Expectation::None
1005         } else {
1006             Expectation::HasType(ty)
1007         }
1008     }
1009
1010     fn from_option(ty: Option<Ty>) -> Self {
1011         ty.map_or(Expectation::None, Expectation::HasType)
1012     }
1013
1014     /// The following explanation is copied straight from rustc:
1015     /// Provides an expectation for an rvalue expression given an *optional*
1016     /// hint, which is not required for type safety (the resulting type might
1017     /// be checked higher up, as is the case with `&expr` and `box expr`), but
1018     /// is useful in determining the concrete type.
1019     ///
1020     /// The primary use case is where the expected type is a fat pointer,
1021     /// like `&[isize]`. For example, consider the following statement:
1022     ///
1023     ///    let x: &[isize] = &[1, 2, 3];
1024     ///
1025     /// In this case, the expected type for the `&[1, 2, 3]` expression is
1026     /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
1027     /// expectation `ExpectHasType([isize])`, that would be too strong --
1028     /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
1029     /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
1030     /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
1031     /// which still is useful, because it informs integer literals and the like.
1032     /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
1033     /// for examples of where this comes up,.
1034     fn rvalue_hint(table: &mut unify::InferenceTable<'_>, ty: Ty) -> Self {
1035         // FIXME: do struct_tail_without_normalization
1036         match table.resolve_ty_shallow(&ty).kind(Interner) {
1037             TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
1038             _ => Expectation::has_type(ty),
1039         }
1040     }
1041
1042     /// This expresses no expectation on the type.
1043     fn none() -> Self {
1044         Expectation::None
1045     }
1046
1047     fn resolve(&self, table: &mut unify::InferenceTable<'_>) -> Expectation {
1048         match self {
1049             Expectation::None => Expectation::None,
1050             Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
1051             Expectation::RValueLikeUnsized(t) => {
1052                 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
1053             }
1054         }
1055     }
1056
1057     fn to_option(&self, table: &mut unify::InferenceTable<'_>) -> Option<Ty> {
1058         match self.resolve(table) {
1059             Expectation::None => None,
1060             Expectation::HasType(t) |
1061             // Expectation::Castable(t) |
1062             Expectation::RValueLikeUnsized(t) => Some(t),
1063         }
1064     }
1065
1066     fn only_has_type(&self, table: &mut unify::InferenceTable<'_>) -> Option<Ty> {
1067         match self {
1068             Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
1069             // Expectation::Castable(_) |
1070             Expectation::RValueLikeUnsized(_) | Expectation::None => None,
1071         }
1072     }
1073
1074     /// Comment copied from rustc:
1075     /// Disregard "castable to" expectations because they
1076     /// can lead us astray. Consider for example `if cond
1077     /// {22} else {c} as u8` -- if we propagate the
1078     /// "castable to u8" constraint to 22, it will pick the
1079     /// type 22u8, which is overly constrained (c might not
1080     /// be a u8). In effect, the problem is that the
1081     /// "castable to" expectation is not the tightest thing
1082     /// we can say, so we want to drop it in this case.
1083     /// The tightest thing we can say is "must unify with
1084     /// else branch". Note that in the case of a "has type"
1085     /// constraint, this limitation does not hold.
1086     ///
1087     /// If the expected type is just a type variable, then don't use
1088     /// an expected type. Otherwise, we might write parts of the type
1089     /// when checking the 'then' block which are incompatible with the
1090     /// 'else' branch.
1091     fn adjust_for_branches(&self, table: &mut unify::InferenceTable<'_>) -> Expectation {
1092         match self {
1093             Expectation::HasType(ety) => {
1094                 let ety = table.resolve_ty_shallow(ety);
1095                 if !ety.is_ty_var() {
1096                     Expectation::HasType(ety)
1097                 } else {
1098                     Expectation::None
1099                 }
1100             }
1101             Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
1102             _ => Expectation::None,
1103         }
1104     }
1105 }
1106
1107 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1108 enum Diverges {
1109     Maybe,
1110     Always,
1111 }
1112
1113 impl Diverges {
1114     fn is_always(self) -> bool {
1115         self == Diverges::Always
1116     }
1117 }
1118
1119 impl std::ops::BitAnd for Diverges {
1120     type Output = Self;
1121     fn bitand(self, other: Self) -> Self {
1122         std::cmp::min(self, other)
1123     }
1124 }
1125
1126 impl std::ops::BitOr for Diverges {
1127     type Output = Self;
1128     fn bitor(self, other: Self) -> Self {
1129         std::cmp::max(self, other)
1130     }
1131 }
1132
1133 impl std::ops::BitAndAssign for Diverges {
1134     fn bitand_assign(&mut self, other: Self) {
1135         *self = *self & other;
1136     }
1137 }
1138
1139 impl std::ops::BitOrAssign for Diverges {
1140     fn bitor_assign(&mut self, other: Self) {
1141         *self = *self | other;
1142     }
1143 }