aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir_ty')
-rw-r--r--crates/hir_ty/src/autoderef.rs15
-rw-r--r--crates/hir_ty/src/db.rs23
-rw-r--r--crates/hir_ty/src/diagnostics/expr.rs21
-rw-r--r--crates/hir_ty/src/diagnostics/match_check.rs8
-rw-r--r--crates/hir_ty/src/diagnostics/unsafe_check.rs6
-rw-r--r--crates/hir_ty/src/display.rs195
-rw-r--r--crates/hir_ty/src/infer.rs70
-rw-r--r--crates/hir_ty/src/infer/coerce.rs38
-rw-r--r--crates/hir_ty/src/infer/expr.rs249
-rw-r--r--crates/hir_ty/src/infer/pat.rs41
-rw-r--r--crates/hir_ty/src/infer/path.rs18
-rw-r--r--crates/hir_ty/src/infer/unify.rs111
-rw-r--r--crates/hir_ty/src/lib.rs412
-rw-r--r--crates/hir_ty/src/lower.rs710
-rw-r--r--crates/hir_ty/src/method_resolution.rs88
-rw-r--r--crates/hir_ty/src/op.rs66
-rw-r--r--crates/hir_ty/src/tests.rs10
-rw-r--r--crates/hir_ty/src/traits.rs38
-rw-r--r--crates/hir_ty/src/traits/chalk.rs85
-rw-r--r--crates/hir_ty/src/traits/chalk/interner.rs2
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs273
-rw-r--r--crates/hir_ty/src/traits/chalk/tls.rs9
22 files changed, 1300 insertions, 1188 deletions
diff --git a/crates/hir_ty/src/autoderef.rs b/crates/hir_ty/src/autoderef.rs
index be1fd1f13..56c6b92d4 100644
--- a/crates/hir_ty/src/autoderef.rs
+++ b/crates/hir_ty/src/autoderef.rs
@@ -12,9 +12,10 @@ use log::{info, warn};
12 12
13use crate::{ 13use crate::{
14 db::HirDatabase, 14 db::HirDatabase,
15 to_assoc_type_id,
15 traits::{InEnvironment, Solution}, 16 traits::{InEnvironment, Solution},
16 utils::generics, 17 utils::generics,
17 BoundVar, Canonical, DebruijnIndex, Obligation, Substs, TraitRef, Ty, 18 BoundVar, Canonical, DebruijnIndex, Interner, Obligation, Substs, TraitRef, Ty, TyKind,
18}; 19};
19 20
20const AUTODEREF_RECURSION_LIMIT: usize = 10; 21const AUTODEREF_RECURSION_LIMIT: usize = 10;
@@ -81,8 +82,12 @@ fn deref_by_trait(
81 82
82 // Now do the assoc type projection 83 // Now do the assoc type projection
83 let projection = super::traits::ProjectionPredicate { 84 let projection = super::traits::ProjectionPredicate {
84 ty: Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, ty.value.kinds.len())), 85 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, ty.value.kinds.len()))
85 projection_ty: super::ProjectionTy { associated_ty: target, parameters }, 86 .intern(&Interner),
87 projection_ty: super::ProjectionTy {
88 associated_ty_id: to_assoc_type_id(target),
89 substitution: parameters,
90 },
86 }; 91 };
87 92
88 let obligation = super::Obligation::Projection(projection); 93 let obligation = super::Obligation::Projection(projection);
@@ -114,8 +119,8 @@ fn deref_by_trait(
114 // new variables in that case 119 // new variables in that case
115 120
116 for i in 1..vars.0.kinds.len() { 121 for i in 1..vars.0.kinds.len() {
117 if vars.0.value[i - 1] 122 if vars.0.value[i - 1].interned(&Interner)
118 != Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i - 1)) 123 != &TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i - 1))
119 { 124 {
120 warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution); 125 warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution);
121 return None; 126 return None;
diff --git a/crates/hir_ty/src/db.rs b/crates/hir_ty/src/db.rs
index 06714409f..74a048672 100644
--- a/crates/hir_ty/src/db.rs
+++ b/crates/hir_ty/src/db.rs
@@ -12,7 +12,7 @@ use la_arena::ArenaMap;
12use crate::{ 12use crate::{
13 method_resolution::{InherentImpls, TraitImpls}, 13 method_resolution::{InherentImpls, TraitImpls},
14 traits::chalk, 14 traits::chalk,
15 Binders, CallableDefId, GenericPredicate, InferenceResult, OpaqueTyId, PolyFnSig, 15 Binders, CallableDefId, FnDefId, GenericPredicate, ImplTraitId, InferenceResult, PolyFnSig,
16 ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId, 16 ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId,
17}; 17};
18use hir_expand::name::Name; 18use hir_expand::name::Name;
@@ -65,6 +65,9 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
65 #[salsa::invoke(crate::lower::generic_predicates_query)] 65 #[salsa::invoke(crate::lower::generic_predicates_query)]
66 fn generic_predicates(&self, def: GenericDefId) -> Arc<[Binders<GenericPredicate>]>; 66 fn generic_predicates(&self, def: GenericDefId) -> Arc<[Binders<GenericPredicate>]>;
67 67
68 #[salsa::invoke(crate::lower::trait_environment_query)]
69 fn trait_environment(&self, def: GenericDefId) -> Arc<crate::TraitEnvironment>;
70
68 #[salsa::invoke(crate::lower::generic_defaults_query)] 71 #[salsa::invoke(crate::lower::generic_defaults_query)]
69 fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>; 72 fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>;
70 73
@@ -81,11 +84,11 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
81 #[salsa::interned] 84 #[salsa::interned]
82 fn intern_callable_def(&self, callable_def: CallableDefId) -> InternedCallableDefId; 85 fn intern_callable_def(&self, callable_def: CallableDefId) -> InternedCallableDefId;
83 #[salsa::interned] 86 #[salsa::interned]
84 fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId; 87 fn intern_type_param_id(&self, param_id: TypeParamId) -> InternedTypeParamId;
85 #[salsa::interned] 88 #[salsa::interned]
86 fn intern_impl_trait_id(&self, id: OpaqueTyId) -> InternedOpaqueTyId; 89 fn intern_impl_trait_id(&self, id: ImplTraitId) -> InternedOpaqueTyId;
87 #[salsa::interned] 90 #[salsa::interned]
88 fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> ClosureId; 91 fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> InternedClosureId;
89 92
90 #[salsa::invoke(chalk::associated_ty_data_query)] 93 #[salsa::invoke(chalk::associated_ty_data_query)]
91 fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>; 94 fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>;
@@ -100,10 +103,10 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
100 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>; 103 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>;
101 104
102 #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)] 105 #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)]
103 fn fn_def_datum(&self, krate: CrateId, fn_def_id: chalk::FnDefId) -> Arc<chalk::FnDefDatum>; 106 fn fn_def_datum(&self, krate: CrateId, fn_def_id: FnDefId) -> Arc<chalk::FnDefDatum>;
104 107
105 #[salsa::invoke(crate::traits::chalk::fn_def_variance_query)] 108 #[salsa::invoke(crate::traits::chalk::fn_def_variance_query)]
106 fn fn_def_variance(&self, krate: CrateId, fn_def_id: chalk::FnDefId) -> chalk::Variances; 109 fn fn_def_variance(&self, krate: CrateId, fn_def_id: FnDefId) -> chalk::Variances;
107 110
108 #[salsa::invoke(crate::traits::chalk::adt_variance_query)] 111 #[salsa::invoke(crate::traits::chalk::adt_variance_query)]
109 fn adt_variance(&self, krate: CrateId, adt_id: chalk::AdtId) -> chalk::Variances; 112 fn adt_variance(&self, krate: CrateId, adt_id: chalk::AdtId) -> chalk::Variances;
@@ -149,16 +152,16 @@ fn hir_database_is_object_safe() {
149} 152}
150 153
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct GlobalTypeParamId(salsa::InternId); 155pub struct InternedTypeParamId(salsa::InternId);
153impl_intern_key!(GlobalTypeParamId); 156impl_intern_key!(InternedTypeParamId);
154 157
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub struct InternedOpaqueTyId(salsa::InternId); 159pub struct InternedOpaqueTyId(salsa::InternId);
157impl_intern_key!(InternedOpaqueTyId); 160impl_intern_key!(InternedOpaqueTyId);
158 161
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub struct ClosureId(salsa::InternId); 163pub struct InternedClosureId(salsa::InternId);
161impl_intern_key!(ClosureId); 164impl_intern_key!(InternedClosureId);
162 165
163/// This exists just for Chalk, because Chalk just has a single `FnDefId` where 166/// This exists just for Chalk, because Chalk just has a single `FnDefId` where
164/// we have different IDs for struct and enum variant constructors. 167/// we have different IDs for struct and enum variant constructors.
diff --git a/crates/hir_ty/src/diagnostics/expr.rs b/crates/hir_ty/src/diagnostics/expr.rs
index 2751cd304..b2bfd68d4 100644
--- a/crates/hir_ty/src/diagnostics/expr.rs
+++ b/crates/hir_ty/src/diagnostics/expr.rs
@@ -15,7 +15,7 @@ use crate::{
15 MissingPatFields, RemoveThisSemicolon, 15 MissingPatFields, RemoveThisSemicolon,
16 }, 16 },
17 utils::variant_data, 17 utils::variant_data,
18 AdtId, InferenceResult, Ty, 18 AdtId, InferenceResult, Interner, Ty, TyKind,
19}; 19};
20 20
21pub(crate) use hir_def::{ 21pub(crate) use hir_def::{
@@ -289,11 +289,10 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
289 let (body, source_map): (Arc<Body>, Arc<BodySourceMap>) = 289 let (body, source_map): (Arc<Body>, Arc<BodySourceMap>) =
290 db.body_with_source_map(self.owner.into()); 290 db.body_with_source_map(self.owner.into());
291 291
292 let match_expr_ty = match infer.type_of_expr.get(match_expr) { 292 let match_expr_ty = if infer.type_of_expr[match_expr].is_unknown() {
293 // If we can't resolve the type of the match expression 293 return;
294 // we cannot perform exhaustiveness checks. 294 } else {
295 None | Some(Ty::Unknown) => return, 295 &infer.type_of_expr[match_expr]
296 Some(ty) => ty,
297 }; 296 };
298 297
299 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db }; 298 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db };
@@ -379,14 +378,14 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
379 _ => return, 378 _ => return,
380 }; 379 };
381 380
382 let (params, required) = match mismatch.expected { 381 let (params, required) = match mismatch.expected.interned(&Interner) {
383 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters) 382 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters)
384 if enum_id == core_result_enum => 383 if *enum_id == core_result_enum =>
385 { 384 {
386 (parameters, "Ok".to_string()) 385 (parameters, "Ok".to_string())
387 } 386 }
388 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters) 387 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ref parameters)
389 if enum_id == core_option_enum => 388 if *enum_id == core_option_enum =>
390 { 389 {
391 (parameters, "Some".to_string()) 390 (parameters, "Some".to_string())
392 } 391 }
diff --git a/crates/hir_ty/src/diagnostics/match_check.rs b/crates/hir_ty/src/diagnostics/match_check.rs
index 04d39c571..5a5cdcbf3 100644
--- a/crates/hir_ty/src/diagnostics/match_check.rs
+++ b/crates/hir_ty/src/diagnostics/match_check.rs
@@ -227,7 +227,7 @@ use hir_def::{
227use la_arena::Idx; 227use la_arena::Idx;
228use smallvec::{smallvec, SmallVec}; 228use smallvec::{smallvec, SmallVec};
229 229
230use crate::{db::HirDatabase, AdtId, InferenceResult, Ty}; 230use crate::{db::HirDatabase, AdtId, InferenceResult, Interner, TyKind};
231 231
232#[derive(Debug, Clone, Copy)] 232#[derive(Debug, Clone, Copy)]
233/// Either a pattern from the source code being analyzed, represented as 233/// Either a pattern from the source code being analyzed, represented as
@@ -626,13 +626,13 @@ pub(super) fn is_useful(
626 // - enum with no variants 626 // - enum with no variants
627 // - `!` type 627 // - `!` type
628 // In those cases, no match arm is useful. 628 // In those cases, no match arm is useful.
629 match cx.infer[cx.match_expr].strip_references() { 629 match cx.infer[cx.match_expr].strip_references().interned(&Interner) {
630 Ty::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => { 630 TyKind::Adt(AdtId(hir_def::AdtId::EnumId(enum_id)), ..) => {
631 if cx.db.enum_data(*enum_id).variants.is_empty() { 631 if cx.db.enum_data(*enum_id).variants.is_empty() {
632 return Ok(Usefulness::NotUseful); 632 return Ok(Usefulness::NotUseful);
633 } 633 }
634 } 634 }
635 Ty::Never => return Ok(Usefulness::NotUseful), 635 TyKind::Never => return Ok(Usefulness::NotUseful),
636 _ => (), 636 _ => (),
637 } 637 }
638 638
diff --git a/crates/hir_ty/src/diagnostics/unsafe_check.rs b/crates/hir_ty/src/diagnostics/unsafe_check.rs
index e77a20fea..20bb64827 100644
--- a/crates/hir_ty/src/diagnostics/unsafe_check.rs
+++ b/crates/hir_ty/src/diagnostics/unsafe_check.rs
@@ -11,7 +11,7 @@ use hir_def::{
11}; 11};
12use hir_expand::diagnostics::DiagnosticSink; 12use hir_expand::diagnostics::DiagnosticSink;
13 13
14use crate::{db::HirDatabase, diagnostics::MissingUnsafe, InferenceResult, Ty}; 14use crate::{db::HirDatabase, diagnostics::MissingUnsafe, InferenceResult, Interner, TyKind};
15 15
16pub(super) struct UnsafeValidator<'a, 'b: 'a> { 16pub(super) struct UnsafeValidator<'a, 'b: 'a> {
17 owner: DefWithBodyId, 17 owner: DefWithBodyId,
@@ -85,7 +85,7 @@ fn walk_unsafe(
85 let expr = &body.exprs[current]; 85 let expr = &body.exprs[current];
86 match expr { 86 match expr {
87 &Expr::Call { callee, .. } => { 87 &Expr::Call { callee, .. } => {
88 if let Some(func) = infer[callee].as_fn_def() { 88 if let Some(func) = infer[callee].as_fn_def(db) {
89 if db.function_data(func).is_unsafe { 89 if db.function_data(func).is_unsafe {
90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
91 } 91 }
@@ -110,7 +110,7 @@ fn walk_unsafe(
110 } 110 }
111 } 111 }
112 Expr::UnaryOp { expr, op: UnaryOp::Deref } => { 112 Expr::UnaryOp { expr, op: UnaryOp::Deref } => {
113 if let Ty::Raw(..) = &infer[*expr] { 113 if let TyKind::Raw(..) = &infer[*expr].interned(&Interner) {
114 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 114 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
115 } 115 }
116 } 116 }
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs
index ab51cb0a6..378c951c5 100644
--- a/crates/hir_ty/src/display.rs
+++ b/crates/hir_ty/src/display.rs
@@ -11,9 +11,10 @@ use hir_def::{
11use hir_expand::name::Name; 11use hir_expand::name::Name;
12 12
13use crate::{ 13use crate::{
14 db::HirDatabase, primitive, utils::generics, AdtId, AliasTy, CallableDefId, CallableSig, 14 db::HirDatabase, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, primitive,
15 GenericPredicate, Lifetime, Obligation, OpaqueTy, OpaqueTyId, ProjectionTy, Scalar, Substs, 15 to_assoc_type_id, traits::chalk::from_chalk, utils::generics, AdtId, AliasTy, CallableDefId,
16 TraitRef, Ty, 16 CallableSig, GenericPredicate, ImplTraitId, Interner, Lifetime, Obligation, OpaqueTy,
17 ProjectionTy, Scalar, Substs, TraitRef, Ty, TyKind,
17}; 18};
18 19
19pub struct HirFormatter<'a> { 20pub struct HirFormatter<'a> {
@@ -244,19 +245,19 @@ impl HirDisplay for ProjectionTy {
244 } 245 }
245 246
246 let trait_ = f.db.trait_data(self.trait_(f.db)); 247 let trait_ = f.db.trait_data(self.trait_(f.db));
247 let first_parameter = self.parameters[0].into_displayable( 248 let first_parameter = self.substitution[0].into_displayable(
248 f.db, 249 f.db,
249 f.max_size, 250 f.max_size,
250 f.omit_verbose_types, 251 f.omit_verbose_types,
251 f.display_target, 252 f.display_target,
252 ); 253 );
253 write!(f, "<{} as {}", first_parameter, trait_.name)?; 254 write!(f, "<{} as {}", first_parameter, trait_.name)?;
254 if self.parameters.len() > 1 { 255 if self.substitution.len() > 1 {
255 write!(f, "<")?; 256 write!(f, "<")?;
256 f.write_joined(&self.parameters[1..], ", ")?; 257 f.write_joined(&self.substitution[1..], ", ")?;
257 write!(f, ">")?; 258 write!(f, ">")?;
258 } 259 }
259 write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; 260 write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?;
260 Ok(()) 261 Ok(())
261 } 262 }
262} 263}
@@ -267,32 +268,32 @@ impl HirDisplay for Ty {
267 return write!(f, "{}", TYPE_HINT_TRUNCATION); 268 return write!(f, "{}", TYPE_HINT_TRUNCATION);
268 } 269 }
269 270
270 match self { 271 match self.interned(&Interner) {
271 Ty::Never => write!(f, "!")?, 272 TyKind::Never => write!(f, "!")?,
272 Ty::Str => write!(f, "str")?, 273 TyKind::Str => write!(f, "str")?,
273 Ty::Scalar(Scalar::Bool) => write!(f, "bool")?, 274 TyKind::Scalar(Scalar::Bool) => write!(f, "bool")?,
274 Ty::Scalar(Scalar::Char) => write!(f, "char")?, 275 TyKind::Scalar(Scalar::Char) => write!(f, "char")?,
275 &Ty::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?, 276 &TyKind::Scalar(Scalar::Float(t)) => write!(f, "{}", primitive::float_ty_to_string(t))?,
276 &Ty::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?, 277 &TyKind::Scalar(Scalar::Int(t)) => write!(f, "{}", primitive::int_ty_to_string(t))?,
277 &Ty::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?, 278 &TyKind::Scalar(Scalar::Uint(t)) => write!(f, "{}", primitive::uint_ty_to_string(t))?,
278 Ty::Slice(parameters) => { 279 TyKind::Slice(parameters) => {
279 let t = parameters.as_single(); 280 let t = parameters.as_single();
280 write!(f, "[")?; 281 write!(f, "[")?;
281 t.hir_fmt(f)?; 282 t.hir_fmt(f)?;
282 write!(f, "]")?; 283 write!(f, "]")?;
283 } 284 }
284 Ty::Array(parameters) => { 285 TyKind::Array(parameters) => {
285 let t = parameters.as_single(); 286 let t = parameters.as_single();
286 write!(f, "[")?; 287 write!(f, "[")?;
287 t.hir_fmt(f)?; 288 t.hir_fmt(f)?;
288 write!(f, "; _]")?; 289 write!(f, "; _]")?;
289 } 290 }
290 Ty::Raw(m, parameters) | Ty::Ref(m, parameters) => { 291 TyKind::Raw(m, parameters) | TyKind::Ref(m, parameters) => {
291 let t = parameters.as_single(); 292 let t = parameters.as_single();
292 let ty_display = 293 let ty_display =
293 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target); 294 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
294 295
295 if matches!(self, Ty::Raw(..)) { 296 if matches!(self.interned(&Interner), TyKind::Raw(..)) {
296 write!( 297 write!(
297 f, 298 f,
298 "*{}", 299 "*{}",
@@ -312,22 +313,29 @@ impl HirDisplay for Ty {
312 )?; 313 )?;
313 } 314 }
314 315
316 // FIXME: all this just to decide whether to use parentheses...
315 let datas; 317 let datas;
316 let predicates = match t { 318 let predicates = match t.interned(&Interner) {
317 Ty::Dyn(predicates) if predicates.len() > 1 => { 319 TyKind::Dyn(predicates) if predicates.len() > 1 => {
318 Cow::Borrowed(predicates.as_ref()) 320 Cow::Borrowed(predicates.as_ref())
319 } 321 }
320 &Ty::Alias(AliasTy::Opaque(OpaqueTy { 322 &TyKind::Alias(AliasTy::Opaque(OpaqueTy {
321 opaque_ty_id: OpaqueTyId::ReturnTypeImplTrait(func, idx), 323 opaque_ty_id,
322 ref parameters, 324 substitution: ref parameters,
323 })) => { 325 })) => {
324 datas = 326 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty_id.into());
325 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 327 if let ImplTraitId::ReturnTypeImplTrait(func, idx) = impl_trait_id {
326 let data = (*datas) 328 datas =
327 .as_ref() 329 f.db.return_type_impl_traits(func)
328 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone()); 330 .expect("impl trait id without data");
329 let bounds = data.subst(parameters); 331 let data = (*datas)
330 Cow::Owned(bounds.value) 332 .as_ref()
333 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
334 let bounds = data.subst(parameters);
335 Cow::Owned(bounds.value)
336 } else {
337 Cow::Borrowed(&[][..])
338 }
331 } 339 }
332 _ => Cow::Borrowed(&[][..]), 340 _ => Cow::Borrowed(&[][..]),
333 }; 341 };
@@ -347,7 +355,7 @@ impl HirDisplay for Ty {
347 write!(f, "{}", ty_display)?; 355 write!(f, "{}", ty_display)?;
348 } 356 }
349 } 357 }
350 Ty::Tuple(_, substs) => { 358 TyKind::Tuple(_, substs) => {
351 if substs.len() == 1 { 359 if substs.len() == 1 {
352 write!(f, "(")?; 360 write!(f, "(")?;
353 substs[0].hir_fmt(f)?; 361 substs[0].hir_fmt(f)?;
@@ -358,12 +366,12 @@ impl HirDisplay for Ty {
358 write!(f, ")")?; 366 write!(f, ")")?;
359 } 367 }
360 } 368 }
361 Ty::Function(fn_ptr) => { 369 TyKind::Function(fn_ptr) => {
362 let sig = CallableSig::from_fn_ptr(fn_ptr); 370 let sig = CallableSig::from_fn_ptr(fn_ptr);
363 sig.hir_fmt(f)?; 371 sig.hir_fmt(f)?;
364 } 372 }
365 Ty::FnDef(def, parameters) => { 373 TyKind::FnDef(def, parameters) => {
366 let def = *def; 374 let def = from_chalk(f.db, *def);
367 let sig = f.db.callable_item_signature(def).subst(parameters); 375 let sig = f.db.callable_item_signature(def).subst(parameters);
368 match def { 376 match def {
369 CallableDefId::FunctionId(ff) => { 377 CallableDefId::FunctionId(ff) => {
@@ -401,7 +409,7 @@ impl HirDisplay for Ty {
401 write!(f, " -> {}", ret_display)?; 409 write!(f, " -> {}", ret_display)?;
402 } 410 }
403 } 411 }
404 Ty::Adt(AdtId(def_id), parameters) => { 412 TyKind::Adt(AdtId(def_id), parameters) => {
405 match f.display_target { 413 match f.display_target {
406 DisplayTarget::Diagnostics | DisplayTarget::Test => { 414 DisplayTarget::Diagnostics | DisplayTarget::Test => {
407 let name = match *def_id { 415 let name = match *def_id {
@@ -427,37 +435,39 @@ impl HirDisplay for Ty {
427 } 435 }
428 436
429 if parameters.len() > 0 { 437 if parameters.len() > 0 {
430 let parameters_to_write = 438 let parameters_to_write = if f.display_target.is_source_code()
431 if f.display_target.is_source_code() || f.omit_verbose_types() { 439 || f.omit_verbose_types()
432 match self 440 {
433 .as_generic_def() 441 match self
434 .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) 442 .as_generic_def(f.db)
435 .filter(|defaults| !defaults.is_empty()) 443 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
436 { 444 .filter(|defaults| !defaults.is_empty())
437 None => parameters.0.as_ref(), 445 {
438 Some(default_parameters) => { 446 None => parameters.0.as_ref(),
439 let mut default_from = 0; 447 Some(default_parameters) => {
440 for (i, parameter) in parameters.iter().enumerate() { 448 let mut default_from = 0;
441 match (parameter, default_parameters.get(i)) { 449 for (i, parameter) in parameters.iter().enumerate() {
442 (&Ty::Unknown, _) | (_, None) => { 450 match (parameter.interned(&Interner), default_parameters.get(i))
451 {
452 (&TyKind::Unknown, _) | (_, None) => {
453 default_from = i + 1;
454 }
455 (_, Some(default_parameter)) => {
456 let actual_default = default_parameter
457 .clone()
458 .subst(&parameters.prefix(i));
459 if parameter != &actual_default {
443 default_from = i + 1; 460 default_from = i + 1;
444 } 461 }
445 (_, Some(default_parameter)) => {
446 let actual_default = default_parameter
447 .clone()
448 .subst(&parameters.prefix(i));
449 if parameter != &actual_default {
450 default_from = i + 1;
451 }
452 }
453 } 462 }
454 } 463 }
455 &parameters.0[0..default_from]
456 } 464 }
465 &parameters.0[0..default_from]
457 } 466 }
458 } else { 467 }
459 parameters.0.as_ref() 468 } else {
460 }; 469 parameters.0.as_ref()
470 };
461 if !parameters_to_write.is_empty() { 471 if !parameters_to_write.is_empty() {
462 write!(f, "<")?; 472 write!(f, "<")?;
463 f.write_joined(parameters_to_write, ", ")?; 473 f.write_joined(parameters_to_write, ", ")?;
@@ -465,13 +475,14 @@ impl HirDisplay for Ty {
465 } 475 }
466 } 476 }
467 } 477 }
468 Ty::AssociatedType(type_alias, parameters) => { 478 TyKind::AssociatedType(assoc_type_id, parameters) => {
479 let type_alias = from_assoc_type_id(*assoc_type_id);
469 let trait_ = match type_alias.lookup(f.db.upcast()).container { 480 let trait_ = match type_alias.lookup(f.db.upcast()).container {
470 AssocContainerId::TraitId(it) => it, 481 AssocContainerId::TraitId(it) => it,
471 _ => panic!("not an associated type"), 482 _ => panic!("not an associated type"),
472 }; 483 };
473 let trait_ = f.db.trait_data(trait_); 484 let trait_ = f.db.trait_data(trait_);
474 let type_alias_data = f.db.type_alias_data(*type_alias); 485 let type_alias_data = f.db.type_alias_data(type_alias);
475 486
476 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types) 487 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
477 if f.display_target.is_test() { 488 if f.display_target.is_test() {
@@ -482,19 +493,22 @@ impl HirDisplay for Ty {
482 write!(f, ">")?; 493 write!(f, ">")?;
483 } 494 }
484 } else { 495 } else {
485 let projection_ty = 496 let projection_ty = ProjectionTy {
486 ProjectionTy { associated_ty: *type_alias, parameters: parameters.clone() }; 497 associated_ty_id: to_assoc_type_id(type_alias),
498 substitution: parameters.clone(),
499 };
487 500
488 projection_ty.hir_fmt(f)?; 501 projection_ty.hir_fmt(f)?;
489 } 502 }
490 } 503 }
491 Ty::ForeignType(type_alias) => { 504 TyKind::ForeignType(type_alias) => {
492 let type_alias = f.db.type_alias_data(*type_alias); 505 let type_alias = f.db.type_alias_data(from_foreign_def_id(*type_alias));
493 write!(f, "{}", type_alias.name)?; 506 write!(f, "{}", type_alias.name)?;
494 } 507 }
495 Ty::OpaqueType(opaque_ty_id, parameters) => { 508 TyKind::OpaqueType(opaque_ty_id, parameters) => {
496 match opaque_ty_id { 509 let impl_trait_id = f.db.lookup_intern_impl_trait_id((*opaque_ty_id).into());
497 &OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 510 match impl_trait_id {
511 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
498 let datas = 512 let datas =
499 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 513 f.db.return_type_impl_traits(func).expect("impl trait id without data");
500 let data = (*datas) 514 let data = (*datas)
@@ -504,14 +518,14 @@ impl HirDisplay for Ty {
504 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?; 518 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?;
505 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution 519 // FIXME: it would maybe be good to distinguish this from the alias type (when debug printing), and to show the substitution
506 } 520 }
507 OpaqueTyId::AsyncBlockTypeImplTrait(..) => { 521 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
508 write!(f, "impl Future<Output = ")?; 522 write!(f, "impl Future<Output = ")?;
509 parameters[0].hir_fmt(f)?; 523 parameters[0].hir_fmt(f)?;
510 write!(f, ">")?; 524 write!(f, ">")?;
511 } 525 }
512 } 526 }
513 } 527 }
514 Ty::Closure(.., substs) => { 528 TyKind::Closure(.., substs) => {
515 let sig = substs[0].callable_sig(f.db); 529 let sig = substs[0].callable_sig(f.db);
516 if let Some(sig) = sig { 530 if let Some(sig) = sig {
517 if sig.params().is_empty() { 531 if sig.params().is_empty() {
@@ -535,7 +549,8 @@ impl HirDisplay for Ty {
535 write!(f, "{{closure}}")?; 549 write!(f, "{{closure}}")?;
536 } 550 }
537 } 551 }
538 Ty::Placeholder(id) => { 552 TyKind::Placeholder(idx) => {
553 let id = from_placeholder_idx(f.db, *idx);
539 let generics = generics(f.db.upcast(), id.parent); 554 let generics = generics(f.db.upcast(), id.parent);
540 let param_data = &generics.params.types[id.local_id]; 555 let param_data = &generics.params.types[id.local_id];
541 match param_data.provenance { 556 match param_data.provenance {
@@ -543,8 +558,8 @@ impl HirDisplay for Ty {
543 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))? 558 write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
544 } 559 }
545 TypeParamProvenance::ArgumentImplTrait => { 560 TypeParamProvenance::ArgumentImplTrait => {
546 let bounds = f.db.generic_predicates_for_param(*id); 561 let bounds = f.db.generic_predicates_for_param(id);
547 let substs = Substs::type_params_for_generics(&generics); 562 let substs = Substs::type_params_for_generics(f.db, &generics);
548 write_bounds_like_dyn_trait_with_prefix( 563 write_bounds_like_dyn_trait_with_prefix(
549 "impl", 564 "impl",
550 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(), 565 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(),
@@ -553,28 +568,29 @@ impl HirDisplay for Ty {
553 } 568 }
554 } 569 }
555 } 570 }
556 Ty::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?, 571 TyKind::BoundVar(idx) => write!(f, "?{}.{}", idx.debruijn.depth(), idx.index)?,
557 Ty::Dyn(predicates) => { 572 TyKind::Dyn(predicates) => {
558 write_bounds_like_dyn_trait_with_prefix("dyn", predicates, f)?; 573 write_bounds_like_dyn_trait_with_prefix("dyn", predicates, f)?;
559 } 574 }
560 Ty::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?, 575 TyKind::Alias(AliasTy::Projection(p_ty)) => p_ty.hir_fmt(f)?,
561 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 576 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
562 match opaque_ty.opaque_ty_id { 577 let impl_trait_id = f.db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into());
563 OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 578 match impl_trait_id {
579 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
564 let datas = 580 let datas =
565 f.db.return_type_impl_traits(func).expect("impl trait id without data"); 581 f.db.return_type_impl_traits(func).expect("impl trait id without data");
566 let data = (*datas) 582 let data = (*datas)
567 .as_ref() 583 .as_ref()
568 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone()); 584 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
569 let bounds = data.subst(&opaque_ty.parameters); 585 let bounds = data.subst(&opaque_ty.substitution);
570 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?; 586 write_bounds_like_dyn_trait_with_prefix("impl", &bounds.value, f)?;
571 } 587 }
572 OpaqueTyId::AsyncBlockTypeImplTrait(..) => { 588 ImplTraitId::AsyncBlockTypeImplTrait(..) => {
573 write!(f, "{{async block}}")?; 589 write!(f, "{{async block}}")?;
574 } 590 }
575 }; 591 };
576 } 592 }
577 Ty::Unknown => { 593 TyKind::Unknown => {
578 if f.display_target.is_source_code() { 594 if f.display_target.is_source_code() {
579 return Err(HirDisplayError::DisplaySourceCodeError( 595 return Err(HirDisplayError::DisplaySourceCodeError(
580 DisplaySourceCodeError::UnknownType, 596 DisplaySourceCodeError::UnknownType,
@@ -582,7 +598,7 @@ impl HirDisplay for Ty {
582 } 598 }
583 write!(f, "{{unknown}}")?; 599 write!(f, "{{unknown}}")?;
584 } 600 }
585 Ty::InferenceVar(..) => write!(f, "_")?, 601 TyKind::InferenceVar(..) => write!(f, "_")?,
586 } 602 }
587 Ok(()) 603 Ok(())
588 } 604 }
@@ -695,7 +711,9 @@ fn write_bounds_like_dyn_trait(
695 write!(f, "<")?; 711 write!(f, "<")?;
696 angle_open = true; 712 angle_open = true;
697 } 713 }
698 let type_alias = f.db.type_alias_data(projection_pred.projection_ty.associated_ty); 714 let type_alias = f.db.type_alias_data(from_assoc_type_id(
715 projection_pred.projection_ty.associated_ty_id,
716 ));
699 write!(f, "{} = ", type_alias.name)?; 717 write!(f, "{} = ", type_alias.name)?;
700 projection_pred.ty.hir_fmt(f)?; 718 projection_pred.ty.hir_fmt(f)?;
701 } 719 }
@@ -766,7 +784,10 @@ impl HirDisplay for GenericPredicate {
766 write!( 784 write!(
767 f, 785 f,
768 ">::{} = ", 786 ">::{} = ",
769 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, 787 f.db.type_alias_data(from_assoc_type_id(
788 projection_pred.projection_ty.associated_ty_id
789 ))
790 .name,
770 )?; 791 )?;
771 projection_pred.ty.hir_fmt(f)?; 792 projection_pred.ty.hir_fmt(f)?;
772 } 793 }
diff --git a/crates/hir_ty/src/infer.rs b/crates/hir_ty/src/infer.rs
index 4d771a91e..fbfedb4e6 100644
--- a/crates/hir_ty/src/infer.rs
+++ b/crates/hir_ty/src/infer.rs
@@ -41,7 +41,8 @@ use super::{
41 InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk, 41 InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk,
42}; 42};
43use crate::{ 43use crate::{
44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode, AliasTy, 44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode,
45 to_assoc_type_id, AliasTy, Interner, TyKind,
45}; 46};
46 47
47pub(crate) use unify::unify; 48pub(crate) use unify::unify;
@@ -169,7 +170,7 @@ impl Index<ExprId> for InferenceResult {
169 type Output = Ty; 170 type Output = Ty;
170 171
171 fn index(&self, expr: ExprId) -> &Ty { 172 fn index(&self, expr: ExprId) -> &Ty {
172 self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) 173 self.type_of_expr.get(expr).unwrap_or(&Ty(TyKind::Unknown))
173 } 174 }
174} 175}
175 176
@@ -177,7 +178,7 @@ impl Index<PatId> for InferenceResult {
177 type Output = Ty; 178 type Output = Ty;
178 179
179 fn index(&self, pat: PatId) -> &Ty { 180 fn index(&self, pat: PatId) -> &Ty {
180 self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) 181 self.type_of_pat.get(pat).unwrap_or(&Ty(TyKind::Unknown))
181 } 182 }
182} 183}
183 184
@@ -226,8 +227,10 @@ impl<'a> InferenceContext<'a> {
226 result: InferenceResult::default(), 227 result: InferenceResult::default(),
227 table: unify::InferenceTable::new(), 228 table: unify::InferenceTable::new(),
228 obligations: Vec::default(), 229 obligations: Vec::default(),
229 return_ty: Ty::Unknown, // set in collect_fn_signature 230 return_ty: TyKind::Unknown.intern(&Interner), // set in collect_fn_signature
230 trait_env: TraitEnvironment::lower(db, &resolver), 231 trait_env: owner
232 .as_generic_def_id()
233 .map_or_else(Default::default, |d| db.trait_environment(d)),
231 db, 234 db,
232 owner, 235 owner,
233 body: db.body(owner), 236 body: db.body(owner),
@@ -237,15 +240,19 @@ impl<'a> InferenceContext<'a> {
237 } 240 }
238 } 241 }
239 242
243 fn err_ty(&self) -> Ty {
244 TyKind::Unknown.intern(&Interner)
245 }
246
240 fn resolve_all(mut self) -> InferenceResult { 247 fn resolve_all(mut self) -> InferenceResult {
241 // FIXME resolve obligations as well (use Guidance if necessary) 248 // FIXME resolve obligations as well (use Guidance if necessary)
242 let mut result = std::mem::take(&mut self.result); 249 let mut result = std::mem::take(&mut self.result);
243 for ty in result.type_of_expr.values_mut() { 250 for ty in result.type_of_expr.values_mut() {
244 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 251 let resolved = self.table.resolve_ty_completely(ty.clone());
245 *ty = resolved; 252 *ty = resolved;
246 } 253 }
247 for ty in result.type_of_pat.values_mut() { 254 for ty in result.type_of_pat.values_mut() {
248 let resolved = self.table.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 255 let resolved = self.table.resolve_ty_completely(ty.clone());
249 *ty = resolved; 256 *ty = resolved;
250 } 257 }
251 result 258 result
@@ -287,7 +294,7 @@ impl<'a> InferenceContext<'a> {
287 // FIXME use right resolver for block 294 // FIXME use right resolver for block
288 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) 295 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
289 .with_impl_trait_mode(impl_trait_mode); 296 .with_impl_trait_mode(impl_trait_mode);
290 let ty = Ty::from_hir(&ctx, type_ref); 297 let ty = ctx.lower_ty(type_ref);
291 let ty = self.insert_type_vars(ty); 298 let ty = self.insert_type_vars(ty);
292 self.normalize_associated_types_in(ty) 299 self.normalize_associated_types_in(ty)
293 } 300 }
@@ -298,8 +305,8 @@ impl<'a> InferenceContext<'a> {
298 305
299 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. 306 /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
300 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { 307 fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty {
301 match ty { 308 match ty.interned(&Interner) {
302 Ty::Unknown => self.table.new_type_var(), 309 TyKind::Unknown => self.table.new_type_var(),
303 _ => ty, 310 _ => ty,
304 } 311 }
305 } 312 }
@@ -377,13 +384,16 @@ impl<'a> InferenceContext<'a> {
377 let trait_ref = TraitRef { trait_, substs: substs.clone() }; 384 let trait_ref = TraitRef { trait_, substs: substs.clone() };
378 let projection = ProjectionPredicate { 385 let projection = ProjectionPredicate {
379 ty: ty.clone(), 386 ty: ty.clone(),
380 projection_ty: ProjectionTy { associated_ty: res_assoc_ty, parameters: substs }, 387 projection_ty: ProjectionTy {
388 associated_ty_id: to_assoc_type_id(res_assoc_ty),
389 substitution: substs,
390 },
381 }; 391 };
382 self.obligations.push(Obligation::Trait(trait_ref)); 392 self.obligations.push(Obligation::Trait(trait_ref));
383 self.obligations.push(Obligation::Projection(projection)); 393 self.obligations.push(Obligation::Projection(projection));
384 self.resolve_ty_as_possible(ty) 394 self.resolve_ty_as_possible(ty)
385 } 395 }
386 None => Ty::Unknown, 396 None => self.err_ty(),
387 } 397 }
388 } 398 }
389 399
@@ -395,8 +405,10 @@ impl<'a> InferenceContext<'a> {
395 /// to do it as well. 405 /// to do it as well.
396 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { 406 fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty {
397 let ty = self.resolve_ty_as_possible(ty); 407 let ty = self.resolve_ty_as_possible(ty);
398 ty.fold(&mut |ty| match ty { 408 ty.fold(&mut |ty| match ty.interned(&Interner) {
399 Ty::Alias(AliasTy::Projection(proj_ty)) => self.normalize_projection_ty(proj_ty), 409 TyKind::Alias(AliasTy::Projection(proj_ty)) => {
410 self.normalize_projection_ty(proj_ty.clone())
411 }
400 _ => ty, 412 _ => ty,
401 }) 413 })
402 } 414 }
@@ -412,7 +424,7 @@ impl<'a> InferenceContext<'a> {
412 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) { 424 fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) {
413 let path = match path { 425 let path = match path {
414 Some(path) => path, 426 Some(path) => path,
415 None => return (Ty::Unknown, None), 427 None => return (self.err_ty(), None),
416 }; 428 };
417 let resolver = &self.resolver; 429 let resolver = &self.resolver;
418 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 430 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
@@ -421,30 +433,30 @@ impl<'a> InferenceContext<'a> {
421 let (resolution, unresolved) = 433 let (resolution, unresolved) =
422 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) { 434 match resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
423 Some(it) => it, 435 Some(it) => it,
424 None => return (Ty::Unknown, None), 436 None => return (self.err_ty(), None),
425 }; 437 };
426 return match resolution { 438 return match resolution {
427 TypeNs::AdtId(AdtId::StructId(strukt)) => { 439 TypeNs::AdtId(AdtId::StructId(strukt)) => {
428 let substs = Ty::substs_from_path(&ctx, path, strukt.into(), true); 440 let substs = ctx.substs_from_path(path, strukt.into(), true);
429 let ty = self.db.ty(strukt.into()); 441 let ty = self.db.ty(strukt.into());
430 let ty = self.insert_type_vars(ty.subst(&substs)); 442 let ty = self.insert_type_vars(ty.subst(&substs));
431 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved) 443 forbid_unresolved_segments((ty, Some(strukt.into())), unresolved)
432 } 444 }
433 TypeNs::AdtId(AdtId::UnionId(u)) => { 445 TypeNs::AdtId(AdtId::UnionId(u)) => {
434 let substs = Ty::substs_from_path(&ctx, path, u.into(), true); 446 let substs = ctx.substs_from_path(path, u.into(), true);
435 let ty = self.db.ty(u.into()); 447 let ty = self.db.ty(u.into());
436 let ty = self.insert_type_vars(ty.subst(&substs)); 448 let ty = self.insert_type_vars(ty.subst(&substs));
437 forbid_unresolved_segments((ty, Some(u.into())), unresolved) 449 forbid_unresolved_segments((ty, Some(u.into())), unresolved)
438 } 450 }
439 TypeNs::EnumVariantId(var) => { 451 TypeNs::EnumVariantId(var) => {
440 let substs = Ty::substs_from_path(&ctx, path, var.into(), true); 452 let substs = ctx.substs_from_path(path, var.into(), true);
441 let ty = self.db.ty(var.parent.into()); 453 let ty = self.db.ty(var.parent.into());
442 let ty = self.insert_type_vars(ty.subst(&substs)); 454 let ty = self.insert_type_vars(ty.subst(&substs));
443 forbid_unresolved_segments((ty, Some(var.into())), unresolved) 455 forbid_unresolved_segments((ty, Some(var.into())), unresolved)
444 } 456 }
445 TypeNs::SelfType(impl_id) => { 457 TypeNs::SelfType(impl_id) => {
446 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 458 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
447 let substs = Substs::type_params_for_generics(&generics); 459 let substs = Substs::type_params_for_generics(self.db, &generics);
448 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 460 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
449 match unresolved { 461 match unresolved {
450 None => { 462 None => {
@@ -462,11 +474,11 @@ impl<'a> InferenceContext<'a> {
462 } 474 }
463 } 475 }
464 // FIXME potentially resolve assoc type 476 // FIXME potentially resolve assoc type
465 (Ty::Unknown, None) 477 (self.err_ty(), None)
466 } 478 }
467 Some(_) => { 479 Some(_) => {
468 // FIXME diagnostic 480 // FIXME diagnostic
469 (Ty::Unknown, None) 481 (self.err_ty(), None)
470 } 482 }
471 } 483 }
472 } 484 }
@@ -480,15 +492,15 @@ impl<'a> InferenceContext<'a> {
480 } 492 }
481 TypeNs::AdtSelfType(_) => { 493 TypeNs::AdtSelfType(_) => {
482 // FIXME this could happen in array size expressions, once we're checking them 494 // FIXME this could happen in array size expressions, once we're checking them
483 (Ty::Unknown, None) 495 (self.err_ty(), None)
484 } 496 }
485 TypeNs::GenericParam(_) => { 497 TypeNs::GenericParam(_) => {
486 // FIXME potentially resolve assoc type 498 // FIXME potentially resolve assoc type
487 (Ty::Unknown, None) 499 (self.err_ty(), None)
488 } 500 }
489 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => { 501 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::TraitId(_) => {
490 // FIXME diagnostic 502 // FIXME diagnostic
491 (Ty::Unknown, None) 503 (self.err_ty(), None)
492 } 504 }
493 }; 505 };
494 506
@@ -500,7 +512,7 @@ impl<'a> InferenceContext<'a> {
500 result 512 result
501 } else { 513 } else {
502 // FIXME diagnostic 514 // FIXME diagnostic
503 (Ty::Unknown, None) 515 (TyKind::Unknown.intern(&Interner), None)
504 } 516 }
505 } 517 }
506 518
@@ -529,7 +541,7 @@ impl<'a> InferenceContext<'a> {
529 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) 541 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
530 .with_impl_trait_mode(ImplTraitLoweringMode::Param); 542 .with_impl_trait_mode(ImplTraitLoweringMode::Param);
531 let param_tys = 543 let param_tys =
532 data.params.iter().map(|type_ref| Ty::from_hir(&ctx, type_ref)).collect::<Vec<_>>(); 544 data.params.iter().map(|type_ref| ctx.lower_ty(type_ref)).collect::<Vec<_>>();
533 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) { 545 for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) {
534 let ty = self.insert_type_vars(ty); 546 let ty = self.insert_type_vars(ty);
535 let ty = self.normalize_associated_types_in(ty); 547 let ty = self.normalize_associated_types_in(ty);
@@ -711,12 +723,12 @@ impl Expectation {
711 723
712 /// This expresses no expectation on the type. 724 /// This expresses no expectation on the type.
713 fn none() -> Self { 725 fn none() -> Self {
714 Expectation { ty: Ty::Unknown, rvalue_hint: false } 726 Expectation { ty: TyKind::Unknown.intern(&Interner), rvalue_hint: false }
715 } 727 }
716 728
717 fn coercion_target(&self) -> &Ty { 729 fn coercion_target(&self) -> &Ty {
718 if self.rvalue_hint { 730 if self.rvalue_hint {
719 &Ty::Unknown 731 &Ty(TyKind::Unknown)
720 } else { 732 } else {
721 &self.ty 733 &self.ty
722 } 734 }
diff --git a/crates/hir_ty/src/infer/coerce.rs b/crates/hir_ty/src/infer/coerce.rs
index 7e8846f27..36670043a 100644
--- a/crates/hir_ty/src/infer/coerce.rs
+++ b/crates/hir_ty/src/infer/coerce.rs
@@ -7,7 +7,7 @@
7use chalk_ir::{Mutability, TyVariableKind}; 7use chalk_ir::{Mutability, TyVariableKind};
8use hir_def::lang_item::LangItemTarget; 8use hir_def::lang_item::LangItemTarget;
9 9
10use crate::{autoderef, traits::Solution, Obligation, Substs, TraitRef, Ty}; 10use crate::{autoderef, traits::Solution, Interner, Obligation, Substs, TraitRef, Ty, TyKind};
11 11
12use super::{InEnvironment, InferenceContext}; 12use super::{InEnvironment, InferenceContext};
13 13
@@ -33,7 +33,9 @@ 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::FnDef(..), Ty::FnDef(..)) = (ty1, ty2) { 36 if let (TyKind::FnDef(..), TyKind::FnDef(..)) =
37 (ty1.interned(&Interner), ty2.interned(&Interner))
38 {
37 cov_mark::hit!(coerce_fn_reification); 39 cov_mark::hit!(coerce_fn_reification);
38 // Special case: two function types. Try to coerce both to 40 // Special case: two function types. Try to coerce both to
39 // pointers to have a chance at getting a match. See 41 // pointers to have a chance at getting a match. See
@@ -51,13 +53,13 @@ impl<'a> InferenceContext<'a> {
51 } 53 }
52 54
53 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { 55 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
54 match (&from_ty, to_ty) { 56 match (from_ty.interned(&Interner), to_ty.interned(&Interner)) {
55 // Never type will make type variable to fallback to Never Type instead of Unknown. 57 // Never type will make type variable to fallback to Never Type instead of Unknown.
56 (Ty::Never, Ty::InferenceVar(tv, TyVariableKind::General)) => { 58 (TyKind::Never, TyKind::InferenceVar(tv, TyVariableKind::General)) => {
57 self.table.type_variable_table.set_diverging(*tv, true); 59 self.table.type_variable_table.set_diverging(*tv, true);
58 return true; 60 return true;
59 } 61 }
60 (Ty::Never, _) => return true, 62 (TyKind::Never, _) => return true,
61 63
62 // Trivial cases, this should go after `never` check to 64 // Trivial cases, this should go after `never` check to
63 // avoid infer result type to be never 65 // avoid infer result type to be never
@@ -69,33 +71,33 @@ impl<'a> InferenceContext<'a> {
69 } 71 }
70 72
71 // Pointer weakening and function to pointer 73 // Pointer weakening and function to pointer
72 match (&mut from_ty, to_ty) { 74 match (&mut from_ty.0, to_ty.interned(&Interner)) {
73 // `*mut T` -> `*const T` 75 // `*mut T` -> `*const T`
74 // `&mut T` -> `&T` 76 // `&mut T` -> `&T`
75 (Ty::Raw(m1, ..), Ty::Raw(m2 @ Mutability::Not, ..)) 77 (TyKind::Raw(m1, ..), TyKind::Raw(m2 @ Mutability::Not, ..))
76 | (Ty::Ref(m1, ..), Ty::Ref(m2 @ Mutability::Not, ..)) => { 78 | (TyKind::Ref(m1, ..), TyKind::Ref(m2 @ Mutability::Not, ..)) => {
77 *m1 = *m2; 79 *m1 = *m2;
78 } 80 }
79 // `&T` -> `*const T` 81 // `&T` -> `*const T`
80 // `&mut T` -> `*mut T`/`*const T` 82 // `&mut T` -> `*mut T`/`*const T`
81 (Ty::Ref(.., substs), &Ty::Raw(m2 @ Mutability::Not, ..)) 83 (TyKind::Ref(.., substs), &TyKind::Raw(m2 @ Mutability::Not, ..))
82 | (Ty::Ref(Mutability::Mut, substs), &Ty::Raw(m2, ..)) => { 84 | (TyKind::Ref(Mutability::Mut, substs), &TyKind::Raw(m2, ..)) => {
83 from_ty = Ty::Raw(m2, substs.clone()); 85 from_ty = TyKind::Raw(m2, substs.clone()).intern(&Interner);
84 } 86 }
85 87
86 // Illegal mutability conversion 88 // Illegal mutability conversion
87 (Ty::Raw(Mutability::Not, ..), Ty::Raw(Mutability::Mut, ..)) 89 (TyKind::Raw(Mutability::Not, ..), TyKind::Raw(Mutability::Mut, ..))
88 | (Ty::Ref(Mutability::Not, ..), Ty::Ref(Mutability::Mut, ..)) => return false, 90 | (TyKind::Ref(Mutability::Not, ..), TyKind::Ref(Mutability::Mut, ..)) => return false,
89 91
90 // `{function_type}` -> `fn()` 92 // `{function_type}` -> `fn()`
91 (Ty::FnDef(..), Ty::Function { .. }) => match from_ty.callable_sig(self.db) { 93 (TyKind::FnDef(..), TyKind::Function { .. }) => match from_ty.callable_sig(self.db) {
92 None => return false, 94 None => return false,
93 Some(sig) => { 95 Some(sig) => {
94 from_ty = Ty::fn_ptr(sig); 96 from_ty = Ty::fn_ptr(sig);
95 } 97 }
96 }, 98 },
97 99
98 (Ty::Closure(.., substs), Ty::Function { .. }) => { 100 (TyKind::Closure(.., substs), TyKind::Function { .. }) => {
99 from_ty = substs[0].clone(); 101 from_ty = substs[0].clone();
100 } 102 }
101 103
@@ -107,9 +109,11 @@ impl<'a> InferenceContext<'a> {
107 } 109 }
108 110
109 // Auto Deref if cannot coerce 111 // Auto Deref if cannot coerce
110 match (&from_ty, to_ty) { 112 match (from_ty.interned(&Interner), to_ty.interned(&Interner)) {
111 // FIXME: DerefMut 113 // FIXME: DerefMut
112 (Ty::Ref(_, st1), Ty::Ref(_, st2)) => self.unify_autoderef_behind_ref(&st1[0], &st2[0]), 114 (TyKind::Ref(_, st1), TyKind::Ref(_, st2)) => {
115 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
116 }
113 117
114 // Otherwise, normal unify 118 // Otherwise, normal unify
115 _ => self.unify(&from_ty, to_ty), 119 _ => self.unify(&from_ty, to_ty),
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs
index 262177ffb..55163c963 100644
--- a/crates/hir_ty/src/infer/expr.rs
+++ b/crates/hir_ty/src/infer/expr.rs
@@ -18,10 +18,11 @@ use crate::{
18 lower::lower_to_chalk_mutability, 18 lower::lower_to_chalk_mutability,
19 method_resolution, op, 19 method_resolution, op,
20 primitive::{self, UintTy}, 20 primitive::{self, UintTy},
21 traits::{FnTrait, InEnvironment}, 21 to_assoc_type_id,
22 traits::{chalk::from_chalk, FnTrait, InEnvironment},
22 utils::{generics, variant_data, Generics}, 23 utils::{generics, variant_data, Generics},
23 AdtId, Binders, CallableDefId, FnPointer, FnSig, Obligation, OpaqueTyId, Rawness, Scalar, 24 AdtId, Binders, CallableDefId, FnPointer, FnSig, Interner, Obligation, Rawness, Scalar, Substs,
24 Substs, TraitRef, Ty, 25 TraitRef, Ty, TyKind,
25}; 26};
26 27
27use super::{ 28use super::{
@@ -57,7 +58,7 @@ impl<'a> InferenceContext<'a> {
57 // Return actual type when type mismatch. 58 // Return actual type when type mismatch.
58 // This is needed for diagnostic when return type mismatch. 59 // This is needed for diagnostic when return type mismatch.
59 ty 60 ty
60 } else if expected.coercion_target() == &Ty::Unknown { 61 } else if expected.coercion_target().is_unknown() {
61 ty 62 ty
62 } else { 63 } else {
63 expected.ty.clone() 64 expected.ty.clone()
@@ -84,7 +85,7 @@ impl<'a> InferenceContext<'a> {
84 arg_tys.push(arg); 85 arg_tys.push(arg);
85 } 86 }
86 let parameters = param_builder.build(); 87 let parameters = param_builder.build();
87 let arg_ty = Ty::Tuple(num_args, parameters); 88 let arg_ty = TyKind::Tuple(num_args, parameters).intern(&Interner);
88 let substs = 89 let substs =
89 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build(); 90 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build();
90 91
@@ -97,8 +98,10 @@ impl<'a> InferenceContext<'a> {
97 }); 98 });
98 if self.db.trait_solve(krate, goal.value).is_some() { 99 if self.db.trait_solve(krate, goal.value).is_some() {
99 self.obligations.push(implements_fn_trait); 100 self.obligations.push(implements_fn_trait);
100 let output_proj_ty = 101 let output_proj_ty = crate::ProjectionTy {
101 crate::ProjectionTy { associated_ty: output_assoc_type, parameters: substs }; 102 associated_ty_id: to_assoc_type_id(output_assoc_type),
103 substitution: substs,
104 };
102 let return_ty = self.normalize_projection_ty(output_proj_ty); 105 let return_ty = self.normalize_projection_ty(output_proj_ty);
103 Some((arg_tys, return_ty)) 106 Some((arg_tys, return_ty))
104 } else { 107 } else {
@@ -116,10 +119,13 @@ impl<'a> InferenceContext<'a> {
116 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { 119 fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
117 let body = Arc::clone(&self.body); // avoid borrow checker problem 120 let body = Arc::clone(&self.body); // avoid borrow checker problem
118 let ty = match &body[tgt_expr] { 121 let ty = match &body[tgt_expr] {
119 Expr::Missing => Ty::Unknown, 122 Expr::Missing => self.err_ty(),
120 Expr::If { condition, then_branch, else_branch } => { 123 Expr::If { condition, then_branch, else_branch } => {
121 // if let is desugared to match, so this is always simple if 124 // if let is desugared to match, so this is always simple if
122 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool))); 125 self.infer_expr(
126 *condition,
127 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
128 );
123 129
124 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe); 130 let condition_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
125 let mut both_arms_diverge = Diverges::Always; 131 let mut both_arms_diverge = Diverges::Always;
@@ -167,14 +173,15 @@ impl<'a> InferenceContext<'a> {
167 Expr::TryBlock { body } => { 173 Expr::TryBlock { body } => {
168 let _inner = self.infer_expr(*body, expected); 174 let _inner = self.infer_expr(*body, expected);
169 // FIXME should be std::result::Result<{inner}, _> 175 // FIXME should be std::result::Result<{inner}, _>
170 Ty::Unknown 176 self.err_ty()
171 } 177 }
172 Expr::Async { body } => { 178 Expr::Async { body } => {
173 // Use the first type parameter as the output type of future. 179 // Use the first type parameter as the output type of future.
174 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType> 180 // existenail type AsyncBlockImplTrait<InnerType>: Future<Output = InnerType>
175 let inner_ty = self.infer_expr(*body, &Expectation::none()); 181 let inner_ty = self.infer_expr(*body, &Expectation::none());
176 let opaque_ty_id = OpaqueTyId::AsyncBlockTypeImplTrait(self.owner, *body); 182 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
177 Ty::OpaqueType(opaque_ty_id, Substs::single(inner_ty)) 183 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
184 TyKind::OpaqueType(opaque_ty_id, Substs::single(inner_ty)).intern(&Interner)
178 } 185 }
179 Expr::Loop { body, label } => { 186 Expr::Loop { body, label } => {
180 self.breakables.push(BreakableContext { 187 self.breakables.push(BreakableContext {
@@ -192,17 +199,20 @@ impl<'a> InferenceContext<'a> {
192 if ctxt.may_break { 199 if ctxt.may_break {
193 ctxt.break_ty 200 ctxt.break_ty
194 } else { 201 } else {
195 Ty::Never 202 TyKind::Never.intern(&Interner)
196 } 203 }
197 } 204 }
198 Expr::While { condition, body, label } => { 205 Expr::While { condition, body, label } => {
199 self.breakables.push(BreakableContext { 206 self.breakables.push(BreakableContext {
200 may_break: false, 207 may_break: false,
201 break_ty: Ty::Unknown, 208 break_ty: self.err_ty(),
202 label: label.map(|label| self.body[label].name.clone()), 209 label: label.map(|label| self.body[label].name.clone()),
203 }); 210 });
204 // while let is desugared to a match loop, so this is always simple while 211 // while let is desugared to a match loop, so this is always simple while
205 self.infer_expr(*condition, &Expectation::has_type(Ty::Scalar(Scalar::Bool))); 212 self.infer_expr(
213 *condition,
214 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
215 );
206 self.infer_expr(*body, &Expectation::has_type(Ty::unit())); 216 self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
207 let _ctxt = self.breakables.pop().expect("breakable stack broken"); 217 let _ctxt = self.breakables.pop().expect("breakable stack broken");
208 // the body may not run, so it diverging doesn't mean we diverge 218 // the body may not run, so it diverging doesn't mean we diverge
@@ -214,7 +224,7 @@ impl<'a> InferenceContext<'a> {
214 224
215 self.breakables.push(BreakableContext { 225 self.breakables.push(BreakableContext {
216 may_break: false, 226 may_break: false,
217 break_ty: Ty::Unknown, 227 break_ty: self.err_ty(),
218 label: label.map(|label| self.body[label].name.clone()), 228 label: label.map(|label| self.body[label].name.clone()),
219 }); 229 });
220 let pat_ty = 230 let pat_ty =
@@ -249,12 +259,15 @@ impl<'a> InferenceContext<'a> {
249 None => self.table.new_type_var(), 259 None => self.table.new_type_var(),
250 }; 260 };
251 sig_tys.push(ret_ty.clone()); 261 sig_tys.push(ret_ty.clone());
252 let sig_ty = Ty::Function(FnPointer { 262 let sig_ty = TyKind::Function(FnPointer {
253 num_args: sig_tys.len() - 1, 263 num_args: sig_tys.len() - 1,
254 sig: FnSig { variadic: false }, 264 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
255 substs: Substs(sig_tys.clone().into()), 265 substs: Substs(sig_tys.clone().into()),
256 }); 266 })
257 let closure_ty = Ty::Closure(self.owner, tgt_expr, Substs::single(sig_ty)); 267 .intern(&Interner);
268 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
269 let closure_ty =
270 TyKind::Closure(closure_id, Substs::single(sig_ty)).intern(&Interner);
258 271
259 // Eagerly try to relate the closure type with the expected 272 // Eagerly try to relate the closure type with the expected
260 // type, otherwise we often won't have enough information to 273 // type, otherwise we often won't have enough information to
@@ -295,7 +308,7 @@ impl<'a> InferenceContext<'a> {
295 args.len(), 308 args.len(),
296 ) 309 )
297 }) 310 })
298 .unwrap_or((Vec::new(), Ty::Unknown)); 311 .unwrap_or((Vec::new(), self.err_ty()));
299 self.register_obligations_for_call(&callee_ty); 312 self.register_obligations_for_call(&callee_ty);
300 self.check_call_arguments(args, &param_tys); 313 self.check_call_arguments(args, &param_tys);
301 self.normalize_associated_types_in(ret_ty) 314 self.normalize_associated_types_in(ret_ty)
@@ -305,8 +318,11 @@ impl<'a> InferenceContext<'a> {
305 Expr::Match { expr, arms } => { 318 Expr::Match { expr, arms } => {
306 let input_ty = self.infer_expr(*expr, &Expectation::none()); 319 let input_ty = self.infer_expr(*expr, &Expectation::none());
307 320
308 let mut result_ty = 321 let mut result_ty = if arms.is_empty() {
309 if arms.is_empty() { Ty::Never } else { self.table.new_type_var() }; 322 TyKind::Never.intern(&Interner)
323 } else {
324 self.table.new_type_var()
325 };
310 326
311 let matchee_diverges = self.diverges; 327 let matchee_diverges = self.diverges;
312 let mut all_arms_diverge = Diverges::Always; 328 let mut all_arms_diverge = Diverges::Always;
@@ -317,7 +333,7 @@ impl<'a> InferenceContext<'a> {
317 if let Some(guard_expr) = arm.guard { 333 if let Some(guard_expr) = arm.guard {
318 self.infer_expr( 334 self.infer_expr(
319 guard_expr, 335 guard_expr,
320 &Expectation::has_type(Ty::Scalar(Scalar::Bool)), 336 &Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner)),
321 ); 337 );
322 } 338 }
323 339
@@ -333,9 +349,9 @@ impl<'a> InferenceContext<'a> {
333 Expr::Path(p) => { 349 Expr::Path(p) => {
334 // FIXME this could be more efficient... 350 // FIXME this could be more efficient...
335 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr); 351 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
336 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) 352 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(self.err_ty())
337 } 353 }
338 Expr::Continue { .. } => Ty::Never, 354 Expr::Continue { .. } => TyKind::Never.intern(&Interner),
339 Expr::Break { expr, label } => { 355 Expr::Break { expr, label } => {
340 let val_ty = if let Some(expr) = expr { 356 let val_ty = if let Some(expr) = expr {
341 self.infer_expr(*expr, &Expectation::none()) 357 self.infer_expr(*expr, &Expectation::none())
@@ -347,7 +363,7 @@ impl<'a> InferenceContext<'a> {
347 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) { 363 if let Some(ctxt) = find_breakable(&mut self.breakables, label.as_ref()) {
348 ctxt.break_ty.clone() 364 ctxt.break_ty.clone()
349 } else { 365 } else {
350 Ty::Unknown 366 self.err_ty()
351 }; 367 };
352 368
353 let merged_type = self.coerce_merge_branch(&last_ty, &val_ty); 369 let merged_type = self.coerce_merge_branch(&last_ty, &val_ty);
@@ -360,7 +376,7 @@ impl<'a> InferenceContext<'a> {
360 expr: tgt_expr, 376 expr: tgt_expr,
361 }); 377 });
362 } 378 }
363 Ty::Never 379 TyKind::Never.intern(&Interner)
364 } 380 }
365 Expr::Return { expr } => { 381 Expr::Return { expr } => {
366 if let Some(expr) = expr { 382 if let Some(expr) = expr {
@@ -369,14 +385,14 @@ impl<'a> InferenceContext<'a> {
369 let unit = Ty::unit(); 385 let unit = Ty::unit();
370 self.coerce(&unit, &self.return_ty.clone()); 386 self.coerce(&unit, &self.return_ty.clone());
371 } 387 }
372 Ty::Never 388 TyKind::Never.intern(&Interner)
373 } 389 }
374 Expr::Yield { expr } => { 390 Expr::Yield { expr } => {
375 // FIXME: track yield type for coercion 391 // FIXME: track yield type for coercion
376 if let Some(expr) = expr { 392 if let Some(expr) = expr {
377 self.infer_expr(*expr, &Expectation::none()); 393 self.infer_expr(*expr, &Expectation::none());
378 } 394 }
379 Ty::Never 395 TyKind::Never.intern(&Interner)
380 } 396 }
381 Expr::RecordLit { path, fields, spread } => { 397 Expr::RecordLit { path, fields, spread } => {
382 let (ty, def_id) = self.resolve_variant(path.as_ref()); 398 let (ty, def_id) = self.resolve_variant(path.as_ref());
@@ -404,8 +420,9 @@ impl<'a> InferenceContext<'a> {
404 if let Some(field_def) = field_def { 420 if let Some(field_def) = field_def {
405 self.result.record_field_resolutions.insert(field.expr, field_def); 421 self.result.record_field_resolutions.insert(field.expr, field_def);
406 } 422 }
407 let field_ty = field_def 423 let field_ty = field_def.map_or(self.err_ty(), |it| {
408 .map_or(Ty::Unknown, |it| field_types[it.local_id].clone().subst(&substs)); 424 field_types[it.local_id].clone().subst(&substs)
425 });
409 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); 426 self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
410 } 427 }
411 if let Some(expr) = spread { 428 if let Some(expr) = spread {
@@ -424,27 +441,33 @@ impl<'a> InferenceContext<'a> {
424 environment: self.trait_env.clone(), 441 environment: self.trait_env.clone(),
425 }, 442 },
426 ) 443 )
427 .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { 444 .find_map(|derefed_ty| {
428 Ty::Tuple(_, substs) => { 445 match canonicalized.decanonicalize_ty(derefed_ty.value).interned(&Interner) {
429 name.as_tuple_index().and_then(|idx| substs.0.get(idx).cloned()) 446 TyKind::Tuple(_, substs) => {
430 } 447 name.as_tuple_index().and_then(|idx| substs.0.get(idx).cloned())
431 Ty::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => { 448 }
432 self.db.struct_data(s).variant_data.field(name).map(|local_id| { 449 TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => {
433 let field = FieldId { parent: s.into(), local_id }; 450 self.db.struct_data(*s).variant_data.field(name).map(|local_id| {
434 self.write_field_resolution(tgt_expr, field); 451 let field = FieldId { parent: (*s).into(), local_id };
435 self.db.field_types(s.into())[field.local_id].clone().subst(&parameters) 452 self.write_field_resolution(tgt_expr, field);
436 }) 453 self.db.field_types((*s).into())[field.local_id]
437 } 454 .clone()
438 Ty::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => { 455 .subst(&parameters)
439 self.db.union_data(u).variant_data.field(name).map(|local_id| { 456 })
440 let field = FieldId { parent: u.into(), local_id }; 457 }
441 self.write_field_resolution(tgt_expr, field); 458 TyKind::Adt(AdtId(hir_def::AdtId::UnionId(u)), parameters) => {
442 self.db.field_types(u.into())[field.local_id].clone().subst(&parameters) 459 self.db.union_data(*u).variant_data.field(name).map(|local_id| {
443 }) 460 let field = FieldId { parent: (*u).into(), local_id };
461 self.write_field_resolution(tgt_expr, field);
462 self.db.field_types((*u).into())[field.local_id]
463 .clone()
464 .subst(&parameters)
465 })
466 }
467 _ => None,
444 } 468 }
445 _ => None,
446 }) 469 })
447 .unwrap_or(Ty::Unknown); 470 .unwrap_or(self.err_ty());
448 let ty = self.insert_type_vars(ty); 471 let ty = self.insert_type_vars(ty);
449 self.normalize_associated_types_in(ty) 472 self.normalize_associated_types_in(ty)
450 } 473 }
@@ -481,9 +504,10 @@ impl<'a> InferenceContext<'a> {
481 }; 504 };
482 let inner_ty = self.infer_expr_inner(*expr, &expectation); 505 let inner_ty = self.infer_expr_inner(*expr, &expectation);
483 match rawness { 506 match rawness {
484 Rawness::RawPtr => Ty::Raw(mutability, Substs::single(inner_ty)), 507 Rawness::RawPtr => TyKind::Raw(mutability, Substs::single(inner_ty)),
485 Rawness::Ref => Ty::Ref(mutability, Substs::single(inner_ty)), 508 Rawness::Ref => TyKind::Ref(mutability, Substs::single(inner_ty)),
486 } 509 }
510 .intern(&Interner)
487 } 511 }
488 Expr::Box { expr } => { 512 Expr::Box { expr } => {
489 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 513 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
@@ -499,7 +523,7 @@ impl<'a> InferenceContext<'a> {
499 sb = sb.fill(repeat_with(|| self.table.new_type_var())); 523 sb = sb.fill(repeat_with(|| self.table.new_type_var()));
500 Ty::adt_ty(box_, sb.build()) 524 Ty::adt_ty(box_, sb.build())
501 } else { 525 } else {
502 Ty::Unknown 526 self.err_ty()
503 } 527 }
504 } 528 }
505 Expr::UnaryOp { expr, op } => { 529 Expr::UnaryOp { expr, op } => {
@@ -519,31 +543,31 @@ impl<'a> InferenceContext<'a> {
519 Some(derefed_ty) => { 543 Some(derefed_ty) => {
520 canonicalized.decanonicalize_ty(derefed_ty.value) 544 canonicalized.decanonicalize_ty(derefed_ty.value)
521 } 545 }
522 None => Ty::Unknown, 546 None => self.err_ty(),
523 } 547 }
524 } 548 }
525 None => Ty::Unknown, 549 None => self.err_ty(),
526 }, 550 },
527 UnaryOp::Neg => { 551 UnaryOp::Neg => {
528 match &inner_ty { 552 match inner_ty.interned(&Interner) {
529 // Fast path for builtins 553 // Fast path for builtins
530 Ty::Scalar(Scalar::Int(_)) 554 TyKind::Scalar(Scalar::Int(_))
531 | Ty::Scalar(Scalar::Uint(_)) 555 | TyKind::Scalar(Scalar::Uint(_))
532 | Ty::Scalar(Scalar::Float(_)) 556 | TyKind::Scalar(Scalar::Float(_))
533 | Ty::InferenceVar(_, TyVariableKind::Integer) 557 | TyKind::InferenceVar(_, TyVariableKind::Integer)
534 | Ty::InferenceVar(_, TyVariableKind::Float) => inner_ty, 558 | TyKind::InferenceVar(_, TyVariableKind::Float) => inner_ty,
535 // Otherwise we resolve via the std::ops::Neg trait 559 // Otherwise we resolve via the std::ops::Neg trait
536 _ => self 560 _ => self
537 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()), 561 .resolve_associated_type(inner_ty, self.resolve_ops_neg_output()),
538 } 562 }
539 } 563 }
540 UnaryOp::Not => { 564 UnaryOp::Not => {
541 match &inner_ty { 565 match inner_ty.interned(&Interner) {
542 // Fast path for builtins 566 // Fast path for builtins
543 Ty::Scalar(Scalar::Bool) 567 TyKind::Scalar(Scalar::Bool)
544 | Ty::Scalar(Scalar::Int(_)) 568 | TyKind::Scalar(Scalar::Int(_))
545 | Ty::Scalar(Scalar::Uint(_)) 569 | TyKind::Scalar(Scalar::Uint(_))
546 | Ty::InferenceVar(_, TyVariableKind::Integer) => inner_ty, 570 | TyKind::InferenceVar(_, TyVariableKind::Integer) => inner_ty,
547 // Otherwise we resolve via the std::ops::Not trait 571 // Otherwise we resolve via the std::ops::Not trait
548 _ => self 572 _ => self
549 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()), 573 .resolve_associated_type(inner_ty, self.resolve_ops_not_output()),
@@ -554,7 +578,9 @@ impl<'a> InferenceContext<'a> {
554 Expr::BinaryOp { lhs, rhs, op } => match op { 578 Expr::BinaryOp { lhs, rhs, op } => match op {
555 Some(op) => { 579 Some(op) => {
556 let lhs_expectation = match op { 580 let lhs_expectation = match op {
557 BinaryOp::LogicOp(..) => Expectation::has_type(Ty::Scalar(Scalar::Bool)), 581 BinaryOp::LogicOp(..) => {
582 Expectation::has_type(TyKind::Scalar(Scalar::Bool).intern(&Interner))
583 }
558 _ => Expectation::none(), 584 _ => Expectation::none(),
559 }; 585 };
560 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); 586 let lhs_ty = self.infer_expr(*lhs, &lhs_expectation);
@@ -563,7 +589,7 @@ impl<'a> InferenceContext<'a> {
563 589
564 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone()); 590 let ret = op::binary_op_return_ty(*op, lhs_ty.clone(), rhs_ty.clone());
565 591
566 if ret == Ty::Unknown { 592 if ret.is_unknown() {
567 cov_mark::hit!(infer_expr_inner_binary_operator_overload); 593 cov_mark::hit!(infer_expr_inner_binary_operator_overload);
568 594
569 self.resolve_associated_type_with_params( 595 self.resolve_associated_type_with_params(
@@ -575,7 +601,7 @@ impl<'a> InferenceContext<'a> {
575 ret 601 ret
576 } 602 }
577 } 603 }
578 _ => Ty::Unknown, 604 _ => self.err_ty(),
579 }, 605 },
580 Expr::Range { lhs, rhs, range_type } => { 606 Expr::Range { lhs, rhs, range_type } => {
581 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none())); 607 let lhs_ty = lhs.map(|e| self.infer_expr_inner(e, &Expectation::none()));
@@ -586,33 +612,33 @@ impl<'a> InferenceContext<'a> {
586 match (range_type, lhs_ty, rhs_ty) { 612 match (range_type, lhs_ty, rhs_ty) {
587 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() { 613 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
588 Some(adt) => Ty::adt_ty(adt, Substs::empty()), 614 Some(adt) => Ty::adt_ty(adt, Substs::empty()),
589 None => Ty::Unknown, 615 None => self.err_ty(),
590 }, 616 },
591 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() { 617 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
592 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 618 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
593 None => Ty::Unknown, 619 None => self.err_ty(),
594 }, 620 },
595 (RangeOp::Inclusive, None, Some(ty)) => { 621 (RangeOp::Inclusive, None, Some(ty)) => {
596 match self.resolve_range_to_inclusive() { 622 match self.resolve_range_to_inclusive() {
597 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 623 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
598 None => Ty::Unknown, 624 None => self.err_ty(),
599 } 625 }
600 } 626 }
601 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() { 627 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
602 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 628 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
603 None => Ty::Unknown, 629 None => self.err_ty(),
604 }, 630 },
605 (RangeOp::Inclusive, Some(_), Some(ty)) => { 631 (RangeOp::Inclusive, Some(_), Some(ty)) => {
606 match self.resolve_range_inclusive() { 632 match self.resolve_range_inclusive() {
607 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 633 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
608 None => Ty::Unknown, 634 None => self.err_ty(),
609 } 635 }
610 } 636 }
611 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() { 637 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
612 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 638 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)),
613 None => Ty::Unknown, 639 None => self.err_ty(),
614 }, 640 },
615 (RangeOp::Inclusive, _, None) => Ty::Unknown, 641 (RangeOp::Inclusive, _, None) => self.err_ty(),
616 } 642 }
617 } 643 }
618 Expr::Index { base, index } => { 644 Expr::Index { base, index } => {
@@ -631,19 +657,19 @@ impl<'a> InferenceContext<'a> {
631 index_trait, 657 index_trait,
632 ); 658 );
633 let self_ty = 659 let self_ty =
634 self_ty.map_or(Ty::Unknown, |t| canonicalized.decanonicalize_ty(t.value)); 660 self_ty.map_or(self.err_ty(), |t| canonicalized.decanonicalize_ty(t.value));
635 self.resolve_associated_type_with_params( 661 self.resolve_associated_type_with_params(
636 self_ty, 662 self_ty,
637 self.resolve_ops_index_output(), 663 self.resolve_ops_index_output(),
638 &[index_ty], 664 &[index_ty],
639 ) 665 )
640 } else { 666 } else {
641 Ty::Unknown 667 self.err_ty()
642 } 668 }
643 } 669 }
644 Expr::Tuple { exprs } => { 670 Expr::Tuple { exprs } => {
645 let mut tys = match &expected.ty { 671 let mut tys = match expected.ty.interned(&Interner) {
646 Ty::Tuple(_, substs) => substs 672 TyKind::Tuple(_, substs) => substs
647 .iter() 673 .iter()
648 .cloned() 674 .cloned()
649 .chain(repeat_with(|| self.table.new_type_var())) 675 .chain(repeat_with(|| self.table.new_type_var()))
@@ -656,11 +682,11 @@ impl<'a> InferenceContext<'a> {
656 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); 682 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
657 } 683 }
658 684
659 Ty::Tuple(tys.len(), Substs(tys.into())) 685 TyKind::Tuple(tys.len(), Substs(tys.into())).intern(&Interner)
660 } 686 }
661 Expr::Array(array) => { 687 Expr::Array(array) => {
662 let elem_ty = match &expected.ty { 688 let elem_ty = match expected.ty.interned(&Interner) {
663 Ty::Array(st) | Ty::Slice(st) => st.as_single().clone(), 689 TyKind::Array(st) | TyKind::Slice(st) => st.as_single().clone(),
664 _ => self.table.new_type_var(), 690 _ => self.table.new_type_var(),
665 }; 691 };
666 692
@@ -677,43 +703,51 @@ impl<'a> InferenceContext<'a> {
677 ); 703 );
678 self.infer_expr( 704 self.infer_expr(
679 *repeat, 705 *repeat,
680 &Expectation::has_type(Ty::Scalar(Scalar::Uint(UintTy::Usize))), 706 &Expectation::has_type(
707 TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner),
708 ),
681 ); 709 );
682 } 710 }
683 } 711 }
684 712
685 Ty::Array(Substs::single(elem_ty)) 713 TyKind::Array(Substs::single(elem_ty)).intern(&Interner)
686 } 714 }
687 Expr::Literal(lit) => match lit { 715 Expr::Literal(lit) => match lit {
688 Literal::Bool(..) => Ty::Scalar(Scalar::Bool), 716 Literal::Bool(..) => TyKind::Scalar(Scalar::Bool).intern(&Interner),
689 Literal::String(..) => Ty::Ref(Mutability::Not, Substs::single(Ty::Str)), 717 Literal::String(..) => {
718 TyKind::Ref(Mutability::Not, Substs::single(TyKind::Str.intern(&Interner)))
719 .intern(&Interner)
720 }
690 Literal::ByteString(..) => { 721 Literal::ByteString(..) => {
691 let byte_type = Ty::Scalar(Scalar::Uint(UintTy::U8)); 722 let byte_type = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(&Interner);
692 let array_type = Ty::Array(Substs::single(byte_type)); 723 let array_type = TyKind::Array(Substs::single(byte_type)).intern(&Interner);
693 Ty::Ref(Mutability::Not, Substs::single(array_type)) 724 TyKind::Ref(Mutability::Not, Substs::single(array_type)).intern(&Interner)
694 } 725 }
695 Literal::Char(..) => Ty::Scalar(Scalar::Char), 726 Literal::Char(..) => TyKind::Scalar(Scalar::Char).intern(&Interner),
696 Literal::Int(_v, ty) => match ty { 727 Literal::Int(_v, ty) => match ty {
697 Some(int_ty) => { 728 Some(int_ty) => {
698 Ty::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty))) 729 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(*int_ty)))
730 .intern(&Interner)
699 } 731 }
700 None => self.table.new_integer_var(), 732 None => self.table.new_integer_var(),
701 }, 733 },
702 Literal::Uint(_v, ty) => match ty { 734 Literal::Uint(_v, ty) => match ty {
703 Some(int_ty) => { 735 Some(int_ty) => {
704 Ty::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty))) 736 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(*int_ty)))
737 .intern(&Interner)
705 } 738 }
706 None => self.table.new_integer_var(), 739 None => self.table.new_integer_var(),
707 }, 740 },
708 Literal::Float(_v, ty) => match ty { 741 Literal::Float(_v, ty) => match ty {
709 Some(float_ty) => { 742 Some(float_ty) => {
710 Ty::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty))) 743 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(*float_ty)))
744 .intern(&Interner)
711 } 745 }
712 None => self.table.new_float_var(), 746 None => self.table.new_float_var(),
713 }, 747 },
714 }, 748 },
715 }; 749 };
716 // use a new type variable if we got Ty::Unknown here 750 // use a new type variable if we got unknown here
717 let ty = self.insert_type_vars_shallow(ty); 751 let ty = self.insert_type_vars_shallow(ty);
718 let ty = self.resolve_ty_as_possible(ty); 752 let ty = self.resolve_ty_as_possible(ty);
719 self.write_expr_ty(tgt_expr, ty.clone()); 753 self.write_expr_ty(tgt_expr, ty.clone());
@@ -730,7 +764,7 @@ impl<'a> InferenceContext<'a> {
730 match stmt { 764 match stmt {
731 Statement::Let { pat, type_ref, initializer } => { 765 Statement::Let { pat, type_ref, initializer } => {
732 let decl_ty = 766 let decl_ty =
733 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); 767 type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(self.err_ty());
734 768
735 // Always use the declared type when specified 769 // Always use the declared type when specified
736 let mut ty = decl_ty.clone(); 770 let mut ty = decl_ty.clone();
@@ -738,7 +772,7 @@ impl<'a> InferenceContext<'a> {
738 if let Some(expr) = initializer { 772 if let Some(expr) = initializer {
739 let actual_ty = 773 let actual_ty =
740 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); 774 self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone()));
741 if decl_ty == Ty::Unknown { 775 if decl_ty.is_unknown() {
742 ty = actual_ty; 776 ty = actual_ty;
743 } 777 }
744 } 778 }
@@ -802,7 +836,7 @@ impl<'a> InferenceContext<'a> {
802 self.write_method_resolution(tgt_expr, func); 836 self.write_method_resolution(tgt_expr, func);
803 (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into()))) 837 (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into())))
804 } 838 }
805 None => (receiver_ty, Binders::new(0, Ty::Unknown), None), 839 None => (receiver_ty, Binders::new(0, self.err_ty()), None),
806 }; 840 };
807 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); 841 let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty);
808 let method_ty = method_ty.subst(&substs); 842 let method_ty = method_ty.subst(&substs);
@@ -813,15 +847,17 @@ impl<'a> InferenceContext<'a> {
813 if !sig.params().is_empty() { 847 if !sig.params().is_empty() {
814 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) 848 (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
815 } else { 849 } else {
816 (Ty::Unknown, Vec::new(), sig.ret().clone()) 850 (self.err_ty(), Vec::new(), sig.ret().clone())
817 } 851 }
818 } 852 }
819 None => (Ty::Unknown, Vec::new(), Ty::Unknown), 853 None => (self.err_ty(), Vec::new(), self.err_ty()),
820 }; 854 };
821 // Apply autoref so the below unification works correctly 855 // Apply autoref so the below unification works correctly
822 // FIXME: return correct autorefs from lookup_method 856 // FIXME: return correct autorefs from lookup_method
823 let actual_receiver_ty = match expected_receiver_ty.as_reference() { 857 let actual_receiver_ty = match expected_receiver_ty.as_reference() {
824 Some((_, mutability)) => Ty::Ref(mutability, Substs::single(derefed_receiver_ty)), 858 Some((_, mutability)) => {
859 TyKind::Ref(mutability, Substs::single(derefed_receiver_ty)).intern(&Interner)
860 }
825 _ => derefed_receiver_ty, 861 _ => derefed_receiver_ty,
826 }; 862 };
827 self.unify(&expected_receiver_ty, &actual_receiver_ty); 863 self.unify(&expected_receiver_ty, &actual_receiver_ty);
@@ -837,7 +873,7 @@ impl<'a> InferenceContext<'a> {
837 // that we have more information about the types of arguments when we 873 // that we have more information about the types of arguments when we
838 // type-check the functions. This isn't really the right way to do this. 874 // type-check the functions. This isn't really the right way to do this.
839 for &check_closures in &[false, true] { 875 for &check_closures in &[false, true] {
840 let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); 876 let param_iter = param_tys.iter().cloned().chain(repeat(self.err_ty()));
841 for (&arg, param_ty) in args.iter().zip(param_iter) { 877 for (&arg, param_ty) in args.iter().zip(param_iter) {
842 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. }); 878 let is_closure = matches!(&self.body[arg], Expr::Lambda { .. });
843 if is_closure != check_closures { 879 if is_closure != check_closures {
@@ -867,7 +903,7 @@ impl<'a> InferenceContext<'a> {
867 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf { 903 if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
868 substs.push(receiver_ty.clone()); 904 substs.push(receiver_ty.clone());
869 } else { 905 } else {
870 substs.push(Ty::Unknown); 906 substs.push(self.err_ty());
871 } 907 }
872 } 908 }
873 } 909 }
@@ -891,14 +927,15 @@ impl<'a> InferenceContext<'a> {
891 }; 927 };
892 let supplied_params = substs.len(); 928 let supplied_params = substs.len();
893 for _ in supplied_params..total_len { 929 for _ in supplied_params..total_len {
894 substs.push(Ty::Unknown); 930 substs.push(self.err_ty());
895 } 931 }
896 assert_eq!(substs.len(), total_len); 932 assert_eq!(substs.len(), total_len);
897 Substs(substs.into()) 933 Substs(substs.into())
898 } 934 }
899 935
900 fn register_obligations_for_call(&mut self, callable_ty: &Ty) { 936 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
901 if let &Ty::FnDef(def, ref parameters) = callable_ty { 937 if let TyKind::FnDef(fn_def, parameters) = callable_ty.interned(&Interner) {
938 let def: CallableDefId = from_chalk(self.db, *fn_def);
902 let generic_predicates = self.db.generic_predicates(def.into()); 939 let generic_predicates = self.db.generic_predicates(def.into());
903 for predicate in generic_predicates.iter() { 940 for predicate in generic_predicates.iter() {
904 let predicate = predicate.clone().subst(parameters); 941 let predicate = predicate.clone().subst(parameters);
diff --git a/crates/hir_ty/src/infer/pat.rs b/crates/hir_ty/src/infer/pat.rs
index a0ac8d80f..a16755cda 100644
--- a/crates/hir_ty/src/infer/pat.rs
+++ b/crates/hir_ty/src/infer/pat.rs
@@ -12,7 +12,7 @@ use hir_def::{
12use hir_expand::name::Name; 12use hir_expand::name::Name;
13 13
14use super::{BindingMode, Expectation, InferenceContext}; 14use super::{BindingMode, Expectation, InferenceContext};
15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Substs, Ty}; 15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Interner, Substs, Ty, TyKind};
16 16
17impl<'a> InferenceContext<'a> { 17impl<'a> InferenceContext<'a> {
18 fn infer_tuple_struct_pat( 18 fn infer_tuple_struct_pat(
@@ -46,7 +46,7 @@ impl<'a> InferenceContext<'a> {
46 let expected_ty = var_data 46 let expected_ty = var_data
47 .as_ref() 47 .as_ref()
48 .and_then(|d| d.field(&Name::new_tuple_field(i))) 48 .and_then(|d| d.field(&Name::new_tuple_field(i)))
49 .map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs)); 49 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
50 let expected_ty = self.normalize_associated_types_in(expected_ty); 50 let expected_ty = self.normalize_associated_types_in(expected_ty);
51 self.infer_pat(subpat, &expected_ty, default_bm); 51 self.infer_pat(subpat, &expected_ty, default_bm);
52 } 52 }
@@ -80,8 +80,8 @@ impl<'a> InferenceContext<'a> {
80 self.result.record_pat_field_resolutions.insert(subpat.pat, field_def); 80 self.result.record_pat_field_resolutions.insert(subpat.pat, field_def);
81 } 81 }
82 82
83 let expected_ty = 83 let expected_ty = matching_field
84 matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs)); 84 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
85 let expected_ty = self.normalize_associated_types_in(expected_ty); 85 let expected_ty = self.normalize_associated_types_in(expected_ty);
86 self.infer_pat(subpat.pat, &expected_ty, default_bm); 86 self.infer_pat(subpat.pat, &expected_ty, default_bm);
87 } 87 }
@@ -129,7 +129,8 @@ impl<'a> InferenceContext<'a> {
129 None => (&args[..], &[][..]), 129 None => (&args[..], &[][..]),
130 }; 130 };
131 let n_uncovered_patterns = expectations.len().saturating_sub(args.len()); 131 let n_uncovered_patterns = expectations.len().saturating_sub(args.len());
132 let mut expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); 132 let err_ty = self.err_ty();
133 let mut expectations_iter = expectations.iter().chain(repeat(&err_ty));
133 let mut infer_pat = |(&pat, ty)| self.infer_pat(pat, ty, default_bm); 134 let mut infer_pat = |(&pat, ty)| self.infer_pat(pat, ty, default_bm);
134 135
135 let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + args.len()); 136 let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + args.len());
@@ -137,7 +138,7 @@ impl<'a> InferenceContext<'a> {
137 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned()); 138 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned());
138 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat)); 139 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat));
139 140
140 Ty::Tuple(inner_tys.len(), Substs(inner_tys.into())) 141 TyKind::Tuple(inner_tys.len(), Substs(inner_tys.into())).intern(&Interner)
141 } 142 }
142 Pat::Or(ref pats) => { 143 Pat::Or(ref pats) => {
143 if let Some((first_pat, rest)) = pats.split_first() { 144 if let Some((first_pat, rest)) = pats.split_first() {
@@ -147,7 +148,7 @@ impl<'a> InferenceContext<'a> {
147 } 148 }
148 ty 149 ty
149 } else { 150 } else {
150 Ty::Unknown 151 self.err_ty()
151 } 152 }
152 } 153 }
153 Pat::Ref { pat, mutability } => { 154 Pat::Ref { pat, mutability } => {
@@ -159,10 +160,10 @@ impl<'a> InferenceContext<'a> {
159 } 160 }
160 inner_ty 161 inner_ty
161 } 162 }
162 _ => &Ty::Unknown, 163 _ => &Ty(TyKind::Unknown),
163 }; 164 };
164 let subty = self.infer_pat(*pat, expectation, default_bm); 165 let subty = self.infer_pat(*pat, expectation, default_bm);
165 Ty::Ref(mutability, Substs::single(subty)) 166 TyKind::Ref(mutability, Substs::single(subty)).intern(&Interner)
166 } 167 }
167 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat( 168 Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat(
168 p.as_ref(), 169 p.as_ref(),
@@ -178,7 +179,7 @@ impl<'a> InferenceContext<'a> {
178 Pat::Path(path) => { 179 Pat::Path(path) => {
179 // FIXME use correct resolver for the surrounding expression 180 // FIXME use correct resolver for the surrounding expression
180 let resolver = self.resolver.clone(); 181 let resolver = self.resolver.clone();
181 self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) 182 self.infer_path(&resolver, &path, pat.into()).unwrap_or(self.err_ty())
182 } 183 }
183 Pat::Bind { mode, name: _, subpat } => { 184 Pat::Bind { mode, name: _, subpat } => {
184 let mode = if mode == &BindingAnnotation::Unannotated { 185 let mode = if mode == &BindingAnnotation::Unannotated {
@@ -195,7 +196,7 @@ impl<'a> InferenceContext<'a> {
195 196
196 let bound_ty = match mode { 197 let bound_ty = match mode {
197 BindingMode::Ref(mutability) => { 198 BindingMode::Ref(mutability) => {
198 Ty::Ref(mutability, Substs::single(inner_ty.clone())) 199 TyKind::Ref(mutability, Substs::single(inner_ty.clone())).intern(&Interner)
199 } 200 }
200 BindingMode::Move => inner_ty.clone(), 201 BindingMode::Move => inner_ty.clone(),
201 }; 202 };
@@ -204,17 +205,17 @@ impl<'a> InferenceContext<'a> {
204 return inner_ty; 205 return inner_ty;
205 } 206 }
206 Pat::Slice { prefix, slice, suffix } => { 207 Pat::Slice { prefix, slice, suffix } => {
207 let (container_ty, elem_ty): (fn(_) -> _, _) = match &expected { 208 let (container_ty, elem_ty): (fn(_) -> _, _) = match expected.interned(&Interner) {
208 Ty::Array(st) => (Ty::Array, st.as_single().clone()), 209 TyKind::Array(st) => (TyKind::Array, st.as_single().clone()),
209 Ty::Slice(st) => (Ty::Slice, st.as_single().clone()), 210 TyKind::Slice(st) => (TyKind::Slice, st.as_single().clone()),
210 _ => (Ty::Slice, Ty::Unknown), 211 _ => (TyKind::Slice, self.err_ty()),
211 }; 212 };
212 213
213 for pat_id in prefix.iter().chain(suffix) { 214 for pat_id in prefix.iter().chain(suffix) {
214 self.infer_pat(*pat_id, &elem_ty, default_bm); 215 self.infer_pat(*pat_id, &elem_ty, default_bm);
215 } 216 }
216 217
217 let pat_ty = container_ty(Substs::single(elem_ty)); 218 let pat_ty = container_ty(Substs::single(elem_ty)).intern(&Interner);
218 if let Some(slice_pat_id) = slice { 219 if let Some(slice_pat_id) = slice {
219 self.infer_pat(*slice_pat_id, &pat_ty, default_bm); 220 self.infer_pat(*slice_pat_id, &pat_ty, default_bm);
220 } 221 }
@@ -232,20 +233,20 @@ impl<'a> InferenceContext<'a> {
232 Some(box_adt) => { 233 Some(box_adt) => {
233 let inner_expected = match expected.as_adt() { 234 let inner_expected = match expected.as_adt() {
234 Some((adt, substs)) if adt == box_adt => substs.as_single(), 235 Some((adt, substs)) if adt == box_adt => substs.as_single(),
235 _ => &Ty::Unknown, 236 _ => &Ty(TyKind::Unknown),
236 }; 237 };
237 238
238 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm); 239 let inner_ty = self.infer_pat(*inner, inner_expected, default_bm);
239 Ty::adt_ty(box_adt, Substs::single(inner_ty)) 240 Ty::adt_ty(box_adt, Substs::single(inner_ty))
240 } 241 }
241 None => Ty::Unknown, 242 None => self.err_ty(),
242 }, 243 },
243 Pat::ConstBlock(expr) => { 244 Pat::ConstBlock(expr) => {
244 self.infer_expr(*expr, &Expectation::has_type(expected.clone())) 245 self.infer_expr(*expr, &Expectation::has_type(expected.clone()))
245 } 246 }
246 Pat::Missing => Ty::Unknown, 247 Pat::Missing => self.err_ty(),
247 }; 248 };
248 // use a new type variable if we got Ty::Unknown here 249 // use a new type variable if we got error type here
249 let ty = self.insert_type_vars_shallow(ty); 250 let ty = self.insert_type_vars_shallow(ty);
250 if !self.unify(&ty, expected) { 251 if !self.unify(&ty, expected) {
251 // FIXME record mismatch, we need to change the type of self.type_mismatches for that 252 // FIXME record mismatch, we need to change the type of self.type_mismatches for that
diff --git a/crates/hir_ty/src/infer/path.rs b/crates/hir_ty/src/infer/path.rs
index ae3554bac..af108fb6c 100644
--- a/crates/hir_ty/src/infer/path.rs
+++ b/crates/hir_ty/src/infer/path.rs
@@ -9,7 +9,7 @@ use hir_def::{
9}; 9};
10use hir_expand::name::Name; 10use hir_expand::name::Name;
11 11
12use crate::{method_resolution, Substs, Ty, ValueTyDefId}; 12use crate::{method_resolution, Interner, Substs, Ty, TyKind, ValueTyDefId};
13 13
14use super::{ExprOrPatId, InferenceContext, TraitRef}; 14use super::{ExprOrPatId, InferenceContext, TraitRef};
15 15
@@ -40,7 +40,7 @@ impl<'a> InferenceContext<'a> {
40 let ty = self.make_ty(type_ref); 40 let ty = self.make_ty(type_ref);
41 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1); 41 let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
42 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver); 42 let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver);
43 let (ty, _) = Ty::from_type_relative_path(&ctx, ty, None, remaining_segments_for_ty); 43 let (ty, _) = ctx.lower_ty_relative_path(ty, None, remaining_segments_for_ty);
44 self.resolve_ty_assoc_item( 44 self.resolve_ty_assoc_item(
45 ty, 45 ty,
46 &path.segments().last().expect("path had at least one segment").name, 46 &path.segments().last().expect("path had at least one segment").name,
@@ -79,7 +79,7 @@ impl<'a> InferenceContext<'a> {
79 } 79 }
80 ValueNs::ImplSelf(impl_id) => { 80 ValueNs::ImplSelf(impl_id) => {
81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
82 let substs = Substs::type_params_for_generics(&generics); 82 let substs = Substs::type_params_for_generics(self.db, &generics);
83 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 83 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() { 84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
85 let ty = self.db.value_ty(struct_id.into()).subst(&substs); 85 let ty = self.db.value_ty(struct_id.into()).subst(&substs);
@@ -96,7 +96,7 @@ impl<'a> InferenceContext<'a> {
96 // self_subst is just for the parent 96 // self_subst is just for the parent
97 let parent_substs = self_subst.unwrap_or_else(Substs::empty); 97 let parent_substs = self_subst.unwrap_or_else(Substs::empty);
98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
99 let substs = Ty::substs_from_path(&ctx, path, typable, true); 99 let substs = ctx.substs_from_path(path, typable, true);
100 let full_substs = Substs::builder(substs.len()) 100 let full_substs = Substs::builder(substs.len())
101 .use_parent_substs(&parent_substs) 101 .use_parent_substs(&parent_substs)
102 .fill(substs.0[parent_substs.len()..].iter().cloned()) 102 .fill(substs.0[parent_substs.len()..].iter().cloned())
@@ -126,7 +126,8 @@ impl<'a> InferenceContext<'a> {
126 let segment = 126 let segment =
127 remaining_segments.last().expect("there should be at least one segment here"); 127 remaining_segments.last().expect("there should be at least one segment here");
128 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 128 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
129 let trait_ref = TraitRef::from_resolved_path(&ctx, trait_, resolved_segment, None); 129 let trait_ref =
130 ctx.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
130 self.resolve_trait_assoc_item(trait_ref, segment, id) 131 self.resolve_trait_assoc_item(trait_ref, segment, id)
131 } 132 }
132 (def, _) => { 133 (def, _) => {
@@ -137,14 +138,13 @@ impl<'a> InferenceContext<'a> {
137 let remaining_segments_for_ty = 138 let remaining_segments_for_ty =
138 remaining_segments.take(remaining_segments.len() - 1); 139 remaining_segments.take(remaining_segments.len() - 1);
139 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 140 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
140 let (ty, _) = Ty::from_partly_resolved_hir_path( 141 let (ty, _) = ctx.lower_partly_resolved_path(
141 &ctx,
142 def, 142 def,
143 resolved_segment, 143 resolved_segment,
144 remaining_segments_for_ty, 144 remaining_segments_for_ty,
145 true, 145 true,
146 ); 146 );
147 if let Ty::Unknown = ty { 147 if let TyKind::Unknown = ty.interned(&Interner) {
148 return None; 148 return None;
149 } 149 }
150 150
@@ -209,7 +209,7 @@ impl<'a> InferenceContext<'a> {
209 name: &Name, 209 name: &Name,
210 id: ExprOrPatId, 210 id: ExprOrPatId,
211 ) -> Option<(ValueNs, Option<Substs>)> { 211 ) -> Option<(ValueNs, Option<Substs>)> {
212 if let Ty::Unknown = ty { 212 if let TyKind::Unknown = ty.interned(&Interner) {
213 return None; 213 return None;
214 } 214 }
215 215
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs
index 54fcfed10..ebc612ca9 100644
--- a/crates/hir_ty/src/infer/unify.rs
+++ b/crates/hir_ty/src/infer/unify.rs
@@ -7,8 +7,8 @@ use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
7 7
8use super::{InferenceContext, Obligation}; 8use super::{InferenceContext, Obligation};
9use crate::{ 9use crate::{
10 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferenceVar, Scalar, 10 BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferenceVar, Interner,
11 Substs, Ty, TypeWalk, 11 Scalar, Substs, Ty, TyKind, TypeWalk,
12}; 12};
13 13
14impl<'a> InferenceContext<'a> { 14impl<'a> InferenceContext<'a> {
@@ -49,8 +49,8 @@ impl<'a, 'b> Canonicalizer<'a, 'b> {
49 49
50 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 {
51 t.fold_binders( 51 t.fold_binders(
52 &mut |ty, binders| match ty { 52 &mut |ty, binders| match ty.interned(&Interner) {
53 Ty::InferenceVar(var, kind) => { 53 &TyKind::InferenceVar(var, kind) => {
54 let inner = var.to_inner(); 54 let inner = var.to_inner();
55 if self.var_stack.contains(&inner) { 55 if self.var_stack.contains(&inner) {
56 // recursive type 56 // recursive type
@@ -66,7 +66,7 @@ impl<'a, 'b> Canonicalizer<'a, 'b> {
66 } else { 66 } else {
67 let root = self.ctx.table.var_unification_table.find(inner); 67 let root = self.ctx.table.var_unification_table.find(inner);
68 let position = self.add(InferenceVar::from_inner(root), kind); 68 let position = self.add(InferenceVar::from_inner(root), kind);
69 Ty::BoundVar(BoundVar::new(binders, position)) 69 TyKind::BoundVar(BoundVar::new(binders, position)).intern(&Interner)
70 } 70 }
71 } 71 }
72 _ => ty, 72 _ => ty,
@@ -108,10 +108,10 @@ impl<T> Canonicalized<T> {
108 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { 108 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
109 ty.walk_mut_binders( 109 ty.walk_mut_binders(
110 &mut |ty, binders| { 110 &mut |ty, binders| {
111 if let &mut Ty::BoundVar(bound) = ty { 111 if let &mut TyKind::BoundVar(bound) = &mut ty.0 {
112 if bound.debruijn >= binders { 112 if bound.debruijn >= binders {
113 let (v, k) = self.free_vars[bound.index]; 113 let (v, k) = self.free_vars[bound.index];
114 *ty = Ty::InferenceVar(v, k); 114 *ty = TyKind::InferenceVar(v, k).intern(&Interner);
115 } 115 }
116 } 116 }
117 }, 117 },
@@ -142,7 +142,7 @@ impl<T> Canonicalized<T> {
142 // eagerly replace projections in the type; we may be getting types 142 // eagerly replace projections in the type; we may be getting types
143 // e.g. from where clauses where this hasn't happened yet 143 // e.g. from where clauses where this hasn't happened yet
144 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));
145 ctx.table.unify(&Ty::InferenceVar(v, k), &ty); 145 ctx.table.unify(&TyKind::InferenceVar(v, k).intern(&Interner), &ty);
146 } 146 }
147 } 147 }
148} 148}
@@ -166,7 +166,10 @@ pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
166 // (kind of hacky) 166 // (kind of hacky)
167 for (i, var) in vars.iter().enumerate() { 167 for (i, var) in vars.iter().enumerate() {
168 if &*table.resolve_ty_shallow(var) == var { 168 if &*table.resolve_ty_shallow(var) == var {
169 table.unify(var, &Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i))); 169 table.unify(
170 var,
171 &TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, i)).intern(&Interner),
172 );
170 } 173 }
171 } 174 }
172 Some( 175 Some(
@@ -196,11 +199,12 @@ impl TypeVariableTable {
196 199
197 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty { 200 fn fallback_value(&self, iv: InferenceVar, kind: TyVariableKind) -> Ty {
198 match kind { 201 match kind {
199 _ if self.inner[iv.to_inner().0 as usize].diverging => Ty::Never, 202 _ if self.inner[iv.to_inner().0 as usize].diverging => TyKind::Never,
200 TyVariableKind::General => Ty::Unknown, 203 TyVariableKind::General => TyKind::Unknown,
201 TyVariableKind::Integer => Ty::Scalar(Scalar::Int(IntTy::I32)), 204 TyVariableKind::Integer => TyKind::Scalar(Scalar::Int(IntTy::I32)),
202 TyVariableKind::Float => Ty::Scalar(Scalar::Float(FloatTy::F64)), 205 TyVariableKind::Float => TyKind::Scalar(Scalar::Float(FloatTy::F64)),
203 } 206 }
207 .intern(&Interner)
204 } 208 }
205} 209}
206 210
@@ -227,7 +231,7 @@ impl InferenceTable {
227 self.type_variable_table.push(TypeVariableData { diverging }); 231 self.type_variable_table.push(TypeVariableData { diverging });
228 let key = self.var_unification_table.new_key(TypeVarValue::Unknown); 232 let key = self.var_unification_table.new_key(TypeVarValue::Unknown);
229 assert_eq!(key.0 as usize, self.type_variable_table.inner.len() - 1); 233 assert_eq!(key.0 as usize, self.type_variable_table.inner.len() - 1);
230 Ty::InferenceVar(InferenceVar::from_inner(key), kind) 234 TyKind::InferenceVar(InferenceVar::from_inner(key), kind).intern(&Interner)
231 } 235 }
232 236
233 pub(crate) fn new_type_var(&mut self) -> Ty { 237 pub(crate) fn new_type_var(&mut self) -> Ty {
@@ -290,12 +294,12 @@ impl InferenceTable {
290 } 294 }
291 295
292 pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { 296 pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool {
293 match (ty1, ty2) { 297 match (ty1.interned(&Interner), ty2.interned(&Interner)) {
294 (Ty::Unknown, _) | (_, Ty::Unknown) => true, 298 (TyKind::Unknown, _) | (_, TyKind::Unknown) => true,
295 299
296 (Ty::Placeholder(p1), Ty::Placeholder(p2)) if *p1 == *p2 => true, 300 (TyKind::Placeholder(p1), TyKind::Placeholder(p2)) if *p1 == *p2 => true,
297 301
298 (Ty::Dyn(dyn1), Ty::Dyn(dyn2)) if dyn1.len() == dyn2.len() => { 302 (TyKind::Dyn(dyn1), TyKind::Dyn(dyn2)) if dyn1.len() == dyn2.len() => {
299 for (pred1, pred2) in dyn1.iter().zip(dyn2.iter()) { 303 for (pred1, pred2) in dyn1.iter().zip(dyn2.iter()) {
300 if !self.unify_preds(pred1, pred2, depth + 1) { 304 if !self.unify_preds(pred1, pred2, depth + 1) {
301 return false; 305 return false;
@@ -305,16 +309,16 @@ impl InferenceTable {
305 } 309 }
306 310
307 ( 311 (
308 Ty::InferenceVar(tv1, TyVariableKind::General), 312 TyKind::InferenceVar(tv1, TyVariableKind::General),
309 Ty::InferenceVar(tv2, TyVariableKind::General), 313 TyKind::InferenceVar(tv2, TyVariableKind::General),
310 ) 314 )
311 | ( 315 | (
312 Ty::InferenceVar(tv1, TyVariableKind::Integer), 316 TyKind::InferenceVar(tv1, TyVariableKind::Integer),
313 Ty::InferenceVar(tv2, TyVariableKind::Integer), 317 TyKind::InferenceVar(tv2, TyVariableKind::Integer),
314 ) 318 )
315 | ( 319 | (
316 Ty::InferenceVar(tv1, TyVariableKind::Float), 320 TyKind::InferenceVar(tv1, TyVariableKind::Float),
317 Ty::InferenceVar(tv2, TyVariableKind::Float), 321 TyKind::InferenceVar(tv2, TyVariableKind::Float),
318 ) if self.type_variable_table.is_diverging(*tv1) 322 ) if self.type_variable_table.is_diverging(*tv1)
319 == self.type_variable_table.is_diverging(*tv2) => 323 == self.type_variable_table.is_diverging(*tv2) =>
320 { 324 {
@@ -326,24 +330,37 @@ impl InferenceTable {
326 // The order of MaybeNeverTypeVar matters here. 330 // The order of MaybeNeverTypeVar matters here.
327 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. 331 // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar.
328 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. 332 // Unifying MaybeNeverTypeVar and other concrete type will let the former become it.
329 (Ty::InferenceVar(tv, TyVariableKind::General), other) 333 (TyKind::InferenceVar(tv, TyVariableKind::General), other)
330 | (other, Ty::InferenceVar(tv, TyVariableKind::General)) 334 | (other, TyKind::InferenceVar(tv, TyVariableKind::General))
331 | (Ty::InferenceVar(tv, TyVariableKind::Integer), other @ Ty::Scalar(Scalar::Int(_)))
332 | (other @ Ty::Scalar(Scalar::Int(_)), Ty::InferenceVar(tv, TyVariableKind::Integer))
333 | ( 335 | (
334 Ty::InferenceVar(tv, TyVariableKind::Integer), 336 TyKind::InferenceVar(tv, TyVariableKind::Integer),
335 other @ Ty::Scalar(Scalar::Uint(_)), 337 other @ TyKind::Scalar(Scalar::Int(_)),
336 ) 338 )
337 | ( 339 | (
338 other @ Ty::Scalar(Scalar::Uint(_)), 340 other @ TyKind::Scalar(Scalar::Int(_)),
339 Ty::InferenceVar(tv, TyVariableKind::Integer), 341 TyKind::InferenceVar(tv, TyVariableKind::Integer),
340 ) 342 )
341 | (Ty::InferenceVar(tv, TyVariableKind::Float), other @ Ty::Scalar(Scalar::Float(_))) 343 | (
342 | (other @ Ty::Scalar(Scalar::Float(_)), Ty::InferenceVar(tv, TyVariableKind::Float)) => 344 TyKind::InferenceVar(tv, TyVariableKind::Integer),
343 { 345 other @ TyKind::Scalar(Scalar::Uint(_)),
346 )
347 | (
348 other @ TyKind::Scalar(Scalar::Uint(_)),
349 TyKind::InferenceVar(tv, TyVariableKind::Integer),
350 )
351 | (
352 TyKind::InferenceVar(tv, TyVariableKind::Float),
353 other @ TyKind::Scalar(Scalar::Float(_)),
354 )
355 | (
356 other @ TyKind::Scalar(Scalar::Float(_)),
357 TyKind::InferenceVar(tv, TyVariableKind::Float),
358 ) => {
344 // the type var is unknown since we tried to resolve it 359 // the type var is unknown since we tried to resolve it
345 self.var_unification_table 360 self.var_unification_table.union_value(
346 .union_value(tv.to_inner(), TypeVarValue::Known(other.clone())); 361 tv.to_inner(),
362 TypeVarValue::Known(other.clone().intern(&Interner)),
363 );
347 true 364 true
348 } 365 }
349 366
@@ -364,11 +381,11 @@ impl InferenceTable {
364 self.unify_substs(&tr1.substs, &tr2.substs, depth + 1) 381 self.unify_substs(&tr1.substs, &tr2.substs, depth + 1)
365 } 382 }
366 (GenericPredicate::Projection(proj1), GenericPredicate::Projection(proj2)) 383 (GenericPredicate::Projection(proj1), GenericPredicate::Projection(proj2))
367 if proj1.projection_ty.associated_ty == proj2.projection_ty.associated_ty => 384 if proj1.projection_ty.associated_ty_id == proj2.projection_ty.associated_ty_id =>
368 { 385 {
369 self.unify_substs( 386 self.unify_substs(
370 &proj1.projection_ty.parameters, 387 &proj1.projection_ty.substitution,
371 &proj2.projection_ty.parameters, 388 &proj2.projection_ty.substitution,
372 depth + 1, 389 depth + 1,
373 ) && self.unify_inner(&proj1.ty, &proj2.ty, depth + 1) 390 ) && self.unify_inner(&proj1.ty, &proj2.ty, depth + 1)
374 } 391 }
@@ -387,8 +404,8 @@ impl InferenceTable {
387 if i > 0 { 404 if i > 0 {
388 cov_mark::hit!(type_var_resolves_to_int_var); 405 cov_mark::hit!(type_var_resolves_to_int_var);
389 } 406 }
390 match &*ty { 407 match &ty.0 {
391 Ty::InferenceVar(tv, _) => { 408 TyKind::InferenceVar(tv, _) => {
392 let inner = tv.to_inner(); 409 let inner = tv.to_inner();
393 match self.var_unification_table.inlined_probe_value(inner).known() { 410 match self.var_unification_table.inlined_probe_value(inner).known() {
394 Some(known_ty) => { 411 Some(known_ty) => {
@@ -410,8 +427,8 @@ impl InferenceTable {
410 /// be resolved as far as possible, i.e. contain no type variables with 427 /// be resolved as far as possible, i.e. contain no type variables with
411 /// known type. 428 /// known type.
412 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 429 fn resolve_ty_as_possible_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
413 ty.fold(&mut |ty| match ty { 430 ty.fold(&mut |ty| match ty.interned(&Interner) {
414 Ty::InferenceVar(tv, kind) => { 431 &TyKind::InferenceVar(tv, kind) => {
415 let inner = tv.to_inner(); 432 let inner = tv.to_inner();
416 if tv_stack.contains(&inner) { 433 if tv_stack.contains(&inner) {
417 cov_mark::hit!(type_var_cycles_resolve_as_possible); 434 cov_mark::hit!(type_var_cycles_resolve_as_possible);
@@ -435,10 +452,10 @@ impl InferenceTable {
435 } 452 }
436 453
437 /// Resolves the type completely; type variables without known type are 454 /// Resolves the type completely; type variables without known type are
438 /// replaced by Ty::Unknown. 455 /// replaced by TyKind::Unknown.
439 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { 456 fn resolve_ty_completely_inner(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
440 ty.fold(&mut |ty| match ty { 457 ty.fold(&mut |ty| match ty.interned(&Interner) {
441 Ty::InferenceVar(tv, kind) => { 458 &TyKind::InferenceVar(tv, kind) => {
442 let inner = tv.to_inner(); 459 let inner = tv.to_inner();
443 if tv_stack.contains(&inner) { 460 if tv_stack.contains(&inner) {
444 cov_mark::hit!(type_var_cycles_resolve_completely); 461 cov_mark::hit!(type_var_cycles_resolve_completely);
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs
index e77f24e4e..484652073 100644
--- a/crates/hir_ty/src/lib.rs
+++ b/crates/hir_ty/src/lib.rs
@@ -27,9 +27,8 @@ use std::{iter, mem, ops::Deref, sync::Arc};
27 27
28use base_db::salsa; 28use base_db::salsa;
29use hir_def::{ 29use hir_def::{
30 builtin_type::BuiltinType, expr::ExprId, type_ref::Rawness, AssocContainerId, DefWithBodyId, 30 builtin_type::BuiltinType, expr::ExprId, type_ref::Rawness, AssocContainerId, FunctionId,
31 FunctionId, GenericDefId, HasModule, LifetimeParamId, Lookup, TraitId, TypeAliasId, 31 GenericDefId, HasModule, LifetimeParamId, Lookup, TraitId, TypeAliasId, TypeParamId,
32 TypeParamId,
33}; 32};
34use itertools::Itertools; 33use itertools::Itertools;
35 34
@@ -47,9 +46,16 @@ pub use lower::{
47}; 46};
48pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; 47pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
49 48
50pub use chalk_ir::{AdtId, BoundVar, DebruijnIndex, Mutability, Scalar, TyVariableKind}; 49pub use chalk_ir::{AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind};
51 50
52pub(crate) use crate::traits::chalk::Interner; 51pub use crate::traits::chalk::Interner;
52
53pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
54pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
55pub type FnDefId = chalk_ir::FnDefId<Interner>;
56pub type ClosureId = chalk_ir::ClosureId<Interner>;
57pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
58pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
53 59
54#[derive(Clone, PartialEq, Eq, Debug, Hash)] 60#[derive(Clone, PartialEq, Eq, Debug, Hash)]
55pub enum Lifetime { 61pub enum Lifetime {
@@ -60,7 +66,7 @@ pub enum Lifetime {
60#[derive(Clone, PartialEq, Eq, Debug, Hash)] 66#[derive(Clone, PartialEq, Eq, Debug, Hash)]
61pub struct OpaqueTy { 67pub struct OpaqueTy {
62 pub opaque_ty_id: OpaqueTyId, 68 pub opaque_ty_id: OpaqueTyId,
63 pub parameters: Substs, 69 pub substitution: Substs,
64} 70}
65 71
66/// A "projection" type corresponds to an (unnormalized) 72/// A "projection" type corresponds to an (unnormalized)
@@ -68,17 +74,17 @@ pub struct OpaqueTy {
68/// trait and all its parameters are fully known. 74/// trait and all its parameters are fully known.
69#[derive(Clone, PartialEq, Eq, Debug, Hash)] 75#[derive(Clone, PartialEq, Eq, Debug, Hash)]
70pub struct ProjectionTy { 76pub struct ProjectionTy {
71 pub associated_ty: TypeAliasId, 77 pub associated_ty_id: AssocTypeId,
72 pub parameters: Substs, 78 pub substitution: Substs,
73} 79}
74 80
75impl ProjectionTy { 81impl ProjectionTy {
76 pub fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef { 82 pub fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
77 TraitRef { trait_: self.trait_(db), substs: self.parameters.clone() } 83 TraitRef { trait_: self.trait_(db), substs: self.substitution.clone() }
78 } 84 }
79 85
80 fn trait_(&self, db: &dyn HirDatabase) -> TraitId { 86 fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
81 match self.associated_ty.lookup(db.upcast()).container { 87 match from_assoc_type_id(self.associated_ty_id).lookup(db.upcast()).container {
82 AssocContainerId::TraitId(it) => it, 88 AssocContainerId::TraitId(it) => it,
83 _ => panic!("projection ty without parent trait"), 89 _ => panic!("projection ty without parent trait"),
84 } 90 }
@@ -87,7 +93,7 @@ impl ProjectionTy {
87 93
88impl TypeWalk for ProjectionTy { 94impl TypeWalk for ProjectionTy {
89 fn walk(&self, f: &mut impl FnMut(&Ty)) { 95 fn walk(&self, f: &mut impl FnMut(&Ty)) {
90 self.parameters.walk(f); 96 self.substitution.walk(f);
91 } 97 }
92 98
93 fn walk_mut_binders( 99 fn walk_mut_binders(
@@ -95,14 +101,11 @@ impl TypeWalk for ProjectionTy {
95 f: &mut impl FnMut(&mut Ty, DebruijnIndex), 101 f: &mut impl FnMut(&mut Ty, DebruijnIndex),
96 binders: DebruijnIndex, 102 binders: DebruijnIndex,
97 ) { 103 ) {
98 self.parameters.walk_mut_binders(f, binders); 104 self.substitution.walk_mut_binders(f, binders);
99 } 105 }
100} 106}
101 107
102#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] 108pub type FnSig = chalk_ir::FnSig<Interner>;
103pub struct FnSig {
104 pub variadic: bool,
105}
106 109
107#[derive(Clone, PartialEq, Eq, Debug, Hash)] 110#[derive(Clone, PartialEq, Eq, Debug, Hash)]
108pub struct FnPointer { 111pub struct FnPointer {
@@ -131,7 +134,7 @@ pub enum AliasTy {
131/// 134///
132/// This should be cheap to clone. 135/// This should be cheap to clone.
133#[derive(Clone, PartialEq, Eq, Debug, Hash)] 136#[derive(Clone, PartialEq, Eq, Debug, Hash)]
134pub enum Ty { 137pub enum TyKind {
135 /// Structures, enumerations and unions. 138 /// Structures, enumerations and unions.
136 Adt(AdtId<Interner>, Substs), 139 Adt(AdtId<Interner>, Substs),
137 140
@@ -139,7 +142,7 @@ pub enum Ty {
139 /// when we have tried to normalize a projection like `T::Item` but 142 /// when we have tried to normalize a projection like `T::Item` but
140 /// couldn't find a better representation. In that case, we generate 143 /// couldn't find a better representation. In that case, we generate
141 /// an **application type** like `(Iterator::Item)<T>`. 144 /// an **application type** like `(Iterator::Item)<T>`.
142 AssociatedType(TypeAliasId, Substs), 145 AssociatedType(AssocTypeId, Substs),
143 146
144 /// a scalar type like `bool` or `u32` 147 /// a scalar type like `bool` or `u32`
145 Scalar(Scalar), 148 Scalar(Scalar),
@@ -179,7 +182,7 @@ pub enum Ty {
179 /// fn foo() -> i32 { 1 } 182 /// fn foo() -> i32 { 1 }
180 /// let bar = foo; // bar: fn() -> i32 {foo} 183 /// let bar = foo; // bar: fn() -> i32 {foo}
181 /// ``` 184 /// ```
182 FnDef(CallableDefId, Substs), 185 FnDef(FnDefId, Substs),
183 186
184 /// The pointee of a string slice. Written as `str`. 187 /// The pointee of a string slice. Written as `str`.
185 Str, 188 Str,
@@ -191,10 +194,10 @@ pub enum Ty {
191 /// 194 ///
192 /// The closure signature is stored in a `FnPtr` type in the first type 195 /// The closure signature is stored in a `FnPtr` type in the first type
193 /// parameter. 196 /// parameter.
194 Closure(DefWithBodyId, ExprId, Substs), 197 Closure(ClosureId, Substs),
195 198
196 /// Represents a foreign type declared in external blocks. 199 /// Represents a foreign type declared in external blocks.
197 ForeignType(TypeAliasId), 200 ForeignType(ForeignDefId),
198 201
199 /// A pointer to a function. Written as `fn() -> i32`. 202 /// A pointer to a function. Written as `fn() -> i32`.
200 /// 203 ///
@@ -216,7 +219,7 @@ pub enum Ty {
216 /// {}` when we're type-checking the body of that function. In this 219 /// {}` when we're type-checking the body of that function. In this
217 /// situation, we know this stands for *some* type, but don't know the exact 220 /// situation, we know this stands for *some* type, but don't know the exact
218 /// type. 221 /// type.
219 Placeholder(TypeParamId), 222 Placeholder(PlaceholderIndex),
220 223
221 /// A bound type variable. This is used in various places: when representing 224 /// A bound type variable. This is used in various places: when representing
222 /// some polymorphic type like the type of function `fn f<T>`, the type 225 /// some polymorphic type like the type of function `fn f<T>`, the type
@@ -244,6 +247,21 @@ pub enum Ty {
244 Unknown, 247 Unknown,
245} 248}
246 249
250#[derive(Clone, PartialEq, Eq, Debug, Hash)]
251pub struct Ty(TyKind);
252
253impl TyKind {
254 pub fn intern(self, _interner: &Interner) -> Ty {
255 Ty(self)
256 }
257}
258
259impl Ty {
260 pub fn interned(&self, _interner: &Interner) -> &TyKind {
261 &self.0
262 }
263}
264
247/// A list of substitutions for generic parameters. 265/// A list of substitutions for generic parameters.
248#[derive(Clone, PartialEq, Eq, Debug, Hash)] 266#[derive(Clone, PartialEq, Eq, Debug, Hash)]
249pub struct Substs(Arc<[Ty]>); 267pub struct Substs(Arc<[Ty]>);
@@ -291,14 +309,22 @@ impl Substs {
291 } 309 }
292 310
293 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 311 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
294 pub(crate) fn type_params_for_generics(generic_params: &Generics) -> Substs { 312 pub(crate) fn type_params_for_generics(
295 Substs(generic_params.iter().map(|(id, _)| Ty::Placeholder(id)).collect()) 313 db: &dyn HirDatabase,
314 generic_params: &Generics,
315 ) -> Substs {
316 Substs(
317 generic_params
318 .iter()
319 .map(|(id, _)| TyKind::Placeholder(to_placeholder_idx(db, id)).intern(&Interner))
320 .collect(),
321 )
296 } 322 }
297 323
298 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 324 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
299 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs { 325 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs {
300 let params = generics(db.upcast(), def.into()); 326 let params = generics(db.upcast(), def.into());
301 Substs::type_params_for_generics(&params) 327 Substs::type_params_for_generics(db, &params)
302 } 328 }
303 329
304 /// Return Substs that replace each parameter by a bound variable. 330 /// Return Substs that replace each parameter by a bound variable.
@@ -307,7 +333,7 @@ impl Substs {
307 generic_params 333 generic_params
308 .iter() 334 .iter()
309 .enumerate() 335 .enumerate()
310 .map(|(idx, _)| Ty::BoundVar(BoundVar::new(debruijn, idx))) 336 .map(|(idx, _)| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner))
311 .collect(), 337 .collect(),
312 ) 338 )
313 } 339 }
@@ -355,11 +381,14 @@ impl SubstsBuilder {
355 } 381 }
356 382
357 pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self { 383 pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self {
358 self.fill((starting_from..).map(|idx| Ty::BoundVar(BoundVar::new(debruijn, idx)))) 384 self.fill(
385 (starting_from..)
386 .map(|idx| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner)),
387 )
359 } 388 }
360 389
361 pub fn fill_with_unknown(self) -> Self { 390 pub fn fill_with_unknown(self) -> Self {
362 self.fill(iter::repeat(Ty::Unknown)) 391 self.fill(iter::repeat(TyKind::Unknown.intern(&Interner)))
363 } 392 }
364 393
365 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { 394 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
@@ -601,45 +630,52 @@ impl TypeWalk for CallableSig {
601 630
602impl Ty { 631impl Ty {
603 pub fn unit() -> Self { 632 pub fn unit() -> Self {
604 Ty::Tuple(0, Substs::empty()) 633 TyKind::Tuple(0, Substs::empty()).intern(&Interner)
605 } 634 }
606 635
607 pub fn adt_ty(adt: hir_def::AdtId, substs: Substs) -> Ty { 636 pub fn adt_ty(adt: hir_def::AdtId, substs: Substs) -> Ty {
608 Ty::Adt(AdtId(adt), substs) 637 TyKind::Adt(AdtId(adt), substs).intern(&Interner)
609 } 638 }
610 639
611 pub fn fn_ptr(sig: CallableSig) -> Self { 640 pub fn fn_ptr(sig: CallableSig) -> Self {
612 Ty::Function(FnPointer { 641 TyKind::Function(FnPointer {
613 num_args: sig.params().len(), 642 num_args: sig.params().len(),
614 sig: FnSig { variadic: sig.is_varargs }, 643 sig: FnSig { abi: (), safety: Safety::Safe, variadic: sig.is_varargs },
615 substs: Substs(sig.params_and_return), 644 substs: Substs(sig.params_and_return),
616 }) 645 })
646 .intern(&Interner)
617 } 647 }
618 648
619 pub fn builtin(builtin: BuiltinType) -> Self { 649 pub fn builtin(builtin: BuiltinType) -> Self {
620 match builtin { 650 match builtin {
621 BuiltinType::Char => Ty::Scalar(Scalar::Char), 651 BuiltinType::Char => TyKind::Scalar(Scalar::Char).intern(&Interner),
622 BuiltinType::Bool => Ty::Scalar(Scalar::Bool), 652 BuiltinType::Bool => TyKind::Scalar(Scalar::Bool).intern(&Interner),
623 BuiltinType::Str => Ty::Str, 653 BuiltinType::Str => TyKind::Str.intern(&Interner),
624 BuiltinType::Int(t) => Ty::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))), 654 BuiltinType::Int(t) => {
625 BuiltinType::Uint(t) => Ty::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))), 655 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))).intern(&Interner)
626 BuiltinType::Float(t) => Ty::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))), 656 }
657 BuiltinType::Uint(t) => {
658 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))).intern(&Interner)
659 }
660 BuiltinType::Float(t) => {
661 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))).intern(&Interner)
662 }
627 } 663 }
628 } 664 }
629 665
630 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { 666 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
631 match self { 667 match self.interned(&Interner) {
632 Ty::Ref(mutability, parameters) => Some((parameters.as_single(), *mutability)), 668 TyKind::Ref(mutability, parameters) => Some((parameters.as_single(), *mutability)),
633 _ => None, 669 _ => None,
634 } 670 }
635 } 671 }
636 672
637 pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> { 673 pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
638 match self { 674 match self.interned(&Interner) {
639 Ty::Ref(mutability, parameters) => { 675 TyKind::Ref(mutability, parameters) => {
640 Some((parameters.as_single(), Rawness::Ref, *mutability)) 676 Some((parameters.as_single(), Rawness::Ref, *mutability))
641 } 677 }
642 Ty::Raw(mutability, parameters) => { 678 TyKind::Raw(mutability, parameters) => {
643 Some((parameters.as_single(), Rawness::RawPtr, *mutability)) 679 Some((parameters.as_single(), Rawness::RawPtr, *mutability))
644 } 680 }
645 _ => None, 681 _ => None,
@@ -649,7 +685,7 @@ impl Ty {
649 pub fn strip_references(&self) -> &Ty { 685 pub fn strip_references(&self) -> &Ty {
650 let mut t: &Ty = self; 686 let mut t: &Ty = self;
651 687
652 while let Ty::Ref(_mutability, parameters) = t { 688 while let TyKind::Ref(_mutability, parameters) = t.interned(&Interner) {
653 t = parameters.as_single(); 689 t = parameters.as_single();
654 } 690 }
655 691
@@ -657,65 +693,71 @@ impl Ty {
657 } 693 }
658 694
659 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substs)> { 695 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substs)> {
660 match self { 696 match self.interned(&Interner) {
661 Ty::Adt(AdtId(adt), parameters) => Some((*adt, parameters)), 697 TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)),
662 _ => None, 698 _ => None,
663 } 699 }
664 } 700 }
665 701
666 pub fn as_tuple(&self) -> Option<&Substs> { 702 pub fn as_tuple(&self) -> Option<&Substs> {
667 match self { 703 match self.interned(&Interner) {
668 Ty::Tuple(_, substs) => Some(substs), 704 TyKind::Tuple(_, substs) => Some(substs),
669 _ => None, 705 _ => None,
670 } 706 }
671 } 707 }
672 708
673 pub fn as_generic_def(&self) -> Option<GenericDefId> { 709 pub fn as_generic_def(&self, db: &dyn HirDatabase) -> Option<GenericDefId> {
674 match *self { 710 match *self.interned(&Interner) {
675 Ty::Adt(AdtId(adt), ..) => Some(adt.into()), 711 TyKind::Adt(AdtId(adt), ..) => Some(adt.into()),
676 Ty::FnDef(callable, ..) => Some(callable.into()), 712 TyKind::FnDef(callable, ..) => {
677 Ty::AssociatedType(type_alias, ..) => Some(type_alias.into()), 713 Some(db.lookup_intern_callable_def(callable.into()).into())
678 Ty::ForeignType(type_alias, ..) => Some(type_alias.into()), 714 }
715 TyKind::AssociatedType(type_alias, ..) => Some(from_assoc_type_id(type_alias).into()),
716 TyKind::ForeignType(type_alias, ..) => Some(from_foreign_def_id(type_alias).into()),
679 _ => None, 717 _ => None,
680 } 718 }
681 } 719 }
682 720
683 pub fn is_never(&self) -> bool { 721 pub fn is_never(&self) -> bool {
684 matches!(self, Ty::Never) 722 matches!(self.interned(&Interner), TyKind::Never)
685 } 723 }
686 724
687 pub fn is_unknown(&self) -> bool { 725 pub fn is_unknown(&self) -> bool {
688 matches!(self, Ty::Unknown) 726 matches!(self.interned(&Interner), TyKind::Unknown)
689 } 727 }
690 728
691 pub fn equals_ctor(&self, other: &Ty) -> bool { 729 pub fn equals_ctor(&self, other: &Ty) -> bool {
692 match (self, other) { 730 match (self.interned(&Interner), other.interned(&Interner)) {
693 (Ty::Adt(adt, ..), Ty::Adt(adt2, ..)) => adt == adt2, 731 (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
694 (Ty::Slice(_), Ty::Slice(_)) | (Ty::Array(_), Ty::Array(_)) => true, 732 (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_), TyKind::Array(_)) => true,
695 (Ty::FnDef(def_id, ..), Ty::FnDef(def_id2, ..)) => def_id == def_id2, 733 (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
696 (Ty::OpaqueType(ty_id, ..), Ty::OpaqueType(ty_id2, ..)) => ty_id == ty_id2, 734 (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
697 (Ty::AssociatedType(ty_id, ..), Ty::AssociatedType(ty_id2, ..)) 735 (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
698 | (Ty::ForeignType(ty_id, ..), Ty::ForeignType(ty_id2, ..)) => ty_id == ty_id2, 736 ty_id == ty_id2
699 (Ty::Closure(def, expr, _), Ty::Closure(def2, expr2, _)) => { 737 }
700 expr == expr2 && def == def2 738 (TyKind::ForeignType(ty_id, ..), TyKind::ForeignType(ty_id2, ..)) => ty_id == ty_id2,
739 (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
740 (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
741 | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
742 mutability == mutability2
701 } 743 }
702 (Ty::Ref(mutability, ..), Ty::Ref(mutability2, ..))
703 | (Ty::Raw(mutability, ..), Ty::Raw(mutability2, ..)) => mutability == mutability2,
704 ( 744 (
705 Ty::Function(FnPointer { num_args, sig, .. }), 745 TyKind::Function(FnPointer { num_args, sig, .. }),
706 Ty::Function(FnPointer { num_args: num_args2, sig: sig2, .. }), 746 TyKind::Function(FnPointer { num_args: num_args2, sig: sig2, .. }),
707 ) => num_args == num_args2 && sig == sig2, 747 ) => num_args == num_args2 && sig == sig2,
708 (Ty::Tuple(cardinality, _), Ty::Tuple(cardinality2, _)) => cardinality == cardinality2, 748 (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
709 (Ty::Str, Ty::Str) | (Ty::Never, Ty::Never) => true, 749 cardinality == cardinality2
710 (Ty::Scalar(scalar), Ty::Scalar(scalar2)) => scalar == scalar2, 750 }
751 (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
752 (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
711 _ => false, 753 _ => false,
712 } 754 }
713 } 755 }
714 756
715 /// If this is a `dyn Trait` type, this returns the `Trait` part. 757 /// If this is a `dyn Trait` type, this returns the `Trait` part.
716 pub fn dyn_trait_ref(&self) -> Option<&TraitRef> { 758 pub fn dyn_trait_ref(&self) -> Option<&TraitRef> {
717 match self { 759 match self.interned(&Interner) {
718 Ty::Dyn(bounds) => bounds.get(0).and_then(|b| match b { 760 TyKind::Dyn(bounds) => bounds.get(0).and_then(|b| match b {
719 GenericPredicate::Implemented(trait_ref) => Some(trait_ref), 761 GenericPredicate::Implemented(trait_ref) => Some(trait_ref),
720 _ => None, 762 _ => None,
721 }), 763 }),
@@ -729,28 +771,37 @@ impl Ty {
729 } 771 }
730 772
731 fn builtin_deref(&self) -> Option<Ty> { 773 fn builtin_deref(&self) -> Option<Ty> {
732 match self { 774 match self.interned(&Interner) {
733 Ty::Ref(.., parameters) => Some(Ty::clone(parameters.as_single())), 775 TyKind::Ref(.., parameters) => Some(Ty::clone(parameters.as_single())),
734 Ty::Raw(.., parameters) => Some(Ty::clone(parameters.as_single())), 776 TyKind::Raw(.., parameters) => Some(Ty::clone(parameters.as_single())),
735 _ => None, 777 _ => None,
736 } 778 }
737 } 779 }
738 780
739 pub fn as_fn_def(&self) -> Option<FunctionId> { 781 pub fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId> {
740 match self { 782 match self.interned(&Interner) {
741 &Ty::FnDef(CallableDefId::FunctionId(func), ..) => Some(func), 783 &TyKind::FnDef(def, ..) => Some(db.lookup_intern_callable_def(def.into())),
742 _ => None, 784 _ => None,
743 } 785 }
744 } 786 }
745 787
788 pub fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> {
789 if let Some(CallableDefId::FunctionId(func)) = self.callable_def(db) {
790 Some(func)
791 } else {
792 None
793 }
794 }
795
746 pub fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> { 796 pub fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> {
747 match self { 797 match self.interned(&Interner) {
748 Ty::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)), 798 TyKind::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)),
749 Ty::FnDef(def, parameters) => { 799 TyKind::FnDef(def, parameters) => {
750 let sig = db.callable_item_signature(*def); 800 let callable_def = db.lookup_intern_callable_def((*def).into());
801 let sig = db.callable_item_signature(callable_def);
751 Some(sig.subst(&parameters)) 802 Some(sig.subst(&parameters))
752 } 803 }
753 Ty::Closure(.., substs) => { 804 TyKind::Closure(.., substs) => {
754 let sig_param = &substs[0]; 805 let sig_param = &substs[0];
755 sig_param.callable_sig(db) 806 sig_param.callable_sig(db)
756 } 807 }
@@ -763,18 +814,18 @@ impl Ty {
763 /// `self` is `Option<_>` and the substs contain `u32`, we'll have 814 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
764 /// `Option<u32>` afterwards.) 815 /// `Option<u32>` afterwards.)
765 pub fn apply_substs(mut self, new_substs: Substs) -> Ty { 816 pub fn apply_substs(mut self, new_substs: Substs) -> Ty {
766 match &mut self { 817 match &mut self.0 {
767 Ty::Adt(_, substs) 818 TyKind::Adt(_, substs)
768 | Ty::Slice(substs) 819 | TyKind::Slice(substs)
769 | Ty::Array(substs) 820 | TyKind::Array(substs)
770 | Ty::Raw(_, substs) 821 | TyKind::Raw(_, substs)
771 | Ty::Ref(_, substs) 822 | TyKind::Ref(_, substs)
772 | Ty::FnDef(_, substs) 823 | TyKind::FnDef(_, substs)
773 | Ty::Function(FnPointer { substs, .. }) 824 | TyKind::Function(FnPointer { substs, .. })
774 | Ty::Tuple(_, substs) 825 | TyKind::Tuple(_, substs)
775 | Ty::OpaqueType(_, substs) 826 | TyKind::OpaqueType(_, substs)
776 | Ty::AssociatedType(_, substs) 827 | TyKind::AssociatedType(_, substs)
777 | Ty::Closure(.., substs) => { 828 | TyKind::Closure(.., substs) => {
778 assert_eq!(substs.len(), new_substs.len()); 829 assert_eq!(substs.len(), new_substs.len());
779 *substs = new_substs; 830 *substs = new_substs;
780 } 831 }
@@ -786,44 +837,44 @@ impl Ty {
786 /// Returns the type parameters of this type if it has some (i.e. is an ADT 837 /// Returns the type parameters of this type if it has some (i.e. is an ADT
787 /// or function); so if `self` is `Option<u32>`, this returns the `u32`. 838 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
788 pub fn substs(&self) -> Option<&Substs> { 839 pub fn substs(&self) -> Option<&Substs> {
789 match self { 840 match self.interned(&Interner) {
790 Ty::Adt(_, substs) 841 TyKind::Adt(_, substs)
791 | Ty::Slice(substs) 842 | TyKind::Slice(substs)
792 | Ty::Array(substs) 843 | TyKind::Array(substs)
793 | Ty::Raw(_, substs) 844 | TyKind::Raw(_, substs)
794 | Ty::Ref(_, substs) 845 | TyKind::Ref(_, substs)
795 | Ty::FnDef(_, substs) 846 | TyKind::FnDef(_, substs)
796 | Ty::Function(FnPointer { substs, .. }) 847 | TyKind::Function(FnPointer { substs, .. })
797 | Ty::Tuple(_, substs) 848 | TyKind::Tuple(_, substs)
798 | Ty::OpaqueType(_, substs) 849 | TyKind::OpaqueType(_, substs)
799 | Ty::AssociatedType(_, substs) 850 | TyKind::AssociatedType(_, substs)
800 | Ty::Closure(.., substs) => Some(substs), 851 | TyKind::Closure(.., substs) => Some(substs),
801 _ => None, 852 _ => None,
802 } 853 }
803 } 854 }
804 855
805 pub fn substs_mut(&mut self) -> Option<&mut Substs> { 856 pub fn substs_mut(&mut self) -> Option<&mut Substs> {
806 match self { 857 match &mut self.0 {
807 Ty::Adt(_, substs) 858 TyKind::Adt(_, substs)
808 | Ty::Slice(substs) 859 | TyKind::Slice(substs)
809 | Ty::Array(substs) 860 | TyKind::Array(substs)
810 | Ty::Raw(_, substs) 861 | TyKind::Raw(_, substs)
811 | Ty::Ref(_, substs) 862 | TyKind::Ref(_, substs)
812 | Ty::FnDef(_, substs) 863 | TyKind::FnDef(_, substs)
813 | Ty::Function(FnPointer { substs, .. }) 864 | TyKind::Function(FnPointer { substs, .. })
814 | Ty::Tuple(_, substs) 865 | TyKind::Tuple(_, substs)
815 | Ty::OpaqueType(_, substs) 866 | TyKind::OpaqueType(_, substs)
816 | Ty::AssociatedType(_, substs) 867 | TyKind::AssociatedType(_, substs)
817 | Ty::Closure(.., substs) => Some(substs), 868 | TyKind::Closure(.., substs) => Some(substs),
818 _ => None, 869 _ => None,
819 } 870 }
820 } 871 }
821 872
822 pub fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<GenericPredicate>> { 873 pub fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<GenericPredicate>> {
823 match self { 874 match self.interned(&Interner) {
824 Ty::OpaqueType(opaque_ty_id, ..) => { 875 TyKind::OpaqueType(opaque_ty_id, ..) => {
825 match opaque_ty_id { 876 match db.lookup_intern_impl_trait_id((*opaque_ty_id).into()) {
826 OpaqueTyId::AsyncBlockTypeImplTrait(def, _expr) => { 877 ImplTraitId::AsyncBlockTypeImplTrait(def, _expr) => {
827 let krate = def.module(db.upcast()).krate(); 878 let krate = def.module(db.upcast()).krate();
828 if let Some(future_trait) = db 879 if let Some(future_trait) = db
829 .lang_item(krate, "future_trait".into()) 880 .lang_item(krate, "future_trait".into())
@@ -841,32 +892,34 @@ impl Ty {
841 None 892 None
842 } 893 }
843 } 894 }
844 OpaqueTyId::ReturnTypeImplTrait(..) => None, 895 ImplTraitId::ReturnTypeImplTrait(..) => None,
845 } 896 }
846 } 897 }
847 Ty::Alias(AliasTy::Opaque(opaque_ty)) => { 898 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
848 let predicates = match opaque_ty.opaque_ty_id { 899 let predicates = match db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into())
849 OpaqueTyId::ReturnTypeImplTrait(func, idx) => { 900 {
901 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
850 db.return_type_impl_traits(func).map(|it| { 902 db.return_type_impl_traits(func).map(|it| {
851 let data = (*it) 903 let data = (*it)
852 .as_ref() 904 .as_ref()
853 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone()); 905 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
854 data.subst(&opaque_ty.parameters) 906 data.subst(&opaque_ty.substitution)
855 }) 907 })
856 } 908 }
857 // It always has an parameter for Future::Output type. 909 // It always has an parameter for Future::Output type.
858 OpaqueTyId::AsyncBlockTypeImplTrait(..) => unreachable!(), 910 ImplTraitId::AsyncBlockTypeImplTrait(..) => unreachable!(),
859 }; 911 };
860 912
861 predicates.map(|it| it.value) 913 predicates.map(|it| it.value)
862 } 914 }
863 Ty::Placeholder(id) => { 915 TyKind::Placeholder(idx) => {
916 let id = from_placeholder_idx(db, *idx);
864 let generic_params = db.generic_params(id.parent); 917 let generic_params = db.generic_params(id.parent);
865 let param_data = &generic_params.types[id.local_id]; 918 let param_data = &generic_params.types[id.local_id];
866 match param_data.provenance { 919 match param_data.provenance {
867 hir_def::generics::TypeParamProvenance::ArgumentImplTrait => { 920 hir_def::generics::TypeParamProvenance::ArgumentImplTrait => {
868 let predicates = db 921 let predicates = db
869 .generic_predicates_for_param(*id) 922 .generic_predicates_for_param(id)
870 .into_iter() 923 .into_iter()
871 .map(|pred| pred.value.clone()) 924 .map(|pred| pred.value.clone())
872 .collect_vec(); 925 .collect_vec();
@@ -881,15 +934,18 @@ impl Ty {
881 } 934 }
882 935
883 pub fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> { 936 pub fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> {
884 match self { 937 match self.interned(&Interner) {
885 Ty::AssociatedType(type_alias_id, ..) => { 938 TyKind::AssociatedType(id, ..) => {
886 match type_alias_id.lookup(db.upcast()).container { 939 match from_assoc_type_id(*id).lookup(db.upcast()).container {
887 AssocContainerId::TraitId(trait_id) => Some(trait_id), 940 AssocContainerId::TraitId(trait_id) => Some(trait_id),
888 _ => None, 941 _ => None,
889 } 942 }
890 } 943 }
891 Ty::Alias(AliasTy::Projection(projection_ty)) => { 944 TyKind::Alias(AliasTy::Projection(projection_ty)) => {
892 match projection_ty.associated_ty.lookup(db.upcast()).container { 945 match from_assoc_type_id(projection_ty.associated_ty_id)
946 .lookup(db.upcast())
947 .container
948 {
893 AssocContainerId::TraitId(trait_id) => Some(trait_id), 949 AssocContainerId::TraitId(trait_id) => Some(trait_id),
894 _ => None, 950 _ => None,
895 } 951 }
@@ -908,13 +964,13 @@ pub trait TypeWalk {
908 } 964 }
909 /// Walk the type, counting entered binders. 965 /// Walk the type, counting entered binders.
910 /// 966 ///
911 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers 967 /// `TyKind::Bound` variables use DeBruijn indexing, which means that 0 refers
912 /// to the innermost binder, 1 to the next, etc.. So when we want to 968 /// to the innermost binder, 1 to the next, etc.. So when we want to
913 /// substitute a certain bound variable, we can't just walk the whole type 969 /// substitute a certain bound variable, we can't just walk the whole type
914 /// and blindly replace each instance of a certain index; when we 'enter' 970 /// and blindly replace each instance of a certain index; when we 'enter'
915 /// things that introduce new bound variables, we have to keep track of 971 /// things that introduce new bound variables, we have to keep track of
916 /// that. Currently, the only thing that introduces bound variables on our 972 /// that. Currently, the only thing that introduces bound variables on our
917 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound 973 /// side are `TyKind::Dyn` and `TyKind::Opaque`, which each introduce a bound
918 /// variable for the self type. 974 /// variable for the self type.
919 fn walk_mut_binders( 975 fn walk_mut_binders(
920 &mut self, 976 &mut self,
@@ -932,7 +988,7 @@ pub trait TypeWalk {
932 { 988 {
933 self.walk_mut_binders( 989 self.walk_mut_binders(
934 &mut |ty_mut, binders| { 990 &mut |ty_mut, binders| {
935 let ty = mem::replace(ty_mut, Ty::Unknown); 991 let ty = mem::replace(ty_mut, Ty(TyKind::Unknown));
936 *ty_mut = f(ty, binders); 992 *ty_mut = f(ty, binders);
937 }, 993 },
938 binders, 994 binders,
@@ -945,13 +1001,13 @@ pub trait TypeWalk {
945 Self: Sized, 1001 Self: Sized,
946 { 1002 {
947 self.walk_mut(&mut |ty_mut| { 1003 self.walk_mut(&mut |ty_mut| {
948 let ty = mem::replace(ty_mut, Ty::Unknown); 1004 let ty = mem::replace(ty_mut, Ty(TyKind::Unknown));
949 *ty_mut = f(ty); 1005 *ty_mut = f(ty);
950 }); 1006 });
951 self 1007 self
952 } 1008 }
953 1009
954 /// Substitutes `Ty::Bound` vars with the given substitution. 1010 /// Substitutes `TyKind::Bound` vars with the given substitution.
955 fn subst_bound_vars(self, substs: &Substs) -> Self 1011 fn subst_bound_vars(self, substs: &Substs) -> Self
956 where 1012 where
957 Self: Sized, 1013 Self: Sized,
@@ -959,14 +1015,14 @@ pub trait TypeWalk {
959 self.subst_bound_vars_at_depth(substs, DebruijnIndex::INNERMOST) 1015 self.subst_bound_vars_at_depth(substs, DebruijnIndex::INNERMOST)
960 } 1016 }
961 1017
962 /// Substitutes `Ty::Bound` vars with the given substitution. 1018 /// Substitutes `TyKind::Bound` vars with the given substitution.
963 fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self 1019 fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self
964 where 1020 where
965 Self: Sized, 1021 Self: Sized,
966 { 1022 {
967 self.walk_mut_binders( 1023 self.walk_mut_binders(
968 &mut |ty, binders| { 1024 &mut |ty, binders| {
969 if let &mut Ty::BoundVar(bound) = ty { 1025 if let &mut TyKind::BoundVar(bound) = &mut ty.0 {
970 if bound.debruijn >= binders { 1026 if bound.debruijn >= binders {
971 *ty = substs.0[bound.index].clone().shift_bound_vars(binders); 1027 *ty = substs.0[bound.index].clone().shift_bound_vars(binders);
972 } 1028 }
@@ -977,17 +1033,17 @@ pub trait TypeWalk {
977 self 1033 self
978 } 1034 }
979 1035
980 /// Shifts up debruijn indices of `Ty::Bound` vars by `n`. 1036 /// Shifts up debruijn indices of `TyKind::Bound` vars by `n`.
981 fn shift_bound_vars(self, n: DebruijnIndex) -> Self 1037 fn shift_bound_vars(self, n: DebruijnIndex) -> Self
982 where 1038 where
983 Self: Sized, 1039 Self: Sized,
984 { 1040 {
985 self.fold_binders( 1041 self.fold_binders(
986 &mut |ty, binders| match ty { 1042 &mut |ty, binders| match &ty.0 {
987 Ty::BoundVar(bound) if bound.debruijn >= binders => { 1043 TyKind::BoundVar(bound) if bound.debruijn >= binders => {
988 Ty::BoundVar(bound.shifted_in_from(n)) 1044 TyKind::BoundVar(bound.shifted_in_from(n)).intern(&Interner)
989 } 1045 }
990 ty => ty, 1046 _ => ty,
991 }, 1047 },
992 DebruijnIndex::INNERMOST, 1048 DebruijnIndex::INNERMOST,
993 )