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