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};
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;
32 use la_arena::ArenaMap;
33 use rustc_hash::FxHashMap;
38 db::HirDatabase, fold_tys, infer::coerce::CoerceMany, lower::ImplTraitLoweringMode,
39 to_assoc_type_id, AliasEq, AliasTy, DomainGoal, Goal, InEnvironment, Interner, ProjectionTy,
40 Substitution, TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
43 // This lint has a false positive here. See the link below for details.
45 // https://github.com/rust-lang/rust/issues/57411
46 #[allow(unreachable_pub)]
47 pub use unify::could_unify;
48 pub(crate) use unify::unify;
57 /// The entry point of type inference.
58 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
59 let _p = profile::span("infer_query");
60 let resolver = def.resolver(db.upcast());
61 let mut ctx = InferenceContext::new(db, def, resolver);
64 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
65 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
66 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
71 Arc::new(ctx.resolve_all())
74 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
79 impl_from!(ExprId, PatId for ExprOrPatId);
81 /// Binding modes inferred for patterns.
82 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
83 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
90 fn convert(annotation: BindingAnnotation) -> BindingMode {
92 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
93 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
94 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
99 impl Default for BindingMode {
100 fn default() -> Self {
106 pub(crate) struct InferOk<T> {
108 goals: Vec<InEnvironment<Goal>>,
112 fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
113 InferOk { value: f(self.value), goals: self.goals }
118 pub(crate) struct TypeError;
119 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
121 #[derive(Debug, PartialEq, Eq, Clone)]
122 pub enum InferenceDiagnostic {
123 NoSuchField { expr: ExprId },
124 BreakOutsideOfLoop { expr: ExprId },
127 /// A mismatch between an expected and an inferred type.
128 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
129 pub struct TypeMismatch {
134 #[derive(Clone, PartialEq, Eq, Debug)]
135 struct InternedStandardTypes {
141 impl Default for InternedStandardTypes {
142 fn default() -> Self {
143 InternedStandardTypes {
144 unknown: TyKind::Error.intern(&Interner),
145 bool_: TyKind::Scalar(Scalar::Bool).intern(&Interner),
146 unit: TyKind::Tuple(0, Substitution::empty(&Interner)).intern(&Interner),
150 /// Represents coercing a value to a different type of value.
152 /// We transform values by following a number of `Adjust` steps in order.
153 /// See the documentation on variants of `Adjust` for more details.
155 /// Here are some common scenarios:
157 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
158 /// Here the pointer will be dereferenced N times (where a dereference can
159 /// happen to raw or borrowed pointers or any smart pointer which implements
160 /// Deref, including Box<_>). The types of dereferences is given by
161 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
162 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
165 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
166 /// with a thin pointer, deref a number of times, unsize the underlying data,
167 /// then autoref. The 'unsize' phase may change a fixed length array to a
168 /// dynamically sized one, a concrete object to a trait object, or statically
169 /// sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
173 /// Deref(None) -> [i32; 4],
174 /// Borrow(AutoBorrow::Ref) -> &[i32; 4],
175 /// Unsize -> &[i32],
178 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
179 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
180 /// The autoderef and -ref are the same as in the above example, but the type
181 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
182 /// the underlying conversions from `[i32; 4]` to `[i32]`.
184 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
185 /// that case, we have the pointer we need coming in, so there are no
186 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
187 /// At some point, of course, `Box` should move out of the compiler, in which
188 /// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
189 /// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
190 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
191 pub struct Adjustment {
196 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198 /// Go from ! to any type.
200 /// Dereference once, producing a place.
201 Deref(Option<OverloadedDeref>),
202 /// Take the address and produce either a `&` or `*` pointer.
204 Pointer(PointerCast),
207 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
208 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
209 /// The target type is `U` in both cases, with the region and mutability
210 /// being those shared by both the receiver and the returned reference.
211 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
212 pub struct OverloadedDeref(Mutability);
214 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
215 pub enum AutoBorrow {
216 /// Converts from T to &T.
218 /// Converts from T to *T.
222 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
223 pub enum PointerCast {
224 /// Go from a fn-item type to a fn-pointer type.
227 /// Go from a safe fn pointer to an unsafe fn pointer.
230 /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
231 /// It cannot convert a closure that requires unsafe.
232 ClosureFnPointer(Safety),
234 /// Go from a mut raw pointer to a const raw pointer.
237 /// Go from `*const [T; N]` to `*const T`
240 /// Unsize a pointer/reference value, e.g., `&[T; n]` to
241 /// `&[T]`. Note that the source could be a thin or fat pointer.
242 /// This will do things like convert thin pointers to fat
243 /// pointers, or convert structs containing thin pointers to
244 /// structs containing fat pointers, or convert between fat
245 /// pointers. We don't store the details of how the transform is
246 /// done (in fact, we don't know that, because it might depend on
247 /// the precise type parameters). We just store the target
248 /// type. Codegen backends and miri figure out what has to be done
249 /// based on the precise source/target type at hand.
253 /// The result of type inference: A mapping from expressions and patterns to types.
254 #[derive(Clone, PartialEq, Eq, Debug, Default)]
255 pub struct InferenceResult {
256 /// For each method call expr, records the function it resolves to.
257 method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
258 /// For each field access expr, records the field it resolves to.
259 field_resolutions: FxHashMap<ExprId, FieldId>,
260 /// For each struct literal or pattern, records the variant it resolves to.
261 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
262 /// For each associated item record what it resolves to
263 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
264 pub diagnostics: Vec<InferenceDiagnostic>,
265 pub type_of_expr: ArenaMap<ExprId, Ty>,
266 /// For each pattern record the type it resolves to.
268 /// **Note**: When a pattern type is resolved it may still contain
269 /// unresolved or missing subpatterns or subpatterns of mismatched types.
270 pub type_of_pat: ArenaMap<PatId, Ty>,
271 type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
272 /// Interned Unknown to return references to.
273 standard_types: InternedStandardTypes,
274 /// Stores the types which were implicitly dereferenced in pattern binding modes.
275 pub pat_adjustments: FxHashMap<PatId, Vec<Adjustment>>,
276 pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
279 impl InferenceResult {
280 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
281 self.method_resolutions.get(&expr).cloned()
283 pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
284 self.field_resolutions.get(&expr).copied()
286 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
287 self.variant_resolutions.get(&id.into()).copied()
289 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
290 self.variant_resolutions.get(&id.into()).copied()
292 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
293 self.assoc_resolutions.get(&id.into()).copied()
295 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
296 self.assoc_resolutions.get(&id.into()).copied()
298 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
299 self.type_mismatches.get(&expr.into())
301 pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
302 self.type_mismatches.get(&pat.into())
304 pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
305 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
306 ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
310 pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
311 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
312 ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
318 impl Index<ExprId> for InferenceResult {
321 fn index(&self, expr: ExprId) -> &Ty {
322 self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
326 impl Index<PatId> for InferenceResult {
329 fn index(&self, pat: PatId) -> &Ty {
330 self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
334 /// The inference context contains all information needed during type inference.
335 #[derive(Clone, Debug)]
336 struct InferenceContext<'a> {
337 db: &'a dyn HirDatabase,
338 owner: DefWithBodyId,
341 table: unify::InferenceTable<'a>,
342 trait_env: Arc<TraitEnvironment>,
343 result: InferenceResult,
344 /// The return type of the function being inferred, or the closure if we're
345 /// currently within one.
347 /// We might consider using a nested inference context for checking
348 /// closures, but currently this is the only field that will change there,
349 /// so it doesn't make sense.
352 breakables: Vec<BreakableContext>,
355 #[derive(Clone, Debug)]
356 struct BreakableContext {
359 label: Option<name::Name>,
362 fn find_breakable<'c>(
363 ctxs: &'c mut [BreakableContext],
364 label: Option<&name::Name>,
365 ) -> Option<&'c mut BreakableContext> {
367 Some(_) => ctxs.iter_mut().rev().find(|ctx| ctx.label.as_ref() == label),
368 None => ctxs.last_mut(),
372 impl<'a> InferenceContext<'a> {
373 fn new(db: &'a dyn HirDatabase, owner: DefWithBodyId, resolver: Resolver) -> Self {
374 let krate = owner.module(db.upcast()).krate();
375 let trait_env = owner
377 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
379 result: InferenceResult::default(),
380 table: unify::InferenceTable::new(db, trait_env.clone()),
382 return_ty: TyKind::Error.intern(&Interner), // set in collect_fn_signature
385 body: db.body(owner),
387 diverges: Diverges::Maybe,
388 breakables: Vec::new(),
392 fn err_ty(&self) -> Ty {
393 self.result.standard_types.unknown.clone()
396 fn resolve_all(mut self) -> InferenceResult {
397 // FIXME resolve obligations as well (use Guidance if necessary)
398 self.table.resolve_obligations_as_possible();
400 // make sure diverging type variables are marked as such
401 self.table.propagate_diverging_flag();
402 let mut result = std::mem::take(&mut self.result);
403 for ty in result.type_of_expr.values_mut() {
404 *ty = self.table.resolve_completely(ty.clone());
406 for ty in result.type_of_pat.values_mut() {
407 *ty = self.table.resolve_completely(ty.clone());
409 for mismatch in result.type_mismatches.values_mut() {
410 mismatch.expected = self.table.resolve_completely(mismatch.expected.clone());
411 mismatch.actual = self.table.resolve_completely(mismatch.actual.clone());
413 for (_, subst) in result.method_resolutions.values_mut() {
414 *subst = self.table.resolve_completely(subst.clone());
416 for adjustment in result.expr_adjustments.values_mut().flatten() {
417 adjustment.target = self.table.resolve_completely(adjustment.target.clone());
419 for adjustment in result.pat_adjustments.values_mut().flatten() {
420 adjustment.target = self.table.resolve_completely(adjustment.target.clone());
425 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
426 self.result.type_of_expr.insert(expr, ty);
429 fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
430 self.result.expr_adjustments.insert(expr, adjustments);
433 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
434 self.result.method_resolutions.insert(expr, (func, subst));
437 fn write_field_resolution(&mut self, expr: ExprId, field: FieldId) {
438 self.result.field_resolutions.insert(expr, field);
441 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
442 self.result.variant_resolutions.insert(id, variant);
445 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
446 self.result.assoc_resolutions.insert(id, item);
449 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
450 self.result.type_of_pat.insert(pat, ty);
453 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
454 self.result.diagnostics.push(diagnostic);
457 fn make_ty_with_mode(
460 impl_trait_mode: ImplTraitLoweringMode,
462 // FIXME use right resolver for block
463 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
464 .with_impl_trait_mode(impl_trait_mode);
465 let ty = ctx.lower_ty(type_ref);
466 let ty = self.insert_type_vars(ty);
467 self.normalize_associated_types_in(ty)
470 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
471 self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
474 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
475 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
476 match ty.kind(&Interner) {
477 TyKind::Error => self.table.new_type_var(),
478 TyKind::InferenceVar(..) => {
479 let ty_resolved = self.resolve_ty_shallow(&ty);
480 if ty_resolved.is_unknown() {
481 self.table.new_type_var()
490 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
491 fold_tys(ty, |ty, _| self.insert_type_vars_shallow(ty), DebruijnIndex::INNERMOST)
494 fn resolve_obligations_as_possible(&mut self) {
495 self.table.resolve_obligations_as_possible();
498 fn push_obligation(&mut self, o: DomainGoal) {
499 self.table.register_obligation(o.cast(&Interner));
502 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
503 self.table.unify(ty1, ty2)
506 fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
507 self.resolve_obligations_as_possible();
508 self.table.resolve_ty_shallow(ty)
511 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
512 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
515 fn resolve_associated_type_with_params(
518 assoc_ty: Option<TypeAliasId>,
522 Some(res_assoc_ty) => {
523 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
524 hir_def::AssocContainerId::TraitId(trait_) => trait_,
525 _ => panic!("resolve_associated_type called with non-associated type"),
527 let ty = self.table.new_type_var();
528 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
530 .fill(params.iter().cloned())
532 let alias_eq = AliasEq {
533 alias: AliasTy::Projection(ProjectionTy {
534 associated_ty_id: to_assoc_type_id(res_assoc_ty),
535 substitution: trait_ref.substitution.clone(),
539 self.push_obligation(trait_ref.cast(&Interner));
540 self.push_obligation(alias_eq.cast(&Interner));
543 None => self.err_ty(),
547 /// Recurses through the given type, normalizing associated types mentioned
548 /// in it by replacing them by type variables and registering obligations to
549 /// resolve later. This should be done once for every type we get from some
550 /// type annotation (e.g. from a let type annotation, field type or function
551 /// call). `make_ty` handles this already, but e.g. for field types we need
552 /// to do it as well.
553 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
554 self.table.normalize_associated_types_in(ty)
557 fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
558 let path = match path {
560 None => return (self.err_ty(), None),
562 let resolver = &self.resolver;
563 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
564 // FIXME: this should resolve assoc items as well, see this example:
565 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
566 let (resolution, unresolved) = if value_ns {
567 match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
568 Some(ResolveValueResult::ValueNs(value)) => match value {
569 ValueNs::EnumVariantId(var) => {
570 let substs = ctx.substs_from_path(path, var.into(), true);
571 let ty = self.db.ty(var.parent.into());
572 let ty = self.insert_type_vars(ty.substitute(&Interner, &substs));
573 return (ty, Some(var.into()));
575 ValueNs::StructId(strukt) => {
576 let substs = ctx.substs_from_path(path, strukt.into(), true);
577 let ty = self.db.ty(strukt.into());
578 let ty = self.insert_type_vars(ty.substitute(&Interner, &substs));
579 return (ty, Some(strukt.into()));
581 _ => return (self.err_ty(), None),
583 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
584 None => return (self.err_ty(), None),
587 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
589 None => return (self.err_ty(), None),
592 return match resolution {
593 TypeNs::AdtId(AdtId::StructId(strukt)) => {
594 let substs = ctx.substs_from_path(path, strukt.into(), true);
595 let ty = self.db.ty(strukt.into());
596 let ty = self.insert_type_vars(ty.substitute(&Interner, &substs));
597 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
599 TypeNs::AdtId(AdtId::UnionId(u)) => {
600 let substs = ctx.substs_from_path(path, u.into(), true);
601 let ty = self.db.ty(u.into());
602 let ty = self.insert_type_vars(ty.substitute(&Interner, &substs));
603 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
605 TypeNs::EnumVariantId(var) => {
606 let substs = ctx.substs_from_path(path, var.into(), true);
607 let ty = self.db.ty(var.parent.into());
608 let ty = self.insert_type_vars(ty.substitute(&Interner, &substs));
609 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
611 TypeNs::SelfType(impl_id) => {
612 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
613 let substs = generics.type_params_subst(self.db);
614 let ty = self.db.impl_self_ty(impl_id).substitute(&Interner, &substs);
615 self.resolve_variant_on_alias(ty, unresolved, path)
617 TypeNs::TypeAliasId(it) => {
618 let ty = TyBuilder::def_ty(self.db, it.into())
619 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
621 self.resolve_variant_on_alias(ty, unresolved, path)
623 TypeNs::AdtSelfType(_) => {
624 // FIXME this could happen in array size expressions, once we're checking them
625 (self.err_ty(), None)
627 TypeNs::GenericParam(_) => {
628 // FIXME potentially resolve assoc type
629 (self.err_ty(), None)
631 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
633 (self.err_ty(), None)
637 fn forbid_unresolved_segments(
638 result: (Ty, Option<VariantId>),
639 unresolved: Option<usize>,
640 ) -> (Ty, Option<VariantId>) {
641 if unresolved.is_none() {
645 (TyKind::Error.intern(&Interner), None)
650 fn resolve_variant_on_alias(
653 unresolved: Option<usize>,
655 ) -> (Ty, Option<VariantId>) {
658 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
659 AdtId::StructId(s) => Some(VariantId::StructId(s)),
660 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
661 AdtId::EnumId(_) => {
662 // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
669 let segment = path.mod_path().segments().last().unwrap();
670 // this could be an enum variant or associated type
671 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
672 let enum_data = self.db.enum_data(enum_id);
673 if let Some(local_id) = enum_data.variant(segment) {
674 let variant = EnumVariantId { parent: enum_id, local_id };
675 return (ty, Some(variant.into()));
678 // FIXME potentially resolve assoc type
679 (self.err_ty(), None)
683 (self.err_ty(), None)
688 fn collect_const(&mut self, data: &ConstData) {
689 self.return_ty = self.make_ty(&data.type_ref);
692 fn collect_static(&mut self, data: &StaticData) {
693 self.return_ty = self.make_ty(&data.type_ref);
696 fn collect_fn(&mut self, data: &FunctionData) {
697 let body = Arc::clone(&self.body); // avoid borrow checker problem
698 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
699 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
701 data.params.iter().map(|type_ref| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
702 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) {
703 let ty = self.insert_type_vars(ty);
704 let ty = self.normalize_associated_types_in(ty);
706 self.infer_pat(*pat, &ty, BindingMode::default());
708 let error_ty = &TypeRef::Error;
709 let return_ty = if data.is_async() {
710 data.async_ret_type.as_deref().unwrap_or(error_ty)
714 let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Disallowed); // FIXME implement RPIT
715 self.return_ty = return_ty;
718 fn infer_body(&mut self) {
719 self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
722 fn resolve_lang_item(&self, name: &str) -> Option<LangItemTarget> {
723 let krate = self.resolver.krate()?;
724 let name = SmolStr::new_inline(name);
725 self.db.lang_item(krate, name)
728 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
729 let path = path![core::iter::IntoIterator];
730 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
731 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
734 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
735 // FIXME resolve via lang_item once try v2 is stable
736 let path = path![core::ops::Try];
737 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
738 let trait_data = self.db.trait_data(trait_);
740 // FIXME remove once try v2 is stable
741 .associated_type_by_name(&name![Ok])
742 .or_else(|| trait_data.associated_type_by_name(&name![Output]))
745 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
746 let trait_ = self.resolve_lang_item("neg")?.as_trait()?;
747 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
750 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
751 let trait_ = self.resolve_lang_item("not")?.as_trait()?;
752 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
755 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
756 let trait_ = self.resolve_lang_item("future_trait")?.as_trait()?;
757 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
760 fn resolve_boxed_box(&self) -> Option<AdtId> {
761 let struct_ = self.resolve_lang_item("owned_box")?.as_struct()?;
765 fn resolve_range_full(&self) -> Option<AdtId> {
766 let path = path![core::ops::RangeFull];
767 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
771 fn resolve_range(&self) -> Option<AdtId> {
772 let path = path![core::ops::Range];
773 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
777 fn resolve_range_inclusive(&self) -> Option<AdtId> {
778 let path = path![core::ops::RangeInclusive];
779 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
783 fn resolve_range_from(&self) -> Option<AdtId> {
784 let path = path![core::ops::RangeFrom];
785 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
789 fn resolve_range_to(&self) -> Option<AdtId> {
790 let path = path![core::ops::RangeTo];
791 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
795 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
796 let path = path![core::ops::RangeToInclusive];
797 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
801 fn resolve_ops_index(&self) -> Option<TraitId> {
802 self.resolve_lang_item("index")?.as_trait()
805 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
806 let trait_ = self.resolve_ops_index()?;
807 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
811 /// When inferring an expression, we propagate downward whatever type hint we
812 /// are able in the form of an `Expectation`.
813 #[derive(Clone, PartialEq, Eq, Debug)]
817 // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
818 RValueLikeUnsized(Ty),
822 /// The expectation that the type of the expression needs to equal the given
824 fn has_type(ty: Ty) -> Self {
826 // FIXME: get rid of this?
829 Expectation::HasType(ty)
833 fn from_option(ty: Option<Ty>) -> Self {
834 ty.map_or(Expectation::None, Expectation::HasType)
837 /// The following explanation is copied straight from rustc:
838 /// Provides an expectation for an rvalue expression given an *optional*
839 /// hint, which is not required for type safety (the resulting type might
840 /// be checked higher up, as is the case with `&expr` and `box expr`), but
841 /// is useful in determining the concrete type.
843 /// The primary use case is where the expected type is a fat pointer,
844 /// like `&[isize]`. For example, consider the following statement:
846 /// let x: &[isize] = &[1, 2, 3];
848 /// In this case, the expected type for the `&[1, 2, 3]` expression is
849 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
850 /// expectation `ExpectHasType([isize])`, that would be too strong --
851 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
852 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
853 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
854 /// which still is useful, because it informs integer literals and the like.
855 /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
856 /// for examples of where this comes up,.
857 fn rvalue_hint(table: &mut unify::InferenceTable, ty: Ty) -> Self {
858 // FIXME: do struct_tail_without_normalization
859 match table.resolve_ty_shallow(&ty).kind(&Interner) {
860 TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
861 _ => Expectation::has_type(ty),
865 /// This expresses no expectation on the type.
870 fn resolve(&self, table: &mut unify::InferenceTable) -> Expectation {
872 Expectation::None => Expectation::None,
873 Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
874 Expectation::RValueLikeUnsized(t) => {
875 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
880 fn to_option(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
881 match self.resolve(table) {
882 Expectation::None => None,
883 Expectation::HasType(t) |
884 // Expectation::Castable(t) |
885 Expectation::RValueLikeUnsized(t) => Some(t),
889 fn only_has_type(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
891 Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
892 // Expectation::Castable(_) |
893 Expectation::RValueLikeUnsized(_) | Expectation::None => None,
897 /// Comment copied from rustc:
898 /// Disregard "castable to" expectations because they
899 /// can lead us astray. Consider for example `if cond
900 /// {22} else {c} as u8` -- if we propagate the
901 /// "castable to u8" constraint to 22, it will pick the
902 /// type 22u8, which is overly constrained (c might not
903 /// be a u8). In effect, the problem is that the
904 /// "castable to" expectation is not the tightest thing
905 /// we can say, so we want to drop it in this case.
906 /// The tightest thing we can say is "must unify with
907 /// else branch". Note that in the case of a "has type"
908 /// constraint, this limitation does not hold.
910 /// If the expected type is just a type variable, then don't use
911 /// an expected type. Otherwise, we might write parts of the type
912 /// when checking the 'then' block which are incompatible with the
914 fn adjust_for_branches(&self, table: &mut unify::InferenceTable) -> Expectation {
916 Expectation::HasType(ety) => {
917 let ety = table.resolve_ty_shallow(ety);
918 if !ety.is_ty_var() {
919 Expectation::HasType(ety)
924 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
925 _ => Expectation::None,
930 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
937 fn is_always(self) -> bool {
938 self == Diverges::Always
942 impl std::ops::BitAnd for Diverges {
944 fn bitand(self, other: Self) -> Self {
945 std::cmp::min(self, other)
949 impl std::ops::BitOr for Diverges {
951 fn bitor(self, other: Self) -> Self {
952 std::cmp::max(self, other)
956 impl std::ops::BitAndAssign for Diverges {
957 fn bitand_assign(&mut self, other: Self) {
958 *self = *self & other;
962 impl std::ops::BitOrAssign for Diverges {
963 fn bitor_assign(&mut self, other: Self) {
964 *self = *self | other;