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.
21 use rustc_hash::FxHashMap;
25 data::{ConstData, FunctionData},
26 expr::{BindingAnnotation, ExprId, PatId},
28 resolver::{HasResolver, Resolver, TypeNs},
29 type_ref::{Mutability, TypeRef},
30 AdtId, AssocItemId, DefWithBodyId, FunctionId, StructFieldId, TypeAliasId, VariantId,
32 use hir_expand::{diagnostics::DiagnosticSink, name::name};
33 use ra_arena::map::ArenaMap;
35 use test_utils::tested_by;
38 primitive::{FloatTy, IntTy},
39 traits::{Guidance, Obligation, ProjectionPredicate, Solution},
40 ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor,
43 use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic};
45 pub(crate) use unify::unify;
48 ($ctor:pat, $param:pat) => {
49 crate::Ty::Apply(crate::ApplicationTy { ctor: $ctor, parameters: $param })
62 /// The entry point of type inference.
63 pub fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
64 let _p = profile("infer_query");
65 let resolver = def.resolver(db);
66 let mut ctx = InferenceContext::new(db, def, resolver);
69 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
70 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
71 DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)),
76 Arc::new(ctx.resolve_all())
79 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
85 impl_froms!(ExprOrPatId: ExprId, PatId);
87 /// Binding modes inferred for patterns.
88 /// https://doc.rust-lang.org/reference/patterns.html#binding-modes
89 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
96 pub fn convert(annotation: BindingAnnotation) -> BindingMode {
98 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
99 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared),
100 BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
105 impl Default for BindingMode {
106 fn default() -> Self {
111 /// A mismatch between an expected and an inferred type.
112 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
113 pub struct TypeMismatch {
118 /// The result of type inference: A mapping from expressions and patterns to types.
119 #[derive(Clone, PartialEq, Eq, Debug, Default)]
120 pub struct InferenceResult {
121 /// For each method call expr, records the function it resolves to.
122 method_resolutions: FxHashMap<ExprId, FunctionId>,
123 /// For each field access expr, records the field it resolves to.
124 field_resolutions: FxHashMap<ExprId, StructFieldId>,
125 /// For each field in record literal, records the field it resolves to.
126 record_field_resolutions: FxHashMap<ExprId, StructFieldId>,
127 /// For each struct literal, records the variant it resolves to.
128 variant_resolutions: FxHashMap<ExprOrPatId, VariantId>,
129 /// For each associated item record what it resolves to
130 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
131 diagnostics: Vec<InferenceDiagnostic>,
132 pub type_of_expr: ArenaMap<ExprId, Ty>,
133 pub type_of_pat: ArenaMap<PatId, Ty>,
134 pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>,
137 impl InferenceResult {
138 pub fn method_resolution(&self, expr: ExprId) -> Option<FunctionId> {
139 self.method_resolutions.get(&expr).copied()
141 pub fn field_resolution(&self, expr: ExprId) -> Option<StructFieldId> {
142 self.field_resolutions.get(&expr).copied()
144 pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructFieldId> {
145 self.record_field_resolutions.get(&expr).copied()
147 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
148 self.variant_resolutions.get(&id.into()).copied()
150 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
151 self.variant_resolutions.get(&id.into()).copied()
153 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> {
154 self.assoc_resolutions.get(&id.into()).copied()
156 pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> {
157 self.assoc_resolutions.get(&id.into()).copied()
159 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
160 self.type_mismatches.get(expr)
162 pub fn add_diagnostics(
164 db: &impl HirDatabase,
166 sink: &mut DiagnosticSink,
168 self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink))
172 impl Index<ExprId> for InferenceResult {
175 fn index(&self, expr: ExprId) -> &Ty {
176 self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown)
180 impl Index<PatId> for InferenceResult {
183 fn index(&self, pat: PatId) -> &Ty {
184 self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown)
188 /// The inference context contains all information needed during type inference.
189 #[derive(Clone, Debug)]
190 struct InferenceContext<'a, D: HirDatabase> {
192 owner: DefWithBodyId,
195 table: unify::InferenceTable,
196 trait_env: Arc<TraitEnvironment>,
197 obligations: Vec<Obligation>,
198 result: InferenceResult,
199 /// The return type of the function being inferred.
202 /// Impls of `CoerceUnsized` used in coercion.
203 /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index
204 // FIXME: Use trait solver for this.
205 // Chalk seems unable to work well with builtin impl of `Unsize` now.
206 coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>,
209 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
210 fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self {
212 result: InferenceResult::default(),
213 table: unify::InferenceTable::new(),
214 obligations: Vec::default(),
215 return_ty: Ty::Unknown, // set in collect_fn_signature
216 trait_env: TraitEnvironment::lower(db, &resolver),
217 coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver),
220 body: db.body(owner.into()),
225 fn resolve_all(mut self) -> InferenceResult {
226 // FIXME resolve obligations as well (use Guidance if necessary)
227 let mut result = mem::replace(&mut self.result, InferenceResult::default());
228 for ty in result.type_of_expr.values_mut() {
229 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown));
232 for ty in result.type_of_pat.values_mut() {
233 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown));
239 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) {
240 self.result.type_of_expr.insert(expr, ty);
243 fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId) {
244 self.result.method_resolutions.insert(expr, func);
247 fn write_field_resolution(&mut self, expr: ExprId, field: StructFieldId) {
248 self.result.field_resolutions.insert(expr, field);
251 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) {
252 self.result.variant_resolutions.insert(id, variant);
255 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) {
256 self.result.assoc_resolutions.insert(id, item.into());
259 fn write_pat_ty(&mut self, pat: PatId, ty: Ty) {
260 self.result.type_of_pat.insert(pat, ty);
263 fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) {
264 self.result.diagnostics.push(diagnostic);
267 fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
268 let ty = Ty::from_hir(
270 // FIXME use right resolver for block
274 let ty = self.insert_type_vars(ty);
275 self.normalize_associated_types_in(ty)
278 /// Replaces `impl Trait` in `ty` by type variables and obligations for
279 /// those variables. This is done for function arguments when calling a
280 /// function, and for return types when inside the function body, i.e. in
281 /// the cases where the `impl Trait` is 'transparent'. In other cases, `impl
282 /// Trait` is represented by `Ty::Opaque`.
283 fn insert_vars_for_impl_trait(&mut self, ty: Ty) -> Ty {
284 ty.fold(&mut |ty| match ty {
285 Ty::Opaque(preds) => {
286 tested_by!(insert_vars_for_impl_trait);
287 let var = self.table.new_type_var();
288 let var_subst = Substs::builder(1).push(var.clone()).build();
289 self.obligations.extend(
292 .map(|pred| pred.clone().subst_bound_vars(&var_subst))
293 .filter_map(Obligation::from_predicate),
301 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
302 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
304 Ty::Unknown => self.table.new_type_var(),
305 Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => {
306 self.table.new_integer_var()
308 Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => {
309 self.table.new_float_var()
315 fn insert_type_vars(&mut self, ty: Ty) -> Ty {
316 ty.fold(&mut |ty| self.insert_type_vars_shallow(ty))
319 fn resolve_obligations_as_possible(&mut self) {
320 let obligations = mem::replace(&mut self.obligations, Vec::new());
321 for obligation in obligations {
322 let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone());
323 let canonicalized = self.canonicalizer().canonicalize_obligation(in_env);
326 .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone());
329 Some(Solution::Unique(substs)) => {
330 canonicalized.apply_solution(self, substs.0);
332 Some(Solution::Ambig(Guidance::Definite(substs))) => {
333 canonicalized.apply_solution(self, substs.0);
334 self.obligations.push(obligation);
337 // FIXME use this when trying to resolve everything at the end
338 self.obligations.push(obligation);
341 // FIXME obligation cannot be fulfilled => diagnostic
347 fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
348 self.table.unify(ty1, ty2)
351 /// Resolves the type as far as currently possible, replacing type variables
352 /// by their known types. All types returned by the infer_* functions should
353 /// be resolved as far as possible, i.e. contain no type variables with
355 fn resolve_ty_as_possible(&mut self, ty: Ty) -> Ty {
356 self.resolve_obligations_as_possible();
358 self.table.resolve_ty_as_possible(ty)
361 fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> {
362 self.table.resolve_ty_shallow(ty)
365 fn resolve_associated_type(&mut self, inner_ty: Ty, assoc_ty: Option<TypeAliasId>) -> Ty {
366 self.resolve_associated_type_with_params(inner_ty, assoc_ty, &[])
369 fn resolve_associated_type_with_params(
372 assoc_ty: Option<TypeAliasId>,
376 Some(res_assoc_ty) => {
377 let ty = self.table.new_type_var();
378 let mut builder = Substs::build_for_def(self.db, res_assoc_ty).push(inner_ty);
380 builder = builder.push(ty.clone());
383 let projection = ProjectionPredicate {
385 projection_ty: ProjectionTy {
386 associated_ty: res_assoc_ty,
387 parameters: builder.build(),
390 self.obligations.push(Obligation::Projection(projection));
391 self.resolve_ty_as_possible(ty)
397 /// Recurses through the given type, normalizing associated types mentioned
398 /// in it by replacing them by type variables and registering obligations to
399 /// resolve later. This should be done once for every type we get from some
400 /// type annotation (e.g. from a let type annotation, field type or function
401 /// call). `make_ty` handles this already, but e.g. for field types we need
402 /// to do it as well.
403 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
404 let ty = self.resolve_ty_as_possible(ty);
405 ty.fold(&mut |ty| match ty {
406 Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty),
411 fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty {
412 let var = self.table.new_type_var();
413 let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() };
414 let obligation = Obligation::Projection(predicate);
415 self.obligations.push(obligation);
419 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
420 let path = match path {
422 None => return (Ty::Unknown, None),
424 let resolver = &self.resolver;
425 // FIXME: this should resolve assoc items as well, see this example:
426 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
427 match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
428 Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
429 let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into());
430 let ty = self.db.ty(strukt.into());
431 let ty = self.insert_type_vars(ty.apply_substs(substs));
432 (ty, Some(strukt.into()))
434 Some(TypeNs::EnumVariantId(var)) => {
435 let substs = Ty::substs_from_path(self.db, resolver, path, var.into());
436 let ty = self.db.ty(var.parent.into());
437 let ty = self.insert_type_vars(ty.apply_substs(substs));
438 (ty, Some(var.into()))
440 Some(_) | None => (Ty::Unknown, None),
444 fn collect_const(&mut self, data: &ConstData) {
445 self.return_ty = self.make_ty(&data.type_ref);
448 fn collect_fn(&mut self, data: &FunctionData) {
449 let body = Arc::clone(&self.body); // avoid borrow checker problem
450 for (type_ref, pat) in data.params.iter().zip(body.params.iter()) {
451 let ty = self.make_ty(type_ref);
453 self.infer_pat(*pat, &ty, BindingMode::default());
455 let return_ty = self.make_ty(&data.ret_type);
456 self.return_ty = self.insert_vars_for_impl_trait(return_ty);
459 fn infer_body(&mut self) {
460 self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
463 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
464 let path = path![std::iter::IntoIterator];
465 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
466 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
469 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
470 let path = path![std::ops::Try];
471 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
472 self.db.trait_data(trait_).associated_type_by_name(&name![Ok])
475 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
476 let path = path![std::ops::Neg];
477 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
478 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
481 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
482 let path = path![std::ops::Not];
483 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
484 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
487 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
488 let path = path![std::future::Future];
489 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
490 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
493 fn resolve_boxed_box(&self) -> Option<AdtId> {
494 let path = path![std::boxed::Box];
495 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
499 fn resolve_range_full(&self) -> Option<AdtId> {
500 let path = path![std::ops::RangeFull];
501 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
505 fn resolve_range(&self) -> Option<AdtId> {
506 let path = path![std::ops::Range];
507 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
511 fn resolve_range_inclusive(&self) -> Option<AdtId> {
512 let path = path![std::ops::RangeInclusive];
513 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
517 fn resolve_range_from(&self) -> Option<AdtId> {
518 let path = path![std::ops::RangeFrom];
519 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
523 fn resolve_range_to(&self) -> Option<AdtId> {
524 let path = path![std::ops::RangeTo];
525 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
529 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
530 let path = path![std::ops::RangeToInclusive];
531 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
535 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
536 let path = path![std::ops::Index];
537 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
538 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
542 /// The kinds of placeholders we need during type inference. There's separate
543 /// values for general types, and for integer and float variables. The latter
544 /// two are used for inference of literal values (e.g. `100` could be one of
545 /// several integer types).
546 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
548 TypeVar(unify::TypeVarId),
549 IntVar(unify::TypeVarId),
550 FloatVar(unify::TypeVarId),
551 MaybeNeverTypeVar(unify::TypeVarId),
555 fn to_inner(self) -> unify::TypeVarId {
558 | InferTy::IntVar(ty)
559 | InferTy::FloatVar(ty)
560 | InferTy::MaybeNeverTypeVar(ty) => ty,
564 fn fallback_value(self) -> Ty {
566 InferTy::TypeVar(..) => Ty::Unknown,
567 InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))),
568 InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))),
569 InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never),
574 /// When inferring an expression, we propagate downward whatever type hint we
575 /// are able in the form of an `Expectation`.
576 #[derive(Clone, PartialEq, Eq, Debug)]
579 // FIXME: In some cases, we need to be aware whether the expectation is that
580 // the type match exactly what we passed, or whether it just needs to be
581 // coercible to the expected type. See Expectation::rvalue_hint in rustc.
585 /// The expectation that the type of the expression needs to equal the given
587 fn has_type(ty: Ty) -> Self {
591 /// This expresses no expectation on the type.
593 Expectation { ty: Ty::Unknown }
598 use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup};
599 use hir_expand::diagnostics::DiagnosticSink;
601 use crate::{db::HirDatabase, diagnostics::NoSuchField};
603 #[derive(Debug, PartialEq, Eq, Clone)]
604 pub(super) enum InferenceDiagnostic {
605 NoSuchField { expr: ExprId, field: usize },
608 impl InferenceDiagnostic {
609 pub(super) fn add_to(
611 db: &impl HirDatabase,
613 sink: &mut DiagnosticSink,
616 InferenceDiagnostic::NoSuchField { expr, field } => {
617 let file = owner.lookup(db).source(db).file_id;
618 let (_, source_map) = db.body_with_source_map(owner.into());
619 let field = source_map.field_syntax(*expr, *field);
620 sink.push(NoSuchField { file, field })