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