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