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, 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;
35 use stdx::{always, impl_from};
38 db::HirDatabase, fold_tys, fold_tys_and_consts, infer::coerce::CoerceMany,
39 lower::ImplTraitLoweringMode, to_assoc_type_id, AliasEq, AliasTy, Const, DomainGoal,
40 GenericArg, Goal, ImplTraitId, InEnvironment, Interner, ProjectionTy, Substitution,
41 TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
44 // This lint has a false positive here. See the link below for details.
46 // https://github.com/rust-lang/rust/issues/57411
47 #[allow(unreachable_pub)]
48 pub use coerce::could_coerce;
49 #[allow(unreachable_pub)]
50 pub use unify::could_unify;
59 /// The entry point of type inference.
60 pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
61 let _p = profile::span("infer_query");
62 let resolver = def.resolver(db.upcast());
63 let body = db.body(def);
64 let mut ctx = InferenceContext::new(db, def, &body, resolver);
67 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
68 DefWithBodyId::FunctionId(f) => ctx.collect_fn(f),
69 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
74 Arc::new(ctx.resolve_all())
77 /// Fully normalize all the types found within `ty` in context of `owner` body definition.
79 /// This is appropriate to use only after type-check: it assumes
80 /// that normalization will succeed, for example.
81 pub(crate) fn normalize(db: &dyn HirDatabase, owner: DefWithBodyId, ty: Ty) -> Ty {
82 if !ty.data(Interner).flags.intersects(TypeFlags::HAS_PROJECTION) {
85 let krate = owner.module(db.upcast()).krate();
88 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
89 let mut table = unify::InferenceTable::new(db, trait_env);
91 let ty_with_vars = table.normalize_associated_types_in(ty);
92 table.resolve_obligations_as_possible();
93 table.propagate_diverging_flag();
94 table.resolve_completely(ty_with_vars)
97 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
102 impl_from!(ExprId, PatId for ExprOrPatId);
104 /// Binding modes inferred for patterns.
105 /// <https://doc.rust-lang.org/reference/patterns.html#binding-modes>
106 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
107 pub enum BindingMode {
113 fn convert(annotation: BindingAnnotation) -> BindingMode {
115 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
116 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Not),
117 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
122 impl Default for BindingMode {
123 fn default() -> Self {
129 pub(crate) struct InferOk<T> {
131 goals: Vec<InEnvironment<Goal>>,
135 fn map<U>(self, f: impl FnOnce(T) -> U) -> InferOk<U> {
136 InferOk { value: f(self.value), goals: self.goals }
141 pub(crate) struct TypeError;
142 pub(crate) type InferResult<T> = Result<InferOk<T>, TypeError>;
144 #[derive(Debug, PartialEq, Eq, Clone)]
145 pub enum InferenceDiagnostic {
146 NoSuchField { expr: ExprId },
147 BreakOutsideOfLoop { expr: ExprId },
148 MismatchedArgCount { call_expr: ExprId, expected: usize, found: usize },
151 /// A mismatch between an expected and an inferred type.
152 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
153 pub struct TypeMismatch {
158 #[derive(Clone, PartialEq, Eq, Debug)]
159 struct InternedStandardTypes {
165 impl Default for InternedStandardTypes {
166 fn default() -> Self {
167 InternedStandardTypes {
168 unknown: TyKind::Error.intern(Interner),
169 bool_: TyKind::Scalar(Scalar::Bool).intern(Interner),
170 unit: TyKind::Tuple(0, Substitution::empty(Interner)).intern(Interner),
174 /// Represents coercing a value to a different type of value.
176 /// We transform values by following a number of `Adjust` steps in order.
177 /// See the documentation on variants of `Adjust` for more details.
179 /// Here are some common scenarios:
181 /// 1. The simplest cases are where a pointer is not adjusted fat vs thin.
182 /// Here the pointer will be dereferenced N times (where a dereference can
183 /// happen to raw or borrowed pointers or any smart pointer which implements
184 /// Deref, including Box<_>). The types of dereferences is given by
185 /// `autoderefs`. It can then be auto-referenced zero or one times, indicated
186 /// by `autoref`, to either a raw or borrowed pointer. In these cases unsize is
189 /// 2. A thin-to-fat coercion involves unsizing the underlying data. We start
190 /// with a thin pointer, deref a number of times, unsize the underlying data,
191 /// then autoref. The 'unsize' phase may change a fixed length array to a
192 /// dynamically sized one, a concrete object to a trait object, or statically
193 /// sized struct to a dynamically sized one. E.g., &[i32; 4] -> &[i32] is
197 /// Deref(None) -> [i32; 4],
198 /// Borrow(AutoBorrow::Ref) -> &[i32; 4],
199 /// Unsize -> &[i32],
202 /// Note that for a struct, the 'deep' unsizing of the struct is not recorded.
203 /// E.g., `struct Foo<T> { x: T }` we can coerce &Foo<[i32; 4]> to &Foo<[i32]>
204 /// The autoderef and -ref are the same as in the above example, but the type
205 /// stored in `unsize` is `Foo<[i32]>`, we don't store any further detail about
206 /// the underlying conversions from `[i32; 4]` to `[i32]`.
208 /// 3. Coercing a `Box<T>` to `Box<dyn Trait>` is an interesting special case. In
209 /// that case, we have the pointer we need coming in, so there are no
210 /// autoderefs, and no autoref. Instead we just do the `Unsize` transformation.
211 /// At some point, of course, `Box` should move out of the compiler, in which
212 /// case this is analogous to transforming a struct. E.g., Box<[i32; 4]> ->
213 /// Box<[i32]> is an `Adjust::Unsize` with the target `Box<[i32]>`.
214 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
215 pub struct Adjustment {
220 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
222 /// Go from ! to any type.
224 /// Dereference once, producing a place.
225 Deref(Option<OverloadedDeref>),
226 /// Take the address and produce either a `&` or `*` pointer.
228 Pointer(PointerCast),
231 /// An overloaded autoderef step, representing a `Deref(Mut)::deref(_mut)`
232 /// call, with the signature `&'a T -> &'a U` or `&'a mut T -> &'a mut U`.
233 /// The target type is `U` in both cases, with the region and mutability
234 /// being those shared by both the receiver and the returned reference.
235 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236 pub struct OverloadedDeref(pub Mutability);
238 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
239 pub enum AutoBorrow {
240 /// Converts from T to &T.
242 /// Converts from T to *T.
246 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
247 pub enum PointerCast {
248 /// Go from a fn-item type to a fn-pointer type.
251 /// Go from a safe fn pointer to an unsafe fn pointer.
254 /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
255 /// It cannot convert a closure that requires unsafe.
256 ClosureFnPointer(Safety),
258 /// Go from a mut raw pointer to a const raw pointer.
262 /// Go from `*const [T; N]` to `*const T`
265 /// Unsize a pointer/reference value, e.g., `&[T; n]` to
266 /// `&[T]`. Note that the source could be a thin or fat pointer.
267 /// This will do things like convert thin pointers to fat
268 /// pointers, or convert structs containing thin pointers to
269 /// structs containing fat pointers, or convert between fat
270 /// pointers. We don't store the details of how the transform is
271 /// done (in fact, we don't know that, because it might depend on
272 /// the precise type parameters). We just store the target
273 /// type. Codegen backends and miri figure out what has to be done
274 /// based on the precise source/target type at hand.
278 /// The result of type inference: A mapping from expressions and patterns to types.
279 #[derive(Clone, PartialEq, Eq, Debug, Default)]
280 pub struct InferenceResult {
281 /// For each method call expr, records the function it resolves to.
282 method_resolutions: FxHashMap<ExprId, (FunctionId, Substitution)>,
283 /// For each field access expr, records the field it resolves to.
284 field_resolutions: FxHashMap<ExprId, FieldId>,
285 /// For each struct literal or pattern, records the variant it resolves to.
286 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
287 /// For each associated item record what it resolves to
288 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
289 pub diagnostics: Vec<InferenceDiagnostic>,
290 pub type_of_expr: ArenaMap<ExprId, Ty>,
291 /// For each pattern record the type it resolves to.
293 /// **Note**: When a pattern type is resolved it may still contain
294 /// unresolved or missing subpatterns or subpatterns of mismatched types.
295 pub type_of_pat: ArenaMap<PatId, Ty>,
296 type_mismatches: FxHashMap<ExprOrPatId, TypeMismatch>,
297 /// Interned Unknown to return references to.
298 standard_types: InternedStandardTypes,
299 /// Stores the types which were implicitly dereferenced in pattern binding modes.
300 pub pat_adjustments: FxHashMap<PatId, Vec<Ty>>,
301 pub pat_binding_modes: FxHashMap<PatId, BindingMode>,
302 pub expr_adjustments: FxHashMap<ExprId, Vec<Adjustment>>,
305 impl InferenceResult {
306 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, Substitution)> {
307 self.method_resolutions.get(&expr).cloned()
309 pub fn field_resolution(&self, expr: ExprId) -> Option<FieldId> {
310 self.field_resolutions.get(&expr).copied()
312 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
313 self.variant_resolutions.get(&id.into()).copied()
315 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
316 self.variant_resolutions.get(&id.into()).copied()
318 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
319 self.assoc_resolutions.get(&id.into()).copied()
321 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
322 self.assoc_resolutions.get(&id.into()).copied()
324 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
325 self.type_mismatches.get(&expr.into())
327 pub fn type_mismatch_for_pat(&self, pat: PatId) -> Option<&TypeMismatch> {
328 self.type_mismatches.get(&pat.into())
330 pub fn expr_type_mismatches(&self) -> impl Iterator<Item = (ExprId, &TypeMismatch)> {
331 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
332 ExprOrPatId::ExprId(expr) => Some((expr, mismatch)),
336 pub fn pat_type_mismatches(&self) -> impl Iterator<Item = (PatId, &TypeMismatch)> {
337 self.type_mismatches.iter().filter_map(|(expr_or_pat, mismatch)| match *expr_or_pat {
338 ExprOrPatId::PatId(pat) => Some((pat, mismatch)),
344 impl Index<ExprId> for InferenceResult {
347 fn index(&self, expr: ExprId) -> &Ty {
348 self.type_of_expr.get(expr).unwrap_or(&self.standard_types.unknown)
352 impl Index<PatId> for InferenceResult {
355 fn index(&self, pat: PatId) -> &Ty {
356 self.type_of_pat.get(pat).unwrap_or(&self.standard_types.unknown)
360 /// The inference context contains all information needed during type inference.
361 #[derive(Clone, Debug)]
362 pub(crate) struct InferenceContext<'a> {
363 pub(crate) db: &'a dyn HirDatabase,
364 pub(crate) owner: DefWithBodyId,
365 pub(crate) body: &'a Body,
366 pub(crate) resolver: Resolver,
367 table: unify::InferenceTable<'a>,
368 trait_env: Arc<TraitEnvironment>,
369 pub(crate) result: InferenceResult,
370 /// The return type of the function being inferred, the closure or async block if we're
371 /// currently within one.
373 /// We might consider using a nested inference context for checking
374 /// closures, but currently this is the only field that will change there,
375 /// so it doesn't make sense.
378 breakables: Vec<BreakableContext>,
381 #[derive(Clone, Debug)]
382 struct BreakableContext {
385 label: Option<name::Name>,
388 fn find_breakable<'c>(
389 ctxs: &'c mut [BreakableContext],
390 label: Option<&name::Name>,
391 ) -> Option<&'c mut BreakableContext> {
393 Some(_) => ctxs.iter_mut().rev().find(|ctx| ctx.label.as_ref() == label),
394 None => ctxs.last_mut(),
398 impl<'a> InferenceContext<'a> {
400 db: &'a dyn HirDatabase,
401 owner: DefWithBodyId,
405 let krate = owner.module(db.upcast()).krate();
406 let trait_env = owner
408 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
410 result: InferenceResult::default(),
411 table: unify::InferenceTable::new(db, trait_env.clone()),
413 return_ty: TyKind::Error.intern(Interner), // set in collect_fn_signature
418 diverges: Diverges::Maybe,
419 breakables: Vec::new(),
423 fn resolve_all(self) -> InferenceResult {
424 let InferenceContext { mut table, mut result, .. } = self;
426 // FIXME resolve obligations as well (use Guidance if necessary)
427 table.resolve_obligations_as_possible();
429 // make sure diverging type variables are marked as such
430 table.propagate_diverging_flag();
431 for ty in result.type_of_expr.values_mut() {
432 *ty = table.resolve_completely(ty.clone());
434 for ty in result.type_of_pat.values_mut() {
435 *ty = table.resolve_completely(ty.clone());
437 for mismatch in result.type_mismatches.values_mut() {
438 mismatch.expected = table.resolve_completely(mismatch.expected.clone());
439 mismatch.actual = table.resolve_completely(mismatch.actual.clone());
441 for (_, subst) in result.method_resolutions.values_mut() {
442 *subst = table.resolve_completely(subst.clone());
444 for adjustment in result.expr_adjustments.values_mut().flatten() {
445 adjustment.target = table.resolve_completely(adjustment.target.clone());
447 for adjustment in result.pat_adjustments.values_mut().flatten() {
448 *adjustment = table.resolve_completely(adjustment.clone());
453 fn collect_const(&mut self, data: &ConstData) {
454 self.return_ty = self.make_ty(&data.type_ref);
457 fn collect_static(&mut self, data: &StaticData) {
458 self.return_ty = self.make_ty(&data.type_ref);
461 fn collect_fn(&mut self, func: FunctionId) {
462 let data = self.db.function_data(func);
463 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
464 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
466 data.params.iter().map(|(_, type_ref)| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
467 for (ty, pat) in param_tys.into_iter().zip(self.body.params.iter()) {
468 let ty = self.insert_type_vars(ty);
469 let ty = self.normalize_associated_types_in(ty);
471 self.infer_pat(*pat, &ty, BindingMode::default());
473 let error_ty = &TypeRef::Error;
474 let return_ty = if data.has_async_kw() {
475 data.async_ret_type.as_deref().unwrap_or(error_ty)
479 let return_ty = self.make_ty_with_mode(return_ty, ImplTraitLoweringMode::Opaque);
480 self.return_ty = return_ty;
482 if let Some(rpits) = self.db.return_type_impl_traits(func) {
483 // RPIT opaque types use substitution of their parent function.
484 let fn_placeholders = TyBuilder::placeholder_subst(self.db, func);
485 self.return_ty = fold_tys(
486 self.return_ty.clone(),
488 let opaque_ty_id = match ty.kind(Interner) {
489 TyKind::OpaqueType(opaque_ty_id, _) => *opaque_ty_id,
492 let idx = match self.db.lookup_intern_impl_trait_id(opaque_ty_id.into()) {
493 ImplTraitId::ReturnTypeImplTrait(_, idx) => idx,
496 let bounds = (*rpits).map_ref(|rpits| {
497 rpits.impl_traits[idx as usize].bounds.map_ref(|it| it.into_iter())
499 let var = self.table.new_type_var();
500 let var_subst = Substitution::from1(Interner, var.clone());
501 for bound in bounds {
503 bound.map(|it| it.cloned()).substitute(Interner, &fn_placeholders);
504 let (var_predicate, binders) = predicate
505 .substitute(Interner, &var_subst)
506 .into_value_and_skipped_binders();
507 always!(binders.len(Interner) == 0); // quantified where clauses not yet handled
508 self.push_obligation(var_predicate.cast(Interner));
512 DebruijnIndex::INNERMOST,
517 fn infer_body(&mut self) {
518 self.infer_expr_coerce(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
521 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
522 self.result.type_of_expr.insert(expr, ty);
525 fn write_expr_adj(&mut self, expr: ExprId, adjustments: Vec<Adjustment>) {
526 self.result.expr_adjustments.insert(expr, adjustments);
529 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId, subst: Substitution) {
530 self.result.method_resolutions.insert(expr, (func, subst));
533 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
534 self.result.variant_resolutions.insert(id, variant);
537 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
538 self.result.assoc_resolutions.insert(id, item);
541 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
542 self.result.type_of_pat.insert(pat, ty);
545 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
546 self.result.diagnostics.push(diagnostic);
549 fn make_ty_with_mode(
552 impl_trait_mode: ImplTraitLoweringMode,
554 // FIXME use right resolver for block
555 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
556 .with_impl_trait_mode(impl_trait_mode);
557 let ty = ctx.lower_ty(type_ref);
558 let ty = self.insert_type_vars(ty);
559 self.normalize_associated_types_in(ty)
562 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
563 self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
566 fn err_ty(&self) -> Ty {
567 self.result.standard_types.unknown.clone()
570 /// Replaces ConstScalar::Unknown by a new type var, so we can maybe still infer it.
571 fn insert_const_vars_shallow(&mut self, c: Const) -> Const {
572 let data = c.data(Interner);
574 ConstValue::Concrete(cc) => match cc.interned {
575 hir_def::type_ref::ConstScalar::Usize(_) => c,
576 hir_def::type_ref::ConstScalar::Unknown => {
577 self.table.new_const_var(data.ty.clone())
584 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
585 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
586 match ty.kind(Interner) {
587 TyKind::Error => self.table.new_type_var(),
588 TyKind::InferenceVar(..) => {
589 let ty_resolved = self.resolve_ty_shallow(&ty);
590 if ty_resolved.is_unknown() {
591 self.table.new_type_var()
600 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
604 Either::Left(ty) => Either::Left(self.insert_type_vars_shallow(ty)),
605 Either::Right(c) => Either::Right(self.insert_const_vars_shallow(c)),
607 DebruijnIndex::INNERMOST,
611 fn resolve_obligations_as_possible(&mut self) {
612 self.table.resolve_obligations_as_possible();
615 fn push_obligation(&mut self, o: DomainGoal) {
616 self.table.register_obligation(o.cast(Interner));
619 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
620 self.table.unify(ty1, ty2)
623 /// Recurses through the given type, normalizing associated types mentioned
624 /// in it by replacing them by type variables and registering obligations to
625 /// resolve later. This should be done once for every type we get from some
626 /// type annotation (e.g. from a let type annotation, field type or function
627 /// call). `make_ty` handles this already, but e.g. for field types we need
628 /// to do it as well.
629 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
630 self.table.normalize_associated_types_in(ty)
633 fn resolve_ty_shallow(&mut self, ty: &Ty) -> Ty {
634 self.resolve_obligations_as_possible();
635 self.table.resolve_ty_shallow(ty)
638 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
639 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
642 fn resolve_associated_type_with_params(
645 assoc_ty: Option<TypeAliasId>,
646 params: &[GenericArg],
649 Some(res_assoc_ty) => {
650 let trait_ = match res_assoc_ty.lookup(self.db.upcast()).container {
651 hir_def::ItemContainerId::TraitId(trait_) => trait_,
652 _ => panic!("resolve_associated_type called with non-associated type"),
654 let ty = self.table.new_type_var();
655 let mut param_iter = params.iter().cloned();
656 let trait_ref = TyBuilder::trait_ref(self.db, trait_)
658 .fill(|_| param_iter.next().unwrap())
660 let alias_eq = AliasEq {
661 alias: AliasTy::Projection(ProjectionTy {
662 associated_ty_id: to_assoc_type_id(res_assoc_ty),
663 substitution: trait_ref.substitution.clone(),
667 self.push_obligation(trait_ref.cast(Interner));
668 self.push_obligation(alias_eq.cast(Interner));
671 None => self.err_ty(),
675 fn resolve_variant(&mut self, path: Option<&Path>, value_ns: bool) -> (Ty, Option<VariantId>) {
676 let path = match path {
678 None => return (self.err_ty(), None),
680 let resolver = &self.resolver;
681 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
682 // FIXME: this should resolve assoc items as well, see this example:
683 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
684 let (resolution, unresolved) = if value_ns {
685 match resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path()) {
686 Some(ResolveValueResult::ValueNs(value)) => match value {
687 ValueNs::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 return (ty, Some(var.into()));
693 ValueNs::StructId(strukt) => {
694 let substs = ctx.substs_from_path(path, strukt.into(), true);
695 let ty = self.db.ty(strukt.into());
696 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
697 return (ty, Some(strukt.into()));
699 _ => return (self.err_ty(), None),
701 Some(ResolveValueResult::Partial(typens, unresolved)) => (typens, Some(unresolved)),
702 None => return (self.err_ty(), None),
705 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
707 None => return (self.err_ty(), None),
710 return match resolution {
711 TypeNs::AdtId(AdtId::StructId(strukt)) => {
712 let substs = ctx.substs_from_path(path, strukt.into(), true);
713 let ty = self.db.ty(strukt.into());
714 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
715 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
717 TypeNs::AdtId(AdtId::UnionId(u)) => {
718 let substs = ctx.substs_from_path(path, u.into(), true);
719 let ty = self.db.ty(u.into());
720 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
721 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
723 TypeNs::EnumVariantId(var) => {
724 let substs = ctx.substs_from_path(path, var.into(), true);
725 let ty = self.db.ty(var.parent.into());
726 let ty = self.insert_type_vars(ty.substitute(Interner, &substs));
727 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
729 TypeNs::SelfType(impl_id) => {
730 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
731 let substs = generics.placeholder_subst(self.db);
732 let ty = self.db.impl_self_ty(impl_id).substitute(Interner, &substs);
733 self.resolve_variant_on_alias(ty, unresolved, path)
735 TypeNs::TypeAliasId(it) => {
736 let ty = TyBuilder::def_ty(self.db, it.into())
737 .fill_with_inference_vars(&mut self.table)
739 self.resolve_variant_on_alias(ty, unresolved, path)
741 TypeNs::AdtSelfType(_) => {
742 // FIXME this could happen in array size expressions, once we're checking them
743 (self.err_ty(), None)
745 TypeNs::GenericParam(_) => {
746 // FIXME potentially resolve assoc type
747 (self.err_ty(), None)
749 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
751 (self.err_ty(), None)
755 fn forbid_unresolved_segments(
756 result: (Ty, Option<VariantId>),
757 unresolved: Option<usize>,
758 ) -> (Ty, Option<VariantId>) {
759 if unresolved.is_none() {
763 (TyKind::Error.intern(Interner), None)
768 fn resolve_variant_on_alias(
771 unresolved: Option<usize>,
773 ) -> (Ty, Option<VariantId>) {
774 let remaining = unresolved.map(|x| path.segments().skip(x).len()).filter(|x| x > &0);
777 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
778 AdtId::StructId(s) => Some(VariantId::StructId(s)),
779 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
780 AdtId::EnumId(_) => {
781 // FIXME Error E0071, expected struct, variant or union type, found enum `Foo`
788 let segment = path.mod_path().segments().last().unwrap();
789 // this could be an enum variant or associated type
790 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
791 let enum_data = self.db.enum_data(enum_id);
792 if let Some(local_id) = enum_data.variant(segment) {
793 let variant = EnumVariantId { parent: enum_id, local_id };
794 return (ty, Some(variant.into()));
797 // FIXME potentially resolve assoc type
798 (self.err_ty(), None)
802 (self.err_ty(), None)
807 fn resolve_lang_item(&self, name: Name) -> Option<LangItemTarget> {
808 let krate = self.resolver.krate();
809 self.db.lang_item(krate, name.to_smol_str())
812 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
813 let path = path![core::iter::IntoIterator];
814 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
815 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
818 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
819 // FIXME resolve via lang_item once try v2 is stable
820 let path = path![core::ops::Try];
821 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
822 let trait_data = self.db.trait_data(trait_);
824 // FIXME remove once try v2 is stable
825 .associated_type_by_name(&name![Ok])
826 .or_else(|| trait_data.associated_type_by_name(&name![Output]))
829 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
830 let trait_ = self.resolve_lang_item(name![neg])?.as_trait()?;
831 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
834 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
835 let trait_ = self.resolve_lang_item(name![not])?.as_trait()?;
836 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
839 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
840 let trait_ = self.resolve_lang_item(name![future_trait])?.as_trait()?;
841 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
844 fn resolve_boxed_box(&self) -> Option<AdtId> {
845 let struct_ = self.resolve_lang_item(name![owned_box])?.as_struct()?;
849 fn resolve_range_full(&self) -> Option<AdtId> {
850 let path = path![core::ops::RangeFull];
851 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
855 fn resolve_range(&self) -> Option<AdtId> {
856 let path = path![core::ops::Range];
857 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
861 fn resolve_range_inclusive(&self) -> Option<AdtId> {
862 let path = path![core::ops::RangeInclusive];
863 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
867 fn resolve_range_from(&self) -> Option<AdtId> {
868 let path = path![core::ops::RangeFrom];
869 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
873 fn resolve_range_to(&self) -> Option<AdtId> {
874 let path = path![core::ops::RangeTo];
875 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
879 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
880 let path = path![core::ops::RangeToInclusive];
881 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
885 fn resolve_ops_index(&self) -> Option<TraitId> {
886 self.resolve_lang_item(name![index])?.as_trait()
889 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
890 let trait_ = self.resolve_ops_index()?;
891 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
895 /// When inferring an expression, we propagate downward whatever type hint we
896 /// are able in the form of an `Expectation`.
897 #[derive(Clone, PartialEq, Eq, Debug)]
898 pub(crate) enum Expectation {
901 // Castable(Ty), // rustc has this, we currently just don't propagate an expectation for casts
902 RValueLikeUnsized(Ty),
906 /// The expectation that the type of the expression needs to equal the given
908 fn has_type(ty: Ty) -> Self {
910 // FIXME: get rid of this?
913 Expectation::HasType(ty)
917 fn from_option(ty: Option<Ty>) -> Self {
918 ty.map_or(Expectation::None, Expectation::HasType)
921 /// The following explanation is copied straight from rustc:
922 /// Provides an expectation for an rvalue expression given an *optional*
923 /// hint, which is not required for type safety (the resulting type might
924 /// be checked higher up, as is the case with `&expr` and `box expr`), but
925 /// is useful in determining the concrete type.
927 /// The primary use case is where the expected type is a fat pointer,
928 /// like `&[isize]`. For example, consider the following statement:
930 /// let x: &[isize] = &[1, 2, 3];
932 /// In this case, the expected type for the `&[1, 2, 3]` expression is
933 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
934 /// expectation `ExpectHasType([isize])`, that would be too strong --
935 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
936 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
937 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
938 /// which still is useful, because it informs integer literals and the like.
939 /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
940 /// for examples of where this comes up,.
941 fn rvalue_hint(table: &mut unify::InferenceTable, ty: Ty) -> Self {
942 // FIXME: do struct_tail_without_normalization
943 match table.resolve_ty_shallow(&ty).kind(Interner) {
944 TyKind::Slice(_) | TyKind::Str | TyKind::Dyn(_) => Expectation::RValueLikeUnsized(ty),
945 _ => Expectation::has_type(ty),
949 /// This expresses no expectation on the type.
954 fn resolve(&self, table: &mut unify::InferenceTable) -> Expectation {
956 Expectation::None => Expectation::None,
957 Expectation::HasType(t) => Expectation::HasType(table.resolve_ty_shallow(t)),
958 Expectation::RValueLikeUnsized(t) => {
959 Expectation::RValueLikeUnsized(table.resolve_ty_shallow(t))
964 fn to_option(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
965 match self.resolve(table) {
966 Expectation::None => None,
967 Expectation::HasType(t) |
968 // Expectation::Castable(t) |
969 Expectation::RValueLikeUnsized(t) => Some(t),
973 fn only_has_type(&self, table: &mut unify::InferenceTable) -> Option<Ty> {
975 Expectation::HasType(t) => Some(table.resolve_ty_shallow(t)),
976 // Expectation::Castable(_) |
977 Expectation::RValueLikeUnsized(_) | Expectation::None => None,
981 /// Comment copied from rustc:
982 /// Disregard "castable to" expectations because they
983 /// can lead us astray. Consider for example `if cond
984 /// {22} else {c} as u8` -- if we propagate the
985 /// "castable to u8" constraint to 22, it will pick the
986 /// type 22u8, which is overly constrained (c might not
987 /// be a u8). In effect, the problem is that the
988 /// "castable to" expectation is not the tightest thing
989 /// we can say, so we want to drop it in this case.
990 /// The tightest thing we can say is "must unify with
991 /// else branch". Note that in the case of a "has type"
992 /// constraint, this limitation does not hold.
994 /// If the expected type is just a type variable, then don't use
995 /// an expected type. Otherwise, we might write parts of the type
996 /// when checking the 'then' block which are incompatible with the
998 fn adjust_for_branches(&self, table: &mut unify::InferenceTable) -> Expectation {
1000 Expectation::HasType(ety) => {
1001 let ety = table.resolve_ty_shallow(ety);
1002 if !ety.is_ty_var() {
1003 Expectation::HasType(ety)
1008 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
1009 _ => Expectation::None,
1014 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1021 fn is_always(self) -> bool {
1022 self == Diverges::Always
1026 impl std::ops::BitAnd for Diverges {
1028 fn bitand(self, other: Self) -> Self {
1029 std::cmp::min(self, other)
1033 impl std::ops::BitOr for Diverges {
1035 fn bitor(self, other: Self) -> Self {
1036 std::cmp::max(self, other)
1040 impl std::ops::BitAndAssign for Diverges {
1041 fn bitand_assign(&mut self, other: Self) {
1042 *self = *self & other;
1046 impl std::ops::BitOrAssign for Diverges {
1047 fn bitor_assign(&mut self, other: Self) {
1048 *self = *self | other;