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 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.
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, DebruijnIndex, Mutability, Safety, Scalar, TypeFlags};
22 data::{ConstData, FunctionData, StaticData},
23 expr::{BindingAnnotation, ExprId, PatId},
24 lang_item::LangItemTarget,
26 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
28 AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId, FunctionId, HasModule, Lookup,
29 TraitId, TypeAliasId, VariantId,
31 use hir_expand::name::{name, Name};
32 use la_arena::ArenaMap;
33 use rustc_hash::FxHashMap;
37 db::HirDatabase, fold_tys, infer::coerce::CoerceMany, lower::ImplTraitLoweringMode,
38 to_assoc_type_id, AliasEq, AliasTy, DomainGoal, Goal, InEnvironment, Interner, ProjectionTy,
39 Substitution, TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
42 // This lint has a false positive here. See the link below for details.
44 // https://github.com/rust-lang/rust/issues/57411
45 #[allow(unreachable_pub)]
46 pub use unify::could_unify;
47 pub(crate) use unify::unify;
56 /// The entry point of type inference.
57 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
58 let _p = profile::span("infer_query");
59 let resolver = def.resolver(db.upcast());
60 let mut ctx = InferenceContext::new(db, def, resolver);
63 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
64 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
65 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
70 Arc::new(ctx.resolve_all())
73 /// Fully normalize all the types found within `ty` in context of `owner` body definition.
75 /// This is appropriate to use only after type-check: it assumes
76 /// that normalization will succeed, for example.
77 pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> Ty {
78 if !ty.data(Interner).flags.intersects(TypeFlags::HAS_PROJECTION) {
81 let krate = owner.module(db.upcast()).krate();
84 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
85 let mut table = unify::InferenceTable::new(db, trait_env.clone());
87 let ty_with_vars = table.normalize_associated_types_in(ty);
88 table.resolve_obligations_as_possible();
89 table.propagate_diverging_flag();
90 table.resolve_completely(ty_with_vars)
93 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
98 impl_from!(ExprId, PatId for ExprOrPatId);
100 /// Binding modes inferred for patterns.
101 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
102 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
103 pub enum BindingMode {
109 fn convert(annotation: BindingAnnotation) -> BindingMode {
111 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
112 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
113 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
118 impl Default for BindingMode {
119 fn default() -> Self {
125 pub(crate) struct InferOk<T> {
127 goals: Vec<InEnvironment<Goal>>,
131 fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
132 InferOk { value: f(self.value), goals: self.goals }
137 pub(crate) struct TypeError;
138 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
140 #[derive(Debug, PartialEq, Eq, Clone)]
141 pub enum InferenceDiagnostic {
142 NoSuchField { expr: ExprId },
143 BreakOutsideOfLoop { expr: ExprId },
146 /// A mismatch between an expected and an inferred type.
147 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
148 pub struct TypeMismatch {
153 #[derive(Clone, PartialEq, Eq, Debug)]
154 struct InternedStandardTypes {
160 impl Default for InternedStandardTypes {
161 fn default() -> Self {
162 InternedStandardTypes {
163 unknown: TyKind::Error.intern(Interner),
164 bool_: TyKind::Scalar(Scalar::Bool).intern(Interner),
165 unit: TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner),
169 /// Represents coercing a value to a different type of value.
171 /// We transform values by following a number of `Adjust` steps in order.
172 /// See the documentation on variants of `Adjust` for more details.
174 /// Here are some common scenarios:
176 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
177 /// Here the pointer will be dereferenced N times (where a dereference can
178 /// happen to raw or borrowed pointers or any smart pointer which implements
179 /// Deref, including Box<_>). The types of dereferences is given by
180 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
181 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
184 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
185 /// with a thin pointer, deref a number of times, unsize the underlying data,
186 /// then autoref. The 'unsize' phase may change a fixed length array to a
187 /// dynamically sized one, a concrete object to a trait object, or statically
188 /// sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
192 /// Deref(None) -> [i32; 4],
193 /// Borrow(AutoBorrow::Ref) -> &[i32; 4],
194 /// Unsize -> &[i32],
197 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
198 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
199 /// The autoderef and -ref are the same as in the above example, but the type
200 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
201 /// the underlying conversions from `[i32; 4]` to `[i32]`.
203 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
204 /// that case, we have the pointer we need coming in, so there are no
205 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
206 /// At some point, of course, `Box` should move out of the compiler, in which
207 /// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
208 /// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
209 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
210 pub struct Adjustment {
215 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
217 /// Go from ! to any type.
219 /// Dereference once, producing a place.
220 Deref(Option<OverloadedDeref>),
221 /// Take the address and produce either a `&` or `*` pointer.
223 Pointer(PointerCast),
226 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
227 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
228 /// The target type is `U` in both cases, with the region and mutability
229 /// being those shared by both the receiver and the returned reference.
230 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
231 pub struct OverloadedDeref(Mutability);
233 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
234 pub enum AutoBorrow {
235 /// Converts from T to &T.
237 /// Converts from T to *T.
241 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
242 pub enum PointerCast {
243 /// Go from a fn-item type to a fn-pointer type.
246 /// Go from a safe fn pointer to an unsafe fn pointer.
249 /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
250 /// It cannot convert a closure that requires unsafe.
251 ClosureFnPointer(Safety),
253 /// Go from a mut raw pointer to a const raw pointer.
257 /// Go from `*const [T; N]` to `*const T`
260 /// Unsize a pointer/reference value, e.g., `&[T; n]` to
261 /// `&[T]`. Note that the source could be a thin or fat pointer.
262 /// This will do things like convert thin pointers to fat
263 /// pointers, or convert structs containing thin pointers to
264 /// structs containing fat pointers, or convert between fat
265 /// pointers. We don't store the details of how the transform is
266 /// done (in fact, we don't know that, because it might depend on
267 /// the precise type parameters). We just store the target
268 /// type. Codegen backends and miri figure out what has to be done
269 /// based on the precise source/target type at hand.
273 /// The result of type inference: A mapping from expressions and patterns to types.
274 #[derive(Clone, PartialEq, Eq, Debug, Default)]
275 pub struct InferenceResult {
276 /// For each method call expr, records the function it resolves to.
277 method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
278 /// For each field access expr, records the field it resolves to.
279 field_resolutions: FxHashMap<ExprId, FieldId>,
280 /// For each struct literal or pattern, records the variant it resolves to.
281 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
282 /// For each associated item record what it resolves to
283 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
284 pub diagnostics: Vec<InferenceDiagnostic>,
285 pub type_of_expr: ArenaMap<ExprId, Ty>,
286 /// For each pattern record the type it resolves to.
288 /// **Note**: When a pattern type is resolved it may still contain
289 /// unresolved or missing subpatterns or subpatterns of mismatched types.
290 pub type_of_pat: ArenaMap<PatId, Ty>,
291 type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
292 /// Interned Unknown to return references to.
293 standard_types: InternedStandardTypes,
294 /// Stores the types which were implicitly dereferenced in pattern binding modes.
295 pub pat_adjustments: FxHashMap<PatId, Vec<Adjustment>>,
296 pub pat_binding_modes: FxHashMap<PatId, BindingMode>,
297 pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
300 impl InferenceResult {
301 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
302 self.method_resolutions.get(&expr).cloned()
304 pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
305 self.field_resolutions.get(&expr).copied()
307 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
308 self.variant_resolutions.get(&id.into()).copied()
310 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
311 self.variant_resolutions.get(&id.into()).copied()
313 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
314 self.assoc_resolutions.get(&id.into()).copied()
316 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
317 self.assoc_resolutions.get(&id.into()).copied()
319 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
320 self.type_mismatches.get(&expr.into())
322 pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
323 self.type_mismatches.get(&pat.into())
325 pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
326 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
327 ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
331 pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
332 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
333 ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
339 impl Index<ExprId> for InferenceResult {
342 fn index(&self, expr: ExprId) -> &Ty {
343 self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
347 impl Index<PatId> for InferenceResult {
350 fn index(&self, pat: PatId) -> &Ty {
351 self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
355 /// The inference context contains all information needed during type inference.
356 #[derive(Clone, Debug)]
357 struct InferenceContext<'a> {
358 db: &'a dyn HirDatabase,
359 owner: DefWithBodyId,
362 table: unify::InferenceTable<'a>,
363 trait_env: Arc<TraitEnvironment>,
364 result: InferenceResult,
365 /// The return type of the function being inferred, or the closure if we're
366 /// currently within one.
368 /// We might consider using a nested inference context for checking
369 /// closures, but currently this is the only field that will change there,
370 /// so it doesn't make sense.
373 breakables: Vec<BreakableContext>,
376 #[derive(Clone, Debug)]
377 struct BreakableContext {
380 label: Option<name::Name>,
383 fn find_breakable<'c>(
384 ctxs: &'c mut [BreakableContext],
385 label: Option<&name::Name>,
386 ) -> Option<&'c mut BreakableContext> {
388 Some(_) => ctxs.iter_mut().rev().find(|ctx| ctx.label.as_ref() == label),
389 None => ctxs.last_mut(),
393 impl<'a> InferenceContext<'a> {
394 fn new(db: &'a dyn HirDatabase, owner: DefWithBodyId, resolver: Resolver) -> Self {
395 let krate = owner.module(db.upcast()).krate();
396 let trait_env = owner
398 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
400 result: InferenceResult::default(),
401 table: unify::InferenceTable::new(db, trait_env.clone()),
403 return_ty: TyKind::Error.intern(Interner), // set in collect_fn_signature
406 body: db.body(owner),
408 diverges: Diverges::Maybe,
409 breakables: Vec::new(),
413 fn err_ty(&self) -> Ty {
414 self.result.standard_types.unknown.clone()
417 fn resolve_all(mut self) -> InferenceResult {
418 // FIXME resolve obligations as well (use Guidance if necessary)
419 self.table.resolve_obligations_as_possible();
421 // make sure diverging type variables are marked as such
422 self.table.propagate_diverging_flag();
423 let mut result = std::mem::take(&mut self.result);
424 for ty in result.type_of_expr.values_mut() {
425 *ty = self.table.resolve_completely(ty.clone());
427 for ty in result.type_of_pat.values_mut() {
428 *ty = self.table.resolve_completely(ty.clone());
430 for mismatch in result.type_mismatches.values_mut() {
431 mismatch.expected = self.table.resolve_completely(mismatch.expected.clone());
432 mismatch.actual = self.table.resolve_completely(mismatch.actual.clone());
434 for (_, subst) in result.method_resolutions.values_mut() {
435 *subst = self.table.resolve_completely(subst.clone());
437 for adjustment in result.expr_adjustments.values_mut().flatten() {
438 adjustment.target = self.table.resolve_completely(adjustment.target.clone());
440 for adjustment in result.pat_adjustments.values_mut().flatten() {
441 adjustment.target = self.table.resolve_completely(adjustment.target.clone());
446 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
447 self.result.type_of_expr.insert(expr, ty);
450 fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
451 self.result.expr_adjustments.insert(expr, adjustments);
454 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
455 self.result.method_resolutions.insert(expr, (func, subst));
458 fn write_field_resolution(&mut self, expr: ExprId, field: FieldId) {
459 self.result.field_resolutions.insert(expr, field);
462 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
463 self.result.variant_resolutions.insert(id, variant);
466 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
467 self.result.assoc_resolutions.insert(id, item);
470 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
471 self.result.type_of_pat.insert(pat, ty);
474 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
475 self.result.diagnostics.push(diagnostic);
478 fn make_ty_with_mode(
481 impl_trait_mode: ImplTraitLoweringMode,
483 // FIXME use right resolver for block
484 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
485 .with_impl_trait_mode(impl_trait_mode);
486 let ty = ctx.lower_ty(type_ref);
487 let ty = self.insert_type_vars(ty);
488 self.normalize_associated_types_in(ty)
491 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
492 self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
495 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
496 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
497 match ty.kind(Interner) {
498 TyKind::Error => self.table.new_type_var(),
499 TyKind::InferenceVar(..) => {
500 let ty_resolved = self.resolve_ty_shallow(&ty);
501 if ty_resolved.is_unknown() {
502 self.table.new_type_var()
511 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
512 fold_tys(ty, |ty, _| self.insert_type_vars_shallow(ty), DebruijnIndex::INNERMOST)
515 fn resolve_obligations_as_possible(&mut self) {
516 self.table.resolve_obligations_as_possible();
519 fn push_obligation(&mut self, o: DomainGoal) {
520 self.table.register_obligation(o.cast(Interner));
523 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
524 self.table.unify(ty1, ty2)
527 fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
528 self.resolve_obligations_as_possible();
529 self.table.resolve_ty_shallow(ty)
532 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
533 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
536 fn resolve_associated_type_with_params(
539 assoc_ty: Option<TypeAliasId>,
543 Some(res_assoc_ty) => {
544 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
545 hir_def::ItemContainerId::TraitId(trait_) => trait_,
546 _ => panic!("resolve_associated_type called with non-associated type"),
548 let ty = self.table.new_type_var();
549 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
551 .fill(params.iter().cloned())
553 let alias_eq = AliasEq {
554 alias: AliasTy::Projection(ProjectionTy {
555 associated_ty_id: to_assoc_type_id(res_assoc_ty),
556 substitution: trait_ref.substitution.clone(),
560 self.push_obligation(trait_ref.cast(Interner));
561 self.push_obligation(alias_eq.cast(Interner));
564 None => self.err_ty(),
568 /// Recurses through the given type, normalizing associated types mentioned
569 /// in it by replacing them by type variables and registering obligations to
570 /// resolve later. This should be done once for every type we get from some
571 /// type annotation (e.g. from a let type annotation, field type or function
572 /// call). `make_ty` handles this already, but e.g. for field types we need
573 /// to do it as well.
574 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
575 self.table.normalize_associated_types_in(ty)
578 fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
579 let path = match path {
581 None => return (self.err_ty(), None),
583 let resolver = &self.resolver;
584 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
585 // FIXME: this should resolve assoc items as well, see this example:
586 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
587 let (resolution, unresolved) = if value_ns {
588 match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
589 Some(ResolveValueResult::ValueNs(value)) => match value {
590 ValueNs::EnumVariantId(var) => {
591 let substs = ctx.substs_from_path(path, var.into(), true);
592 let ty = self.db.ty(var.parent.into());
593 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
594 return (ty, Some(var.into()));
596 ValueNs::StructId(strukt) => {
597 let substs = ctx.substs_from_path(path, strukt.into(), true);
598 let ty = self.db.ty(strukt.into());
599 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
600 return (ty, Some(strukt.into()));
602 _ => return (self.err_ty(), None),
604 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
605 None => return (self.err_ty(), None),
608 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
610 None => return (self.err_ty(), None),
613 return match resolution {
614 TypeNs::AdtId(AdtId::StructId(strukt)) => {
615 let substs = ctx.substs_from_path(path, strukt.into(), true);
616 let ty = self.db.ty(strukt.into());
617 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
618 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
620 TypeNs::AdtId(AdtId::UnionId(u)) => {
621 let substs = ctx.substs_from_path(path, u.into(), true);
622 let ty = self.db.ty(u.into());
623 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
624 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
626 TypeNs::EnumVariantId(var) => {
627 let substs = ctx.substs_from_path(path, var.into(), true);
628 let ty = self.db.ty(var.parent.into());
629 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
630 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
632 TypeNs::SelfType(impl_id) => {
633 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
634 let substs = generics.type_params_subst(self.db);
635 let ty = self.db.impl_self_ty(impl_id).substitute(Interner, &substs);
636 self.resolve_variant_on_alias(ty, unresolved, path)
638 TypeNs::TypeAliasId(it) => {
639 let ty = TyBuilder::def_ty(self.db, it.into())
640 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
642 self.resolve_variant_on_alias(ty, unresolved, path)
644 TypeNs::AdtSelfType(_) => {
645 // FIXME this could happen in array size expressions, once we're checking them
646 (self.err_ty(), None)
648 TypeNs::GenericParam(_) => {
649 // FIXME potentially resolve assoc type
650 (self.err_ty(), None)
652 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
654 (self.err_ty(), None)
658 fn forbid_unresolved_segments(
659 result: (Ty, Option<VariantId>),
660 unresolved: Option<usize>,
661 ) -> (Ty, Option<VariantId>) {
662 if unresolved.is_none() {
666 (TyKind::Error.intern(Interner), None)
671 fn resolve_variant_on_alias(
674 unresolved: Option<usize>,
676 ) -> (Ty, Option<VariantId>) {
679 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
680 AdtId::StructId(s) => Some(VariantId::StructId(s)),
681 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
682 AdtId::EnumId(_) => {
683 // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
690 let segment = path.mod_path().segments().last().unwrap();
691 // this could be an enum variant or associated type
692 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
693 let enum_data = self.db.enum_data(enum_id);
694 if let Some(local_id) = enum_data.variant(segment) {
695 let variant = EnumVariantId { parent: enum_id, local_id };
696 return (ty, Some(variant.into()));
699 // FIXME potentially resolve assoc type
700 (self.err_ty(), None)
704 (self.err_ty(), None)
709 fn collect_const(&mut self, data: &ConstData) {
710 self.return_ty = self.make_ty(&data.type_ref);
713 fn collect_static(&mut self, data: &StaticData) {
714 self.return_ty = self.make_ty(&data.type_ref);
717 fn collect_fn(&mut self, data: &FunctionData) {
718 let body = Arc::clone(&self.body); // avoid borrow checker problem
719 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
720 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
722 data.params.iter().map(|(_, type_ref)| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
723 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) {
724 let ty = self.insert_type_vars(ty);
725 let ty = self.normalize_associated_types_in(ty);
727 self.infer_pat(*pat, &ty, BindingMode::default());
729 let error_ty = &TypeRef::Error;
730 let return_ty = if data.is_async() {
731 data.async_ret_type.as_deref().unwrap_or(error_ty)
735 let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Disallowed); // FIXME implement RPIT
736 self.return_ty = return_ty;
739 fn infer_body(&mut self) {
740 self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
743 fn resolve_lang_item(&self, name: Name) -> Option<LangItemTarget> {
744 let krate = self.resolver.krate()?;
745 self.db.lang_item(krate, name.to_smol_str())
748 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
749 let path = path![core::iter::IntoIterator];
750 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
751 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
754 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
755 // FIXME resolve via lang_item once try v2 is stable
756 let path = path![core::ops::Try];
757 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
758 let trait_data = self.db.trait_data(trait_);
760 // FIXME remove once try v2 is stable
761 .associated_type_by_name(&name![Ok])
762 .or_else(|| trait_data.associated_type_by_name(&name![Output]))
765 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
766 let trait_ = self.resolve_lang_item(name![neg])?.as_trait()?;
767 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
770 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
771 let trait_ = self.resolve_lang_item(name![not])?.as_trait()?;
772 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
775 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
776 let trait_ = self.resolve_lang_item(name![future_trait])?.as_trait()?;
777 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
780 fn resolve_boxed_box(&self) -> Option<AdtId> {
781 let struct_ = self.resolve_lang_item(name![owned_box])?.as_struct()?;
785 fn resolve_range_full(&self) -> Option<AdtId> {
786 let path = path![core::ops::RangeFull];
787 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
791 fn resolve_range(&self) -> Option<AdtId> {
792 let path = path![core::ops::Range];
793 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
797 fn resolve_range_inclusive(&self) -> Option<AdtId> {
798 let path = path![core::ops::RangeInclusive];
799 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
803 fn resolve_range_from(&self) -> Option<AdtId> {
804 let path = path![core::ops::RangeFrom];
805 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
809 fn resolve_range_to(&self) -> Option<AdtId> {
810 let path = path![core::ops::RangeTo];
811 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
815 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
816 let path = path![core::ops::RangeToInclusive];
817 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
821 fn resolve_ops_index(&self) -> Option<TraitId> {
822 self.resolve_lang_item(name![index])?.as_trait()
825 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
826 let trait_ = self.resolve_ops_index()?;
827 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
831 /// When inferring an expression, we propagate downward whatever type hint we
832 /// are able in the form of an `Expectation`.
833 #[derive(Clone, PartialEq, Eq, Debug)]
837 // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
838 RValueLikeUnsized(Ty),
842 /// The expectation that the type of the expression needs to equal the given
844 fn has_type(ty: Ty) -> Self {
846 // FIXME: get rid of this?
849 Expectation::HasType(ty)
853 fn from_option(ty: Option<Ty>) -> Self {
854 ty.map_or(Expectation::None, Expectation::HasType)
857 /// The following explanation is copied straight from rustc:
858 /// Provides an expectation for an rvalue expression given an *optional*
859 /// hint, which is not required for type safety (the resulting type might
860 /// be checked higher up, as is the case with `&expr` and `box expr`), but
861 /// is useful in determining the concrete type.
863 /// The primary use case is where the expected type is a fat pointer,
864 /// like `&[isize]`. For example, consider the following statement:
866 /// let x: &[isize] = &[1, 2, 3];
868 /// In this case, the expected type for the `&[1, 2, 3]` expression is
869 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
870 /// expectation `ExpectHasType([isize])`, that would be too strong --
871 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
872 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
873 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
874 /// which still is useful, because it informs integer literals and the like.
875 /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
876 /// for examples of where this comes up,.
877 fn rvalue_hint(table: &mut unify::InferenceTable, ty: Ty) -> Self {
878 // FIXME: do struct_tail_without_normalization
879 match table.resolve_ty_shallow(&ty).kind(Interner) {
880 TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
881 _ => Expectation::has_type(ty),
885 /// This expresses no expectation on the type.
890 fn resolve(&self, table: &mut unify::InferenceTable) -> Expectation {
892 Expectation::None => Expectation::None,
893 Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
894 Expectation::RValueLikeUnsized(t) => {
895 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
900 fn to_option(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
901 match self.resolve(table) {
902 Expectation::None => None,
903 Expectation::HasType(t) |
904 // Expectation::Castable(t) |
905 Expectation::RValueLikeUnsized(t) => Some(t),
909 fn only_has_type(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
911 Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
912 // Expectation::Castable(_) |
913 Expectation::RValueLikeUnsized(_) | Expectation::None => None,
917 /// Comment copied from rustc:
918 /// Disregard "castable to" expectations because they
919 /// can lead us astray. Consider for example `if cond
920 /// {22} else {c} as u8` -- if we propagate the
921 /// "castable to u8" constraint to 22, it will pick the
922 /// type 22u8, which is overly constrained (c might not
923 /// be a u8). In effect, the problem is that the
924 /// "castable to" expectation is not the tightest thing
925 /// we can say, so we want to drop it in this case.
926 /// The tightest thing we can say is "must unify with
927 /// else branch". Note that in the case of a "has type"
928 /// constraint, this limitation does not hold.
930 /// If the expected type is just a type variable, then don't use
931 /// an expected type. Otherwise, we might write parts of the type
932 /// when checking the 'then' block which are incompatible with the
934 fn adjust_for_branches(&self, table: &mut unify::InferenceTable) -> Expectation {
936 Expectation::HasType(ety) => {
937 let ety = table.resolve_ty_shallow(ety);
938 if !ety.is_ty_var() {
939 Expectation::HasType(ety)
944 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
945 _ => Expectation::None,
950 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
957 fn is_always(self) -> bool {
958 self == Diverges::Always
962 impl std::ops::BitAnd for Diverges {
964 fn bitand(self, other: Self) -> Self {
965 std::cmp::min(self, other)
969 impl std::ops::BitOr for Diverges {
971 fn bitor(self, other: Self) -> Self {
972 std::cmp::max(self, other)
976 impl std::ops::BitAndAssign for Diverges {
977 fn bitand_assign(&mut self, other: Self) {
978 *self = *self & other;
982 impl std::ops::BitOrAssign for Diverges {
983 fn bitor_assign(&mut self, other: Self) {
984 *self = *self | other;