aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty/src/infer
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir_ty/src/infer')
-rw-r--r--crates/hir_ty/src/infer/coerce.rs92
-rw-r--r--crates/hir_ty/src/infer/expr.rs241
-rw-r--r--crates/hir_ty/src/infer/pat.rs37
-rw-r--r--crates/hir_ty/src/infer/path.rs2
-rw-r--r--crates/hir_ty/src/infer/unify.rs208
5 files changed, 300 insertions, 280 deletions
diff --git a/crates/hir_ty/src/infer/coerce.rs b/crates/hir_ty/src/infer/coerce.rs
index 32c7c57cd..7e8846f27 100644
--- a/crates/hir_ty/src/infer/coerce.rs
+++ b/crates/hir_ty/src/infer/coerce.rs
@@ -4,12 +4,12 @@
4//! 4//!
5//! See: https://doc.rust-lang.org/nomicon/coercions.html 5//! See: https://doc.rust-lang.org/nomicon/coercions.html
6 6
7use hir_def::{lang_item::LangItemTarget, type_ref::Mutability}; 7use chalk_ir::{Mutability, TyVariableKind};
8use test_utils::mark; 8use hir_def::lang_item::LangItemTarget;
9 9
10use crate::{autoderef, traits::Solution, Obligation, Substs, TraitRef, Ty, TypeCtor}; 10use crate::{autoderef, traits::Solution, Obligation, Substs, TraitRef, Ty};
11 11
12use super::{unify::TypeVarValue, InEnvironment, InferTy, InferenceContext}; 12use super::{InEnvironment, InferenceContext};
13 13
14impl<'a> InferenceContext<'a> { 14impl<'a> InferenceContext<'a> {
15 /// Unify two types, but may coerce the first one to the second one 15 /// Unify two types, but may coerce the first one to the second one
@@ -33,8 +33,8 @@ impl<'a> InferenceContext<'a> {
33 } else if self.coerce(ty2, ty1) { 33 } else if self.coerce(ty2, ty1) {
34 ty1.clone() 34 ty1.clone()
35 } else { 35 } else {
36 if let (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnDef(_))) = (ty1, ty2) { 36 if let (Ty::FnDef(..), Ty::FnDef(..)) = (ty1, ty2) {
37 mark::hit!(coerce_fn_reification); 37 cov_mark::hit!(coerce_fn_reification);
38 // Special case: two function types. Try to coerce both to 38 // Special case: two function types. Try to coerce both to
39 // pointers to have a chance at getting a match. See 39 // pointers to have a chance at getting a match. See
40 // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916 40 // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916
@@ -44,7 +44,7 @@ impl<'a> InferenceContext<'a> {
44 let ptr_ty2 = Ty::fn_ptr(sig2); 44 let ptr_ty2 = Ty::fn_ptr(sig2);
45 self.coerce_merge_branch(&ptr_ty1, &ptr_ty2) 45 self.coerce_merge_branch(&ptr_ty1, &ptr_ty2)
46 } else { 46 } else {
47 mark::hit!(coerce_merge_fail_fallback); 47 cov_mark::hit!(coerce_merge_fail_fallback);
48 ty1.clone() 48 ty1.clone()
49 } 49 }
50 } 50 }
@@ -53,12 +53,11 @@ impl<'a> InferenceContext<'a> {
53 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { 53 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
54 match (&from_ty, to_ty) { 54 match (&from_ty, to_ty) {
55 // Never type will make type variable to fallback to Never Type instead of Unknown. 55 // Never type will make type variable to fallback to Never Type instead of Unknown.
56 (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { 56 (Ty::Never, Ty::InferenceVar(tv, TyVariableKind::General)) => {
57 let var = self.table.new_maybe_never_type_var(); 57 self.table.type_variable_table.set_diverging(*tv, true);
58 self.table.var_unification_table.union_value(*tv, TypeVarValue::Known(var));
59 return true; 58 return true;
60 } 59 }
61 (ty_app!(TypeCtor::Never), _) => return true, 60 (Ty::Never, _) => return true,
62 61
63 // Trivial cases, this should go after `never` check to 62 // Trivial cases, this should go after `never` check to
64 // avoid infer result type to be never 63 // avoid infer result type to be never
@@ -71,38 +70,33 @@ impl<'a> InferenceContext<'a> {
71 70
72 // Pointer weakening and function to pointer 71 // Pointer weakening and function to pointer
73 match (&mut from_ty, to_ty) { 72 match (&mut from_ty, to_ty) {
74 // `*mut T`, `&mut T, `&T`` -> `*const T` 73 // `*mut T` -> `*const T`
75 // `&mut T` -> `&T` 74 // `&mut T` -> `&T`
76 // `&mut T` -> `*mut T` 75 (Ty::Raw(m1, ..), Ty::Raw(m2 @ Mutability::Not, ..))
77 (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) 76 | (Ty::Ref(m1, ..), Ty::Ref(m2 @ Mutability::Not, ..)) => {
78 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) 77 *m1 = *m2;
79 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) 78 }
80 | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { 79 // `&T` -> `*const T`
81 *c1 = *c2; 80 // `&mut T` -> `*mut T`/`*const T`
81 (Ty::Ref(.., substs), &Ty::Raw(m2 @ Mutability::Not, ..))
82 | (Ty::Ref(Mutability::Mut, substs), &Ty::Raw(m2, ..)) => {
83 from_ty = Ty::Raw(m2, substs.clone());
82 } 84 }
83 85
84 // Illegal mutablity conversion 86 // Illegal mutability conversion
85 ( 87 (Ty::Raw(Mutability::Not, ..), Ty::Raw(Mutability::Mut, ..))
86 ty_app!(TypeCtor::RawPtr(Mutability::Shared)), 88 | (Ty::Ref(Mutability::Not, ..), Ty::Ref(Mutability::Mut, ..)) => return false,
87 ty_app!(TypeCtor::RawPtr(Mutability::Mut)),
88 )
89 | (
90 ty_app!(TypeCtor::Ref(Mutability::Shared)),
91 ty_app!(TypeCtor::Ref(Mutability::Mut)),
92 ) => return false,
93 89
94 // `{function_type}` -> `fn()` 90 // `{function_type}` -> `fn()`
95 (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { 91 (Ty::FnDef(..), Ty::Function { .. }) => match from_ty.callable_sig(self.db) {
96 match from_ty.callable_sig(self.db) { 92 None => return false,
97 None => return false, 93 Some(sig) => {
98 Some(sig) => { 94 from_ty = Ty::fn_ptr(sig);
99 from_ty = Ty::fn_ptr(sig);
100 }
101 } 95 }
102 } 96 },
103 97
104 (ty_app!(TypeCtor::Closure { .. }, params), ty_app!(TypeCtor::FnPtr { .. })) => { 98 (Ty::Closure(.., substs), Ty::Function { .. }) => {
105 from_ty = params[0].clone(); 99 from_ty = substs[0].clone();
106 } 100 }
107 101
108 _ => {} 102 _ => {}
@@ -115,9 +109,7 @@ impl<'a> InferenceContext<'a> {
115 // Auto Deref if cannot coerce 109 // Auto Deref if cannot coerce
116 match (&from_ty, to_ty) { 110 match (&from_ty, to_ty) {
117 // FIXME: DerefMut 111 // FIXME: DerefMut
118 (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { 112 (Ty::Ref(_, st1), Ty::Ref(_, st2)) => self.unify_autoderef_behind_ref(&st1[0], &st2[0]),
119 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
120 }
121 113
122 // Otherwise, normal unify 114 // Otherwise, normal unify
123 _ => self.unify(&from_ty, to_ty), 115 _ => self.unify(&from_ty, to_ty),
@@ -178,17 +170,17 @@ impl<'a> InferenceContext<'a> {
178 }, 170 },
179 ) { 171 ) {
180 let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); 172 let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value);
181 match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { 173 let from_ty = self.resolve_ty_shallow(&derefed_ty);
182 // Stop when constructor matches. 174 // Stop when constructor matches.
183 (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { 175 if from_ty.equals_ctor(&to_ty) {
184 // It will not recurse to `coerce`. 176 // It will not recurse to `coerce`.
185 return self.table.unify_substs(st1, st2, 0); 177 return match (from_ty.substs(), to_ty.substs()) {
186 } 178 (Some(st1), Some(st2)) => self.table.unify_substs(st1, st2, 0),
187 _ => { 179 (None, None) => true,
188 if self.table.unify_inner_trivial(&derefed_ty, &to_ty, 0) { 180 _ => false,
189 return true; 181 };
190 } 182 } else if self.table.unify_inner_trivial(&derefed_ty, &to_ty, 0) {
191 } 183 return true;
192 } 184 }
193 } 185 }
194 186
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs
index cb59a6937..262177ffb 100644
--- a/crates/hir_ty/src/infer/expr.rs
+++ b/crates/hir_ty/src/infer/expr.rs
@@ -3,23 +3,25 @@
3use std::iter::{repeat, repeat_with}; 3use std::iter::{repeat, repeat_with};
4use std::{mem, sync::Arc}; 4use std::{mem, sync::Arc};
5 5
6use chalk_ir::{Mutability, TyVariableKind};
6use hir_def::{ 7use hir_def::{
7 builtin_type::Signedness,
8 expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, 8 expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp},
9 path::{GenericArg, GenericArgs}, 9 path::{GenericArg, GenericArgs},
10 resolver::resolver_for_expr, 10 resolver::resolver_for_expr,
11 AdtId, AssocContainerId, FieldId, Lookup, 11 AssocContainerId, FieldId, Lookup,
12}; 12};
13use hir_expand::name::{name, Name}; 13use hir_expand::name::{name, Name};
14use syntax::ast::RangeOp; 14use syntax::ast::RangeOp;
15use test_utils::mark;
16 15
17use crate::{ 16use crate::{
18 autoderef, method_resolution, op, 17 autoderef,
18 lower::lower_to_chalk_mutability,
19 method_resolution, op,
20 primitive::{self, UintTy},
19 traits::{FnTrait, InEnvironment}, 21 traits::{FnTrait, InEnvironment},
20 utils::{generics, variant_data, Generics}, 22 utils::{generics, variant_data, Generics},
21 ApplicationTy, Binders, CallableDefId, InferTy, IntTy, Mutability, Obligation, OpaqueTyId, 23 AdtId, Binders, CallableDefId, FnPointer, FnSig, Obligation, OpaqueTyId, Rawness, Scalar,
22 Rawness, Substs, TraitRef, Ty, TypeCtor, 24 Substs, TraitRef, Ty,
23}; 25};
24 26
25use super::{ 27use super::{
@@ -82,10 +84,7 @@ impl<'a> InferenceContext<'a> {
82 arg_tys.push(arg); 84 arg_tys.push(arg);
83 } 85 }
84 let parameters = param_builder.build(); 86 let parameters = param_builder.build();
85 let arg_ty = Ty::Apply(ApplicationTy { 87 let arg_ty = Ty::Tuple(num_args, parameters);
86 ctor: TypeCtor::Tuple { cardinality: num_args as u16 },
87 parameters,
88 });
89 let substs = 88 let substs =
90 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build(); 89 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build();
91 90
@@ -120,7 +119,7 @@ impl<'a> InferenceContext<'a> {
120 Expr::Missing => Ty::Unknown, 119 Expr::Missing => Ty::Unknown,
121 Expr::If { condition, then_branch, else_branch } => { 120 Expr::If { condition, then_branch, else_branch } => {
122 // if let is desugared to match, so this is always simple if 121 // if let is desugared to match, so this is always simple if
123 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); 122 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool)));
124 123
125 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe); 124 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
126 let mut both_arms_diverge = Diverges::Always; 125 let mut both_arms_diverge = Diverges::Always;
@@ -175,7 +174,7 @@ impl<'a> InferenceContext<'a> {
175 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType> 174 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
176 let inner_ty = self.infer_expr(*body, &Expectation::none()); 175 let inner_ty = self.infer_expr(*body, &Expectation::none());
177 let opaque_ty_id = OpaqueTyId::AsyncBlockTypeImplTrait(self.owner, *body); 176 let opaque_ty_id = OpaqueTyId::AsyncBlockTypeImplTrait(self.owner, *body);
178 Ty::apply_one(TypeCtor::OpaqueType(opaque_ty_id), inner_ty) 177 Ty::OpaqueType(opaque_ty_id, Substs::single(inner_ty))
179 } 178 }
180 Expr::Loop { body, label } => { 179 Expr::Loop { body, label } => {
181 self.breakables.push(BreakableContext { 180 self.breakables.push(BreakableContext {
@@ -193,7 +192,7 @@ impl<'a> InferenceContext<'a> {
193 if ctxt.may_break { 192 if ctxt.may_break {
194 ctxt.break_ty 193 ctxt.break_ty
195 } else { 194 } else {
196 Ty::simple(TypeCtor::Never) 195 Ty::Never
197 } 196 }
198 } 197 }
199 Expr::While { condition, body, label } => { 198 Expr::While { condition, body, label } => {
@@ -203,7 +202,7 @@ impl<'a> InferenceContext<'a> {
203 label: label.map(|label| self.body[label].name.clone()), 202 label: label.map(|label| self.body[label].name.clone()),
204 }); 203 });
205 // while let is desugared to a match loop, so this is always simple while 204 // while let is desugared to a match loop, so this is always simple while
206 self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); 205 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool)));
207 self.infer_expr(*body, &Expectation::has_type(Ty::unit())); 206 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
208 let _ctxt = self.breakables.pop().expect("breakable stack broken"); 207 let _ctxt = self.breakables.pop().expect("breakable stack broken");
209 // the body may not run, so it diverging doesn't mean we diverge 208 // the body may not run, so it diverging doesn't mean we diverge
@@ -250,12 +249,12 @@ impl<'a> InferenceContext<'a> {
250 None => self.table.new_type_var(), 249 None => self.table.new_type_var(),
251 }; 250 };
252 sig_tys.push(ret_ty.clone()); 251 sig_tys.push(ret_ty.clone());
253 let sig_ty = Ty::apply( 252 let sig_ty = Ty::Function(FnPointer {
254 TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1, is_varargs: false }, 253 num_args: sig_tys.len() - 1,
255 Substs(sig_tys.clone().into()), 254 sig: FnSig { variadic: false },
256 ); 255 substs: Substs(sig_tys.clone().into()),
257 let closure_ty = 256 });
258 Ty::apply_one(TypeCtor::Closure { def: self.owner, expr: tgt_expr }, sig_ty); 257 let closure_ty = Ty::Closure(self.owner, tgt_expr, Substs::single(sig_ty));
259 258
260 // Eagerly try to relate the closure type with the expected 259 // Eagerly try to relate the closure type with the expected
261 // type, otherwise we often won't have enough information to 260 // type, otherwise we often won't have enough information to
@@ -306,11 +305,8 @@ impl<'a> InferenceContext<'a> {
306 Expr::Match { expr, arms } => { 305 Expr::Match { expr, arms } => {
307 let input_ty = self.infer_expr(*expr, &Expectation::none()); 306 let input_ty = self.infer_expr(*expr, &Expectation::none());
308 307
309 let mut result_ty = if arms.is_empty() { 308 let mut result_ty =
310 Ty::simple(TypeCtor::Never) 309 if arms.is_empty() { Ty::Never } else { self.table.new_type_var() };
311 } else {
312 self.table.new_type_var()
313 };
314 310
315 let matchee_diverges = self.diverges; 311 let matchee_diverges = self.diverges;
316 let mut all_arms_diverge = Diverges::Always; 312 let mut all_arms_diverge = Diverges::Always;
@@ -321,7 +317,7 @@ impl<'a> InferenceContext<'a> {
321 if let Some(guard_expr) = arm.guard { 317 if let Some(guard_expr) = arm.guard {
322 self.infer_expr( 318 self.infer_expr(
323 guard_expr, 319 guard_expr,
324 &Expectation::has_type(Ty::simple(TypeCtor::Bool)), 320 &Expectation::has_type(Ty::Scalar(Scalar::Bool)),
325 ); 321 );
326 } 322 }
327 323
@@ -339,7 +335,7 @@ impl<'a> InferenceContext<'a> {
339 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); 335 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
340 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) 336 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown)
341 } 337 }
342 Expr::Continue { .. } => Ty::simple(TypeCtor::Never), 338 Expr::Continue { .. } => Ty::Never,
343 Expr::Break { expr, label } => { 339 Expr::Break { expr, label } => {
344 let val_ty = if let Some(expr) = expr { 340 let val_ty = if let Some(expr) = expr {
345 self.infer_expr(*expr, &Expectation::none()) 341 self.infer_expr(*expr, &Expectation::none())
@@ -364,8 +360,7 @@ impl<'a> InferenceContext<'a> {
364 expr: tgt_expr, 360 expr: tgt_expr,
365 }); 361 });
366 } 362 }
367 363 Ty::Never
368 Ty::simple(TypeCtor::Never)
369 } 364 }
370 Expr::Return { expr } => { 365 Expr::Return { expr } => {
371 if let Some(expr) = expr { 366 if let Some(expr) = expr {
@@ -374,14 +369,14 @@ impl<'a> InferenceContext<'a> {
374 let unit = Ty::unit(); 369 let unit = Ty::unit();
375 self.coerce(&unit, &self.return_ty.clone()); 370 self.coerce(&unit, &self.return_ty.clone());
376 } 371 }
377 Ty::simple(TypeCtor::Never) 372 Ty::Never
378 } 373 }
379 Expr::Yield { expr } => { 374 Expr::Yield { expr } => {
380 // FIXME: track yield type for coercion 375 // FIXME: track yield type for coercion
381 if let Some(expr) = expr { 376 if let Some(expr) = expr {
382 self.infer_expr(*expr, &Expectation::none()); 377 self.infer_expr(*expr, &Expectation::none());
383 } 378 }
384 Ty::simple(TypeCtor::Never) 379 Ty::Never
385 } 380 }
386 Expr::RecordLit { path, fields, spread } => { 381 Expr::RecordLit { path, fields, spread } => {
387 let (ty, def_id) = self.resolve_variant(path.as_ref()); 382 let (ty, def_id) = self.resolve_variant(path.as_ref());
@@ -391,7 +386,7 @@ impl<'a> InferenceContext<'a> {
391 386
392 self.unify(&ty, &expected.ty); 387 self.unify(&ty, &expected.ty);
393 388
394 let substs = ty.substs().unwrap_or_else(Substs::empty); 389 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty);
395 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default(); 390 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
396 let variant_data = def_id.map(|it| variant_data(self.db.upcast(), it)); 391 let variant_data = def_id.map(|it| variant_data(self.db.upcast(), it));
397 for (field_idx, field) in fields.iter().enumerate() { 392 for (field_idx, field) in fields.iter().enumerate() {
@@ -430,30 +425,23 @@ impl<'a> InferenceContext<'a> {
430 }, 425 },
431 ) 426 )
432 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { 427 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) {
433 Ty::Apply(a_ty) => match a_ty.ctor { 428 Ty::Tuple(_, substs) => {
434 TypeCtor::Tuple { .. } => name 429 name.as_tuple_index().and_then(|idx| substs.0.get(idx).cloned())
435 .as_tuple_index() 430 }
436 .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), 431 Ty::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
437 TypeCtor::Adt(AdtId::StructId(s)) => { 432 self.db.struct_data(s).variant_data.field(name).map(|local_id| {
438 self.db.struct_data(s).variant_data.field(name).map(|local_id| { 433 let field = FieldId { parent: s.into(), local_id };
439 let field = FieldId { parent: s.into(), local_id }; 434 self.write_field_resolution(tgt_expr, field);
440 self.write_field_resolution(tgt_expr, field); 435 self.db.field_types(s.into())[field.local_id].clone().subst(&parameters)
441 self.db.field_types(s.into())[field.local_id] 436 })
442 .clone() 437 }
443 .subst(&a_ty.parameters) 438 Ty::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
444 }) 439 self.db.union_data(u).variant_data.field(name).map(|local_id| {
445 } 440 let field = FieldId { parent: u.into(), local_id };
446 TypeCtor::Adt(AdtId::UnionId(u)) => { 441 self.write_field_resolution(tgt_expr, field);
447 self.db.union_data(u).variant_data.field(name).map(|local_id| { 442 self.db.field_types(u.into())[field.local_id].clone().subst(&parameters)
448 let field = FieldId { parent: u.into(), local_id }; 443 })
449 self.write_field_resolution(tgt_expr, field); 444 }
450 self.db.field_types(u.into())[field.local_id]
451 .clone()
452 .subst(&a_ty.parameters)
453 })
454 }
455 _ => None,
456 },
457 _ => None, 445 _ => None,
458 }) 446 })
459 .unwrap_or(Ty::Unknown); 447 .unwrap_or(Ty::Unknown);
@@ -475,10 +463,11 @@ impl<'a> InferenceContext<'a> {
475 cast_ty 463 cast_ty
476 } 464 }
477 Expr::Ref { expr, rawness, mutability } => { 465 Expr::Ref { expr, rawness, mutability } => {
466 let mutability = lower_to_chalk_mutability(*mutability);
478 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) = 467 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) =
479 &expected.ty.as_reference_or_ptr() 468 &expected.ty.as_reference_or_ptr()
480 { 469 {
481 if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { 470 if *exp_mutability == Mutability::Mut && mutability == Mutability::Not {
482 // FIXME: throw type error - expected mut reference but found shared ref, 471 // FIXME: throw type error - expected mut reference but found shared ref,
483 // which cannot be coerced 472 // which cannot be coerced
484 } 473 }
@@ -491,19 +480,24 @@ impl<'a> InferenceContext<'a> {
491 Expectation::none() 480 Expectation::none()
492 }; 481 };
493 let inner_ty = self.infer_expr_inner(*expr, &expectation); 482 let inner_ty = self.infer_expr_inner(*expr, &expectation);
494 let ty = match rawness { 483 match rawness {
495 Rawness::RawPtr => TypeCtor::RawPtr(*mutability), 484 Rawness::RawPtr => Ty::Raw(mutability, Substs::single(inner_ty)),
496 Rawness::Ref => TypeCtor::Ref(*mutability), 485 Rawness::Ref => Ty::Ref(mutability, Substs::single(inner_ty)),
497 }; 486 }
498 Ty::apply_one(ty, inner_ty)
499 } 487 }
500 Expr::Box { expr } => { 488 Expr::Box { expr } => {
501 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 489 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
502 if let Some(box_) = self.resolve_boxed_box() { 490 if let Some(box_) = self.resolve_boxed_box() {
503 let mut sb = Substs::build_for_type_ctor(self.db, TypeCtor::Adt(box_)); 491 let mut sb = Substs::builder(generics(self.db.upcast(), box_.into()).len());
504 sb = sb.push(inner_ty); 492 sb = sb.push(inner_ty);
493 match self.db.generic_defaults(box_.into()).as_ref() {
494 [_, alloc_ty, ..] if !alloc_ty.value.is_unknown() => {
495 sb = sb.push(alloc_ty.value.clone());
496 }
497 _ => (),
498 }
505 sb = sb.fill(repeat_with(|| self.table.new_type_var())); 499 sb = sb.fill(repeat_with(|| self.table.new_type_var()));
506 Ty::apply(TypeCtor::Adt(box_), sb.build()) 500 Ty::adt_ty(box_, sb.build())
507 } else { 501 } else {
508 Ty::Unknown 502 Ty::Unknown
509 } 503 }
@@ -533,13 +527,11 @@ impl<'a> InferenceContext<'a> {
533 UnaryOp::Neg => { 527 UnaryOp::Neg => {
534 match &inner_ty { 528 match &inner_ty {
535 // Fast path for builtins 529 // Fast path for builtins
536 Ty::Apply(ApplicationTy { 530 Ty::Scalar(Scalar::Int(_))
537 ctor: TypeCtor::Int(IntTy { signedness: Signedness::Signed, .. }), 531 | Ty::Scalar(Scalar::Uint(_))
538 .. 532 | Ty::Scalar(Scalar::Float(_))
539 }) 533 | Ty::InferenceVar(_, TyVariableKind::Integer)
540 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(_), .. }) 534 | Ty::InferenceVar(_, TyVariableKind::Float) => inner_ty,
541 | Ty::Infer(InferTy::IntVar(..))
542 | Ty::Infer(InferTy::FloatVar(..)) => inner_ty,
543 // Otherwise we resolve via the std::ops::Neg trait 535 // Otherwise we resolve via the std::ops::Neg trait
544 _ => self 536 _ => self
545 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()), 537 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
@@ -548,9 +540,10 @@ impl<'a> InferenceContext<'a> {
548 UnaryOp::Not => { 540 UnaryOp::Not => {
549 match &inner_ty { 541 match &inner_ty {
550 // Fast path for builtins 542 // Fast path for builtins
551 Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. }) 543 Ty::Scalar(Scalar::Bool)
552 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(_), .. }) 544 | Ty::Scalar(Scalar::Int(_))
553 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, 545 | Ty::Scalar(Scalar::Uint(_))
546 | Ty::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
554 // Otherwise we resolve via the std::ops::Not trait 547 // Otherwise we resolve via the std::ops::Not trait
555 _ => self 548 _ => self
556 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()), 549 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
@@ -561,7 +554,7 @@ impl<'a> InferenceContext<'a> {
561 Expr::BinaryOp { lhs, rhs, op } => match op { 554 Expr::BinaryOp { lhs, rhs, op } => match op {
562 Some(op) => { 555 Some(op) => {
563 let lhs_expectation = match op { 556 let lhs_expectation = match op {
564 BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), 557 BinaryOp::LogicOp(..) => Expectation::has_type(Ty::Scalar(Scalar::Bool)),
565 _ => Expectation::none(), 558 _ => Expectation::none(),
566 }; 559 };
567 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); 560 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
@@ -571,7 +564,7 @@ impl<'a> InferenceContext<'a> {
571 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone()); 564 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
572 565
573 if ret == Ty::Unknown { 566 if ret == Ty::Unknown {
574 mark::hit!(infer_expr_inner_binary_operator_overload); 567 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
575 568
576 self.resolve_associated_type_with_params( 569 self.resolve_associated_type_with_params(
577 lhs_ty, 570 lhs_ty,
@@ -592,31 +585,31 @@ impl<'a> InferenceContext<'a> {
592 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect)); 585 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
593 match (range_type, lhs_ty, rhs_ty) { 586 match (range_type, lhs_ty, rhs_ty) {
594 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() { 587 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
595 Some(adt) => Ty::simple(TypeCtor::Adt(adt)), 588 Some(adt) => Ty::adt_ty(adt, Substs::empty()),
596 None => Ty::Unknown, 589 None => Ty::Unknown,
597 }, 590 },
598 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() { 591 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
599 Some(adt) => Ty::apply_one(TypeCtor::Adt(adt), ty), 592 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
600 None => Ty::Unknown, 593 None => Ty::Unknown,
601 }, 594 },
602 (RangeOp::Inclusive, None, Some(ty)) => { 595 (RangeOp::Inclusive, None, Some(ty)) => {
603 match self.resolve_range_to_inclusive() { 596 match self.resolve_range_to_inclusive() {
604 Some(adt) => Ty::apply_one(TypeCtor::Adt(adt), ty), 597 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
605 None => Ty::Unknown, 598 None => Ty::Unknown,
606 } 599 }
607 } 600 }
608 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() { 601 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
609 Some(adt) => Ty::apply_one(TypeCtor::Adt(adt), ty), 602 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
610 None => Ty::Unknown, 603 None => Ty::Unknown,
611 }, 604 },
612 (RangeOp::Inclusive, Some(_), Some(ty)) => { 605 (RangeOp::Inclusive, Some(_), Some(ty)) => {
613 match self.resolve_range_inclusive() { 606 match self.resolve_range_inclusive() {
614 Some(adt) => Ty::apply_one(TypeCtor::Adt(adt), ty), 607 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
615 None => Ty::Unknown, 608 None => Ty::Unknown,
616 } 609 }
617 } 610 }
618 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() { 611 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
619 Some(adt) => Ty::apply_one(TypeCtor::Adt(adt), ty), 612 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
620 None => Ty::Unknown, 613 None => Ty::Unknown,
621 }, 614 },
622 (RangeOp::Inclusive, _, None) => Ty::Unknown, 615 (RangeOp::Inclusive, _, None) => Ty::Unknown,
@@ -650,7 +643,7 @@ impl<'a> InferenceContext<'a> {
650 } 643 }
651 Expr::Tuple { exprs } => { 644 Expr::Tuple { exprs } => {
652 let mut tys = match &expected.ty { 645 let mut tys = match &expected.ty {
653 ty_app!(TypeCtor::Tuple { .. }, st) => st 646 Ty::Tuple(_, substs) => substs
654 .iter() 647 .iter()
655 .cloned() 648 .cloned()
656 .chain(repeat_with(|| self.table.new_type_var())) 649 .chain(repeat_with(|| self.table.new_type_var()))
@@ -663,15 +656,11 @@ impl<'a> InferenceContext<'a> {
663 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); 656 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
664 } 657 }
665 658
666 Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) 659 Ty::Tuple(tys.len(), Substs(tys.into()))
667 } 660 }
668 Expr::Array(array) => { 661 Expr::Array(array) => {
669 let elem_ty = match &expected.ty { 662 let elem_ty = match &expected.ty {
670 // FIXME: remove when https://github.com/rust-lang/rust/issues/80501 is fixed 663 Ty::Array(st) | Ty::Slice(st) => st.as_single().clone(),
671 #[allow(unreachable_patterns)]
672 ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => {
673 st.as_single().clone()
674 }
675 _ => self.table.new_type_var(), 664 _ => self.table.new_type_var(),
676 }; 665 };
677 666
@@ -688,30 +677,38 @@ impl<'a> InferenceContext<'a> {
688 ); 677 );
689 self.infer_expr( 678 self.infer_expr(
690 *repeat, 679 *repeat,
691 &Expectation::has_type(Ty::simple(TypeCtor::Int(IntTy::usize()))), 680 &Expectation::has_type(Ty::Scalar(Scalar::Uint(UintTy::Usize))),
692 ); 681 );
693 } 682 }
694 } 683 }
695 684
696 Ty::apply_one(TypeCtor::Array, elem_ty) 685 Ty::Array(Substs::single(elem_ty))
697 } 686 }
698 Expr::Literal(lit) => match lit { 687 Expr::Literal(lit) => match lit {
699 Literal::Bool(..) => Ty::simple(TypeCtor::Bool), 688 Literal::Bool(..) => Ty::Scalar(Scalar::Bool),
700 Literal::String(..) => { 689 Literal::String(..) => Ty::Ref(Mutability::Not, Substs::single(Ty::Str)),
701 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str))
702 }
703 Literal::ByteString(..) => { 690 Literal::ByteString(..) => {
704 let byte_type = Ty::simple(TypeCtor::Int(IntTy::u8())); 691 let byte_type = Ty::Scalar(Scalar::Uint(UintTy::U8));
705 let array_type = Ty::apply_one(TypeCtor::Array, byte_type); 692 let array_type = Ty::Array(Substs::single(byte_type));
706 Ty::apply_one(TypeCtor::Ref(Mutability::Shared), array_type) 693 Ty::Ref(Mutability::Not, Substs::single(array_type))
707 } 694 }
708 Literal::Char(..) => Ty::simple(TypeCtor::Char), 695 Literal::Char(..) => Ty::Scalar(Scalar::Char),
709 Literal::Int(_v, ty) => match ty { 696 Literal::Int(_v, ty) => match ty {
710 Some(int_ty) => Ty::simple(TypeCtor::Int((*int_ty).into())), 697 Some(int_ty) => {
698 Ty::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
699 }
700 None => self.table.new_integer_var(),
701 },
702 Literal::Uint(_v, ty) => match ty {
703 Some(int_ty) => {
704 Ty::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
705 }
711 None => self.table.new_integer_var(), 706 None => self.table.new_integer_var(),
712 }, 707 },
713 Literal::Float(_v, ty) => match ty { 708 Literal::Float(_v, ty) => match ty {
714 Some(float_ty) => Ty::simple(TypeCtor::Float((*float_ty).into())), 709 Some(float_ty) => {
710 Ty::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
711 }
715 None => self.table.new_float_var(), 712 None => self.table.new_float_var(),
716 }, 713 },
717 }, 714 },
@@ -767,7 +764,7 @@ impl<'a> InferenceContext<'a> {
767 // `!`). 764 // `!`).
768 if self.diverges.is_always() { 765 if self.diverges.is_always() {
769 // we don't even make an attempt at coercion 766 // we don't even make an attempt at coercion
770 self.table.new_maybe_never_type_var() 767 self.table.new_maybe_never_var()
771 } else { 768 } else {
772 self.coerce(&Ty::unit(), expected.coercion_target()); 769 self.coerce(&Ty::unit(), expected.coercion_target());
773 Ty::unit() 770 Ty::unit()
@@ -824,7 +821,7 @@ impl<'a> InferenceContext<'a> {
824 // Apply autoref so the below unification works correctly 821 // Apply autoref so the below unification works correctly
825 // FIXME: return correct autorefs from lookup_method 822 // FIXME: return correct autorefs from lookup_method
826 let actual_receiver_ty = match expected_receiver_ty.as_reference() { 823 let actual_receiver_ty = match expected_receiver_ty.as_reference() {
827 Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), 824 Some((_, mutability)) => Ty::Ref(mutability, Substs::single(derefed_receiver_ty)),
828 _ => derefed_receiver_ty, 825 _ => derefed_receiver_ty,
829 }; 826 };
830 self.unify(&expected_receiver_ty, &actual_receiver_ty); 827 self.unify(&expected_receiver_ty, &actual_receiver_ty);
@@ -901,30 +898,26 @@ impl<'a> InferenceContext<'a> {
901 } 898 }
902 899
903 fn register_obligations_for_call(&mut self, callable_ty: &Ty) { 900 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
904 if let Ty::Apply(a_ty) = callable_ty { 901 if let &Ty::FnDef(def, ref parameters) = callable_ty {
905 if let TypeCtor::FnDef(def) = a_ty.ctor { 902 let generic_predicates = self.db.generic_predicates(def.into());
906 let generic_predicates = self.db.generic_predicates(def.into()); 903 for predicate in generic_predicates.iter() {
907 for predicate in generic_predicates.iter() { 904 let predicate = predicate.clone().subst(parameters);
908 let predicate = predicate.clone().subst(&a_ty.parameters); 905 if let Some(obligation) = Obligation::from_predicate(predicate) {
909 if let Some(obligation) = Obligation::from_predicate(predicate) { 906 self.obligations.push(obligation);
910 self.obligations.push(obligation);
911 }
912 } 907 }
913 // add obligation for trait implementation, if this is a trait method 908 }
914 match def { 909 // add obligation for trait implementation, if this is a trait method
915 CallableDefId::FunctionId(f) => { 910 match def {
916 if let AssocContainerId::TraitId(trait_) = 911 CallableDefId::FunctionId(f) => {
917 f.lookup(self.db.upcast()).container 912 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db.upcast()).container
918 { 913 {
919 // construct a TraitDef 914 // construct a TraitDef
920 let substs = a_ty 915 let substs =
921 .parameters 916 parameters.prefix(generics(self.db.upcast(), trait_.into()).len());
922 .prefix(generics(self.db.upcast(), trait_.into()).len()); 917 self.obligations.push(Obligation::Trait(TraitRef { trait_, substs }));
923 self.obligations.push(Obligation::Trait(TraitRef { trait_, substs }));
924 }
925 } 918 }
926 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
927 } 919 }
920 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {}
928 } 921 }
929 } 922 }
930 } 923 }
diff --git a/crates/hir_ty/src/infer/pat.rs b/crates/hir_ty/src/infer/pat.rs
index d974f805b..a0ac8d80f 100644
--- a/crates/hir_ty/src/infer/pat.rs
+++ b/crates/hir_ty/src/infer/pat.rs
@@ -3,17 +3,16 @@
3use std::iter::repeat; 3use std::iter::repeat;
4use std::sync::Arc; 4use std::sync::Arc;
5 5
6use chalk_ir::Mutability;
6use hir_def::{ 7use hir_def::{
7 expr::{BindingAnnotation, Expr, Literal, Pat, PatId, RecordFieldPat}, 8 expr::{BindingAnnotation, Expr, Literal, Pat, PatId, RecordFieldPat},
8 path::Path, 9 path::Path,
9 type_ref::Mutability,
10 FieldId, 10 FieldId,
11}; 11};
12use hir_expand::name::Name; 12use hir_expand::name::Name;
13use test_utils::mark;
14 13
15use super::{BindingMode, Expectation, InferenceContext}; 14use super::{BindingMode, Expectation, InferenceContext};
16use crate::{utils::variant_data, Substs, Ty, TypeCtor}; 15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Substs, Ty};
17 16
18impl<'a> InferenceContext<'a> { 17impl<'a> InferenceContext<'a> {
19 fn infer_tuple_struct_pat( 18 fn infer_tuple_struct_pat(
@@ -32,7 +31,7 @@ impl<'a> InferenceContext<'a> {
32 } 31 }
33 self.unify(&ty, expected); 32 self.unify(&ty, expected);
34 33
35 let substs = ty.substs().unwrap_or_else(Substs::empty); 34 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty);
36 35
37 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default(); 36 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
38 let (pre, post) = match ellipsis { 37 let (pre, post) = match ellipsis {
@@ -71,7 +70,7 @@ impl<'a> InferenceContext<'a> {
71 70
72 self.unify(&ty, expected); 71 self.unify(&ty, expected);
73 72
74 let substs = ty.substs().unwrap_or_else(Substs::empty); 73 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty);
75 74
76 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default(); 75 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
77 for subpat in subpats { 76 for subpat in subpats {
@@ -103,12 +102,12 @@ impl<'a> InferenceContext<'a> {
103 expected = inner; 102 expected = inner;
104 default_bm = match default_bm { 103 default_bm = match default_bm {
105 BindingMode::Move => BindingMode::Ref(mutability), 104 BindingMode::Move => BindingMode::Ref(mutability),
106 BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), 105 BindingMode::Ref(Mutability::Not) => BindingMode::Ref(Mutability::Not),
107 BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), 106 BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability),
108 } 107 }
109 } 108 }
110 } else if let Pat::Ref { .. } = &body[pat] { 109 } else if let Pat::Ref { .. } = &body[pat] {
111 mark::hit!(match_ergonomics_ref); 110 cov_mark::hit!(match_ergonomics_ref);
112 // When you encounter a `&pat` pattern, reset to Move. 111 // When you encounter a `&pat` pattern, reset to Move.
113 // This is so that `w` is by value: `let (_, &w) = &(1, &2);` 112 // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
114 default_bm = BindingMode::Move; 113 default_bm = BindingMode::Move;
@@ -138,10 +137,7 @@ impl<'a> InferenceContext<'a> {
138 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned()); 137 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned());
139 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat)); 138 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat));
140 139
141 Ty::apply( 140 Ty::Tuple(inner_tys.len(), Substs(inner_tys.into()))
142 TypeCtor::Tuple { cardinality: inner_tys.len() as u16 },
143 Substs(inner_tys.into()),
144 )
145 } 141 }
146 Pat::Or(ref pats) => { 142 Pat::Or(ref pats) => {
147 if let Some((first_pat, rest)) = pats.split_first() { 143 if let Some((first_pat, rest)) = pats.split_first() {
@@ -155,9 +151,10 @@ impl<'a> InferenceContext<'a> {
155 } 151 }
156 } 152 }
157 Pat::Ref { pat, mutability } => { 153 Pat::Ref { pat, mutability } => {
154 let mutability = lower_to_chalk_mutability(*mutability);
158 let expectation = match expected.as_reference() { 155 let expectation = match expected.as_reference() {
159 Some((inner_ty, exp_mut)) => { 156 Some((inner_ty, exp_mut)) => {
160 if *mutability != exp_mut { 157 if mutability != exp_mut {
161 // FIXME: emit type error? 158 // FIXME: emit type error?
162 } 159 }
163 inner_ty 160 inner_ty
@@ -165,7 +162,7 @@ impl<'a> InferenceContext<'a> {
165 _ => &Ty::Unknown, 162 _ => &Ty::Unknown,
166 }; 163 };
167 let subty = self.infer_pat(*pat, expectation, default_bm); 164 let subty = self.infer_pat(*pat, expectation, default_bm);
168 Ty::apply_one(TypeCtor::Ref(*mutability), subty) 165 Ty::Ref(mutability, Substs::single(subty))
169 } 166 }
170 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat( 167 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat(
171 p.as_ref(), 168 p.as_ref(),
@@ -198,7 +195,7 @@ impl<'a> InferenceContext<'a> {
198 195
199 let bound_ty = match mode { 196 let bound_ty = match mode {
200 BindingMode::Ref(mutability) => { 197 BindingMode::Ref(mutability) => {
201 Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) 198 Ty::Ref(mutability, Substs::single(inner_ty.clone()))
202 } 199 }
203 BindingMode::Move => inner_ty.clone(), 200 BindingMode::Move => inner_ty.clone(),
204 }; 201 };
@@ -207,17 +204,17 @@ impl<'a> InferenceContext<'a> {
207 return inner_ty; 204 return inner_ty;
208 } 205 }
209 Pat::Slice { prefix, slice, suffix } => { 206 Pat::Slice { prefix, slice, suffix } => {
210 let (container_ty, elem_ty) = match &expected { 207 let (container_ty, elem_ty): (fn(_) -> _, _) = match &expected {
211 ty_app!(TypeCtor::Array, st) => (TypeCtor::Array, st.as_single().clone()), 208 Ty::Array(st) => (Ty::Array, st.as_single().clone()),
212 ty_app!(TypeCtor::Slice, st) => (TypeCtor::Slice, st.as_single().clone()), 209 Ty::Slice(st) => (Ty::Slice, st.as_single().clone()),
213 _ => (TypeCtor::Slice, Ty::Unknown), 210 _ => (Ty::Slice, Ty::Unknown),
214 }; 211 };
215 212
216 for pat_id in prefix.iter().chain(suffix) { 213 for pat_id in prefix.iter().chain(suffix) {
217 self.infer_pat(*pat_id, &elem_ty, default_bm); 214 self.infer_pat(*pat_id, &elem_ty, default_bm);
218 } 215 }
219 216
220 let pat_ty = Ty::apply_one(container_ty, elem_ty); 217 let pat_ty = container_ty(Substs::single(elem_ty));
221 if let Some(slice_pat_id) = slice { 218 if let Some(slice_pat_id) = slice {
222 self.infer_pat(*slice_pat_id, &pat_ty, default_bm); 219 self.infer_pat(*slice_pat_id, &pat_ty, default_bm);
223 } 220 }
@@ -239,7 +236,7 @@ impl<'a> InferenceContext<'a> {
239 }; 236 };
240 237
241 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm); 238 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm);
242 Ty::apply_one(TypeCtor::Adt(box_adt), inner_ty) 239 Ty::adt_ty(box_adt, Substs::single(inner_ty))
243 } 240 }
244 None => Ty::Unknown, 241 None => Ty::Unknown,
245 }, 242 },
diff --git a/crates/hir_ty/src/infer/path.rs b/crates/hir_ty/src/infer/path.rs
index 5d541104e..ae3554bac 100644
--- a/crates/hir_ty/src/infer/path.rs
+++ b/crates/hir_ty/src/infer/path.rs
@@ -260,7 +260,7 @@ impl<'a> InferenceContext<'a> {
260 })); 260 }));
261 Some(trait_substs) 261 Some(trait_substs)
262 } 262 }
263 AssocContainerId::ContainerId(_) => None, 263 AssocContainerId::ModuleId(_) => None,
264 }; 264 };
265 265
266 self.write_assoc_resolution(id, item); 266 self.write_assoc_resolution(id, item);
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs
index 76984242e..54fcfed10 100644
--- a/crates/hir_ty/src/infer/unify.rs
+++ b/crates/hir_ty/src/infer/unify.rs
@@ -2,14 +2,13 @@
2 2
3use std::borrow::Cow; 3use std::borrow::Cow;
4 4
5use chalk_ir::{FloatTy, IntTy, TyVariableKind};
5use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; 6use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
6 7
7use test_utils::mark;
8
9use super::{InferenceContext, Obligation}; 8use super::{InferenceContext, Obligation};
10use crate::{ 9use crate::{
11 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferTy, Substs, Ty, 10 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferenceVar, Scalar,
12 TyKind, TypeCtor, TypeWalk, 11 Substs, Ty, TypeWalk,
13}; 12};
14 13
15impl<'a> InferenceContext<'a> { 14impl<'a> InferenceContext<'a> {
@@ -26,7 +25,7 @@ where
26 'a: 'b, 25 'a: 'b,
27{ 26{
28 ctx: &'b mut InferenceContext<'a>, 27 ctx: &'b mut InferenceContext<'a>,
29 free_vars: Vec<InferTy>, 28 free_vars: Vec<(InferenceVar, TyVariableKind)>,
30 /// A stack of type variables that is used to detect recursive types (which 29 /// A stack of type variables that is used to detect recursive types (which
31 /// are an error, but we need to protect against them to avoid stack 30 /// are an error, but we need to protect against them to avoid stack
32 /// overflows). 31 /// overflows).
@@ -36,17 +35,14 @@ where
36#[derive(Debug)] 35#[derive(Debug)]
37pub(super) struct Canonicalized<T> { 36pub(super) struct Canonicalized<T> {
38 pub(super) value: Canonical<T>, 37 pub(super) value: Canonical<T>,
39 free_vars: Vec<InferTy>, 38 free_vars: Vec<(InferenceVar, TyVariableKind)>,
40} 39}
41 40
42impl<'a, 'b> Canonicalizer<'a, 'b> 41impl<'a, 'b> Canonicalizer<'a, 'b> {
43where 42 fn add(&mut self, free_var: InferenceVar, kind: TyVariableKind) -> usize {
44 'a: 'b, 43 self.free_vars.iter().position(|&(v, _)| v == free_var).unwrap_or_else(|| {
45{
46 fn add(&mut self, free_var: InferTy) -> usize {
47 self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| {
48 let next_index = self.free_vars.len(); 44 let next_index = self.free_vars.len();
49 self.free_vars.push(free_var); 45 self.free_vars.push((free_var, kind));
50 next_index 46 next_index
51 }) 47 })
52 } 48 }
@@ -54,11 +50,11 @@ where
54 fn do_canonicalize<T: TypeWalk>(&mut self, t: T, binders: DebruijnIndex) -> T { 50 fn do_canonicalize<T: TypeWalk>(&mut self, t: T, binders: DebruijnIndex) -> T {
55 t.fold_binders( 51 t.fold_binders(
56 &mut |ty, binders| match ty { 52 &mut |ty, binders| match ty {
57 Ty::Infer(tv) => { 53 Ty::InferenceVar(var, kind) => {
58 let inner = tv.to_inner(); 54 let inner = var.to_inner();
59 if self.var_stack.contains(&inner) { 55 if self.var_stack.contains(&inner) {
60 // recursive type 56 // recursive type
61 return tv.fallback_value(); 57 return self.ctx.table.type_variable_table.fallback_value(var, kind);
62 } 58 }
63 if let Some(known_ty) = 59 if let Some(known_ty) =
64 self.ctx.table.var_unification_table.inlined_probe_value(inner).known() 60 self.ctx.table.var_unification_table.inlined_probe_value(inner).known()
@@ -69,14 +65,8 @@ where
69 result 65 result
70 } else { 66 } else {
71 let root = self.ctx.table.var_unification_table.find(inner); 67 let root = self.ctx.table.var_unification_table.find(inner);
72 let free_var = match tv { 68 let position = self.add(InferenceVar::from_inner(root), kind);
73 InferTy::TypeVar(_) => InferTy::TypeVar(root), 69 Ty::BoundVar(BoundVar::new(binders, position))
74 InferTy::IntVar(_) => InferTy::IntVar(root),
75 InferTy::FloatVar(_) => InferTy::FloatVar(root),
76 InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root),
77 };
78 let position = self.add(free_var);
79 Ty::Bound(BoundVar::new(binders, position))
80 } 70 }
81 } 71 }
82 _ => ty, 72 _ => ty,
@@ -86,19 +76,7 @@ where
86 } 76 }
87 77
88 fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { 78 fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> {
89 let kinds = self 79 let kinds = self.free_vars.iter().map(|&(_, k)| k).collect();
90 .free_vars
91 .iter()
92 .map(|v| match v {
93 // mapping MaybeNeverTypeVar to the same kind as general ones
94 // should be fine, because as opposed to int or float type vars,
95 // they don't restrict what kind of type can go into them, they
96 // just affect fallback.
97 InferTy::TypeVar(_) | InferTy::MaybeNeverTypeVar(_) => TyKind::General,
98 InferTy::IntVar(_) => TyKind::Integer,
99 InferTy::FloatVar(_) => TyKind::Float,
100 })
101 .collect();
102 Canonicalized { value: Canonical { value: result, kinds }, free_vars: self.free_vars } 80 Canonicalized { value: Canonical { value: result, kinds }, free_vars: self.free_vars }
103 } 81 }
104 82
@@ -130,9 +108,10 @@ impl<T> Canonicalized<T> {
130 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { 108 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
131 ty.walk_mut_binders( 109 ty.walk_mut_binders(
132 &mut |ty, binders| { 110 &mut |ty, binders| {
133 if let &mut Ty::Bound(bound) = ty { 111 if let &mut Ty::BoundVar(bound) = ty {
134 if bound.debruijn >= binders { 112 if bound.debruijn >= binders {
135 *ty = Ty::Infer(self.free_vars[bound.index]); 113 let (v, k) = self.free_vars[bound.index];
114 *ty = Ty::InferenceVar(v, k);
136 } 115 }
137 } 116 }
138 }, 117 },
@@ -152,18 +131,18 @@ impl<T> Canonicalized<T> {
152 .kinds 131 .kinds
153 .iter() 132 .iter()
154 .map(|k| match k { 133 .map(|k| match k {
155 TyKind::General => ctx.table.new_type_var(), 134 TyVariableKind::General => ctx.table.new_type_var(),
156 TyKind::Integer => ctx.table.new_integer_var(), 135 TyVariableKind::Integer => ctx.table.new_integer_var(),
157 TyKind::Float => ctx.table.new_float_var(), 136 TyVariableKind::Float => ctx.table.new_float_var(),
158 }) 137 })
159 .collect(), 138 .collect(),
160 ); 139 );
161 for (i, ty) in solution.value.into_iter().enumerate() { 140 for (i, ty) in solution.value.into_iter().enumerate() {
162 let var = self.free_vars[i]; 141 let (v, k) = self.free_vars[i];
163 // eagerly replace projections in the type; we may be getting types 142 // eagerly replace projections in the type; we may be getting types
164 // e.g. from where clauses where this hasn't happened yet 143 // e.g. from where clauses where this hasn't happened yet
165 let ty = ctx.normalize_associated_types_in(ty.clone().subst_bound_vars(&new_vars)); 144 let ty = ctx.normalize_associated_types_in(ty.clone().subst_bound_vars(&new_vars));
166 ctx.table.unify(&Ty::Infer(var), &ty); 145 ctx.table.unify(&Ty::InferenceVar(v, k), &ty);
167 } 146 }
168 } 147 }
169} 148}
@@ -187,7 +166,7 @@ pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
187 // (kind of hacky) 166 // (kind of hacky)
188 for (i, var) in vars.iter().enumerate() { 167 for (i, var) in vars.iter().enumerate() {
189 if &*table.resolve_ty_shallow(var) == var { 168 if &*table.resolve_ty_shallow(var) == var {
190 table.unify(var, &Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, i))); 169 table.unify(var, &Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i)));
191 } 170 }
192 } 171 }
193 Some( 172 Some(
@@ -198,31 +177,73 @@ pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
198} 177}
199 178
200#[derive(Clone, Debug)] 179#[derive(Clone, Debug)]
180pub(super) struct TypeVariableTable {
181 inner: Vec<TypeVariableData>,
182}
183
184impl TypeVariableTable {
185 fn push(&mut self, data: TypeVariableData) {
186 self.inner.push(data);
187 }
188
189 pub(super) fn set_diverging(&mut self, iv: InferenceVar, diverging: bool) {
190 self.inner[iv.to_inner().0 as usize].diverging = diverging;
191 }
192
193 fn is_diverging(&mut self, iv: InferenceVar) -> bool {
194 self.inner[iv.to_inner().0 as usize].diverging
195 }
196
197 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty {
198 match kind {
199 _ if self.inner[iv.to_inner().0 as usize].diverging => Ty::Never,
200 TyVariableKind::General => Ty::Unknown,
201 TyVariableKind::Integer => Ty::Scalar(Scalar::Int(IntTy::I32)),
202 TyVariableKind::Float => Ty::Scalar(Scalar::Float(FloatTy::F64)),
203 }
204 }
205}
206
207#[derive(Copy, Clone, Debug)]
208pub(crate) struct TypeVariableData {
209 diverging: bool,
210}
211
212#[derive(Clone, Debug)]
201pub(crate) struct InferenceTable { 213pub(crate) struct InferenceTable {
202 pub(super) var_unification_table: InPlaceUnificationTable<TypeVarId>, 214 pub(super) var_unification_table: InPlaceUnificationTable<TypeVarId>,
215 pub(super) type_variable_table: TypeVariableTable,
203} 216}
204 217
205impl InferenceTable { 218impl InferenceTable {
206 pub(crate) fn new() -> Self { 219 pub(crate) fn new() -> Self {
207 InferenceTable { var_unification_table: InPlaceUnificationTable::new() } 220 InferenceTable {
221 var_unification_table: InPlaceUnificationTable::new(),
222 type_variable_table: TypeVariableTable { inner: Vec::new() },
223 }
224 }
225
226 fn new_var(&mut self, kind: TyVariableKind, diverging: bool) -> Ty {
227 self.type_variable_table.push(TypeVariableData { diverging });
228 let key = self.var_unification_table.new_key(TypeVarValue::Unknown);
229 assert_eq!(key.0 as usize, self.type_variable_table.inner.len() - 1);
230 Ty::InferenceVar(InferenceVar::from_inner(key), kind)
208 } 231 }
209 232
210 pub(crate) fn new_type_var(&mut self) -> Ty { 233 pub(crate) fn new_type_var(&mut self) -> Ty {
211 Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 234 self.new_var(TyVariableKind::General, false)
212 } 235 }
213 236
214 pub(crate) fn new_integer_var(&mut self) -> Ty { 237 pub(crate) fn new_integer_var(&mut self) -> Ty {
215 Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 238 self.new_var(TyVariableKind::Integer, false)
216 } 239 }
217 240
218 pub(crate) fn new_float_var(&mut self) -> Ty { 241 pub(crate) fn new_float_var(&mut self) -> Ty {
219 Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 242 self.new_var(TyVariableKind::Float, false)
220 } 243 }
221 244
222 pub(crate) fn new_maybe_never_type_var(&mut self) -> Ty { 245 pub(crate) fn new_maybe_never_var(&mut self) -> Ty {
223 Ty::Infer(InferTy::MaybeNeverTypeVar( 246 self.new_var(TyVariableKind::General, true)
224 self.var_unification_table.new_key(TypeVarValue::Unknown),
225 ))
226 } 247 }
227 248
228 pub(crate) fn resolve_ty_completely(&mut self, ty: Ty) -> Ty { 249 pub(crate) fn resolve_ty_completely(&mut self, ty: Ty) -> Ty {
@@ -257,12 +278,14 @@ impl InferenceTable {
257 // try to resolve type vars first 278 // try to resolve type vars first
258 let ty1 = self.resolve_ty_shallow(ty1); 279 let ty1 = self.resolve_ty_shallow(ty1);
259 let ty2 = self.resolve_ty_shallow(ty2); 280 let ty2 = self.resolve_ty_shallow(ty2);
260 match (&*ty1, &*ty2) { 281 if ty1.equals_ctor(&ty2) {
261 (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { 282 match (ty1.substs(), ty2.substs()) {
262 self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) 283 (Some(st1), Some(st2)) => self.unify_substs(st1, st2, depth + 1),
284 (None, None) => true,
285 _ => false,
263 } 286 }
264 287 } else {
265 _ => self.unify_inner_trivial(&ty1, &ty2, depth), 288 self.unify_inner_trivial(&ty1, &ty2, depth)
266 } 289 }
267 } 290 }
268 291
@@ -281,31 +304,46 @@ impl InferenceTable {
281 true 304 true
282 } 305 }
283 306
284 (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) 307 (
285 | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) 308 Ty::InferenceVar(tv1, TyVariableKind::General),
286 | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) 309 Ty::InferenceVar(tv2, TyVariableKind::General),
310 )
287 | ( 311 | (
288 Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), 312 Ty::InferenceVar(tv1, TyVariableKind::Integer),
289 Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), 313 Ty::InferenceVar(tv2, TyVariableKind::Integer),
290 ) => { 314 )
315 | (
316 Ty::InferenceVar(tv1, TyVariableKind::Float),
317 Ty::InferenceVar(tv2, TyVariableKind::Float),
318 ) if self.type_variable_table.is_diverging(*tv1)
319 == self.type_variable_table.is_diverging(*tv2) =>
320 {
291 // both type vars are unknown since we tried to resolve them 321 // both type vars are unknown since we tried to resolve them
292 self.var_unification_table.union(*tv1, *tv2); 322 self.var_unification_table.union(tv1.to_inner(), tv2.to_inner());
293 true 323 true
294 } 324 }
295 325
296 // The order of MaybeNeverTypeVar matters here. 326 // The order of MaybeNeverTypeVar matters here.
297 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. 327 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar.
298 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. 328 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it.
299 (Ty::Infer(InferTy::TypeVar(tv)), other) 329 (Ty::InferenceVar(tv, TyVariableKind::General), other)
300 | (other, Ty::Infer(InferTy::TypeVar(tv))) 330 | (other, Ty::InferenceVar(tv, TyVariableKind::General))
301 | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) 331 | (Ty::InferenceVar(tv, TyVariableKind::Integer), other @ Ty::Scalar(Scalar::Int(_)))
302 | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) 332 | (other @ Ty::Scalar(Scalar::Int(_)), Ty::InferenceVar(tv, TyVariableKind::Integer))
303 | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) 333 | (
304 | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) 334 Ty::InferenceVar(tv, TyVariableKind::Integer),
305 | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) 335 other @ Ty::Scalar(Scalar::Uint(_)),
306 | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { 336 )
337 | (
338 other @ Ty::Scalar(Scalar::Uint(_)),
339 Ty::InferenceVar(tv, TyVariableKind::Integer),
340 )
341 | (Ty::InferenceVar(tv, TyVariableKind::Float), other @ Ty::Scalar(Scalar::Float(_)))
342 | (other @ Ty::Scalar(Scalar::Float(_)), Ty::InferenceVar(tv, TyVariableKind::Float)) =>
343 {
307 // the type var is unknown since we tried to resolve it 344 // the type var is unknown since we tried to resolve it
308 self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); 345 self.var_unification_table
346 .union_value(tv.to_inner(), TypeVarValue::Known(other.clone()));
309 true 347 true
310 } 348 }
311 349
@@ -347,10 +385,10 @@ impl InferenceTable {
347 // more than once 385 // more than once
348 for i in 0..3 { 386 for i in 0..3 {
349 if i > 0 { 387 if i > 0 {
350 mark::hit!(type_var_resolves_to_int_var); 388 cov_mark::hit!(type_var_resolves_to_int_var);
351 } 389 }
352 match &*ty { 390 match &*ty {
353 Ty::Infer(tv) => { 391 Ty::InferenceVar(tv, _) => {
354 let inner = tv.to_inner(); 392 let inner = tv.to_inner();
355 match self.var_unification_table.inlined_probe_value(inner).known() { 393 match self.var_unification_table.inlined_probe_value(inner).known() {
356 Some(known_ty) => { 394 Some(known_ty) => {
@@ -373,12 +411,12 @@ impl InferenceTable {
373 /// known type. 411 /// known type.
374 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 412 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
375 ty.fold(&mut |ty| match ty { 413 ty.fold(&mut |ty| match ty {
376 Ty::Infer(tv) => { 414 Ty::InferenceVar(tv, kind) => {
377 let inner = tv.to_inner(); 415 let inner = tv.to_inner();
378 if tv_stack.contains(&inner) { 416 if tv_stack.contains(&inner) {
379 mark::hit!(type_var_cycles_resolve_as_possible); 417 cov_mark::hit!(type_var_cycles_resolve_as_possible);
380 // recursive type 418 // recursive type
381 return tv.fallback_value(); 419 return self.type_variable_table.fallback_value(tv, kind);
382 } 420 }
383 if let Some(known_ty) = 421 if let Some(known_ty) =
384 self.var_unification_table.inlined_probe_value(inner).known() 422 self.var_unification_table.inlined_probe_value(inner).known()
@@ -400,12 +438,12 @@ impl InferenceTable {
400 /// replaced by Ty::Unknown. 438 /// replaced by Ty::Unknown.
401 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 439 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
402 ty.fold(&mut |ty| match ty { 440 ty.fold(&mut |ty| match ty {
403 Ty::Infer(tv) => { 441 Ty::InferenceVar(tv, kind) => {
404 let inner = tv.to_inner(); 442 let inner = tv.to_inner();
405 if tv_stack.contains(&inner) { 443 if tv_stack.contains(&inner) {
406 mark::hit!(type_var_cycles_resolve_completely); 444 cov_mark::hit!(type_var_cycles_resolve_completely);
407 // recursive type 445 // recursive type
408 return tv.fallback_value(); 446 return self.type_variable_table.fallback_value(tv, kind);
409 } 447 }
410 if let Some(known_ty) = 448 if let Some(known_ty) =
411 self.var_unification_table.inlined_probe_value(inner).known() 449 self.var_unification_table.inlined_probe_value(inner).known()
@@ -416,7 +454,7 @@ impl InferenceTable {
416 tv_stack.pop(); 454 tv_stack.pop();
417 result 455 result
418 } else { 456 } else {
419 tv.fallback_value() 457 self.type_variable_table.fallback_value(tv, kind)
420 } 458 }
421 } 459 }
422 _ => ty, 460 _ => ty,
@@ -426,7 +464,7 @@ impl InferenceTable {
426 464
427/// The ID of a type variable. 465/// The ID of a type variable.
428#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] 466#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
429pub struct TypeVarId(pub(super) u32); 467pub(super) struct TypeVarId(pub(super) u32);
430 468
431impl UnifyKey for TypeVarId { 469impl UnifyKey for TypeVarId {
432 type Value = TypeVarValue; 470 type Value = TypeVarValue;
@@ -447,7 +485,7 @@ impl UnifyKey for TypeVarId {
447/// The value of a type variable: either we already know the type, or we don't 485/// The value of a type variable: either we already know the type, or we don't
448/// know it yet. 486/// know it yet.
449#[derive(Clone, PartialEq, Eq, Debug)] 487#[derive(Clone, PartialEq, Eq, Debug)]
450pub enum TypeVarValue { 488pub(super) enum TypeVarValue {
451 Known(Ty), 489 Known(Ty),
452 Unknown, 490 Unknown,
453} 491}