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, ConstValue, 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 itertools::Either;
33 use la_arena::ArenaMap;
34 use rustc_hash::FxHashMap;
38 db::HirDatabase, fold_tys_and_consts, infer::coerce::CoerceMany, lower::ImplTraitLoweringMode,
39 to_assoc_type_id, AliasEq, AliasTy, Const, DomainGoal, GenericArg, Goal, InEnvironment,
40 Interner, ProjectionTy, Substitution, TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
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 coerce::could_coerce;
48 #[allow(unreachable_pub)]
49 pub use unify::could_unify;
58 /// The entry point of type inference.
59 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
60 let _p = profile::span("infer_query");
61 let resolver = def.resolver(db.upcast());
62 let body = db.body(def);
63 let mut ctx = InferenceContext::new(db, def, &body, resolver);
66 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
67 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
68 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
73 Arc::new(ctx.resolve_all())
76 /// Fully normalize all the types found within `ty` in context of `owner` body definition.
78 /// This is appropriate to use only after type-check: it assumes
79 /// that normalization will succeed, for example.
80 pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> Ty {
81 if !ty.data(Interner).flags.intersects(TypeFlags::HAS_PROJECTION) {
84 let krate = owner.module(db.upcast()).krate();
87 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
88 let mut table = unify::InferenceTable::new(db, trait_env);
90 let ty_with_vars = table.normalize_associated_types_in(ty);
91 table.resolve_obligations_as_possible();
92 table.propagate_diverging_flag();
93 table.resolve_completely(ty_with_vars)
96 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
101 impl_from!(ExprId, PatId for ExprOrPatId);
103 /// Binding modes inferred for patterns.
104 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
105 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
106 pub enum BindingMode {
112 fn convert(annotation: BindingAnnotation) -> BindingMode {
114 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
115 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
116 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
121 impl Default for BindingMode {
122 fn default() -> Self {
128 pub(crate) struct InferOk<T> {
130 goals: Vec<InEnvironment<Goal>>,
134 fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
135 InferOk { value: f(self.value), goals: self.goals }
140 pub(crate) struct TypeError;
141 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
143 #[derive(Debug, PartialEq, Eq, Clone)]
144 pub enum InferenceDiagnostic {
145 NoSuchField { expr: ExprId },
146 BreakOutsideOfLoop { expr: ExprId },
147 MismatchedArgCount { call_expr: ExprId, expected: usize, found: usize },
150 /// A mismatch between an expected and an inferred type.
151 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
152 pub struct TypeMismatch {
157 #[derive(Clone, PartialEq, Eq, Debug)]
158 struct InternedStandardTypes {
164 impl Default for InternedStandardTypes {
165 fn default() -> Self {
166 InternedStandardTypes {
167 unknown: TyKind::Error.intern(Interner),
168 bool_: TyKind::Scalar(Scalar::Bool).intern(Interner),
169 unit: TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner),
173 /// Represents coercing a value to a different type of value.
175 /// We transform values by following a number of `Adjust` steps in order.
176 /// See the documentation on variants of `Adjust` for more details.
178 /// Here are some common scenarios:
180 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
181 /// Here the pointer will be dereferenced N times (where a dereference can
182 /// happen to raw or borrowed pointers or any smart pointer which implements
183 /// Deref, including Box<_>). The types of dereferences is given by
184 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
185 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
188 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
189 /// with a thin pointer, deref a number of times, unsize the underlying data,
190 /// then autoref. The 'unsize' phase may change a fixed length array to a
191 /// dynamically sized one, a concrete object to a trait object, or statically
192 /// sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
196 /// Deref(None) -> [i32; 4],
197 /// Borrow(AutoBorrow::Ref) -> &[i32; 4],
198 /// Unsize -> &[i32],
201 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
202 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
203 /// The autoderef and -ref are the same as in the above example, but the type
204 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
205 /// the underlying conversions from `[i32; 4]` to `[i32]`.
207 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
208 /// that case, we have the pointer we need coming in, so there are no
209 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
210 /// At some point, of course, `Box` should move out of the compiler, in which
211 /// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
212 /// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
213 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
214 pub struct Adjustment {
219 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
221 /// Go from ! to any type.
223 /// Dereference once, producing a place.
224 Deref(Option<OverloadedDeref>),
225 /// Take the address and produce either a `&` or `*` pointer.
227 Pointer(PointerCast),
230 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
231 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
232 /// The target type is `U` in both cases, with the region and mutability
233 /// being those shared by both the receiver and the returned reference.
234 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
235 pub struct OverloadedDeref(pub Mutability);
237 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
238 pub enum AutoBorrow {
239 /// Converts from T to &T.
241 /// Converts from T to *T.
245 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
246 pub enum PointerCast {
247 /// Go from a fn-item type to a fn-pointer type.
250 /// Go from a safe fn pointer to an unsafe fn pointer.
253 /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
254 /// It cannot convert a closure that requires unsafe.
255 ClosureFnPointer(Safety),
257 /// Go from a mut raw pointer to a const raw pointer.
261 /// Go from `*const [T; N]` to `*const T`
264 /// Unsize a pointer/reference value, e.g., `&[T; n]` to
265 /// `&[T]`. Note that the source could be a thin or fat pointer.
266 /// This will do things like convert thin pointers to fat
267 /// pointers, or convert structs containing thin pointers to
268 /// structs containing fat pointers, or convert between fat
269 /// pointers. We don't store the details of how the transform is
270 /// done (in fact, we don't know that, because it might depend on
271 /// the precise type parameters). We just store the target
272 /// type. Codegen backends and miri figure out what has to be done
273 /// based on the precise source/target type at hand.
277 /// The result of type inference: A mapping from expressions and patterns to types.
278 #[derive(Clone, PartialEq, Eq, Debug, Default)]
279 pub struct InferenceResult {
280 /// For each method call expr, records the function it resolves to.
281 method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
282 /// For each field access expr, records the field it resolves to.
283 field_resolutions: FxHashMap<ExprId, FieldId>,
284 /// For each struct literal or pattern, records the variant it resolves to.
285 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
286 /// For each associated item record what it resolves to
287 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
288 pub diagnostics: Vec<InferenceDiagnostic>,
289 pub type_of_expr: ArenaMap<ExprId, Ty>,
290 /// For each pattern record the type it resolves to.
292 /// **Note**: When a pattern type is resolved it may still contain
293 /// unresolved or missing subpatterns or subpatterns of mismatched types.
294 pub type_of_pat: ArenaMap<PatId, Ty>,
295 type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
296 /// Interned Unknown to return references to.
297 standard_types: InternedStandardTypes,
298 /// Stores the types which were implicitly dereferenced in pattern binding modes.
299 pub pat_adjustments: FxHashMap<PatId, Vec<Adjustment>>,
300 pub pat_binding_modes: FxHashMap<PatId, BindingMode>,
301 pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
304 impl InferenceResult {
305 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
306 self.method_resolutions.get(&expr).cloned()
308 pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
309 self.field_resolutions.get(&expr).copied()
311 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
312 self.variant_resolutions.get(&id.into()).copied()
314 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
315 self.variant_resolutions.get(&id.into()).copied()
317 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
318 self.assoc_resolutions.get(&id.into()).copied()
320 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
321 self.assoc_resolutions.get(&id.into()).copied()
323 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
324 self.type_mismatches.get(&expr.into())
326 pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
327 self.type_mismatches.get(&pat.into())
329 pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
330 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
331 ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
335 pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
336 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
337 ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
343 impl Index<ExprId> for InferenceResult {
346 fn index(&self, expr: ExprId) -> &Ty {
347 self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
351 impl Index<PatId> for InferenceResult {
354 fn index(&self, pat: PatId) -> &Ty {
355 self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
359 /// The inference context contains all information needed during type inference.
360 #[derive(Clone, Debug)]
361 pub(crate) struct InferenceContext<'a> {
362 pub(crate) db: &'a dyn HirDatabase,
363 pub(crate) owner: DefWithBodyId,
364 pub(crate) body: &'a Body,
365 pub(crate) resolver: Resolver,
366 table: unify::InferenceTable<'a>,
367 trait_env: Arc<TraitEnvironment>,
368 pub(crate) result: InferenceResult,
369 /// The return type of the function being inferred, the closure or async block if we're
370 /// currently within one.
372 /// We might consider using a nested inference context for checking
373 /// closures, but currently this is the only field that will change there,
374 /// so it doesn't make sense.
377 breakables: Vec<BreakableContext>,
380 #[derive(Clone, Debug)]
381 struct BreakableContext {
384 label: Option<name::Name>,
387 fn find_breakable<'c>(
388 ctxs: &'c mut [BreakableContext],
389 label: Option<&name::Name>,
390 ) -> Option<&'c mut BreakableContext> {
392 Some(_) => ctxs.iter_mut().rev().find(|ctx| ctx.label.as_ref() == label),
393 None => ctxs.last_mut(),
397 impl<'a> InferenceContext<'a> {
399 db: &'a dyn HirDatabase,
400 owner: DefWithBodyId,
404 let krate = owner.module(db.upcast()).krate();
405 let trait_env = owner
407 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
409 result: InferenceResult::default(),
410 table: unify::InferenceTable::new(db, trait_env.clone()),
412 return_ty: TyKind::Error.intern(Interner), // set in collect_fn_signature
417 diverges: Diverges::Maybe,
418 breakables: Vec::new(),
422 fn resolve_all(self) -> InferenceResult {
423 let InferenceContext { mut table, mut result, .. } = self;
425 // FIXME resolve obligations as well (use Guidance if necessary)
426 table.resolve_obligations_as_possible();
428 // make sure diverging type variables are marked as such
429 table.propagate_diverging_flag();
430 for ty in result.type_of_expr.values_mut() {
431 *ty = table.resolve_completely(ty.clone());
433 for ty in result.type_of_pat.values_mut() {
434 *ty = table.resolve_completely(ty.clone());
436 for mismatch in result.type_mismatches.values_mut() {
437 mismatch.expected = table.resolve_completely(mismatch.expected.clone());
438 mismatch.actual = table.resolve_completely(mismatch.actual.clone());
440 for (_, subst) in result.method_resolutions.values_mut() {
441 *subst = table.resolve_completely(subst.clone());
443 for adjustment in result.expr_adjustments.values_mut().flatten() {
444 adjustment.target = table.resolve_completely(adjustment.target.clone());
446 for adjustment in result.pat_adjustments.values_mut().flatten() {
447 adjustment.target = table.resolve_completely(adjustment.target.clone());
452 fn collect_const(&mut self, data: &ConstData) {
453 self.return_ty = self.make_ty(&data.type_ref);
456 fn collect_static(&mut self, data: &StaticData) {
457 self.return_ty = self.make_ty(&data.type_ref);
460 fn collect_fn(&mut self, data: &FunctionData) {
461 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
462 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
464 data.params.iter().map(|(_, type_ref)| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
465 for (ty, pat) in param_tys.into_iter().zip(self.body.params.iter()) {
466 let ty = self.insert_type_vars(ty);
467 let ty = self.normalize_associated_types_in(ty);
469 self.infer_pat(*pat, &ty, BindingMode::default());
471 let error_ty = &TypeRef::Error;
472 let return_ty = if data.has_async_kw() {
473 data.async_ret_type.as_deref().unwrap_or(error_ty)
477 let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Disallowed); // FIXME implement RPIT
478 self.return_ty = return_ty;
481 fn infer_body(&mut self) {
482 self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
485 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
486 self.result.type_of_expr.insert(expr, ty);
489 fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
490 self.result.expr_adjustments.insert(expr, adjustments);
493 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
494 self.result.method_resolutions.insert(expr, (func, subst));
497 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
498 self.result.variant_resolutions.insert(id, variant);
501 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
502 self.result.assoc_resolutions.insert(id, item);
505 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
506 self.result.type_of_pat.insert(pat, ty);
509 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
510 self.result.diagnostics.push(diagnostic);
513 fn make_ty_with_mode(
516 impl_trait_mode: ImplTraitLoweringMode,
518 // FIXME use right resolver for block
519 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
520 .with_impl_trait_mode(impl_trait_mode);
521 let ty = ctx.lower_ty(type_ref);
522 let ty = self.insert_type_vars(ty);
523 self.normalize_associated_types_in(ty)
526 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
527 self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
530 fn err_ty(&self) -> Ty {
531 self.result.standard_types.unknown.clone()
534 /// Replaces ConstScalar::Unknown by a new type var, so we can maybe still infer it.
535 fn insert_const_vars_shallow(&mut self, c: Const) -> Const {
536 let data = c.data(Interner);
538 ConstValue::Concrete(cc) => match cc.interned {
539 hir_def::type_ref::ConstScalar::Usize(_) => c,
540 hir_def::type_ref::ConstScalar::Unknown => {
541 self.table.new_const_var(data.ty.clone())
548 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
549 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
550 match ty.kind(Interner) {
551 TyKind::Error => self.table.new_type_var(),
552 TyKind::InferenceVar(..) => {
553 let ty_resolved = self.resolve_ty_shallow(&ty);
554 if ty_resolved.is_unknown() {
555 self.table.new_type_var()
564 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
568 Either::Left(ty) => Either::Left(self.insert_type_vars_shallow(ty)),
569 Either::Right(c) => Either::Right(self.insert_const_vars_shallow(c)),
571 DebruijnIndex::INNERMOST,
575 fn resolve_obligations_as_possible(&mut self) {
576 self.table.resolve_obligations_as_possible();
579 fn push_obligation(&mut self, o: DomainGoal) {
580 self.table.register_obligation(o.cast(Interner));
583 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
584 self.table.unify(ty1, ty2)
587 /// Recurses through the given type, normalizing associated types mentioned
588 /// in it by replacing them by type variables and registering obligations to
589 /// resolve later. This should be done once for every type we get from some
590 /// type annotation (e.g. from a let type annotation, field type or function
591 /// call). `make_ty` handles this already, but e.g. for field types we need
592 /// to do it as well.
593 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
594 self.table.normalize_associated_types_in(ty)
597 fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
598 self.resolve_obligations_as_possible();
599 self.table.resolve_ty_shallow(ty)
602 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
603 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
606 fn resolve_associated_type_with_params(
609 assoc_ty: Option<TypeAliasId>,
610 params: &[GenericArg],
613 Some(res_assoc_ty) => {
614 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
615 hir_def::ItemContainerId::TraitId(trait_) => trait_,
616 _ => panic!("resolve_associated_type called with non-associated type"),
618 let ty = self.table.new_type_var();
619 let mut param_iter = params.iter().cloned();
620 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
622 .fill(|_| param_iter.next().unwrap())
624 let alias_eq = AliasEq {
625 alias: AliasTy::Projection(ProjectionTy {
626 associated_ty_id: to_assoc_type_id(res_assoc_ty),
627 substitution: trait_ref.substitution.clone(),
631 self.push_obligation(trait_ref.cast(Interner));
632 self.push_obligation(alias_eq.cast(Interner));
635 None => self.err_ty(),
639 fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
640 let path = match path {
642 None => return (self.err_ty(), None),
644 let resolver = &self.resolver;
645 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
646 // FIXME: this should resolve assoc items as well, see this example:
647 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
648 let (resolution, unresolved) = if value_ns {
649 match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
650 Some(ResolveValueResult::ValueNs(value)) => match value {
651 ValueNs::EnumVariantId(var) => {
652 let substs = ctx.substs_from_path(path, var.into(), true);
653 let ty = self.db.ty(var.parent.into());
654 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
655 return (ty, Some(var.into()));
657 ValueNs::StructId(strukt) => {
658 let substs = ctx.substs_from_path(path, strukt.into(), true);
659 let ty = self.db.ty(strukt.into());
660 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
661 return (ty, Some(strukt.into()));
663 _ => return (self.err_ty(), None),
665 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
666 None => return (self.err_ty(), None),
669 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
671 None => return (self.err_ty(), None),
674 return match resolution {
675 TypeNs::AdtId(AdtId::StructId(strukt)) => {
676 let substs = ctx.substs_from_path(path, strukt.into(), true);
677 let ty = self.db.ty(strukt.into());
678 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
679 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
681 TypeNs::AdtId(AdtId::UnionId(u)) => {
682 let substs = ctx.substs_from_path(path, u.into(), true);
683 let ty = self.db.ty(u.into());
684 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
685 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
687 TypeNs::EnumVariantId(var) => {
688 let substs = ctx.substs_from_path(path, var.into(), true);
689 let ty = self.db.ty(var.parent.into());
690 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
691 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
693 TypeNs::SelfType(impl_id) => {
694 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
695 let substs = generics.placeholder_subst(self.db);
696 let ty = self.db.impl_self_ty(impl_id).substitute(Interner, &substs);
697 self.resolve_variant_on_alias(ty, unresolved, path)
699 TypeNs::TypeAliasId(it) => {
700 let ty = TyBuilder::def_ty(self.db, it.into())
701 .fill_with_inference_vars(&mut self.table)
703 self.resolve_variant_on_alias(ty, unresolved, path)
705 TypeNs::AdtSelfType(_) => {
706 // FIXME this could happen in array size expressions, once we're checking them
707 (self.err_ty(), None)
709 TypeNs::GenericParam(_) => {
710 // FIXME potentially resolve assoc type
711 (self.err_ty(), None)
713 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
715 (self.err_ty(), None)
719 fn forbid_unresolved_segments(
720 result: (Ty, Option<VariantId>),
721 unresolved: Option<usize>,
722 ) -> (Ty, Option<VariantId>) {
723 if unresolved.is_none() {
727 (TyKind::Error.intern(Interner), None)
732 fn resolve_variant_on_alias(
735 unresolved: Option<usize>,
737 ) -> (Ty, Option<VariantId>) {
738 let remaining = unresolved.map(|x| path.segments().skip(x).len()).filter(|x| x > &0);
741 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
742 AdtId::StructId(s) => Some(VariantId::StructId(s)),
743 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
744 AdtId::EnumId(_) => {
745 // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
752 let segment = path.mod_path().segments().last().unwrap();
753 // this could be an enum variant or associated type
754 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
755 let enum_data = self.db.enum_data(enum_id);
756 if let Some(local_id) = enum_data.variant(segment) {
757 let variant = EnumVariantId { parent: enum_id, local_id };
758 return (ty, Some(variant.into()));
761 // FIXME potentially resolve assoc type
762 (self.err_ty(), None)
766 (self.err_ty(), None)
771 fn resolve_lang_item(&self, name: Name) -> Option<LangItemTarget> {
772 let krate = self.resolver.krate();
773 self.db.lang_item(krate, name.to_smol_str())
776 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
777 let path = path![core::iter::IntoIterator];
778 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
779 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
782 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
783 // FIXME resolve via lang_item once try v2 is stable
784 let path = path![core::ops::Try];
785 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
786 let trait_data = self.db.trait_data(trait_);
788 // FIXME remove once try v2 is stable
789 .associated_type_by_name(&name![Ok])
790 .or_else(|| trait_data.associated_type_by_name(&name![Output]))
793 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
794 let trait_ = self.resolve_lang_item(name![neg])?.as_trait()?;
795 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
798 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
799 let trait_ = self.resolve_lang_item(name![not])?.as_trait()?;
800 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
803 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
804 let trait_ = self.resolve_lang_item(name![future_trait])?.as_trait()?;
805 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
808 fn resolve_boxed_box(&self) -> Option<AdtId> {
809 let struct_ = self.resolve_lang_item(name![owned_box])?.as_struct()?;
813 fn resolve_range_full(&self) -> Option<AdtId> {
814 let path = path![core::ops::RangeFull];
815 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
819 fn resolve_range(&self) -> Option<AdtId> {
820 let path = path![core::ops::Range];
821 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
825 fn resolve_range_inclusive(&self) -> Option<AdtId> {
826 let path = path![core::ops::RangeInclusive];
827 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
831 fn resolve_range_from(&self) -> Option<AdtId> {
832 let path = path![core::ops::RangeFrom];
833 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
837 fn resolve_range_to(&self) -> Option<AdtId> {
838 let path = path![core::ops::RangeTo];
839 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
843 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
844 let path = path![core::ops::RangeToInclusive];
845 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
849 fn resolve_ops_index(&self) -> Option<TraitId> {
850 self.resolve_lang_item(name![index])?.as_trait()
853 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
854 let trait_ = self.resolve_ops_index()?;
855 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
859 /// When inferring an expression, we propagate downward whatever type hint we
860 /// are able in the form of an `Expectation`.
861 #[derive(Clone, PartialEq, Eq, Debug)]
862 pub(crate) enum Expectation {
865 // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
866 RValueLikeUnsized(Ty),
870 /// The expectation that the type of the expression needs to equal the given
872 fn has_type(ty: Ty) -> Self {
874 // FIXME: get rid of this?
877 Expectation::HasType(ty)
881 fn from_option(ty: Option<Ty>) -> Self {
882 ty.map_or(Expectation::None, Expectation::HasType)
885 /// The following explanation is copied straight from rustc:
886 /// Provides an expectation for an rvalue expression given an *optional*
887 /// hint, which is not required for type safety (the resulting type might
888 /// be checked higher up, as is the case with `&expr` and `box expr`), but
889 /// is useful in determining the concrete type.
891 /// The primary use case is where the expected type is a fat pointer,
892 /// like `&[isize]`. For example, consider the following statement:
894 /// let x: &[isize] = &[1, 2, 3];
896 /// In this case, the expected type for the `&[1, 2, 3]` expression is
897 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
898 /// expectation `ExpectHasType([isize])`, that would be too strong --
899 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
900 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
901 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
902 /// which still is useful, because it informs integer literals and the like.
903 /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
904 /// for examples of where this comes up,.
905 fn rvalue_hint(table: &mut unify::InferenceTable, ty: Ty) -> Self {
906 // FIXME: do struct_tail_without_normalization
907 match table.resolve_ty_shallow(&ty).kind(Interner) {
908 TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
909 _ => Expectation::has_type(ty),
913 /// This expresses no expectation on the type.
918 fn resolve(&self, table: &mut unify::InferenceTable) -> Expectation {
920 Expectation::None => Expectation::None,
921 Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
922 Expectation::RValueLikeUnsized(t) => {
923 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
928 fn to_option(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
929 match self.resolve(table) {
930 Expectation::None => None,
931 Expectation::HasType(t) |
932 // Expectation::Castable(t) |
933 Expectation::RValueLikeUnsized(t) => Some(t),
937 fn only_has_type(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
939 Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
940 // Expectation::Castable(_) |
941 Expectation::RValueLikeUnsized(_) | Expectation::None => None,
945 /// Comment copied from rustc:
946 /// Disregard "castable to" expectations because they
947 /// can lead us astray. Consider for example `if cond
948 /// {22} else {c} as u8` -- if we propagate the
949 /// "castable to u8" constraint to 22, it will pick the
950 /// type 22u8, which is overly constrained (c might not
951 /// be a u8). In effect, the problem is that the
952 /// "castable to" expectation is not the tightest thing
953 /// we can say, so we want to drop it in this case.
954 /// The tightest thing we can say is "must unify with
955 /// else branch". Note that in the case of a "has type"
956 /// constraint, this limitation does not hold.
958 /// If the expected type is just a type variable, then don't use
959 /// an expected type. Otherwise, we might write parts of the type
960 /// when checking the 'then' block which are incompatible with the
962 fn adjust_for_branches(&self, table: &mut unify::InferenceTable) -> Expectation {
964 Expectation::HasType(ety) => {
965 let ety = table.resolve_ty_shallow(ety);
966 if !ety.is_ty_var() {
967 Expectation::HasType(ety)
972 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
973 _ => Expectation::None,
978 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
985 fn is_always(self) -> bool {
986 self == Diverges::Always
990 impl std::ops::BitAnd for Diverges {
992 fn bitand(self, other: Self) -> Self {
993 std::cmp::min(self, other)
997 impl std::ops::BitOr for Diverges {
999 fn bitor(self, other: Self) -> Self {
1000 std::cmp::max(self, other)
1004 impl std::ops::BitAndAssign for Diverges {
1005 fn bitand_assign(&mut self, other: Self) {
1006 *self = *self & other;
1010 impl std::ops::BitOrAssign for Diverges {
1011 fn bitor_assign(&mut self, other: Self) {
1012 *self = *self | other;