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