1 //! Type inference, i.e. the process of walking through the code and determining
2 //! the type of each expression and pattern.
4 //! For type inference, compare the implementations in rustc (the various
5 //! check_* methods in rustc_hir_analysis/check/mod.rs are a good entry point) and
6 //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for
7 //! inference here is the `infer` function, which infers the types of all
8 //! expressions in a given function.
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.
19 use chalk_ir::{cast::Cast, ConstValue, DebruijnIndex, Mutability, Safety, Scalar, TypeFlags};
22 builtin_type::BuiltinType,
23 data::{ConstData, StaticData},
24 expr::{BindingAnnotation, ExprId, PatId},
25 lang_item::LangItemTarget,
27 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
29 AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId, FunctionId, HasModule,
30 ItemContainerId, Lookup, TraitId, TypeAliasId, VariantId,
32 use hir_expand::name::{name, Name};
33 use itertools::Either;
34 use la_arena::ArenaMap;
35 use rustc_hash::FxHashMap;
36 use stdx::{always, impl_from};
39 db::HirDatabase, fold_tys, fold_tys_and_consts, infer::coerce::CoerceMany,
40 lower::ImplTraitLoweringMode, to_assoc_type_id, AliasEq, AliasTy, Const, DomainGoal,
41 GenericArg, Goal, ImplTraitId, InEnvironment, Interner, ProjectionTy, Substitution,
42 TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
45 // This lint has a false positive here. See the link below for details.
47 // https://github.com/rust-lang/rust/issues/57411
48 #[allow(unreachable_pub)]
49 pub use coerce::could_coerce;
50 #[allow(unreachable_pub)]
51 pub use unify::could_unify;
60 /// The entry point of type inference.
61 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
62 let _p = profile::span("infer_query");
63 let resolver = def.resolver(db.upcast());
64 let body = db.body(def);
65 let mut ctx = InferenceContext::new(db, def, &body, resolver);
68 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
69 DefWithBodyId::FunctionId(f) => ctx.collect_fn(f),
70 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
71 DefWithBodyId::VariantId(v) => {
72 ctx.return_ty = TyBuilder::builtin(match db.enum_data(v.parent).variant_body_type() {
73 Either::Left(builtin) => BuiltinType::Int(builtin),
74 Either::Right(builtin) => BuiltinType::Uint(builtin),
81 Arc::new(ctx.resolve_all())
84 /// Fully normalize all the types found within `ty` in context of `owner` body definition.
86 /// This is appropriate to use only after type-check: it assumes
87 /// that normalization will succeed, for example.
88 pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> Ty {
89 if !ty.data(Interner).flags.intersects(TypeFlags::HAS_PROJECTION) {
92 let krate = owner.module(db.upcast()).krate();
95 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
96 let mut table = unify::InferenceTable::new(db, trait_env);
98 let ty_with_vars = table.normalize_associated_types_in(ty);
99 table.resolve_obligations_as_possible();
100 table.propagate_diverging_flag();
101 table.resolve_completely(ty_with_vars)
104 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
109 impl_from!(ExprId, PatId for ExprOrPatId);
111 /// Binding modes inferred for patterns.
112 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
113 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
114 pub enum BindingMode {
120 fn convert(annotation: BindingAnnotation) -> BindingMode {
122 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
123 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
124 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
129 impl Default for BindingMode {
130 fn default() -> Self {
135 /// Used to generalize patterns and assignee expressions.
136 trait PatLike: Into<ExprOrPatId> + Copy {
137 type BindingMode: Copy;
140 this: &mut InferenceContext<'_>,
143 default_bm: Self::BindingMode,
147 impl PatLike for ExprId {
148 type BindingMode = ();
151 this: &mut InferenceContext<'_>,
154 _: Self::BindingMode,
156 this.infer_assignee_expr(id, expected_ty)
160 impl PatLike for PatId {
161 type BindingMode = BindingMode;
164 this: &mut InferenceContext<'_>,
167 default_bm: Self::BindingMode,
169 this.infer_pat(id, expected_ty, default_bm)
174 pub(crate) struct InferOk<T> {
176 goals: Vec<InEnvironment<Goal>>,
180 fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
181 InferOk { value: f(self.value), goals: self.goals }
186 pub(crate) struct TypeError;
187 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
189 #[derive(Debug, PartialEq, Eq, Clone)]
190 pub enum InferenceDiagnostic {
191 NoSuchField { expr: ExprId },
192 BreakOutsideOfLoop { expr: ExprId, is_break: bool },
193 MismatchedArgCount { call_expr: ExprId, expected: usize, found: usize },
196 /// A mismatch between an expected and an inferred type.
197 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
198 pub struct TypeMismatch {
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 struct InternedStandardTypes {
210 impl Default for InternedStandardTypes {
211 fn default() -> Self {
212 InternedStandardTypes {
213 unknown: TyKind::Error.intern(Interner),
214 bool_: TyKind::Scalar(Scalar::Bool).intern(Interner),
215 unit: TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner),
219 /// Represents coercing a value to a different type of value.
221 /// We transform values by following a number of `Adjust` steps in order.
222 /// See the documentation on variants of `Adjust` for more details.
224 /// Here are some common scenarios:
226 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
227 /// Here the pointer will be dereferenced N times (where a dereference can
228 /// happen to raw or borrowed pointers or any smart pointer which implements
229 /// Deref, including Box<_>). The types of dereferences is given by
230 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
231 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
234 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
235 /// with a thin pointer, deref a number of times, unsize the underlying data,
236 /// then autoref. The 'unsize' phase may change a fixed length array to a
237 /// dynamically sized one, a concrete object to a trait object, or statically
238 /// sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
242 /// Deref(None) -> [i32; 4],
243 /// Borrow(AutoBorrow::Ref) -> &[i32; 4],
244 /// Unsize -> &[i32],
247 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
248 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
249 /// The autoderef and -ref are the same as in the above example, but the type
250 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
251 /// the underlying conversions from `[i32; 4]` to `[i32]`.
253 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
254 /// that case, we have the pointer we need coming in, so there are no
255 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
256 /// At some point, of course, `Box` should move out of the compiler, in which
257 /// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
258 /// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
259 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
260 pub struct Adjustment {
265 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
267 /// Go from ! to any type.
269 /// Dereference once, producing a place.
270 Deref(Option<OverloadedDeref>),
271 /// Take the address and produce either a `&` or `*` pointer.
273 Pointer(PointerCast),
276 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
277 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
278 /// The target type is `U` in both cases, with the region and mutability
279 /// being those shared by both the receiver and the returned reference.
280 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
281 pub struct OverloadedDeref(pub Mutability);
283 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
284 pub enum AutoBorrow {
285 /// Converts from T to &T.
287 /// Converts from T to *T.
291 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
292 pub enum PointerCast {
293 /// Go from a fn-item type to a fn-pointer type.
296 /// Go from a safe fn pointer to an unsafe fn pointer.
299 /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
300 /// It cannot convert a closure that requires unsafe.
301 ClosureFnPointer(Safety),
303 /// Go from a mut raw pointer to a const raw pointer.
307 /// Go from `*const [T; N]` to `*const T`
310 /// Unsize a pointer/reference value, e.g., `&[T; n]` to
311 /// `&[T]`. Note that the source could be a thin or fat pointer.
312 /// This will do things like convert thin pointers to fat
313 /// pointers, or convert structs containing thin pointers to
314 /// structs containing fat pointers, or convert between fat
315 /// pointers. We don't store the details of how the transform is
316 /// done (in fact, we don't know that, because it might depend on
317 /// the precise type parameters). We just store the target
318 /// type. Codegen backends and miri figure out what has to be done
319 /// based on the precise source/target type at hand.
323 /// The result of type inference: A mapping from expressions and patterns to types.
324 #[derive(Clone, PartialEq, Eq, Debug, Default)]
325 pub struct InferenceResult {
326 /// For each method call expr, records the function it resolves to.
327 method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
328 /// For each field access expr, records the field it resolves to.
329 field_resolutions: FxHashMap<ExprId, FieldId>,
330 /// For each struct literal or pattern, records the variant it resolves to.
331 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
332 /// For each associated item record what it resolves to
333 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
334 pub diagnostics: Vec<InferenceDiagnostic>,
335 pub type_of_expr: ArenaMap<ExprId, Ty>,
336 /// For each pattern record the type it resolves to.
338 /// **Note**: When a pattern type is resolved it may still contain
339 /// unresolved or missing subpatterns or subpatterns of mismatched types.
340 pub type_of_pat: ArenaMap<PatId, Ty>,
341 type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
342 /// Interned common types to return references to.
343 standard_types: InternedStandardTypes,
344 /// Stores the types which were implicitly dereferenced in pattern binding modes.
345 pub pat_adjustments: FxHashMap<PatId, Vec<Ty>>,
346 pub pat_binding_modes: FxHashMap<PatId, BindingMode>,
347 pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
350 impl InferenceResult {
351 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
352 self.method_resolutions.get(&expr).cloned()
354 pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
355 self.field_resolutions.get(&expr).copied()
357 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
358 self.variant_resolutions.get(&id.into()).copied()
360 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
361 self.variant_resolutions.get(&id.into()).copied()
363 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
364 self.assoc_resolutions.get(&id.into()).copied()
366 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
367 self.assoc_resolutions.get(&id.into()).copied()
369 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
370 self.type_mismatches.get(&expr.into())
372 pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
373 self.type_mismatches.get(&pat.into())
375 pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
376 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
377 ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
381 pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
382 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
383 ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
389 impl Index<ExprId> for InferenceResult {
392 fn index(&self, expr: ExprId) -> &Ty {
393 self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
397 impl Index<PatId> for InferenceResult {
400 fn index(&self, pat: PatId) -> &Ty {
401 self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
405 /// The inference context contains all information needed during type inference.
406 #[derive(Clone, Debug)]
407 pub(crate) struct InferenceContext<'a> {
408 pub(crate) db: &'a dyn HirDatabase,
409 pub(crate) owner: DefWithBodyId,
410 pub(crate) body: &'a Body,
411 pub(crate) resolver: Resolver,
412 table: unify::InferenceTable<'a>,
413 trait_env: Arc<TraitEnvironment>,
414 pub(crate) result: InferenceResult,
415 /// The return type of the function being inferred, the closure or async block if we're
416 /// currently within one.
418 /// We might consider using a nested inference context for checking
419 /// closures, but currently this is the only field that will change there,
420 /// so it doesn't make sense.
422 /// The resume type and the yield type, respectively, of the generator being inferred.
423 resume_yield_tys: Option<(Ty, Ty)>,
425 breakables: Vec<BreakableContext>,
428 #[derive(Clone, Debug)]
429 struct BreakableContext {
430 /// Whether this context contains at least one break expression.
432 /// The coercion target of the context.
434 /// The optional label of the context.
435 label: Option<name::Name>,
439 #[derive(Clone, Debug)]
443 /// A border is something like an async block, closure etc. Anything that prevents
444 /// breaking/continuing through
448 fn find_breakable<'c>(
449 ctxs: &'c mut [BreakableContext],
450 label: Option<&name::Name>,
451 ) -> Option<&'c mut BreakableContext> {
455 .take_while(|it| matches!(it.kind, BreakableKind::Block | BreakableKind::Loop));
457 Some(_) => ctxs.find(|ctx| ctx.label.as_ref() == label),
458 None => ctxs.find(|ctx| matches!(ctx.kind, BreakableKind::Loop)),
462 fn find_continuable<'c>(
463 ctxs: &'c mut [BreakableContext],
464 label: Option<&name::Name>,
465 ) -> Option<&'c mut BreakableContext> {
467 Some(_) => find_breakable(ctxs, label).filter(|it| matches!(it.kind, BreakableKind::Loop)),
468 None => find_breakable(ctxs, label),
472 impl<'a> InferenceContext<'a> {
474 db: &'a dyn HirDatabase,
475 owner: DefWithBodyId,
479 let krate = owner.module(db.upcast()).krate();
480 let trait_env = owner
482 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
484 result: InferenceResult::default(),
485 table: unify::InferenceTable::new(db, trait_env.clone()),
487 return_ty: TyKind::Error.intern(Interner), // set in collect_fn_signature
488 resume_yield_tys: None,
493 diverges: Diverges::Maybe,
494 breakables: Vec::new(),
498 fn resolve_all(self) -> InferenceResult {
499 let InferenceContext { mut table, mut result, .. } = self;
501 // FIXME resolve obligations as well (use Guidance if necessary)
502 table.resolve_obligations_as_possible();
504 // make sure diverging type variables are marked as such
505 table.propagate_diverging_flag();
506 for ty in result.type_of_expr.values_mut() {
507 *ty = table.resolve_completely(ty.clone());
509 for ty in result.type_of_pat.values_mut() {
510 *ty = table.resolve_completely(ty.clone());
512 for mismatch in result.type_mismatches.values_mut() {
513 mismatch.expected = table.resolve_completely(mismatch.expected.clone());
514 mismatch.actual = table.resolve_completely(mismatch.actual.clone());
516 for (_, subst) in result.method_resolutions.values_mut() {
517 *subst = table.resolve_completely(subst.clone());
519 for adjustment in result.expr_adjustments.values_mut().flatten() {
520 adjustment.target = table.resolve_completely(adjustment.target.clone());
522 for adjustment in result.pat_adjustments.values_mut().flatten() {
523 *adjustment = table.resolve_completely(adjustment.clone());
528 fn collect_const(&mut self, data: &ConstData) {
529 self.return_ty = self.make_ty(&data.type_ref);
532 fn collect_static(&mut self, data: &StaticData) {
533 self.return_ty = self.make_ty(&data.type_ref);
536 fn collect_fn(&mut self, func: FunctionId) {
537 let data = self.db.function_data(func);
538 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
539 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
541 data.params.iter().map(|(_, type_ref)| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
542 for (ty, pat) in param_tys.into_iter().zip(self.body.params.iter()) {
543 let ty = self.insert_type_vars(ty);
544 let ty = self.normalize_associated_types_in(ty);
546 self.infer_pat(*pat, &ty, BindingMode::default());
548 let error_ty = &TypeRef::Error;
549 let return_ty = if data.has_async_kw() {
550 data.async_ret_type.as_deref().unwrap_or(error_ty)
554 let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Opaque);
555 self.return_ty = return_ty;
557 if let Some(rpits) = self.db.return_type_impl_traits(func) {
558 // RPIT opaque types use substitution of their parent function.
559 let fn_placeholders = TyBuilder::placeholder_subst(self.db, func);
560 self.return_ty = fold_tys(
561 self.return_ty.clone(),
563 let opaque_ty_id = match ty.kind(Interner) {
564 TyKind::OpaqueType(opaque_ty_id, _) => *opaque_ty_id,
567 let idx = match self.db.lookup_intern_impl_trait_id(opaque_ty_id.into()) {
568 ImplTraitId::ReturnTypeImplTrait(_, idx) => idx,
571 let bounds = (*rpits).map_ref(|rpits| {
572 rpits.impl_traits[idx as usize].bounds.map_ref(|it| it.into_iter())
574 let var = self.table.new_type_var();
575 let var_subst = Substitution::from1(Interner, var.clone());
576 for bound in bounds {
578 bound.map(|it| it.cloned()).substitute(Interner, &fn_placeholders);
579 let (var_predicate, binders) = predicate
580 .substitute(Interner, &var_subst)
581 .into_value_and_skipped_binders();
582 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
583 self.push_obligation(var_predicate.cast(Interner));
587 DebruijnIndex::INNERMOST,
592 fn infer_body(&mut self) {
593 self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
596 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
597 self.result.type_of_expr.insert(expr, ty);
600 fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
601 self.result.expr_adjustments.insert(expr, adjustments);
604 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
605 self.result.method_resolutions.insert(expr, (func, subst));
608 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
609 self.result.variant_resolutions.insert(id, variant);
612 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
613 self.result.assoc_resolutions.insert(id, item);
616 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
617 self.result.type_of_pat.insert(pat, ty);
620 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
621 self.result.diagnostics.push(diagnostic);
624 fn make_ty_with_mode(
627 impl_trait_mode: ImplTraitLoweringMode,
629 // FIXME use right resolver for block
630 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
631 .with_impl_trait_mode(impl_trait_mode);
632 let ty = ctx.lower_ty(type_ref);
633 let ty = self.insert_type_vars(ty);
634 self.normalize_associated_types_in(ty)
637 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
638 self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
641 fn err_ty(&self) -> Ty {
642 self.result.standard_types.unknown.clone()
645 /// Replaces ConstScalar::Unknown by a new type var, so we can maybe still infer it.
646 fn insert_const_vars_shallow(&mut self, c: Const) -> Const {
647 let data = c.data(Interner);
649 ConstValue::Concrete(cc) => match cc.interned {
650 hir_def::type_ref::ConstScalar::Unknown => {
651 self.table.new_const_var(data.ty.clone())
659 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
660 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
661 match ty.kind(Interner) {
662 TyKind::Error => self.table.new_type_var(),
663 TyKind::InferenceVar(..) => {
664 let ty_resolved = self.resolve_ty_shallow(&ty);
665 if ty_resolved.is_unknown() {
666 self.table.new_type_var()
675 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
679 Either::Left(ty) => Either::Left(self.insert_type_vars_shallow(ty)),
680 Either::Right(c) => Either::Right(self.insert_const_vars_shallow(c)),
682 DebruijnIndex::INNERMOST,
686 fn push_obligation(&mut self, o: DomainGoal) {
687 self.table.register_obligation(o.cast(Interner));
690 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
691 self.table.unify(ty1, ty2)
694 /// Recurses through the given type, normalizing associated types mentioned
695 /// in it by replacing them by type variables and registering obligations to
696 /// resolve later. This should be done once for every type we get from some
697 /// type annotation (e.g. from a let type annotation, field type or function
698 /// call). `make_ty` handles this already, but e.g. for field types we need
699 /// to do it as well.
700 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
701 self.table.normalize_associated_types_in(ty)
704 fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
705 self.table.resolve_ty_shallow(ty)
708 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
709 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
712 fn resolve_associated_type_with_params(
715 assoc_ty: Option<TypeAliasId>,
716 // FIXME(GATs): these are args for the trait ref, args for assoc type itself should be
717 // handled when we support them.
718 params: &[GenericArg],
721 Some(res_assoc_ty) => {
722 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
723 hir_def::ItemContainerId::TraitId(trait_) => trait_,
724 _ => panic!("resolve_associated_type called with non-associated type"),
726 let ty = self.table.new_type_var();
727 let mut param_iter = params.iter().cloned();
728 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
730 .fill(|_| param_iter.next().unwrap())
732 let alias_eq = AliasEq {
733 alias: AliasTy::Projection(ProjectionTy {
734 associated_ty_id: to_assoc_type_id(res_assoc_ty),
735 substitution: trait_ref.substitution.clone(),
739 self.push_obligation(trait_ref.cast(Interner));
740 self.push_obligation(alias_eq.cast(Interner));
743 None => self.err_ty(),
747 fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
748 let path = match path {
750 None => return (self.err_ty(), None),
752 let resolver = &self.resolver;
753 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
754 // FIXME: this should resolve assoc items as well, see this example:
755 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
756 let (resolution, unresolved) = if value_ns {
757 match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
758 Some(ResolveValueResult::ValueNs(value)) => match value {
759 ValueNs::EnumVariantId(var) => {
760 let substs = ctx.substs_from_path(path, var.into(), true);
761 let ty = self.db.ty(var.parent.into());
762 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
763 return (ty, Some(var.into()));
765 ValueNs::StructId(strukt) => {
766 let substs = ctx.substs_from_path(path, strukt.into(), true);
767 let ty = self.db.ty(strukt.into());
768 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
769 return (ty, Some(strukt.into()));
771 ValueNs::ImplSelf(impl_id) => (TypeNs::SelfType(impl_id), None),
772 _ => return (self.err_ty(), None),
774 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
775 None => return (self.err_ty(), None),
778 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
780 None => return (self.err_ty(), None),
783 return match resolution {
784 TypeNs::AdtId(AdtId::StructId(strukt)) => {
785 let substs = ctx.substs_from_path(path, strukt.into(), true);
786 let ty = self.db.ty(strukt.into());
787 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
788 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
790 TypeNs::AdtId(AdtId::UnionId(u)) => {
791 let substs = ctx.substs_from_path(path, u.into(), true);
792 let ty = self.db.ty(u.into());
793 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
794 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
796 TypeNs::EnumVariantId(var) => {
797 let substs = ctx.substs_from_path(path, var.into(), true);
798 let ty = self.db.ty(var.parent.into());
799 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
800 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
802 TypeNs::SelfType(impl_id) => {
803 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
804 let substs = generics.placeholder_subst(self.db);
805 let ty = self.db.impl_self_ty(impl_id).substitute(Interner, &substs);
806 self.resolve_variant_on_alias(ty, unresolved, path)
808 TypeNs::TypeAliasId(it) => {
809 let container = it.lookup(self.db.upcast()).container;
810 let parent_subst = match container {
811 ItemContainerId::TraitId(id) => {
812 let subst = TyBuilder::subst_for_def(self.db, id, None)
813 .fill_with_inference_vars(&mut self.table)
817 // Type aliases do not exist in impls.
820 let ty = TyBuilder::def_ty(self.db, it.into(), parent_subst)
821 .fill_with_inference_vars(&mut self.table)
823 self.resolve_variant_on_alias(ty, unresolved, path)
825 TypeNs::AdtSelfType(_) => {
826 // FIXME this could happen in array size expressions, once we're checking them
827 (self.err_ty(), None)
829 TypeNs::GenericParam(_) => {
830 // FIXME potentially resolve assoc type
831 (self.err_ty(), None)
833 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
835 (self.err_ty(), None)
839 fn forbid_unresolved_segments(
840 result: (Ty, Option<VariantId>),
841 unresolved: Option<usize>,
842 ) -> (Ty, Option<VariantId>) {
843 if unresolved.is_none() {
847 (TyKind::Error.intern(Interner), None)
852 fn resolve_variant_on_alias(
855 unresolved: Option<usize>,
857 ) -> (Ty, Option<VariantId>) {
858 let remaining = unresolved.map(|x| path.segments().skip(x).len()).filter(|x| x > &0);
861 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
862 AdtId::StructId(s) => Some(VariantId::StructId(s)),
863 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
864 AdtId::EnumId(_) => {
865 // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
872 let segment = path.mod_path().segments().last().unwrap();
873 // this could be an enum variant or associated type
874 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
875 let enum_data = self.db.enum_data(enum_id);
876 if let Some(local_id) = enum_data.variant(segment) {
877 let variant = EnumVariantId { parent: enum_id, local_id };
878 return (ty, Some(variant.into()));
881 // FIXME potentially resolve assoc type
882 (self.err_ty(), None)
886 (self.err_ty(), None)
891 fn resolve_lang_item(&self, name: Name) -> Option<LangItemTarget> {
892 let krate = self.resolver.krate();
893 self.db.lang_item(krate, name.to_smol_str())
896 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
897 let path = path![core::iter::IntoIterator];
898 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
899 self.db.trait_data(trait_).associated_type_by_name(&name![IntoIter])
902 fn resolve_iterator_item(&self) -> Option<TypeAliasId> {
903 let path = path![core::iter::Iterator];
904 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
905 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
908 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
909 // FIXME resolve via lang_item once try v2 is stable
910 let path = path![core::ops::Try];
911 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
912 let trait_data = self.db.trait_data(trait_);
914 // FIXME remove once try v2 is stable
915 .associated_type_by_name(&name![Ok])
916 .or_else(|| trait_data.associated_type_by_name(&name![Output]))
919 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
920 let trait_ = self.resolve_lang_item(name![neg])?.as_trait()?;
921 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
924 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
925 let trait_ = self.resolve_lang_item(name![not])?.as_trait()?;
926 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
929 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
932 .resolve_known_trait(self.db.upcast(), &path![core::future::IntoFuture])
933 .or_else(|| self.resolve_lang_item(name![future_trait])?.as_trait())?;
934 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
937 fn resolve_boxed_box(&self) -> Option<AdtId> {
938 let struct_ = self.resolve_lang_item(name![owned_box])?.as_struct()?;
942 fn resolve_range_full(&self) -> Option<AdtId> {
943 let path = path![core::ops::RangeFull];
944 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
948 fn resolve_range(&self) -> Option<AdtId> {
949 let path = path![core::ops::Range];
950 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
954 fn resolve_range_inclusive(&self) -> Option<AdtId> {
955 let path = path![core::ops::RangeInclusive];
956 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
960 fn resolve_range_from(&self) -> Option<AdtId> {
961 let path = path![core::ops::RangeFrom];
962 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
966 fn resolve_range_to(&self) -> Option<AdtId> {
967 let path = path![core::ops::RangeTo];
968 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
972 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
973 let path = path![core::ops::RangeToInclusive];
974 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
978 fn resolve_ops_index(&self) -> Option<TraitId> {
979 self.resolve_lang_item(name![index])?.as_trait()
982 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
983 let trait_ = self.resolve_ops_index()?;
984 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
988 /// When inferring an expression, we propagate downward whatever type hint we
989 /// are able in the form of an `Expectation`.
990 #[derive(Clone, PartialEq, Eq, Debug)]
991 pub(crate) enum Expectation {
994 // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
995 RValueLikeUnsized(Ty),
999 /// The expectation that the type of the expression needs to equal the given
1001 fn has_type(ty: Ty) -> Self {
1002 if ty.is_unknown() {
1003 // FIXME: get rid of this?
1006 Expectation::HasType(ty)
1010 fn from_option(ty: Option<Ty>) -> Self {
1011 ty.map_or(Expectation::None, Expectation::HasType)
1014 /// The following explanation is copied straight from rustc:
1015 /// Provides an expectation for an rvalue expression given an *optional*
1016 /// hint, which is not required for type safety (the resulting type might
1017 /// be checked higher up, as is the case with `&expr` and `box expr`), but
1018 /// is useful in determining the concrete type.
1020 /// The primary use case is where the expected type is a fat pointer,
1021 /// like `&[isize]`. For example, consider the following statement:
1023 /// let x: &[isize] = &[1, 2, 3];
1025 /// In this case, the expected type for the `&[1, 2, 3]` expression is
1026 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
1027 /// expectation `ExpectHasType([isize])`, that would be too strong --
1028 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
1029 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
1030 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
1031 /// which still is useful, because it informs integer literals and the like.
1032 /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
1033 /// for examples of where this comes up,.
1034 fn rvalue_hint(table: &mut unify::InferenceTable<'_>, ty: Ty) -> Self {
1035 // FIXME: do struct_tail_without_normalization
1036 match table.resolve_ty_shallow(&ty).kind(Interner) {
1037 TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
1038 _ => Expectation::has_type(ty),
1042 /// This expresses no expectation on the type.
1047 fn resolve(&self, table: &mut unify::InferenceTable<'_>) -> Expectation {
1049 Expectation::None => Expectation::None,
1050 Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
1051 Expectation::RValueLikeUnsized(t) => {
1052 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
1057 fn to_option(&self, table: &mut unify::InferenceTable<'_>) -> Option<Ty> {
1058 match self.resolve(table) {
1059 Expectation::None => None,
1060 Expectation::HasType(t) |
1061 // Expectation::Castable(t) |
1062 Expectation::RValueLikeUnsized(t) => Some(t),
1066 fn only_has_type(&self, table: &mut unify::InferenceTable<'_>) -> Option<Ty> {
1068 Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
1069 // Expectation::Castable(_) |
1070 Expectation::RValueLikeUnsized(_) | Expectation::None => None,
1074 /// Comment copied from rustc:
1075 /// Disregard "castable to" expectations because they
1076 /// can lead us astray. Consider for example `if cond
1077 /// {22} else {c} as u8` -- if we propagate the
1078 /// "castable to u8" constraint to 22, it will pick the
1079 /// type 22u8, which is overly constrained (c might not
1080 /// be a u8). In effect, the problem is that the
1081 /// "castable to" expectation is not the tightest thing
1082 /// we can say, so we want to drop it in this case.
1083 /// The tightest thing we can say is "must unify with
1084 /// else branch". Note that in the case of a "has type"
1085 /// constraint, this limitation does not hold.
1087 /// If the expected type is just a type variable, then don't use
1088 /// an expected type. Otherwise, we might write parts of the type
1089 /// when checking the 'then' block which are incompatible with the
1091 fn adjust_for_branches(&self, table: &mut unify::InferenceTable<'_>) -> Expectation {
1093 Expectation::HasType(ety) => {
1094 let ety = table.resolve_ty_shallow(ety);
1095 if !ety.is_ty_var() {
1096 Expectation::HasType(ety)
1101 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
1102 _ => Expectation::None,
1107 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1114 fn is_always(self) -> bool {
1115 self == Diverges::Always
1119 impl std::ops::BitAnd for Diverges {
1121 fn bitand(self, other: Self) -> Self {
1122 std::cmp::min(self, other)
1126 impl std::ops::BitOr for Diverges {
1128 fn bitor(self, other: Self) -> Self {
1129 std::cmp::max(self, other)
1133 impl std::ops::BitAndAssign for Diverges {
1134 fn bitand_assign(&mut self, other: Self) {
1135 *self = *self & other;
1139 impl std::ops::BitOrAssign for Diverges {
1140 fn bitor_assign(&mut self, other: Self) {
1141 *self = *self | other;