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 builder = Substs::build_for_def(self.db, res_assoc_ty)
380 .fill(params.iter().cloned());
381 let projection = ProjectionPredicate {
383 projection_ty: ProjectionTy {
384 associated_ty: res_assoc_ty,
385 parameters: builder.build(),
388 self.obligations.push(Obligation::Projection(projection));
389 self.resolve_ty_as_possible(ty)
395 /// Recurses through the given type, normalizing associated types mentioned
396 /// in it by replacing them by type variables and registering obligations to
397 /// resolve later. This should be done once for every type we get from some
398 /// type annotation (e.g. from a let type annotation, field type or function
399 /// call). `make_ty` handles this already, but e.g. for field types we need
400 /// to do it as well.
401 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
402 let ty = self.resolve_ty_as_possible(ty);
403 ty.fold(&mut |ty| match ty {
404 Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty),
409 fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty {
410 let var = self.table.new_type_var();
411 let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() };
412 let obligation = Obligation::Projection(predicate);
413 self.obligations.push(obligation);
417 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
418 let path = match path {
420 None => return (Ty::Unknown, None),
422 let resolver = &self.resolver;
423 // FIXME: this should resolve assoc items as well, see this example:
424 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
425 match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
426 Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
427 let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into());
428 let ty = self.db.ty(strukt.into());
429 let ty = self.insert_type_vars(ty.apply_substs(substs));
430 (ty, Some(strukt.into()))
432 Some(TypeNs::EnumVariantId(var)) => {
433 let substs = Ty::substs_from_path(self.db, resolver, path, var.into());
434 let ty = self.db.ty(var.parent.into());
435 let ty = self.insert_type_vars(ty.apply_substs(substs));
436 (ty, Some(var.into()))
438 Some(_) | None => (Ty::Unknown, None),
442 fn collect_const(&mut self, data: &ConstData) {
443 self.return_ty = self.make_ty(&data.type_ref);
446 fn collect_fn(&mut self, data: &FunctionData) {
447 let body = Arc::clone(&self.body); // avoid borrow checker problem
448 for (type_ref, pat) in data.params.iter().zip(body.params.iter()) {
449 let ty = self.make_ty(type_ref);
451 self.infer_pat(*pat, &ty, BindingMode::default());
453 let return_ty = self.make_ty(&data.ret_type);
454 self.return_ty = self.insert_vars_for_impl_trait(return_ty);
457 fn infer_body(&mut self) {
458 self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone()));
461 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
462 let path = path![std::iter::IntoIterator];
463 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
464 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
467 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
468 let path = path![std::ops::Try];
469 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
470 self.db.trait_data(trait_).associated_type_by_name(&name![Ok])
473 fn resolve_ops_neg_output(&self) -> Option<TypeAliasId> {
474 let path = path![std::ops::Neg];
475 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
476 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
479 fn resolve_ops_not_output(&self) -> Option<TypeAliasId> {
480 let path = path![std::ops::Not];
481 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
482 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
485 fn resolve_future_future_output(&self) -> Option<TypeAliasId> {
486 let path = path![std::future::Future];
487 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
488 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
491 fn resolve_boxed_box(&self) -> Option<AdtId> {
492 let path = path![std::boxed::Box];
493 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
497 fn resolve_range_full(&self) -> Option<AdtId> {
498 let path = path![std::ops::RangeFull];
499 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
503 fn resolve_range(&self) -> Option<AdtId> {
504 let path = path![std::ops::Range];
505 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
509 fn resolve_range_inclusive(&self) -> Option<AdtId> {
510 let path = path![std::ops::RangeInclusive];
511 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
515 fn resolve_range_from(&self) -> Option<AdtId> {
516 let path = path![std::ops::RangeFrom];
517 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
521 fn resolve_range_to(&self) -> Option<AdtId> {
522 let path = path![std::ops::RangeTo];
523 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
527 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
528 let path = path![std::ops::RangeToInclusive];
529 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?;
533 fn resolve_ops_index_output(&self) -> Option<TypeAliasId> {
534 let path = path![std::ops::Index];
535 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?;
536 self.db.trait_data(trait_).associated_type_by_name(&name![Output])
540 /// The kinds of placeholders we need during type inference. There's separate
541 /// values for general types, and for integer and float variables. The latter
542 /// two are used for inference of literal values (e.g. `100` could be one of
543 /// several integer types).
544 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
546 TypeVar(unify::TypeVarId),
547 IntVar(unify::TypeVarId),
548 FloatVar(unify::TypeVarId),
549 MaybeNeverTypeVar(unify::TypeVarId),
553 fn to_inner(self) -> unify::TypeVarId {
556 | InferTy::IntVar(ty)
557 | InferTy::FloatVar(ty)
558 | InferTy::MaybeNeverTypeVar(ty) => ty,
562 fn fallback_value(self) -> Ty {
564 InferTy::TypeVar(..) => Ty::Unknown,
565 InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))),
566 InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))),
567 InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never),
572 /// When inferring an expression, we propagate downward whatever type hint we
573 /// are able in the form of an `Expectation`.
574 #[derive(Clone, PartialEq, Eq, Debug)]
577 // FIXME: In some cases, we need to be aware whether the expectation is that
578 // the type match exactly what we passed, or whether it just needs to be
579 // coercible to the expected type. See Expectation::rvalue_hint in rustc.
583 /// The expectation that the type of the expression needs to equal the given
585 fn has_type(ty: Ty) -> Self {
589 /// This expresses no expectation on the type.
591 Expectation { ty: Ty::Unknown }
596 use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup};
597 use hir_expand::diagnostics::DiagnosticSink;
599 use crate::{db::HirDatabase, diagnostics::NoSuchField};
601 #[derive(Debug, PartialEq, Eq, Clone)]
602 pub(super) enum InferenceDiagnostic {
603 NoSuchField { expr: ExprId, field: usize },
606 impl InferenceDiagnostic {
607 pub(super) fn add_to(
609 db: &impl HirDatabase,
611 sink: &mut DiagnosticSink,
614 InferenceDiagnostic::NoSuchField { expr, field } => {
615 let file = owner.lookup(db).source(db).file_id;
616 let (_, source_map) = db.body_with_source_map(owner.into());
617 let field = source_map.field_syntax(*expr, *field);
618 sink.push(NoSuchField { file, field })