aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_ty
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_ty')
-rw-r--r--crates/ra_hir_ty/Cargo.toml5
-rw-r--r--crates/ra_hir_ty/src/db.rs7
-rw-r--r--crates/ra_hir_ty/src/diagnostics.rs4
-rw-r--r--crates/ra_hir_ty/src/infer/coerce.rs4
-rw-r--r--crates/ra_hir_ty/src/infer/expr.rs53
-rw-r--r--crates/ra_hir_ty/src/lib.rs26
-rw-r--r--crates/ra_hir_ty/src/tests/coercion.rs17
-rw-r--r--crates/ra_hir_ty/src/tests/patterns.rs50
-rw-r--r--crates/ra_hir_ty/src/tests/simple.rs22
-rw-r--r--crates/ra_hir_ty/src/tests/traits.rs196
-rw-r--r--crates/ra_hir_ty/src/traits/builtin.rs3
-rw-r--r--crates/ra_hir_ty/src/traits/chalk.rs937
-rw-r--r--crates/ra_hir_ty/src/traits/chalk/interner.rs353
-rw-r--r--crates/ra_hir_ty/src/traits/chalk/mapping.rs701
-rw-r--r--crates/ra_hir_ty/src/traits/chalk/tls.rs83
15 files changed, 1593 insertions, 868 deletions
diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml
index 5fc0ec5e3..4b8dcdc07 100644
--- a/crates/ra_hir_ty/Cargo.toml
+++ b/crates/ra_hir_ty/Cargo.toml
@@ -27,9 +27,8 @@ test_utils = { path = "../test_utils" }
27 27
28scoped-tls = "1" 28scoped-tls = "1"
29 29
30chalk-solve = { git = "https://github.com/rust-lang/chalk.git", rev = "3e9c2503ae9c5277c2acb74624dc267876dd89b3" } 30chalk-solve = { git = "https://github.com/rust-lang/chalk.git", rev = "329b7f3fdd2431ed6f6778cde53f22374c7d094c" }
31chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "3e9c2503ae9c5277c2acb74624dc267876dd89b3" } 31chalk-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "329b7f3fdd2431ed6f6778cde53f22374c7d094c" }
32chalk-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "3e9c2503ae9c5277c2acb74624dc267876dd89b3" }
33 32
34[dev-dependencies] 33[dev-dependencies]
35insta = "0.16.0" 34insta = "0.16.0"
diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs
index fdb49560b..0a8bb24ac 100644
--- a/crates/ra_hir_ty/src/db.rs
+++ b/crates/ra_hir_ty/src/db.rs
@@ -76,6 +76,8 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
76 #[salsa::interned] 76 #[salsa::interned]
77 fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId; 77 fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
78 #[salsa::interned] 78 #[salsa::interned]
79 fn intern_callable_def(&self, callable_def: CallableDef) -> crate::CallableDefId;
80 #[salsa::interned]
79 fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId; 81 fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId;
80 #[salsa::interned] 82 #[salsa::interned]
81 fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId; 83 fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
@@ -89,11 +91,14 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
89 fn trait_datum(&self, krate: CrateId, trait_id: chalk::TraitId) -> Arc<chalk::TraitDatum>; 91 fn trait_datum(&self, krate: CrateId, trait_id: chalk::TraitId) -> Arc<chalk::TraitDatum>;
90 92
91 #[salsa::invoke(chalk::struct_datum_query)] 93 #[salsa::invoke(chalk::struct_datum_query)]
92 fn struct_datum(&self, krate: CrateId, struct_id: chalk::StructId) -> Arc<chalk::StructDatum>; 94 fn struct_datum(&self, krate: CrateId, struct_id: chalk::AdtId) -> Arc<chalk::StructDatum>;
93 95
94 #[salsa::invoke(crate::traits::chalk::impl_datum_query)] 96 #[salsa::invoke(crate::traits::chalk::impl_datum_query)]
95 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>; 97 fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>;
96 98
99 #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)]
100 fn fn_def_datum(&self, krate: CrateId, fn_def_id: chalk::FnDefId) -> Arc<chalk::FnDefDatum>;
101
97 #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)] 102 #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)]
98 fn associated_ty_value( 103 fn associated_ty_value(
99 &self, 104 &self,
diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs
index 41ac70272..2c7298714 100644
--- a/crates/ra_hir_ty/src/diagnostics.rs
+++ b/crates/ra_hir_ty/src/diagnostics.rs
@@ -40,7 +40,7 @@ impl Diagnostic for MissingFields {
40 fn message(&self) -> String { 40 fn message(&self) -> String {
41 let mut buf = String::from("Missing structure fields:\n"); 41 let mut buf = String::from("Missing structure fields:\n");
42 for field in &self.missed_fields { 42 for field in &self.missed_fields {
43 format_to!(buf, "- {}", field); 43 format_to!(buf, "- {}\n", field);
44 } 44 }
45 buf 45 buf
46 } 46 }
@@ -73,7 +73,7 @@ impl Diagnostic for MissingPatFields {
73 fn message(&self) -> String { 73 fn message(&self) -> String {
74 let mut buf = String::from("Missing structure fields:\n"); 74 let mut buf = String::from("Missing structure fields:\n");
75 for field in &self.missed_fields { 75 for field in &self.missed_fields {
76 format_to!(buf, "- {}", field); 76 format_to!(buf, "- {}\n", field);
77 } 77 }
78 buf 78 buf
79 } 79 }
diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs
index 2ee9adb16..32c7c57cd 100644
--- a/crates/ra_hir_ty/src/infer/coerce.rs
+++ b/crates/ra_hir_ty/src/infer/coerce.rs
@@ -45,9 +45,7 @@ impl<'a> InferenceContext<'a> {
45 self.coerce_merge_branch(&ptr_ty1, &ptr_ty2) 45 self.coerce_merge_branch(&ptr_ty1, &ptr_ty2)
46 } else { 46 } else {
47 mark::hit!(coerce_merge_fail_fallback); 47 mark::hit!(coerce_merge_fail_fallback);
48 // For incompatible types, we use the latter one as result 48 ty1.clone()
49 // to be better recovery for `if` without `else`.
50 ty2.clone()
51 } 49 }
52 } 50 }
53 } 51 }
diff --git a/crates/ra_hir_ty/src/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs
index b28724f0e..78084cb57 100644
--- a/crates/ra_hir_ty/src/infer/expr.rs
+++ b/crates/ra_hir_ty/src/infer/expr.rs
@@ -17,8 +17,8 @@ use crate::{
17 autoderef, method_resolution, op, 17 autoderef, method_resolution, op,
18 traits::InEnvironment, 18 traits::InEnvironment,
19 utils::{generics, variant_data, Generics}, 19 utils::{generics, variant_data, Generics},
20 ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef, 20 ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Rawness, Substs,
21 Ty, TypeCtor, Uncertain, 21 TraitRef, Ty, TypeCtor, Uncertain,
22}; 22};
23 23
24use super::{ 24use super::{
@@ -140,13 +140,13 @@ impl<'a> InferenceContext<'a> {
140 140
141 let mut sig_tys = Vec::new(); 141 let mut sig_tys = Vec::new();
142 142
143 for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { 143 // collect explicitly written argument types
144 let expected = if let Some(type_ref) = arg_type { 144 for arg_type in arg_types.iter() {
145 let arg_ty = if let Some(type_ref) = arg_type {
145 self.make_ty(type_ref) 146 self.make_ty(type_ref)
146 } else { 147 } else {
147 Ty::Unknown 148 self.table.new_type_var()
148 }; 149 };
149 let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default());
150 sig_tys.push(arg_ty); 150 sig_tys.push(arg_ty);
151 } 151 }
152 152
@@ -158,7 +158,7 @@ impl<'a> InferenceContext<'a> {
158 sig_tys.push(ret_ty.clone()); 158 sig_tys.push(ret_ty.clone());
159 let sig_ty = Ty::apply( 159 let sig_ty = Ty::apply(
160 TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, 160 TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 },
161 Substs(sig_tys.into()), 161 Substs(sig_tys.clone().into()),
162 ); 162 );
163 let closure_ty = 163 let closure_ty =
164 Ty::apply_one(TypeCtor::Closure { def: self.owner, expr: tgt_expr }, sig_ty); 164 Ty::apply_one(TypeCtor::Closure { def: self.owner, expr: tgt_expr }, sig_ty);
@@ -168,6 +168,12 @@ impl<'a> InferenceContext<'a> {
168 // infer the body. 168 // infer the body.
169 self.coerce(&closure_ty, &expected.ty); 169 self.coerce(&closure_ty, &expected.ty);
170 170
171 // Now go through the argument patterns
172 for (arg_pat, arg_ty) in args.iter().zip(sig_tys) {
173 let resolved = self.resolve_ty_as_possible(arg_ty);
174 self.infer_pat(*arg_pat, &resolved, BindingMode::default());
175 }
176
171 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe); 177 let prev_diverges = mem::replace(&mut self.diverges, Diverges::Maybe);
172 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone()); 178 let prev_ret_ty = mem::replace(&mut self.return_ty, ret_ty.clone());
173 179
@@ -350,19 +356,28 @@ impl<'a> InferenceContext<'a> {
350 // FIXME check the cast... 356 // FIXME check the cast...
351 cast_ty 357 cast_ty
352 } 358 }
353 Expr::Ref { expr, mutability } => { 359 Expr::Ref { expr, rawness, mutability } => {
354 let expectation = 360 let expectation = if let Some((exp_inner, exp_rawness, exp_mutability)) =
355 if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { 361 &expected.ty.as_reference_or_ptr()
356 if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { 362 {
357 // FIXME: throw type error - expected mut reference but found shared ref, 363 if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared {
358 // which cannot be coerced 364 // FIXME: throw type error - expected mut reference but found shared ref,
359 } 365 // which cannot be coerced
360 Expectation::rvalue_hint(Ty::clone(exp_inner)) 366 }
361 } else { 367 if *exp_rawness == Rawness::Ref && *rawness == Rawness::RawPtr {
362 Expectation::none() 368 // FIXME: throw type error - expected reference but found ptr,
363 }; 369 // which cannot be coerced
370 }
371 Expectation::rvalue_hint(Ty::clone(exp_inner))
372 } else {
373 Expectation::none()
374 };
364 let inner_ty = self.infer_expr_inner(*expr, &expectation); 375 let inner_ty = self.infer_expr_inner(*expr, &expectation);
365 Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) 376 let ty = match rawness {
377 Rawness::RawPtr => TypeCtor::RawPtr(*mutability),
378 Rawness::Ref => TypeCtor::Ref(*mutability),
379 };
380 Ty::apply_one(ty, inner_ty)
366 } 381 }
367 Expr::Box { expr } => { 382 Expr::Box { expr } => {
368 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 383 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs
index c87ee06ce..9fa8d3bdc 100644
--- a/crates/ra_hir_ty/src/lib.rs
+++ b/crates/ra_hir_ty/src/lib.rs
@@ -49,8 +49,10 @@ use std::sync::Arc;
49use std::{iter, mem}; 49use std::{iter, mem};
50 50
51use hir_def::{ 51use hir_def::{
52 expr::ExprId, type_ref::Mutability, AdtId, AssocContainerId, DefWithBodyId, GenericDefId, 52 expr::ExprId,
53 HasModule, Lookup, TraitId, TypeAliasId, TypeParamId, 53 type_ref::{Mutability, Rawness},
54 AdtId, AssocContainerId, DefWithBodyId, GenericDefId, HasModule, Lookup, TraitId, TypeAliasId,
55 TypeParamId,
54}; 56};
55use ra_db::{impl_intern_key, salsa, CrateId}; 57use ra_db::{impl_intern_key, salsa, CrateId};
56 58
@@ -155,10 +157,16 @@ pub enum TypeCtor {
155/// This exists just for Chalk, because Chalk just has a single `StructId` where 157/// This exists just for Chalk, because Chalk just has a single `StructId` where
156/// we have different kinds of ADTs, primitive types and special type 158/// we have different kinds of ADTs, primitive types and special type
157/// constructors like tuples and function pointers. 159/// constructors like tuples and function pointers.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
159pub struct TypeCtorId(salsa::InternId); 161pub struct TypeCtorId(salsa::InternId);
160impl_intern_key!(TypeCtorId); 162impl_intern_key!(TypeCtorId);
161 163
164/// This exists just for Chalk, because Chalk just has a single `FnDefId` where
165/// we have different IDs for struct and enum variant constructors.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
167pub struct CallableDefId(salsa::InternId);
168impl_intern_key!(CallableDefId);
169
162impl TypeCtor { 170impl TypeCtor {
163 pub fn num_ty_params(self, db: &dyn HirDatabase) -> usize { 171 pub fn num_ty_params(self, db: &dyn HirDatabase) -> usize {
164 match self { 172 match self {
@@ -703,6 +711,18 @@ impl Ty {
703 } 711 }
704 } 712 }
705 713
714 pub fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
715 match self {
716 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
717 Some((parameters.as_single(), Rawness::Ref, *mutability))
718 }
719 Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(mutability), parameters }) => {
720 Some((parameters.as_single(), Rawness::RawPtr, *mutability))
721 }
722 _ => None,
723 }
724 }
725
706 pub fn strip_references(&self) -> &Ty { 726 pub fn strip_references(&self) -> &Ty {
707 let mut t: &Ty = self; 727 let mut t: &Ty = self;
708 728
diff --git a/crates/ra_hir_ty/src/tests/coercion.rs b/crates/ra_hir_ty/src/tests/coercion.rs
index 2cc4f4bf9..6f777ed8c 100644
--- a/crates/ra_hir_ty/src/tests/coercion.rs
+++ b/crates/ra_hir_ty/src/tests/coercion.rs
@@ -116,15 +116,20 @@ fn infer_let_stmt_coerce() {
116 assert_snapshot!( 116 assert_snapshot!(
117 infer(r#" 117 infer(r#"
118fn test() { 118fn test() {
119 let x: &[i32] = &[1]; 119 let x: &[isize] = &[1];
120 let x: *const [isize] = &[1];
120} 121}
121"#), 122"#),
122 @r###" 123 @r###"
123 11..40 '{ ...[1]; }': () 124 11..76 '{ ...[1]; }': ()
124 21..22 'x': &[i32] 125 21..22 'x': &[isize]
125 33..37 '&[1]': &[i32; _] 126 35..39 '&[1]': &[isize; _]
126 34..37 '[1]': [i32; _] 127 36..39 '[1]': [isize; _]
127 35..36 '1': i32 128 37..38 '1': isize
129 49..50 'x': *const [isize]
130 69..73 '&[1]': &[isize; _]
131 70..73 '[1]': [isize; _]
132 71..72 '1': isize
128 "###); 133 "###);
129} 134}
130 135
diff --git a/crates/ra_hir_ty/src/tests/patterns.rs b/crates/ra_hir_ty/src/tests/patterns.rs
index 0c5f972a2..fe62587c0 100644
--- a/crates/ra_hir_ty/src/tests/patterns.rs
+++ b/crates/ra_hir_ty/src/tests/patterns.rs
@@ -520,3 +520,53 @@ fn main() {
520 105..107 '()': () 520 105..107 '()': ()
521 ") 521 ")
522} 522}
523
524#[test]
525fn match_ergonomics_in_closure_params() {
526 assert_snapshot!(
527 infer(r#"
528#[lang = "fn_once"]
529trait FnOnce<Args> {
530 type Output;
531}
532
533fn foo<T, U, F: FnOnce(T) -> U>(t: T, f: F) -> U { loop {} }
534
535fn test() {
536 foo(&(1, "a"), |&(x, y)| x); // normal, no match ergonomics
537 foo(&(1, "a"), |(x, y)| x);
538}
539"#),
540 @r###"
541 94..95 't': T
542 100..101 'f': F
543 111..122 '{ loop {} }': U
544 113..120 'loop {}': !
545 118..120 '{}': ()
546 134..233 '{ ... x); }': ()
547 140..143 'foo': fn foo<&(i32, &str), i32, |&(i32, &str)| -> i32>(&(i32, &str), |&(i32, &str)| -> i32) -> i32
548 140..167 'foo(&(...y)| x)': i32
549 144..153 '&(1, "a")': &(i32, &str)
550 145..153 '(1, "a")': (i32, &str)
551 146..147 '1': i32
552 149..152 '"a"': &str
553 155..166 '|&(x, y)| x': |&(i32, &str)| -> i32
554 156..163 '&(x, y)': &(i32, &str)
555 157..163 '(x, y)': (i32, &str)
556 158..159 'x': i32
557 161..162 'y': &str
558 165..166 'x': i32
559 204..207 'foo': fn foo<&(i32, &str), &i32, |&(i32, &str)| -> &i32>(&(i32, &str), |&(i32, &str)| -> &i32) -> &i32
560 204..230 'foo(&(...y)| x)': &i32
561 208..217 '&(1, "a")': &(i32, &str)
562 209..217 '(1, "a")': (i32, &str)
563 210..211 '1': i32
564 213..216 '"a"': &str
565 219..229 '|(x, y)| x': |&(i32, &str)| -> &i32
566 220..226 '(x, y)': (i32, &str)
567 221..222 'x': &i32
568 224..225 'y': &&str
569 228..229 'x': &i32
570 "###
571 );
572}
diff --git a/crates/ra_hir_ty/src/tests/simple.rs b/crates/ra_hir_ty/src/tests/simple.rs
index fd2208af2..839491b9e 100644
--- a/crates/ra_hir_ty/src/tests/simple.rs
+++ b/crates/ra_hir_ty/src/tests/simple.rs
@@ -385,6 +385,26 @@ fn test(a: &u32, b: &mut u32, c: *const u32, d: *mut u32) {
385} 385}
386 386
387#[test] 387#[test]
388fn infer_raw_ref() {
389 assert_snapshot!(
390 infer(r#"
391fn test(a: i32) {
392 &raw mut a;
393 &raw const a;
394}
395"#),
396 @r###"
397 9..10 'a': i32
398 17..54 '{ ...t a; }': ()
399 23..33 '&raw mut a': *mut i32
400 32..33 'a': i32
401 39..51 '&raw const a': *const i32
402 50..51 'a': i32
403 "###
404 );
405}
406
407#[test]
388fn infer_literals() { 408fn infer_literals() {
389 assert_snapshot!( 409 assert_snapshot!(
390 infer(r##" 410 infer(r##"
@@ -937,7 +957,7 @@ fn main(foo: Foo) {
937 51..107 'if tru... }': () 957 51..107 'if tru... }': ()
938 54..58 'true': bool 958 54..58 'true': bool
939 59..67 '{ }': () 959 59..67 '{ }': ()
940 73..107 'if fal... }': () 960 73..107 'if fal... }': i32
941 76..81 'false': bool 961 76..81 'false': bool
942 82..107 '{ ... }': i32 962 82..107 '{ ... }': i32
943 92..95 'foo': Foo 963 92..95 'foo': Foo
diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs
index 34f4b9039..e8778d419 100644
--- a/crates/ra_hir_ty/src/tests/traits.rs
+++ b/crates/ra_hir_ty/src/tests/traits.rs
@@ -2602,3 +2602,199 @@ fn test(x: &dyn Foo) {
2602 "### 2602 "###
2603 ); 2603 );
2604} 2604}
2605
2606#[test]
2607fn builtin_copy() {
2608 assert_snapshot!(
2609 infer_with_mismatches(r#"
2610#[lang = "copy"]
2611trait Copy {}
2612
2613struct IsCopy;
2614impl Copy for IsCopy {}
2615struct NotCopy;
2616
2617trait Test { fn test(&self) -> bool; }
2618impl<T: Copy> Test for T {}
2619
2620fn test() {
2621 IsCopy.test();
2622 NotCopy.test();
2623 (IsCopy, IsCopy).test();
2624 (IsCopy, NotCopy).test();
2625}
2626"#, true),
2627 @r###"
2628 111..115 'self': &Self
2629 167..268 '{ ...t(); }': ()
2630 173..179 'IsCopy': IsCopy
2631 173..186 'IsCopy.test()': bool
2632 192..199 'NotCopy': NotCopy
2633 192..206 'NotCopy.test()': {unknown}
2634 212..228 '(IsCop...sCopy)': (IsCopy, IsCopy)
2635 212..235 '(IsCop...test()': bool
2636 213..219 'IsCopy': IsCopy
2637 221..227 'IsCopy': IsCopy
2638 241..258 '(IsCop...tCopy)': (IsCopy, NotCopy)
2639 241..265 '(IsCop...test()': {unknown}
2640 242..248 'IsCopy': IsCopy
2641 250..257 'NotCopy': NotCopy
2642 "###
2643 );
2644}
2645
2646#[test]
2647fn builtin_fn_def_copy() {
2648 assert_snapshot!(
2649 infer_with_mismatches(r#"
2650#[lang = "copy"]
2651trait Copy {}
2652
2653fn foo() {}
2654fn bar<T: Copy>(T) -> T {}
2655struct Struct(usize);
2656enum Enum { Variant(usize) }
2657
2658trait Test { fn test(&self) -> bool; }
2659impl<T: Copy> Test for T {}
2660
2661fn test() {
2662 foo.test();
2663 bar.test();
2664 Struct.test();
2665 Enum::Variant.test();
2666}
2667"#, true),
2668 @r###"
2669 42..44 '{}': ()
2670 61..62 'T': {unknown}
2671 69..71 '{}': ()
2672 69..71: expected T, got ()
2673 146..150 'self': &Self
2674 202..282 '{ ...t(); }': ()
2675 208..211 'foo': fn foo()
2676 208..218 'foo.test()': bool
2677 224..227 'bar': fn bar<{unknown}>({unknown}) -> {unknown}
2678 224..234 'bar.test()': bool
2679 240..246 'Struct': Struct(usize) -> Struct
2680 240..253 'Struct.test()': bool
2681 259..272 'Enum::Variant': Variant(usize) -> Enum
2682 259..279 'Enum::...test()': bool
2683 "###
2684 );
2685}
2686
2687#[test]
2688fn builtin_fn_ptr_copy() {
2689 assert_snapshot!(
2690 infer_with_mismatches(r#"
2691#[lang = "copy"]
2692trait Copy {}
2693
2694trait Test { fn test(&self) -> bool; }
2695impl<T: Copy> Test for T {}
2696
2697fn test(f1: fn(), f2: fn(usize) -> u8, f3: fn(u8, u8) -> &u8) {
2698 f1.test();
2699 f2.test();
2700 f3.test();
2701}
2702"#, true),
2703 @r###"
2704 55..59 'self': &Self
2705 109..111 'f1': fn()
2706 119..121 'f2': fn(usize) -> u8
2707 140..142 'f3': fn(u8, u8) -> &u8
2708 163..211 '{ ...t(); }': ()
2709 169..171 'f1': fn()
2710 169..178 'f1.test()': bool
2711 184..186 'f2': fn(usize) -> u8
2712 184..193 'f2.test()': bool
2713 199..201 'f3': fn(u8, u8) -> &u8
2714 199..208 'f3.test()': bool
2715 "###
2716 );
2717}
2718
2719#[test]
2720fn builtin_sized() {
2721 assert_snapshot!(
2722 infer_with_mismatches(r#"
2723#[lang = "sized"]
2724trait Sized {}
2725
2726trait Test { fn test(&self) -> bool; }
2727impl<T: Sized> Test for T {}
2728
2729fn test() {
2730 1u8.test();
2731 (*"foo").test(); // not Sized
2732 (1u8, 1u8).test();
2733 (1u8, *"foo").test(); // not Sized
2734}
2735"#, true),
2736 @r###"
2737 57..61 'self': &Self
2738 114..229 '{ ...ized }': ()
2739 120..123 '1u8': u8
2740 120..130 '1u8.test()': bool
2741 136..151 '(*"foo").test()': {unknown}
2742 137..143 '*"foo"': str
2743 138..143 '"foo"': &str
2744 170..180 '(1u8, 1u8)': (u8, u8)
2745 170..187 '(1u8, ...test()': bool
2746 171..174 '1u8': u8
2747 176..179 '1u8': u8
2748 193..206 '(1u8, *"foo")': (u8, str)
2749 193..213 '(1u8, ...test()': {unknown}
2750 194..197 '1u8': u8
2751 199..205 '*"foo"': str
2752 200..205 '"foo"': &str
2753 "###
2754 );
2755}
2756
2757#[test]
2758fn integer_range_iterate() {
2759 let t = type_at(
2760 r#"
2761//- /main.rs crate:main deps:std
2762fn test() {
2763 for x in 0..100 { x<|>; }
2764}
2765
2766//- /std.rs crate:std
2767pub mod ops {
2768 pub struct Range<Idx> {
2769 pub start: Idx,
2770 pub end: Idx,
2771 }
2772}
2773
2774pub mod iter {
2775 pub trait Iterator {
2776 type Item;
2777 }
2778
2779 pub trait IntoIterator {
2780 type Item;
2781 type IntoIter: Iterator<Item = Self::Item>;
2782 }
2783
2784 impl<T> IntoIterator for T where T: Iterator {
2785 type Item = <T as Iterator>::Item;
2786 type IntoIter = Self;
2787 }
2788}
2789
2790trait Step {}
2791impl Step for i32 {}
2792impl Step for i64 {}
2793
2794impl<A: Step> iter::Iterator for ops::Range<A> {
2795 type Item = A;
2796}
2797"#,
2798 );
2799 assert_eq!(t, "i32");
2800}
diff --git a/crates/ra_hir_ty/src/traits/builtin.rs b/crates/ra_hir_ty/src/traits/builtin.rs
index ccab246bf..88a422d2c 100644
--- a/crates/ra_hir_ty/src/traits/builtin.rs
+++ b/crates/ra_hir_ty/src/traits/builtin.rs
@@ -290,8 +290,7 @@ fn trait_object_unsize_impl_datum(
290 let self_trait_ref = TraitRef { trait_, substs: self_substs }; 290 let self_trait_ref = TraitRef { trait_, substs: self_substs };
291 let where_clauses = vec![GenericPredicate::Implemented(self_trait_ref)]; 291 let where_clauses = vec![GenericPredicate::Implemented(self_trait_ref)];
292 292
293 let impl_substs = 293 let impl_substs = Substs::builder(2).push(self_ty).push(Ty::Dyn(target_bounds.into())).build();
294 Substs::builder(2).push(self_ty).push(Ty::Dyn(target_bounds.clone().into())).build();
295 294
296 let trait_ref = TraitRef { trait_: unsize_trait, substs: impl_substs }; 295 let trait_ref = TraitRef { trait_: unsize_trait, substs: impl_substs };
297 296
diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs
index 5870618a0..61de3cc30 100644
--- a/crates/ra_hir_ty/src/traits/chalk.rs
+++ b/crates/ra_hir_ty/src/traits/chalk.rs
@@ -1,301 +1,29 @@
1//! Conversion code from/to Chalk. 1//! Conversion code from/to Chalk.
2use std::{fmt, sync::Arc}; 2use std::sync::Arc;
3 3
4use log::debug; 4use log::debug;
5 5
6use chalk_ir::{ 6use chalk_ir::{fold::shift::Shift, GenericArg, TypeName};
7 cast::Cast, fold::shift::Shift, interner::HasInterner, Goal, GoalData, Parameter, 7use chalk_solve::rust_ir::{self, WellKnownTrait};
8 PlaceholderIndex, TypeName, UniverseIndex,
9};
10 8
11use hir_def::{AssocContainerId, AssocItemId, GenericDefId, HasModule, Lookup, TypeAliasId}; 9use hir_def::{
12use ra_db::{ 10 lang_item::{lang_attr, LangItemTarget},
13 salsa::{InternId, InternKey}, 11 AssocContainerId, AssocItemId, HasModule, Lookup, TypeAliasId,
14 CrateId,
15}; 12};
13use ra_db::{salsa::InternKey, CrateId};
16 14
17use super::{builtin, AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; 15use super::{builtin, AssocTyValue, ChalkContext, Impl};
18use crate::{ 16use crate::{
19 db::HirDatabase, display::HirDisplay, method_resolution::TyFingerprint, utils::generics, 17 db::HirDatabase, display::HirDisplay, method_resolution::TyFingerprint, utils::generics,
20 ApplicationTy, DebruijnIndex, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, 18 CallableDef, DebruijnIndex, GenericPredicate, Substs, Ty, TypeCtor,
21}; 19};
20use mapping::{convert_where_clauses, generic_predicate_to_inline_bound, make_binders};
22 21
23pub(super) mod tls; 22pub use self::interner::*;
24
25#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
26pub struct Interner;
27
28impl chalk_ir::interner::Interner for Interner {
29 type InternedType = Box<chalk_ir::TyData<Self>>;
30 type InternedLifetime = chalk_ir::LifetimeData<Self>;
31 type InternedParameter = chalk_ir::ParameterData<Self>;
32 type InternedGoal = Arc<GoalData<Self>>;
33 type InternedGoals = Vec<Goal<Self>>;
34 type InternedSubstitution = Vec<Parameter<Self>>;
35 type InternedProgramClause = chalk_ir::ProgramClauseData<Self>;
36 type InternedProgramClauses = Arc<[chalk_ir::ProgramClause<Self>]>;
37 type InternedQuantifiedWhereClauses = Vec<chalk_ir::QuantifiedWhereClause<Self>>;
38 type InternedParameterKinds = Vec<chalk_ir::ParameterKind<()>>;
39 type InternedCanonicalVarKinds = Vec<chalk_ir::ParameterKind<UniverseIndex>>;
40 type Identifier = TypeAliasId;
41 type DefId = InternId;
42
43 fn debug_struct_id(
44 type_kind_id: StructId,
45 fmt: &mut fmt::Formatter<'_>,
46 ) -> Option<fmt::Result> {
47 tls::with_current_program(|prog| Some(prog?.debug_struct_id(type_kind_id, fmt)))
48 }
49
50 fn debug_trait_id(type_kind_id: TraitId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
51 tls::with_current_program(|prog| Some(prog?.debug_trait_id(type_kind_id, fmt)))
52 }
53
54 fn debug_assoc_type_id(id: AssocTypeId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
55 tls::with_current_program(|prog| Some(prog?.debug_assoc_type_id(id, fmt)))
56 }
57
58 fn debug_alias(
59 alias: &chalk_ir::AliasTy<Interner>,
60 fmt: &mut fmt::Formatter<'_>,
61 ) -> Option<fmt::Result> {
62 tls::with_current_program(|prog| Some(prog?.debug_alias(alias, fmt)))
63 }
64
65 fn debug_projection_ty(
66 proj: &chalk_ir::ProjectionTy<Interner>,
67 fmt: &mut fmt::Formatter<'_>,
68 ) -> Option<fmt::Result> {
69 tls::with_current_program(|prog| Some(prog?.debug_projection_ty(proj, fmt)))
70 }
71
72 fn debug_opaque_ty(
73 opaque_ty: &chalk_ir::OpaqueTy<Interner>,
74 fmt: &mut fmt::Formatter<'_>,
75 ) -> Option<fmt::Result> {
76 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty(opaque_ty, fmt)))
77 }
78
79 fn debug_opaque_ty_id(
80 opaque_ty_id: chalk_ir::OpaqueTyId<Self>,
81 fmt: &mut fmt::Formatter<'_>,
82 ) -> Option<fmt::Result> {
83 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty_id(opaque_ty_id, fmt)))
84 }
85
86 fn debug_ty(ty: &chalk_ir::Ty<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
87 tls::with_current_program(|prog| Some(prog?.debug_ty(ty, fmt)))
88 }
89
90 fn debug_lifetime(
91 lifetime: &chalk_ir::Lifetime<Interner>,
92 fmt: &mut fmt::Formatter<'_>,
93 ) -> Option<fmt::Result> {
94 tls::with_current_program(|prog| Some(prog?.debug_lifetime(lifetime, fmt)))
95 }
96
97 fn debug_parameter(
98 parameter: &Parameter<Interner>,
99 fmt: &mut fmt::Formatter<'_>,
100 ) -> Option<fmt::Result> {
101 tls::with_current_program(|prog| Some(prog?.debug_parameter(parameter, fmt)))
102 }
103
104 fn debug_goal(goal: &Goal<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
105 tls::with_current_program(|prog| Some(prog?.debug_goal(goal, fmt)))
106 }
107
108 fn debug_goals(
109 goals: &chalk_ir::Goals<Interner>,
110 fmt: &mut fmt::Formatter<'_>,
111 ) -> Option<fmt::Result> {
112 tls::with_current_program(|prog| Some(prog?.debug_goals(goals, fmt)))
113 }
114
115 fn debug_program_clause_implication(
116 pci: &chalk_ir::ProgramClauseImplication<Interner>,
117 fmt: &mut fmt::Formatter<'_>,
118 ) -> Option<fmt::Result> {
119 tls::with_current_program(|prog| Some(prog?.debug_program_clause_implication(pci, fmt)))
120 }
121
122 fn debug_application_ty(
123 application_ty: &chalk_ir::ApplicationTy<Interner>,
124 fmt: &mut fmt::Formatter<'_>,
125 ) -> Option<fmt::Result> {
126 tls::with_current_program(|prog| Some(prog?.debug_application_ty(application_ty, fmt)))
127 }
128
129 fn debug_substitution(
130 substitution: &chalk_ir::Substitution<Interner>,
131 fmt: &mut fmt::Formatter<'_>,
132 ) -> Option<fmt::Result> {
133 tls::with_current_program(|prog| Some(prog?.debug_substitution(substitution, fmt)))
134 }
135
136 fn debug_separator_trait_ref(
137 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>,
138 fmt: &mut fmt::Formatter<'_>,
139 ) -> Option<fmt::Result> {
140 tls::with_current_program(|prog| {
141 Some(prog?.debug_separator_trait_ref(separator_trait_ref, fmt))
142 })
143 }
144
145 fn intern_ty(&self, ty: chalk_ir::TyData<Self>) -> Box<chalk_ir::TyData<Self>> {
146 Box::new(ty)
147 }
148
149 fn ty_data<'a>(&self, ty: &'a Box<chalk_ir::TyData<Self>>) -> &'a chalk_ir::TyData<Self> {
150 ty
151 }
152
153 fn intern_lifetime(
154 &self,
155 lifetime: chalk_ir::LifetimeData<Self>,
156 ) -> chalk_ir::LifetimeData<Self> {
157 lifetime
158 }
159
160 fn lifetime_data<'a>(
161 &self,
162 lifetime: &'a chalk_ir::LifetimeData<Self>,
163 ) -> &'a chalk_ir::LifetimeData<Self> {
164 lifetime
165 }
166
167 fn intern_parameter(
168 &self,
169 parameter: chalk_ir::ParameterData<Self>,
170 ) -> chalk_ir::ParameterData<Self> {
171 parameter
172 }
173
174 fn parameter_data<'a>(
175 &self,
176 parameter: &'a chalk_ir::ParameterData<Self>,
177 ) -> &'a chalk_ir::ParameterData<Self> {
178 parameter
179 }
180
181 fn intern_goal(&self, goal: GoalData<Self>) -> Arc<GoalData<Self>> {
182 Arc::new(goal)
183 }
184
185 fn intern_goals<E>(
186 &self,
187 data: impl IntoIterator<Item = Result<Goal<Self>, E>>,
188 ) -> Result<Self::InternedGoals, E> {
189 data.into_iter().collect()
190 }
191
192 fn goal_data<'a>(&self, goal: &'a Arc<GoalData<Self>>) -> &'a GoalData<Self> {
193 goal
194 }
195
196 fn goals_data<'a>(&self, goals: &'a Vec<Goal<Interner>>) -> &'a [Goal<Interner>] {
197 goals
198 }
199
200 fn intern_substitution<E>(
201 &self,
202 data: impl IntoIterator<Item = Result<Parameter<Self>, E>>,
203 ) -> Result<Vec<Parameter<Self>>, E> {
204 data.into_iter().collect()
205 }
206
207 fn substitution_data<'a>(
208 &self,
209 substitution: &'a Vec<Parameter<Self>>,
210 ) -> &'a [Parameter<Self>] {
211 substitution
212 }
213
214 fn intern_program_clause(
215 &self,
216 data: chalk_ir::ProgramClauseData<Self>,
217 ) -> chalk_ir::ProgramClauseData<Self> {
218 data
219 }
220
221 fn program_clause_data<'a>(
222 &self,
223 clause: &'a chalk_ir::ProgramClauseData<Self>,
224 ) -> &'a chalk_ir::ProgramClauseData<Self> {
225 clause
226 }
227
228 fn intern_program_clauses<E>(
229 &self,
230 data: impl IntoIterator<Item = Result<chalk_ir::ProgramClause<Self>, E>>,
231 ) -> Result<Arc<[chalk_ir::ProgramClause<Self>]>, E> {
232 data.into_iter().collect()
233 }
234
235 fn program_clauses_data<'a>(
236 &self,
237 clauses: &'a Arc<[chalk_ir::ProgramClause<Self>]>,
238 ) -> &'a [chalk_ir::ProgramClause<Self>] {
239 &clauses
240 }
241
242 fn intern_quantified_where_clauses<E>(
243 &self,
244 data: impl IntoIterator<Item = Result<chalk_ir::QuantifiedWhereClause<Self>, E>>,
245 ) -> Result<Self::InternedQuantifiedWhereClauses, E> {
246 data.into_iter().collect()
247 }
248 23
249 fn quantified_where_clauses_data<'a>( 24pub(super) mod tls;
250 &self, 25mod interner;
251 clauses: &'a Self::InternedQuantifiedWhereClauses, 26mod mapping;
252 ) -> &'a [chalk_ir::QuantifiedWhereClause<Self>] {
253 clauses
254 }
255
256 fn intern_parameter_kinds<E>(
257 &self,
258 data: impl IntoIterator<Item = Result<chalk_ir::ParameterKind<()>, E>>,
259 ) -> Result<Self::InternedParameterKinds, E> {
260 data.into_iter().collect()
261 }
262
263 fn parameter_kinds_data<'a>(
264 &self,
265 parameter_kinds: &'a Self::InternedParameterKinds,
266 ) -> &'a [chalk_ir::ParameterKind<()>] {
267 &parameter_kinds
268 }
269
270 fn intern_canonical_var_kinds<E>(
271 &self,
272 data: impl IntoIterator<Item = Result<chalk_ir::ParameterKind<UniverseIndex>, E>>,
273 ) -> Result<Self::InternedCanonicalVarKinds, E> {
274 data.into_iter().collect()
275 }
276
277 fn canonical_var_kinds_data<'a>(
278 &self,
279 canonical_var_kinds: &'a Self::InternedCanonicalVarKinds,
280 ) -> &'a [chalk_ir::ParameterKind<UniverseIndex>] {
281 &canonical_var_kinds
282 }
283}
284
285impl chalk_ir::interner::HasInterner for Interner {
286 type Interner = Self;
287}
288
289pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
290pub type AssociatedTyDatum = chalk_rust_ir::AssociatedTyDatum<Interner>;
291pub type TraitId = chalk_ir::TraitId<Interner>;
292pub type TraitDatum = chalk_rust_ir::TraitDatum<Interner>;
293pub type StructId = chalk_ir::StructId<Interner>;
294pub type StructDatum = chalk_rust_ir::StructDatum<Interner>;
295pub type ImplId = chalk_ir::ImplId<Interner>;
296pub type ImplDatum = chalk_rust_ir::ImplDatum<Interner>;
297pub type AssociatedTyValueId = chalk_rust_ir::AssociatedTyValueId<Interner>;
298pub type AssociatedTyValue = chalk_rust_ir::AssociatedTyValue<Interner>;
299 27
300pub(super) trait ToChalk { 28pub(super) trait ToChalk {
301 type Chalk; 29 type Chalk;
@@ -310,508 +38,6 @@ where
310 T::from_chalk(db, chalk) 38 T::from_chalk(db, chalk)
311} 39}
312 40
313impl ToChalk for Ty {
314 type Chalk = chalk_ir::Ty<Interner>;
315 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> {
316 match self {
317 Ty::Apply(apply_ty) => {
318 let name = apply_ty.ctor.to_chalk(db);
319 let substitution = apply_ty.parameters.to_chalk(db);
320 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner)
321 }
322 Ty::Projection(proj_ty) => {
323 let associated_ty_id = proj_ty.associated_ty.to_chalk(db);
324 let substitution = proj_ty.parameters.to_chalk(db);
325 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
326 associated_ty_id,
327 substitution,
328 })
329 .cast(&Interner)
330 .intern(&Interner)
331 }
332 Ty::Placeholder(id) => {
333 let interned_id = db.intern_type_param_id(id);
334 PlaceholderIndex {
335 ui: UniverseIndex::ROOT,
336 idx: interned_id.as_intern_id().as_usize(),
337 }
338 .to_ty::<Interner>(&Interner)
339 }
340 Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx).intern(&Interner),
341 Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
342 Ty::Dyn(predicates) => {
343 let where_clauses = chalk_ir::QuantifiedWhereClauses::from(
344 &Interner,
345 predicates.iter().filter(|p| !p.is_error()).cloned().map(|p| p.to_chalk(db)),
346 );
347 let bounded_ty = chalk_ir::DynTy { bounds: make_binders(where_clauses, 1) };
348 chalk_ir::TyData::Dyn(bounded_ty).intern(&Interner)
349 }
350 Ty::Opaque(_) | Ty::Unknown => {
351 let substitution = chalk_ir::Substitution::empty(&Interner);
352 let name = TypeName::Error;
353 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner)
354 }
355 }
356 }
357 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
358 match chalk.data(&Interner).clone() {
359 chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name {
360 TypeName::Error => Ty::Unknown,
361 _ => {
362 let ctor = from_chalk(db, apply_ty.name);
363 let parameters = from_chalk(db, apply_ty.substitution);
364 Ty::Apply(ApplicationTy { ctor, parameters })
365 }
366 },
367 chalk_ir::TyData::Placeholder(idx) => {
368 assert_eq!(idx.ui, UniverseIndex::ROOT);
369 let interned_id = crate::db::GlobalTypeParamId::from_intern_id(
370 crate::salsa::InternId::from(idx.idx),
371 );
372 Ty::Placeholder(db.lookup_intern_type_param_id(interned_id))
373 }
374 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Projection(proj)) => {
375 let associated_ty = from_chalk(db, proj.associated_ty_id);
376 let parameters = from_chalk(db, proj.substitution);
377 Ty::Projection(ProjectionTy { associated_ty, parameters })
378 }
379 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Opaque(_)) => unimplemented!(),
380 chalk_ir::TyData::Function(_) => unimplemented!(),
381 chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx),
382 chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown,
383 chalk_ir::TyData::Dyn(where_clauses) => {
384 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1);
385 let predicates = where_clauses
386 .bounds
387 .skip_binders()
388 .iter(&Interner)
389 .map(|c| from_chalk(db, c.clone()))
390 .collect();
391 Ty::Dyn(predicates)
392 }
393 }
394 }
395}
396
397impl ToChalk for Substs {
398 type Chalk = chalk_ir::Substitution<Interner>;
399
400 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> {
401 chalk_ir::Substitution::from(&Interner, self.iter().map(|ty| ty.clone().to_chalk(db)))
402 }
403
404 fn from_chalk(db: &dyn HirDatabase, parameters: chalk_ir::Substitution<Interner>) -> Substs {
405 let tys = parameters
406 .iter(&Interner)
407 .map(|p| match p.ty(&Interner) {
408 Some(ty) => from_chalk(db, ty.clone()),
409 None => unimplemented!(),
410 })
411 .collect();
412 Substs(tys)
413 }
414}
415
416impl ToChalk for TraitRef {
417 type Chalk = chalk_ir::TraitRef<Interner>;
418
419 fn to_chalk(self: TraitRef, db: &dyn HirDatabase) -> chalk_ir::TraitRef<Interner> {
420 let trait_id = self.trait_.to_chalk(db);
421 let substitution = self.substs.to_chalk(db);
422 chalk_ir::TraitRef { trait_id, substitution }
423 }
424
425 fn from_chalk(db: &dyn HirDatabase, trait_ref: chalk_ir::TraitRef<Interner>) -> Self {
426 let trait_ = from_chalk(db, trait_ref.trait_id);
427 let substs = from_chalk(db, trait_ref.substitution);
428 TraitRef { trait_, substs }
429 }
430}
431
432impl ToChalk for hir_def::TraitId {
433 type Chalk = TraitId;
434
435 fn to_chalk(self, _db: &dyn HirDatabase) -> TraitId {
436 chalk_ir::TraitId(self.as_intern_id())
437 }
438
439 fn from_chalk(_db: &dyn HirDatabase, trait_id: TraitId) -> hir_def::TraitId {
440 InternKey::from_intern_id(trait_id.0)
441 }
442}
443
444impl ToChalk for TypeCtor {
445 type Chalk = TypeName<Interner>;
446
447 fn to_chalk(self, db: &dyn HirDatabase) -> TypeName<Interner> {
448 match self {
449 TypeCtor::AssociatedType(type_alias) => {
450 let type_id = type_alias.to_chalk(db);
451 TypeName::AssociatedType(type_id)
452 }
453 _ => {
454 // other TypeCtors get interned and turned into a chalk StructId
455 let struct_id = db.intern_type_ctor(self).into();
456 TypeName::Struct(struct_id)
457 }
458 }
459 }
460
461 fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
462 match type_name {
463 TypeName::Struct(struct_id) => db.lookup_intern_type_ctor(struct_id.into()),
464 TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
465 TypeName::OpaqueType(_) => unreachable!(),
466
467 TypeName::Scalar(_) => unreachable!(),
468 TypeName::Tuple(_) => unreachable!(),
469 TypeName::Raw(_) => unreachable!(),
470 TypeName::Slice => unreachable!(),
471 TypeName::Ref(_) => unreachable!(),
472 TypeName::Str => unreachable!(),
473
474 TypeName::Error => {
475 // this should not be reached, since we don't represent TypeName::Error with TypeCtor
476 unreachable!()
477 }
478 }
479 }
480}
481
482impl ToChalk for Impl {
483 type Chalk = ImplId;
484
485 fn to_chalk(self, db: &dyn HirDatabase) -> ImplId {
486 db.intern_chalk_impl(self).into()
487 }
488
489 fn from_chalk(db: &dyn HirDatabase, impl_id: ImplId) -> Impl {
490 db.lookup_intern_chalk_impl(impl_id.into())
491 }
492}
493
494impl ToChalk for TypeAliasId {
495 type Chalk = AssocTypeId;
496
497 fn to_chalk(self, _db: &dyn HirDatabase) -> AssocTypeId {
498 chalk_ir::AssocTypeId(self.as_intern_id())
499 }
500
501 fn from_chalk(_db: &dyn HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId {
502 InternKey::from_intern_id(type_alias_id.0)
503 }
504}
505
506impl ToChalk for AssocTyValue {
507 type Chalk = AssociatedTyValueId;
508
509 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValueId {
510 db.intern_assoc_ty_value(self).into()
511 }
512
513 fn from_chalk(db: &dyn HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue {
514 db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
515 }
516}
517
518impl ToChalk for GenericPredicate {
519 type Chalk = chalk_ir::QuantifiedWhereClause<Interner>;
520
521 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::QuantifiedWhereClause<Interner> {
522 match self {
523 GenericPredicate::Implemented(trait_ref) => {
524 let chalk_trait_ref = trait_ref.to_chalk(db);
525 let chalk_trait_ref = chalk_trait_ref.shifted_in(&Interner);
526 make_binders(chalk_ir::WhereClause::Implemented(chalk_trait_ref), 0)
527 }
528 GenericPredicate::Projection(projection_pred) => {
529 let ty = projection_pred.ty.to_chalk(db).shifted_in(&Interner);
530 let projection = projection_pred.projection_ty.to_chalk(db).shifted_in(&Interner);
531 let alias = chalk_ir::AliasTy::Projection(projection);
532 make_binders(chalk_ir::WhereClause::AliasEq(chalk_ir::AliasEq { alias, ty }), 0)
533 }
534 GenericPredicate::Error => panic!("tried passing GenericPredicate::Error to Chalk"),
535 }
536 }
537
538 fn from_chalk(
539 db: &dyn HirDatabase,
540 where_clause: chalk_ir::QuantifiedWhereClause<Interner>,
541 ) -> GenericPredicate {
542 // we don't produce any where clauses with binders and can't currently deal with them
543 match where_clause
544 .skip_binders()
545 .shifted_out(&Interner)
546 .expect("unexpected bound vars in where clause")
547 {
548 chalk_ir::WhereClause::Implemented(tr) => {
549 GenericPredicate::Implemented(from_chalk(db, tr))
550 }
551 chalk_ir::WhereClause::AliasEq(projection_eq) => {
552 let projection_ty = from_chalk(
553 db,
554 match projection_eq.alias {
555 chalk_ir::AliasTy::Projection(p) => p,
556 _ => unimplemented!(),
557 },
558 );
559 let ty = from_chalk(db, projection_eq.ty);
560 GenericPredicate::Projection(super::ProjectionPredicate { projection_ty, ty })
561 }
562 }
563 }
564}
565
566impl ToChalk for ProjectionTy {
567 type Chalk = chalk_ir::ProjectionTy<Interner>;
568
569 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::ProjectionTy<Interner> {
570 chalk_ir::ProjectionTy {
571 associated_ty_id: self.associated_ty.to_chalk(db),
572 substitution: self.parameters.to_chalk(db),
573 }
574 }
575
576 fn from_chalk(
577 db: &dyn HirDatabase,
578 projection_ty: chalk_ir::ProjectionTy<Interner>,
579 ) -> ProjectionTy {
580 ProjectionTy {
581 associated_ty: from_chalk(db, projection_ty.associated_ty_id),
582 parameters: from_chalk(db, projection_ty.substitution),
583 }
584 }
585}
586
587impl ToChalk for super::ProjectionPredicate {
588 type Chalk = chalk_ir::AliasEq<Interner>;
589
590 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::AliasEq<Interner> {
591 chalk_ir::AliasEq {
592 alias: chalk_ir::AliasTy::Projection(self.projection_ty.to_chalk(db)),
593 ty: self.ty.to_chalk(db),
594 }
595 }
596
597 fn from_chalk(_db: &dyn HirDatabase, _normalize: chalk_ir::AliasEq<Interner>) -> Self {
598 unimplemented!()
599 }
600}
601
602impl ToChalk for Obligation {
603 type Chalk = chalk_ir::DomainGoal<Interner>;
604
605 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::DomainGoal<Interner> {
606 match self {
607 Obligation::Trait(tr) => tr.to_chalk(db).cast(&Interner),
608 Obligation::Projection(pr) => pr.to_chalk(db).cast(&Interner),
609 }
610 }
611
612 fn from_chalk(_db: &dyn HirDatabase, _goal: chalk_ir::DomainGoal<Interner>) -> Self {
613 unimplemented!()
614 }
615}
616
617impl<T> ToChalk for Canonical<T>
618where
619 T: ToChalk,
620 T::Chalk: HasInterner<Interner = Interner>,
621{
622 type Chalk = chalk_ir::Canonical<T::Chalk>;
623
624 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
625 let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT);
626 let value = self.value.to_chalk(db);
627 chalk_ir::Canonical {
628 value,
629 binders: chalk_ir::CanonicalVarKinds::from(&Interner, vec![parameter; self.num_vars]),
630 }
631 }
632
633 fn from_chalk(db: &dyn HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {
634 Canonical {
635 num_vars: canonical.binders.len(&Interner),
636 value: from_chalk(db, canonical.value),
637 }
638 }
639}
640
641impl ToChalk for Arc<super::TraitEnvironment> {
642 type Chalk = chalk_ir::Environment<Interner>;
643
644 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Environment<Interner> {
645 let mut clauses = Vec::new();
646 for pred in &self.predicates {
647 if pred.is_error() {
648 // for env, we just ignore errors
649 continue;
650 }
651 let program_clause: chalk_ir::ProgramClause<Interner> =
652 pred.clone().to_chalk(db).cast(&Interner);
653 clauses.push(program_clause.into_from_env_clause(&Interner));
654 }
655 chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses)
656 }
657
658 fn from_chalk(
659 _db: &dyn HirDatabase,
660 _env: chalk_ir::Environment<Interner>,
661 ) -> Arc<super::TraitEnvironment> {
662 unimplemented!()
663 }
664}
665
666impl<T: ToChalk> ToChalk for super::InEnvironment<T>
667where
668 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>,
669{
670 type Chalk = chalk_ir::InEnvironment<T::Chalk>;
671
672 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
673 chalk_ir::InEnvironment {
674 environment: self.environment.to_chalk(db),
675 goal: self.value.to_chalk(db),
676 }
677 }
678
679 fn from_chalk(
680 db: &dyn HirDatabase,
681 in_env: chalk_ir::InEnvironment<T::Chalk>,
682 ) -> super::InEnvironment<T> {
683 super::InEnvironment {
684 environment: from_chalk(db, in_env.environment),
685 value: from_chalk(db, in_env.goal),
686 }
687 }
688}
689
690impl ToChalk for builtin::BuiltinImplData {
691 type Chalk = ImplDatum;
692
693 fn to_chalk(self, db: &dyn HirDatabase) -> ImplDatum {
694 let impl_type = chalk_rust_ir::ImplType::External;
695 let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect();
696
697 let impl_datum_bound =
698 chalk_rust_ir::ImplDatumBound { trait_ref: self.trait_ref.to_chalk(db), where_clauses };
699 let associated_ty_value_ids =
700 self.assoc_ty_values.into_iter().map(|v| v.to_chalk(db)).collect();
701 chalk_rust_ir::ImplDatum {
702 binders: make_binders(impl_datum_bound, self.num_vars),
703 impl_type,
704 polarity: chalk_rust_ir::Polarity::Positive,
705 associated_ty_value_ids,
706 }
707 }
708
709 fn from_chalk(_db: &dyn HirDatabase, _data: ImplDatum) -> Self {
710 unimplemented!()
711 }
712}
713
714impl ToChalk for builtin::BuiltinImplAssocTyValueData {
715 type Chalk = AssociatedTyValue;
716
717 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValue {
718 let ty = self.value.to_chalk(db);
719 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty };
720
721 chalk_rust_ir::AssociatedTyValue {
722 associated_ty_id: self.assoc_ty_id.to_chalk(db),
723 impl_id: self.impl_.to_chalk(db),
724 value: make_binders(value_bound, self.num_vars),
725 }
726 }
727
728 fn from_chalk(
729 _db: &dyn HirDatabase,
730 _data: AssociatedTyValue,
731 ) -> builtin::BuiltinImplAssocTyValueData {
732 unimplemented!()
733 }
734}
735
736fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T>
737where
738 T: HasInterner<Interner = Interner>,
739{
740 chalk_ir::Binders::new(
741 chalk_ir::ParameterKinds::from(
742 &Interner,
743 std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars),
744 ),
745 value,
746 )
747}
748
749fn convert_where_clauses(
750 db: &dyn HirDatabase,
751 def: GenericDefId,
752 substs: &Substs,
753) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
754 let generic_predicates = db.generic_predicates(def);
755 let mut result = Vec::with_capacity(generic_predicates.len());
756 for pred in generic_predicates.iter() {
757 if pred.value.is_error() {
758 // skip errored predicates completely
759 continue;
760 }
761 result.push(pred.clone().subst(substs).to_chalk(db));
762 }
763 result
764}
765
766fn generic_predicate_to_inline_bound(
767 db: &dyn HirDatabase,
768 pred: &GenericPredicate,
769 self_ty: &Ty,
770) -> Option<chalk_rust_ir::InlineBound<Interner>> {
771 // An InlineBound is like a GenericPredicate, except the self type is left out.
772 // We don't have a special type for this, but Chalk does.
773 match pred {
774 GenericPredicate::Implemented(trait_ref) => {
775 if &trait_ref.substs[0] != self_ty {
776 // we can only convert predicates back to type bounds if they
777 // have the expected self type
778 return None;
779 }
780 let args_no_self = trait_ref.substs[1..]
781 .iter()
782 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
783 .collect();
784 let trait_bound =
785 chalk_rust_ir::TraitBound { trait_id: trait_ref.trait_.to_chalk(db), args_no_self };
786 Some(chalk_rust_ir::InlineBound::TraitBound(trait_bound))
787 }
788 GenericPredicate::Projection(proj) => {
789 if &proj.projection_ty.parameters[0] != self_ty {
790 return None;
791 }
792 let trait_ = match proj.projection_ty.associated_ty.lookup(db.upcast()).container {
793 AssocContainerId::TraitId(t) => t,
794 _ => panic!("associated type not in trait"),
795 };
796 let args_no_self = proj.projection_ty.parameters[1..]
797 .iter()
798 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
799 .collect();
800 let alias_eq_bound = chalk_rust_ir::AliasEqBound {
801 value: proj.ty.clone().to_chalk(db),
802 trait_bound: chalk_rust_ir::TraitBound {
803 trait_id: trait_.to_chalk(db),
804 args_no_self,
805 },
806 associated_ty_id: proj.projection_ty.associated_ty.to_chalk(db),
807 parameters: Vec::new(), // FIXME we don't support generic associated types yet
808 };
809 Some(chalk_rust_ir::InlineBound::AliasEqBound(alias_eq_bound))
810 }
811 GenericPredicate::Error => None,
812 }
813}
814
815impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { 41impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
816 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> { 42 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
817 self.db.associated_ty_data(id) 43 self.db.associated_ty_data(id)
@@ -819,16 +45,24 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
819 fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> { 45 fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
820 self.db.trait_datum(self.krate, trait_id) 46 self.db.trait_datum(self.krate, trait_id)
821 } 47 }
822 fn struct_datum(&self, struct_id: StructId) -> Arc<StructDatum> { 48 fn adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum> {
823 self.db.struct_datum(self.krate, struct_id) 49 self.db.struct_datum(self.krate, struct_id)
824 } 50 }
825 fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> { 51 fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
826 self.db.impl_datum(self.krate, impl_id) 52 self.db.impl_datum(self.krate, impl_id)
827 } 53 }
54
55 fn fn_def_datum(
56 &self,
57 fn_def_id: chalk_ir::FnDefId<Interner>,
58 ) -> Arc<rust_ir::FnDefDatum<Interner>> {
59 self.db.fn_def_datum(self.krate, fn_def_id)
60 }
61
828 fn impls_for_trait( 62 fn impls_for_trait(
829 &self, 63 &self,
830 trait_id: TraitId, 64 trait_id: TraitId,
831 parameters: &[Parameter<Interner>], 65 parameters: &[GenericArg<Interner>],
832 ) -> Vec<ImplId> { 66 ) -> Vec<ImplId> {
833 debug!("impls_for_trait {:?}", trait_id); 67 debug!("impls_for_trait {:?}", trait_id);
834 let trait_: hir_def::TraitId = from_chalk(self.db, trait_id); 68 let trait_: hir_def::TraitId = from_chalk(self.db, trait_id);
@@ -859,7 +93,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
859 debug!("impls_for_trait returned {} impls", result.len()); 93 debug!("impls_for_trait returned {} impls", result.len());
860 result 94 result
861 } 95 }
862 fn impl_provided_for(&self, auto_trait_id: TraitId, struct_id: StructId) -> bool { 96 fn impl_provided_for(&self, auto_trait_id: TraitId, struct_id: AdtId) -> bool {
863 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); 97 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id);
864 false // FIXME 98 false // FIXME
865 } 99 }
@@ -878,10 +112,15 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
878 } 112 }
879 fn well_known_trait_id( 113 fn well_known_trait_id(
880 &self, 114 &self,
881 _well_known_trait: chalk_rust_ir::WellKnownTrait, 115 well_known_trait: rust_ir::WellKnownTrait,
882 ) -> Option<chalk_ir::TraitId<Interner>> { 116 ) -> Option<chalk_ir::TraitId<Interner>> {
883 // FIXME tell Chalk about well-known traits (here and in trait_datum) 117 let lang_attr = lang_attr_from_well_known_trait(well_known_trait);
884 None 118 let lang_items = self.db.crate_lang_items(self.krate);
119 let trait_ = match lang_items.target(lang_attr) {
120 Some(LangItemTarget::TraitId(trait_)) => trait_,
121 _ => return None,
122 };
123 Some(trait_.to_chalk(self.db))
885 } 124 }
886 125
887 fn program_clauses_for_env( 126 fn program_clauses_for_env(
@@ -894,13 +133,13 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
894 fn opaque_ty_data( 133 fn opaque_ty_data(
895 &self, 134 &self,
896 _id: chalk_ir::OpaqueTyId<Interner>, 135 _id: chalk_ir::OpaqueTyId<Interner>,
897 ) -> Arc<chalk_rust_ir::OpaqueTyDatum<Interner>> { 136 ) -> Arc<rust_ir::OpaqueTyDatum<Interner>> {
898 unimplemented!() 137 unimplemented!()
899 } 138 }
900 139
901 fn force_impl_for( 140 fn force_impl_for(
902 &self, 141 &self,
903 _well_known: chalk_rust_ir::WellKnownTrait, 142 _well_known: rust_ir::WellKnownTrait,
904 _ty: &chalk_ir::TyData<Interner>, 143 _ty: &chalk_ir::TyData<Interner>,
905 ) -> Option<bool> { 144 ) -> Option<bool> {
906 // this method is mostly for rustc 145 // this method is mostly for rustc
@@ -911,6 +150,10 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
911 // FIXME: implement actual object safety 150 // FIXME: implement actual object safety
912 true 151 true
913 } 152 }
153
154 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
155 Ty::Unknown.to_chalk(self.db)
156 }
914} 157}
915 158
916pub(crate) fn program_clauses_for_chalk_env_query( 159pub(crate) fn program_clauses_for_chalk_env_query(
@@ -949,7 +192,7 @@ pub(crate) fn associated_ty_data_query(
949 .collect(); 192 .collect();
950 193
951 let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars); 194 let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars);
952 let bound_data = chalk_rust_ir::AssociatedTyDatumBound { bounds, where_clauses }; 195 let bound_data = rust_ir::AssociatedTyDatumBound { bounds, where_clauses };
953 let datum = AssociatedTyDatum { 196 let datum = AssociatedTyDatum {
954 trait_id: trait_.to_chalk(db), 197 trait_id: trait_.to_chalk(db),
955 id, 198 id,
@@ -970,7 +213,7 @@ pub(crate) fn trait_datum_query(
970 debug!("trait {:?} = {:?}", trait_id, trait_data.name); 213 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
971 let generic_params = generics(db.upcast(), trait_.into()); 214 let generic_params = generics(db.upcast(), trait_.into());
972 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 215 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
973 let flags = chalk_rust_ir::TraitFlags { 216 let flags = rust_ir::TraitFlags {
974 auto: trait_data.auto, 217 auto: trait_data.auto,
975 upstream: trait_.lookup(db.upcast()).container.module(db.upcast()).krate != krate, 218 upstream: trait_.lookup(db.upcast()).container.module(db.upcast()).krate != krate,
976 non_enumerable: true, 219 non_enumerable: true,
@@ -982,8 +225,9 @@ pub(crate) fn trait_datum_query(
982 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars); 225 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
983 let associated_ty_ids = 226 let associated_ty_ids =
984 trait_data.associated_types().map(|type_alias| type_alias.to_chalk(db)).collect(); 227 trait_data.associated_types().map(|type_alias| type_alias.to_chalk(db)).collect();
985 let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses }; 228 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
986 let well_known = None; // FIXME set this (depending on lang items) 229 let well_known =
230 lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name));
987 let trait_datum = TraitDatum { 231 let trait_datum = TraitDatum {
988 id: trait_id, 232 id: trait_id,
989 binders: make_binders(trait_datum_bound, bound_vars.len()), 233 binders: make_binders(trait_datum_bound, bound_vars.len()),
@@ -994,13 +238,32 @@ pub(crate) fn trait_datum_query(
994 Arc::new(trait_datum) 238 Arc::new(trait_datum)
995} 239}
996 240
241fn well_known_trait_from_lang_attr(name: &str) -> Option<WellKnownTrait> {
242 Some(match name {
243 "sized" => WellKnownTrait::SizedTrait,
244 "copy" => WellKnownTrait::CopyTrait,
245 "clone" => WellKnownTrait::CloneTrait,
246 "drop" => WellKnownTrait::DropTrait,
247 _ => return None,
248 })
249}
250
251fn lang_attr_from_well_known_trait(attr: WellKnownTrait) -> &'static str {
252 match attr {
253 WellKnownTrait::SizedTrait => "sized",
254 WellKnownTrait::CopyTrait => "copy",
255 WellKnownTrait::CloneTrait => "clone",
256 WellKnownTrait::DropTrait => "drop",
257 }
258}
259
997pub(crate) fn struct_datum_query( 260pub(crate) fn struct_datum_query(
998 db: &dyn HirDatabase, 261 db: &dyn HirDatabase,
999 krate: CrateId, 262 krate: CrateId,
1000 struct_id: StructId, 263 struct_id: AdtId,
1001) -> Arc<StructDatum> { 264) -> Arc<StructDatum> {
1002 debug!("struct_datum {:?}", struct_id); 265 debug!("struct_datum {:?}", struct_id);
1003 let type_ctor: TypeCtor = from_chalk(db, TypeName::Struct(struct_id)); 266 let type_ctor: TypeCtor = from_chalk(db, TypeName::Adt(struct_id));
1004 debug!("struct {:?} = {:?}", struct_id, type_ctor); 267 debug!("struct {:?} = {:?}", struct_id, type_ctor);
1005 let num_params = type_ctor.num_ty_params(db); 268 let num_params = type_ctor.num_ty_params(db);
1006 let upstream = type_ctor.krate(db) != Some(krate); 269 let upstream = type_ctor.krate(db) != Some(krate);
@@ -1012,12 +275,12 @@ pub(crate) fn struct_datum_query(
1012 convert_where_clauses(db, generic_def, &bound_vars) 275 convert_where_clauses(db, generic_def, &bound_vars)
1013 }) 276 })
1014 .unwrap_or_else(Vec::new); 277 .unwrap_or_else(Vec::new);
1015 let flags = chalk_rust_ir::StructFlags { 278 let flags = rust_ir::AdtFlags {
1016 upstream, 279 upstream,
1017 // FIXME set fundamental flag correctly 280 // FIXME set fundamental flag correctly
1018 fundamental: false, 281 fundamental: false,
1019 }; 282 };
1020 let struct_datum_bound = chalk_rust_ir::StructDatumBound { 283 let struct_datum_bound = rust_ir::AdtDatumBound {
1021 fields: Vec::new(), // FIXME add fields (only relevant for auto traits) 284 fields: Vec::new(), // FIXME add fields (only relevant for auto traits)
1022 where_clauses, 285 where_clauses,
1023 }; 286 };
@@ -1057,9 +320,9 @@ fn impl_def_datum(
1057 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 320 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
1058 let trait_ = trait_ref.trait_; 321 let trait_ = trait_ref.trait_;
1059 let impl_type = if impl_id.lookup(db.upcast()).container.module(db.upcast()).krate == krate { 322 let impl_type = if impl_id.lookup(db.upcast()).container.module(db.upcast()).krate == krate {
1060 chalk_rust_ir::ImplType::Local 323 rust_ir::ImplType::Local
1061 } else { 324 } else {
1062 chalk_rust_ir::ImplType::External 325 rust_ir::ImplType::External
1063 }; 326 };
1064 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars); 327 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
1065 let negative = impl_data.is_negative; 328 let negative = impl_data.is_negative;
@@ -1072,13 +335,9 @@ fn impl_def_datum(
1072 ); 335 );
1073 let trait_ref = trait_ref.to_chalk(db); 336 let trait_ref = trait_ref.to_chalk(db);
1074 337
1075 let polarity = if negative { 338 let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
1076 chalk_rust_ir::Polarity::Negative
1077 } else {
1078 chalk_rust_ir::Polarity::Positive
1079 };
1080 339
1081 let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses }; 340 let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
1082 let trait_data = db.trait_data(trait_); 341 let trait_data = db.trait_data(trait_);
1083 let associated_ty_value_ids = impl_data 342 let associated_ty_value_ids = impl_data
1084 .items 343 .items
@@ -1136,8 +395,8 @@ fn type_alias_associated_ty_value(
1136 .associated_type_by_name(&type_alias_data.name) 395 .associated_type_by_name(&type_alias_data.name)
1137 .expect("assoc ty value should not exist"); // validated when building the impl data as well 396 .expect("assoc ty value should not exist"); // validated when building the impl data as well
1138 let ty = db.ty(type_alias.into()); 397 let ty = db.ty(type_alias.into());
1139 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) }; 398 let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
1140 let value = chalk_rust_ir::AssociatedTyValue { 399 let value = rust_ir::AssociatedTyValue {
1141 impl_id: Impl::ImplDef(impl_id).to_chalk(db), 400 impl_id: Impl::ImplDef(impl_id).to_chalk(db),
1142 associated_ty_id: assoc_ty.to_chalk(db), 401 associated_ty_id: assoc_ty.to_chalk(db),
1143 value: make_binders(value_bound, ty.num_binders), 402 value: make_binders(value_bound, ty.num_binders),
@@ -1145,15 +404,47 @@ fn type_alias_associated_ty_value(
1145 Arc::new(value) 404 Arc::new(value)
1146} 405}
1147 406
1148impl From<StructId> for crate::TypeCtorId { 407pub(crate) fn fn_def_datum_query(
1149 fn from(struct_id: StructId) -> Self { 408 db: &dyn HirDatabase,
1150 InternKey::from_intern_id(struct_id.0) 409 _krate: CrateId,
410 fn_def_id: FnDefId,
411) -> Arc<FnDefDatum> {
412 let callable_def: CallableDef = from_chalk(db, fn_def_id);
413 let generic_params = generics(db.upcast(), callable_def.into());
414 let sig = db.callable_item_signature(callable_def);
415 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
416 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
417 let bound = rust_ir::FnDefDatumBound {
418 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
419 argument_types: sig.value.params().iter().map(|ty| ty.clone().to_chalk(db)).collect(),
420 return_type: sig.value.ret().clone().to_chalk(db),
421 where_clauses,
422 };
423 let datum = FnDefDatum { id: fn_def_id, binders: make_binders(bound, sig.num_binders) };
424 Arc::new(datum)
425}
426
427impl From<AdtId> for crate::TypeCtorId {
428 fn from(struct_id: AdtId) -> Self {
429 struct_id.0
1151 } 430 }
1152} 431}
1153 432
1154impl From<crate::TypeCtorId> for StructId { 433impl From<crate::TypeCtorId> for AdtId {
1155 fn from(type_ctor_id: crate::TypeCtorId) -> Self { 434 fn from(type_ctor_id: crate::TypeCtorId) -> Self {
1156 chalk_ir::StructId(type_ctor_id.as_intern_id()) 435 chalk_ir::AdtId(type_ctor_id)
436 }
437}
438
439impl From<FnDefId> for crate::CallableDefId {
440 fn from(fn_def_id: FnDefId) -> Self {
441 InternKey::from_intern_id(fn_def_id.0)
442 }
443}
444
445impl From<crate::CallableDefId> for FnDefId {
446 fn from(callable_def_id: crate::CallableDefId) -> Self {
447 chalk_ir::FnDefId(callable_def_id.as_intern_id())
1157 } 448 }
1158} 449}
1159 450
@@ -1169,14 +460,14 @@ impl From<crate::traits::GlobalImplId> for ImplId {
1169 } 460 }
1170} 461}
1171 462
1172impl From<chalk_rust_ir::AssociatedTyValueId<Interner>> for crate::traits::AssocTyValueId { 463impl From<rust_ir::AssociatedTyValueId<Interner>> for crate::traits::AssocTyValueId {
1173 fn from(id: chalk_rust_ir::AssociatedTyValueId<Interner>) -> Self { 464 fn from(id: rust_ir::AssociatedTyValueId<Interner>) -> Self {
1174 Self::from_intern_id(id.0) 465 Self::from_intern_id(id.0)
1175 } 466 }
1176} 467}
1177 468
1178impl From<crate::traits::AssocTyValueId> for chalk_rust_ir::AssociatedTyValueId<Interner> { 469impl From<crate::traits::AssocTyValueId> for rust_ir::AssociatedTyValueId<Interner> {
1179 fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self { 470 fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self {
1180 chalk_rust_ir::AssociatedTyValueId(assoc_ty_value_id.as_intern_id()) 471 rust_ir::AssociatedTyValueId(assoc_ty_value_id.as_intern_id())
1181 } 472 }
1182} 473}
diff --git a/crates/ra_hir_ty/src/traits/chalk/interner.rs b/crates/ra_hir_ty/src/traits/chalk/interner.rs
new file mode 100644
index 000000000..e27074ba6
--- /dev/null
+++ b/crates/ra_hir_ty/src/traits/chalk/interner.rs
@@ -0,0 +1,353 @@
1//! Implementation of the Chalk `Interner` trait, which allows customizing the
2//! representation of the various objects Chalk deals with (types, goals etc.).
3
4use super::tls;
5use chalk_ir::{GenericArg, Goal, GoalData};
6use hir_def::TypeAliasId;
7use ra_db::salsa::InternId;
8use std::{fmt, sync::Arc};
9
10#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
11pub struct Interner;
12
13pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
14pub type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
15pub type TraitId = chalk_ir::TraitId<Interner>;
16pub type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
17pub type AdtId = chalk_ir::AdtId<Interner>;
18pub type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
19pub type ImplId = chalk_ir::ImplId<Interner>;
20pub type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
21pub type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
22pub type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
23pub type FnDefId = chalk_ir::FnDefId<Interner>;
24pub type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
25
26impl chalk_ir::interner::Interner for Interner {
27 type InternedType = Box<chalk_ir::TyData<Self>>; // FIXME use Arc?
28 type InternedLifetime = chalk_ir::LifetimeData<Self>;
29 type InternedConst = Arc<chalk_ir::ConstData<Self>>;
30 type InternedConcreteConst = ();
31 type InternedGenericArg = chalk_ir::GenericArgData<Self>;
32 type InternedGoal = Arc<GoalData<Self>>;
33 type InternedGoals = Vec<Goal<Self>>;
34 type InternedSubstitution = Vec<GenericArg<Self>>;
35 type InternedProgramClause = chalk_ir::ProgramClauseData<Self>;
36 type InternedProgramClauses = Arc<[chalk_ir::ProgramClause<Self>]>;
37 type InternedQuantifiedWhereClauses = Vec<chalk_ir::QuantifiedWhereClause<Self>>;
38 type InternedVariableKinds = Vec<chalk_ir::VariableKind<Self>>;
39 type InternedCanonicalVarKinds = Vec<chalk_ir::CanonicalVarKind<Self>>;
40 type DefId = InternId;
41 type InternedAdtId = crate::TypeCtorId;
42 type Identifier = TypeAliasId;
43
44 fn debug_adt_id(type_kind_id: AdtId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
45 tls::with_current_program(|prog| Some(prog?.debug_struct_id(type_kind_id, fmt)))
46 }
47
48 fn debug_trait_id(type_kind_id: TraitId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
49 tls::with_current_program(|prog| Some(prog?.debug_trait_id(type_kind_id, fmt)))
50 }
51
52 fn debug_assoc_type_id(id: AssocTypeId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
53 tls::with_current_program(|prog| Some(prog?.debug_assoc_type_id(id, fmt)))
54 }
55
56 fn debug_alias(
57 alias: &chalk_ir::AliasTy<Interner>,
58 fmt: &mut fmt::Formatter<'_>,
59 ) -> Option<fmt::Result> {
60 tls::with_current_program(|prog| Some(prog?.debug_alias(alias, fmt)))
61 }
62
63 fn debug_projection_ty(
64 proj: &chalk_ir::ProjectionTy<Interner>,
65 fmt: &mut fmt::Formatter<'_>,
66 ) -> Option<fmt::Result> {
67 tls::with_current_program(|prog| Some(prog?.debug_projection_ty(proj, fmt)))
68 }
69
70 fn debug_opaque_ty(
71 opaque_ty: &chalk_ir::OpaqueTy<Interner>,
72 fmt: &mut fmt::Formatter<'_>,
73 ) -> Option<fmt::Result> {
74 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty(opaque_ty, fmt)))
75 }
76
77 fn debug_opaque_ty_id(
78 opaque_ty_id: chalk_ir::OpaqueTyId<Self>,
79 fmt: &mut fmt::Formatter<'_>,
80 ) -> Option<fmt::Result> {
81 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty_id(opaque_ty_id, fmt)))
82 }
83
84 fn debug_ty(ty: &chalk_ir::Ty<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
85 tls::with_current_program(|prog| Some(prog?.debug_ty(ty, fmt)))
86 }
87
88 fn debug_lifetime(
89 lifetime: &chalk_ir::Lifetime<Interner>,
90 fmt: &mut fmt::Formatter<'_>,
91 ) -> Option<fmt::Result> {
92 tls::with_current_program(|prog| Some(prog?.debug_lifetime(lifetime, fmt)))
93 }
94
95 fn debug_generic_arg(
96 parameter: &GenericArg<Interner>,
97 fmt: &mut fmt::Formatter<'_>,
98 ) -> Option<fmt::Result> {
99 tls::with_current_program(|prog| Some(prog?.debug_generic_arg(parameter, fmt)))
100 }
101
102 fn debug_goal(goal: &Goal<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
103 tls::with_current_program(|prog| Some(prog?.debug_goal(goal, fmt)))
104 }
105
106 fn debug_goals(
107 goals: &chalk_ir::Goals<Interner>,
108 fmt: &mut fmt::Formatter<'_>,
109 ) -> Option<fmt::Result> {
110 tls::with_current_program(|prog| Some(prog?.debug_goals(goals, fmt)))
111 }
112
113 fn debug_program_clause_implication(
114 pci: &chalk_ir::ProgramClauseImplication<Interner>,
115 fmt: &mut fmt::Formatter<'_>,
116 ) -> Option<fmt::Result> {
117 tls::with_current_program(|prog| Some(prog?.debug_program_clause_implication(pci, fmt)))
118 }
119
120 fn debug_application_ty(
121 application_ty: &chalk_ir::ApplicationTy<Interner>,
122 fmt: &mut fmt::Formatter<'_>,
123 ) -> Option<fmt::Result> {
124 tls::with_current_program(|prog| Some(prog?.debug_application_ty(application_ty, fmt)))
125 }
126
127 fn debug_substitution(
128 substitution: &chalk_ir::Substitution<Interner>,
129 fmt: &mut fmt::Formatter<'_>,
130 ) -> Option<fmt::Result> {
131 tls::with_current_program(|prog| Some(prog?.debug_substitution(substitution, fmt)))
132 }
133
134 fn debug_separator_trait_ref(
135 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>,
136 fmt: &mut fmt::Formatter<'_>,
137 ) -> Option<fmt::Result> {
138 tls::with_current_program(|prog| {
139 Some(prog?.debug_separator_trait_ref(separator_trait_ref, fmt))
140 })
141 }
142
143 fn debug_fn_def_id(
144 fn_def_id: chalk_ir::FnDefId<Self>,
145 fmt: &mut fmt::Formatter<'_>,
146 ) -> Option<fmt::Result> {
147 tls::with_current_program(|prog| Some(prog?.debug_fn_def_id(fn_def_id, fmt)))
148 }
149 fn debug_const(
150 constant: &chalk_ir::Const<Self>,
151 fmt: &mut fmt::Formatter<'_>,
152 ) -> Option<fmt::Result> {
153 tls::with_current_program(|prog| Some(prog?.debug_const(constant, fmt)))
154 }
155 fn debug_variable_kinds(
156 variable_kinds: &chalk_ir::VariableKinds<Self>,
157 fmt: &mut fmt::Formatter<'_>,
158 ) -> Option<fmt::Result> {
159 tls::with_current_program(|prog| Some(prog?.debug_variable_kinds(variable_kinds, fmt)))
160 }
161 fn debug_variable_kinds_with_angles(
162 variable_kinds: &chalk_ir::VariableKinds<Self>,
163 fmt: &mut fmt::Formatter<'_>,
164 ) -> Option<fmt::Result> {
165 tls::with_current_program(|prog| {
166 Some(prog?.debug_variable_kinds_with_angles(variable_kinds, fmt))
167 })
168 }
169 fn debug_canonical_var_kinds(
170 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Self>,
171 fmt: &mut fmt::Formatter<'_>,
172 ) -> Option<fmt::Result> {
173 tls::with_current_program(|prog| {
174 Some(prog?.debug_canonical_var_kinds(canonical_var_kinds, fmt))
175 })
176 }
177 fn debug_program_clause(
178 clause: &chalk_ir::ProgramClause<Self>,
179 fmt: &mut fmt::Formatter<'_>,
180 ) -> Option<fmt::Result> {
181 tls::with_current_program(|prog| Some(prog?.debug_program_clause(clause, fmt)))
182 }
183 fn debug_program_clauses(
184 clauses: &chalk_ir::ProgramClauses<Self>,
185 fmt: &mut fmt::Formatter<'_>,
186 ) -> Option<fmt::Result> {
187 tls::with_current_program(|prog| Some(prog?.debug_program_clauses(clauses, fmt)))
188 }
189 fn debug_quantified_where_clauses(
190 clauses: &chalk_ir::QuantifiedWhereClauses<Self>,
191 fmt: &mut fmt::Formatter<'_>,
192 ) -> Option<fmt::Result> {
193 tls::with_current_program(|prog| Some(prog?.debug_quantified_where_clauses(clauses, fmt)))
194 }
195
196 fn intern_ty(&self, ty: chalk_ir::TyData<Self>) -> Box<chalk_ir::TyData<Self>> {
197 Box::new(ty)
198 }
199
200 fn ty_data<'a>(&self, ty: &'a Box<chalk_ir::TyData<Self>>) -> &'a chalk_ir::TyData<Self> {
201 ty
202 }
203
204 fn intern_lifetime(
205 &self,
206 lifetime: chalk_ir::LifetimeData<Self>,
207 ) -> chalk_ir::LifetimeData<Self> {
208 lifetime
209 }
210
211 fn lifetime_data<'a>(
212 &self,
213 lifetime: &'a chalk_ir::LifetimeData<Self>,
214 ) -> &'a chalk_ir::LifetimeData<Self> {
215 lifetime
216 }
217
218 fn intern_const(&self, constant: chalk_ir::ConstData<Self>) -> Arc<chalk_ir::ConstData<Self>> {
219 Arc::new(constant)
220 }
221
222 fn const_data<'a>(
223 &self,
224 constant: &'a Arc<chalk_ir::ConstData<Self>>,
225 ) -> &'a chalk_ir::ConstData<Self> {
226 constant
227 }
228
229 fn const_eq(&self, _ty: &Box<chalk_ir::TyData<Self>>, _c1: &(), _c2: &()) -> bool {
230 true
231 }
232
233 fn intern_generic_arg(
234 &self,
235 parameter: chalk_ir::GenericArgData<Self>,
236 ) -> chalk_ir::GenericArgData<Self> {
237 parameter
238 }
239
240 fn generic_arg_data<'a>(
241 &self,
242 parameter: &'a chalk_ir::GenericArgData<Self>,
243 ) -> &'a chalk_ir::GenericArgData<Self> {
244 parameter
245 }
246
247 fn intern_goal(&self, goal: GoalData<Self>) -> Arc<GoalData<Self>> {
248 Arc::new(goal)
249 }
250
251 fn intern_goals<E>(
252 &self,
253 data: impl IntoIterator<Item = Result<Goal<Self>, E>>,
254 ) -> Result<Self::InternedGoals, E> {
255 data.into_iter().collect()
256 }
257
258 fn goal_data<'a>(&self, goal: &'a Arc<GoalData<Self>>) -> &'a GoalData<Self> {
259 goal
260 }
261
262 fn goals_data<'a>(&self, goals: &'a Vec<Goal<Interner>>) -> &'a [Goal<Interner>] {
263 goals
264 }
265
266 fn intern_substitution<E>(
267 &self,
268 data: impl IntoIterator<Item = Result<GenericArg<Self>, E>>,
269 ) -> Result<Vec<GenericArg<Self>>, E> {
270 data.into_iter().collect()
271 }
272
273 fn substitution_data<'a>(
274 &self,
275 substitution: &'a Vec<GenericArg<Self>>,
276 ) -> &'a [GenericArg<Self>] {
277 substitution
278 }
279
280 fn intern_program_clause(
281 &self,
282 data: chalk_ir::ProgramClauseData<Self>,
283 ) -> chalk_ir::ProgramClauseData<Self> {
284 data
285 }
286
287 fn program_clause_data<'a>(
288 &self,
289 clause: &'a chalk_ir::ProgramClauseData<Self>,
290 ) -> &'a chalk_ir::ProgramClauseData<Self> {
291 clause
292 }
293
294 fn intern_program_clauses<E>(
295 &self,
296 data: impl IntoIterator<Item = Result<chalk_ir::ProgramClause<Self>, E>>,
297 ) -> Result<Arc<[chalk_ir::ProgramClause<Self>]>, E> {
298 data.into_iter().collect()
299 }
300
301 fn program_clauses_data<'a>(
302 &self,
303 clauses: &'a Arc<[chalk_ir::ProgramClause<Self>]>,
304 ) -> &'a [chalk_ir::ProgramClause<Self>] {
305 &clauses
306 }
307
308 fn intern_quantified_where_clauses<E>(
309 &self,
310 data: impl IntoIterator<Item = Result<chalk_ir::QuantifiedWhereClause<Self>, E>>,
311 ) -> Result<Self::InternedQuantifiedWhereClauses, E> {
312 data.into_iter().collect()
313 }
314
315 fn quantified_where_clauses_data<'a>(
316 &self,
317 clauses: &'a Self::InternedQuantifiedWhereClauses,
318 ) -> &'a [chalk_ir::QuantifiedWhereClause<Self>] {
319 clauses
320 }
321
322 fn intern_generic_arg_kinds<E>(
323 &self,
324 data: impl IntoIterator<Item = Result<chalk_ir::VariableKind<Self>, E>>,
325 ) -> Result<Self::InternedVariableKinds, E> {
326 data.into_iter().collect()
327 }
328
329 fn variable_kinds_data<'a>(
330 &self,
331 parameter_kinds: &'a Self::InternedVariableKinds,
332 ) -> &'a [chalk_ir::VariableKind<Self>] {
333 &parameter_kinds
334 }
335
336 fn intern_canonical_var_kinds<E>(
337 &self,
338 data: impl IntoIterator<Item = Result<chalk_ir::CanonicalVarKind<Self>, E>>,
339 ) -> Result<Self::InternedCanonicalVarKinds, E> {
340 data.into_iter().collect()
341 }
342
343 fn canonical_var_kinds_data<'a>(
344 &self,
345 canonical_var_kinds: &'a Self::InternedCanonicalVarKinds,
346 ) -> &'a [chalk_ir::CanonicalVarKind<Self>] {
347 &canonical_var_kinds
348 }
349}
350
351impl chalk_ir::interner::HasInterner for Interner {
352 type Interner = Self;
353}
diff --git a/crates/ra_hir_ty/src/traits/chalk/mapping.rs b/crates/ra_hir_ty/src/traits/chalk/mapping.rs
new file mode 100644
index 000000000..5f6daf842
--- /dev/null
+++ b/crates/ra_hir_ty/src/traits/chalk/mapping.rs
@@ -0,0 +1,701 @@
1//! This module contains the implementations of the `ToChalk` trait, which
2//! handles conversion between our data types and their corresponding types in
3//! Chalk (in both directions); plus some helper functions for more specialized
4//! conversions.
5
6use chalk_ir::{
7 cast::Cast, fold::shift::Shift, interner::HasInterner, PlaceholderIndex, Scalar, TypeName,
8 UniverseIndex,
9};
10use chalk_solve::rust_ir;
11
12use hir_def::{type_ref::Mutability, AssocContainerId, GenericDefId, Lookup, TypeAliasId};
13use ra_db::salsa::InternKey;
14
15use crate::{
16 db::HirDatabase,
17 primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness, Uncertain},
18 traits::{builtin, AssocTyValue, Canonical, Impl, Obligation},
19 ApplicationTy, CallableDef, GenericPredicate, InEnvironment, ProjectionPredicate, ProjectionTy,
20 Substs, TraitEnvironment, TraitRef, Ty, TypeCtor,
21};
22
23use super::interner::*;
24use super::*;
25
26impl ToChalk for Ty {
27 type Chalk = chalk_ir::Ty<Interner>;
28 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> {
29 match self {
30 Ty::Apply(apply_ty) => match apply_ty.ctor {
31 TypeCtor::Ref(m) => ref_to_chalk(db, m, apply_ty.parameters),
32 TypeCtor::FnPtr { num_args: _ } => {
33 let substitution = apply_ty.parameters.to_chalk(db).shifted_in(&Interner);
34 chalk_ir::TyData::Function(chalk_ir::Fn { num_binders: 0, substitution })
35 .intern(&Interner)
36 }
37 _ => {
38 let name = apply_ty.ctor.to_chalk(db);
39 let substitution = apply_ty.parameters.to_chalk(db);
40 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner)
41 }
42 },
43 Ty::Projection(proj_ty) => {
44 let associated_ty_id = proj_ty.associated_ty.to_chalk(db);
45 let substitution = proj_ty.parameters.to_chalk(db);
46 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
47 associated_ty_id,
48 substitution,
49 })
50 .cast(&Interner)
51 .intern(&Interner)
52 }
53 Ty::Placeholder(id) => {
54 let interned_id = db.intern_type_param_id(id);
55 PlaceholderIndex {
56 ui: UniverseIndex::ROOT,
57 idx: interned_id.as_intern_id().as_usize(),
58 }
59 .to_ty::<Interner>(&Interner)
60 }
61 Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx).intern(&Interner),
62 Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
63 Ty::Dyn(predicates) => {
64 let where_clauses = chalk_ir::QuantifiedWhereClauses::from(
65 &Interner,
66 predicates.iter().filter(|p| !p.is_error()).cloned().map(|p| p.to_chalk(db)),
67 );
68 let bounded_ty = chalk_ir::DynTy { bounds: make_binders(where_clauses, 1) };
69 chalk_ir::TyData::Dyn(bounded_ty).intern(&Interner)
70 }
71 Ty::Opaque(_) | Ty::Unknown => {
72 let substitution = chalk_ir::Substitution::empty(&Interner);
73 let name = TypeName::Error;
74 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner)
75 }
76 }
77 }
78 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
79 match chalk.data(&Interner).clone() {
80 chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name {
81 TypeName::Error => Ty::Unknown,
82 TypeName::Ref(m) => ref_from_chalk(db, m, apply_ty.substitution),
83 _ => {
84 let ctor = from_chalk(db, apply_ty.name);
85 let parameters = from_chalk(db, apply_ty.substitution);
86 Ty::Apply(ApplicationTy { ctor, parameters })
87 }
88 },
89 chalk_ir::TyData::Placeholder(idx) => {
90 assert_eq!(idx.ui, UniverseIndex::ROOT);
91 let interned_id = crate::db::GlobalTypeParamId::from_intern_id(
92 crate::salsa::InternId::from(idx.idx),
93 );
94 Ty::Placeholder(db.lookup_intern_type_param_id(interned_id))
95 }
96 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Projection(proj)) => {
97 let associated_ty = from_chalk(db, proj.associated_ty_id);
98 let parameters = from_chalk(db, proj.substitution);
99 Ty::Projection(ProjectionTy { associated_ty, parameters })
100 }
101 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Opaque(_)) => unimplemented!(),
102 chalk_ir::TyData::Function(chalk_ir::Fn { num_binders: _, substitution }) => {
103 let parameters: Substs = from_chalk(db, substitution);
104 Ty::Apply(ApplicationTy {
105 ctor: TypeCtor::FnPtr { num_args: (parameters.len() - 1) as u16 },
106 parameters,
107 })
108 }
109 chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx),
110 chalk_ir::TyData::InferenceVar(_iv, _kind) => Ty::Unknown,
111 chalk_ir::TyData::Dyn(where_clauses) => {
112 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1);
113 let predicates = where_clauses
114 .bounds
115 .skip_binders()
116 .iter(&Interner)
117 .map(|c| from_chalk(db, c.clone()))
118 .collect();
119 Ty::Dyn(predicates)
120 }
121 }
122 }
123}
124
125const LIFETIME_PLACEHOLDER: PlaceholderIndex =
126 PlaceholderIndex { ui: UniverseIndex::ROOT, idx: usize::MAX };
127
128/// We currently don't model lifetimes, but Chalk does. So, we have to insert a
129/// fake lifetime here, because Chalks built-in logic may expect it to be there.
130fn ref_to_chalk(
131 db: &dyn HirDatabase,
132 mutability: Mutability,
133 subst: Substs,
134) -> chalk_ir::Ty<Interner> {
135 let arg = subst[0].clone().to_chalk(db);
136 let lifetime = LIFETIME_PLACEHOLDER.to_lifetime(&Interner);
137 chalk_ir::ApplicationTy {
138 name: TypeName::Ref(mutability.to_chalk(db)),
139 substitution: chalk_ir::Substitution::from(
140 &Interner,
141 vec![lifetime.cast(&Interner), arg.cast(&Interner)],
142 ),
143 }
144 .intern(&Interner)
145}
146
147/// Here we remove the lifetime from the type we got from Chalk.
148fn ref_from_chalk(
149 db: &dyn HirDatabase,
150 mutability: chalk_ir::Mutability,
151 subst: chalk_ir::Substitution<Interner>,
152) -> Ty {
153 let tys = subst
154 .iter(&Interner)
155 .filter_map(|p| Some(from_chalk(db, p.ty(&Interner)?.clone())))
156 .collect();
157 Ty::apply(TypeCtor::Ref(from_chalk(db, mutability)), Substs(tys))
158}
159
160impl ToChalk for Substs {
161 type Chalk = chalk_ir::Substitution<Interner>;
162
163 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> {
164 chalk_ir::Substitution::from(&Interner, self.iter().map(|ty| ty.clone().to_chalk(db)))
165 }
166
167 fn from_chalk(db: &dyn HirDatabase, parameters: chalk_ir::Substitution<Interner>) -> Substs {
168 let tys = parameters
169 .iter(&Interner)
170 .map(|p| match p.ty(&Interner) {
171 Some(ty) => from_chalk(db, ty.clone()),
172 None => unimplemented!(),
173 })
174 .collect();
175 Substs(tys)
176 }
177}
178
179impl ToChalk for TraitRef {
180 type Chalk = chalk_ir::TraitRef<Interner>;
181
182 fn to_chalk(self: TraitRef, db: &dyn HirDatabase) -> chalk_ir::TraitRef<Interner> {
183 let trait_id = self.trait_.to_chalk(db);
184 let substitution = self.substs.to_chalk(db);
185 chalk_ir::TraitRef { trait_id, substitution }
186 }
187
188 fn from_chalk(db: &dyn HirDatabase, trait_ref: chalk_ir::TraitRef<Interner>) -> Self {
189 let trait_ = from_chalk(db, trait_ref.trait_id);
190 let substs = from_chalk(db, trait_ref.substitution);
191 TraitRef { trait_, substs }
192 }
193}
194
195impl ToChalk for hir_def::TraitId {
196 type Chalk = TraitId;
197
198 fn to_chalk(self, _db: &dyn HirDatabase) -> TraitId {
199 chalk_ir::TraitId(self.as_intern_id())
200 }
201
202 fn from_chalk(_db: &dyn HirDatabase, trait_id: TraitId) -> hir_def::TraitId {
203 InternKey::from_intern_id(trait_id.0)
204 }
205}
206
207impl ToChalk for TypeCtor {
208 type Chalk = TypeName<Interner>;
209
210 fn to_chalk(self, db: &dyn HirDatabase) -> TypeName<Interner> {
211 match self {
212 TypeCtor::AssociatedType(type_alias) => {
213 let type_id = type_alias.to_chalk(db);
214 TypeName::AssociatedType(type_id)
215 }
216
217 TypeCtor::Bool => TypeName::Scalar(Scalar::Bool),
218 TypeCtor::Char => TypeName::Scalar(Scalar::Char),
219 TypeCtor::Int(Uncertain::Known(int_ty)) => TypeName::Scalar(int_ty_to_chalk(int_ty)),
220 TypeCtor::Float(Uncertain::Known(FloatTy { bitness: FloatBitness::X32 })) => {
221 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F32))
222 }
223 TypeCtor::Float(Uncertain::Known(FloatTy { bitness: FloatBitness::X64 })) => {
224 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F64))
225 }
226
227 TypeCtor::Tuple { cardinality } => TypeName::Tuple(cardinality.into()),
228 TypeCtor::RawPtr(mutability) => TypeName::Raw(mutability.to_chalk(db)),
229 TypeCtor::Slice => TypeName::Slice,
230 TypeCtor::Ref(mutability) => TypeName::Ref(mutability.to_chalk(db)),
231 TypeCtor::Str => TypeName::Str,
232 TypeCtor::FnDef(callable_def) => {
233 let id = callable_def.to_chalk(db);
234 TypeName::FnDef(id)
235 }
236 TypeCtor::Never => TypeName::Never,
237
238 TypeCtor::Int(Uncertain::Unknown)
239 | TypeCtor::Float(Uncertain::Unknown)
240 | TypeCtor::Adt(_)
241 | TypeCtor::Array
242 | TypeCtor::FnPtr { .. }
243 | TypeCtor::Closure { .. } => {
244 // other TypeCtors get interned and turned into a chalk StructId
245 let struct_id = db.intern_type_ctor(self).into();
246 TypeName::Adt(struct_id)
247 }
248 }
249 }
250
251 fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
252 match type_name {
253 TypeName::Adt(struct_id) => db.lookup_intern_type_ctor(struct_id.into()),
254 TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
255 TypeName::OpaqueType(_) => unreachable!(),
256
257 TypeName::Scalar(Scalar::Bool) => TypeCtor::Bool,
258 TypeName::Scalar(Scalar::Char) => TypeCtor::Char,
259 TypeName::Scalar(Scalar::Int(int_ty)) => TypeCtor::Int(Uncertain::Known(IntTy {
260 signedness: Signedness::Signed,
261 bitness: bitness_from_chalk_int(int_ty),
262 })),
263 TypeName::Scalar(Scalar::Uint(uint_ty)) => TypeCtor::Int(Uncertain::Known(IntTy {
264 signedness: Signedness::Unsigned,
265 bitness: bitness_from_chalk_uint(uint_ty),
266 })),
267 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F32)) => {
268 TypeCtor::Float(Uncertain::Known(FloatTy { bitness: FloatBitness::X32 }))
269 }
270 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F64)) => {
271 TypeCtor::Float(Uncertain::Known(FloatTy { bitness: FloatBitness::X64 }))
272 }
273 TypeName::Tuple(cardinality) => TypeCtor::Tuple { cardinality: cardinality as u16 },
274 TypeName::Raw(mutability) => TypeCtor::RawPtr(from_chalk(db, mutability)),
275 TypeName::Slice => TypeCtor::Slice,
276 TypeName::Ref(mutability) => TypeCtor::Ref(from_chalk(db, mutability)),
277 TypeName::Str => TypeCtor::Str,
278 TypeName::Never => TypeCtor::Never,
279
280 TypeName::FnDef(fn_def_id) => {
281 let callable_def = from_chalk(db, fn_def_id);
282 TypeCtor::FnDef(callable_def)
283 }
284
285 TypeName::Array | TypeName::Error => {
286 // this should not be reached, since we don't represent TypeName::Error with TypeCtor
287 unreachable!()
288 }
289 }
290 }
291}
292
293fn bitness_from_chalk_uint(uint_ty: chalk_ir::UintTy) -> IntBitness {
294 use chalk_ir::UintTy;
295
296 match uint_ty {
297 UintTy::Usize => IntBitness::Xsize,
298 UintTy::U8 => IntBitness::X8,
299 UintTy::U16 => IntBitness::X16,
300 UintTy::U32 => IntBitness::X32,
301 UintTy::U64 => IntBitness::X64,
302 UintTy::U128 => IntBitness::X128,
303 }
304}
305
306fn bitness_from_chalk_int(int_ty: chalk_ir::IntTy) -> IntBitness {
307 use chalk_ir::IntTy;
308
309 match int_ty {
310 IntTy::Isize => IntBitness::Xsize,
311 IntTy::I8 => IntBitness::X8,
312 IntTy::I16 => IntBitness::X16,
313 IntTy::I32 => IntBitness::X32,
314 IntTy::I64 => IntBitness::X64,
315 IntTy::I128 => IntBitness::X128,
316 }
317}
318
319fn int_ty_to_chalk(int_ty: IntTy) -> Scalar {
320 use chalk_ir::{IntTy, UintTy};
321
322 match int_ty.signedness {
323 Signedness::Signed => Scalar::Int(match int_ty.bitness {
324 IntBitness::Xsize => IntTy::Isize,
325 IntBitness::X8 => IntTy::I8,
326 IntBitness::X16 => IntTy::I16,
327 IntBitness::X32 => IntTy::I32,
328 IntBitness::X64 => IntTy::I64,
329 IntBitness::X128 => IntTy::I128,
330 }),
331 Signedness::Unsigned => Scalar::Uint(match int_ty.bitness {
332 IntBitness::Xsize => UintTy::Usize,
333 IntBitness::X8 => UintTy::U8,
334 IntBitness::X16 => UintTy::U16,
335 IntBitness::X32 => UintTy::U32,
336 IntBitness::X64 => UintTy::U64,
337 IntBitness::X128 => UintTy::U128,
338 }),
339 }
340}
341
342impl ToChalk for Mutability {
343 type Chalk = chalk_ir::Mutability;
344 fn to_chalk(self, _db: &dyn HirDatabase) -> Self::Chalk {
345 match self {
346 Mutability::Shared => chalk_ir::Mutability::Not,
347 Mutability::Mut => chalk_ir::Mutability::Mut,
348 }
349 }
350 fn from_chalk(_db: &dyn HirDatabase, chalk: Self::Chalk) -> Self {
351 match chalk {
352 chalk_ir::Mutability::Mut => Mutability::Mut,
353 chalk_ir::Mutability::Not => Mutability::Shared,
354 }
355 }
356}
357
358impl ToChalk for Impl {
359 type Chalk = ImplId;
360
361 fn to_chalk(self, db: &dyn HirDatabase) -> ImplId {
362 db.intern_chalk_impl(self).into()
363 }
364
365 fn from_chalk(db: &dyn HirDatabase, impl_id: ImplId) -> Impl {
366 db.lookup_intern_chalk_impl(impl_id.into())
367 }
368}
369
370impl ToChalk for CallableDef {
371 type Chalk = FnDefId;
372
373 fn to_chalk(self, db: &dyn HirDatabase) -> FnDefId {
374 db.intern_callable_def(self).into()
375 }
376
377 fn from_chalk(db: &dyn HirDatabase, fn_def_id: FnDefId) -> CallableDef {
378 db.lookup_intern_callable_def(fn_def_id.into())
379 }
380}
381
382impl ToChalk for TypeAliasId {
383 type Chalk = AssocTypeId;
384
385 fn to_chalk(self, _db: &dyn HirDatabase) -> AssocTypeId {
386 chalk_ir::AssocTypeId(self.as_intern_id())
387 }
388
389 fn from_chalk(_db: &dyn HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId {
390 InternKey::from_intern_id(type_alias_id.0)
391 }
392}
393
394impl ToChalk for AssocTyValue {
395 type Chalk = AssociatedTyValueId;
396
397 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValueId {
398 db.intern_assoc_ty_value(self).into()
399 }
400
401 fn from_chalk(db: &dyn HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue {
402 db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
403 }
404}
405
406impl ToChalk for GenericPredicate {
407 type Chalk = chalk_ir::QuantifiedWhereClause<Interner>;
408
409 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::QuantifiedWhereClause<Interner> {
410 match self {
411 GenericPredicate::Implemented(trait_ref) => {
412 let chalk_trait_ref = trait_ref.to_chalk(db);
413 let chalk_trait_ref = chalk_trait_ref.shifted_in(&Interner);
414 make_binders(chalk_ir::WhereClause::Implemented(chalk_trait_ref), 0)
415 }
416 GenericPredicate::Projection(projection_pred) => {
417 let ty = projection_pred.ty.to_chalk(db).shifted_in(&Interner);
418 let projection = projection_pred.projection_ty.to_chalk(db).shifted_in(&Interner);
419 let alias = chalk_ir::AliasTy::Projection(projection);
420 make_binders(chalk_ir::WhereClause::AliasEq(chalk_ir::AliasEq { alias, ty }), 0)
421 }
422 GenericPredicate::Error => panic!("tried passing GenericPredicate::Error to Chalk"),
423 }
424 }
425
426 fn from_chalk(
427 db: &dyn HirDatabase,
428 where_clause: chalk_ir::QuantifiedWhereClause<Interner>,
429 ) -> GenericPredicate {
430 // we don't produce any where clauses with binders and can't currently deal with them
431 match where_clause
432 .skip_binders()
433 .shifted_out(&Interner)
434 .expect("unexpected bound vars in where clause")
435 {
436 chalk_ir::WhereClause::Implemented(tr) => {
437 GenericPredicate::Implemented(from_chalk(db, tr))
438 }
439 chalk_ir::WhereClause::AliasEq(projection_eq) => {
440 let projection_ty = from_chalk(
441 db,
442 match projection_eq.alias {
443 chalk_ir::AliasTy::Projection(p) => p,
444 _ => unimplemented!(),
445 },
446 );
447 let ty = from_chalk(db, projection_eq.ty);
448 GenericPredicate::Projection(ProjectionPredicate { projection_ty, ty })
449 }
450 }
451 }
452}
453
454impl ToChalk for ProjectionTy {
455 type Chalk = chalk_ir::ProjectionTy<Interner>;
456
457 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::ProjectionTy<Interner> {
458 chalk_ir::ProjectionTy {
459 associated_ty_id: self.associated_ty.to_chalk(db),
460 substitution: self.parameters.to_chalk(db),
461 }
462 }
463
464 fn from_chalk(
465 db: &dyn HirDatabase,
466 projection_ty: chalk_ir::ProjectionTy<Interner>,
467 ) -> ProjectionTy {
468 ProjectionTy {
469 associated_ty: from_chalk(db, projection_ty.associated_ty_id),
470 parameters: from_chalk(db, projection_ty.substitution),
471 }
472 }
473}
474
475impl ToChalk for ProjectionPredicate {
476 type Chalk = chalk_ir::AliasEq<Interner>;
477
478 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::AliasEq<Interner> {
479 chalk_ir::AliasEq {
480 alias: chalk_ir::AliasTy::Projection(self.projection_ty.to_chalk(db)),
481 ty: self.ty.to_chalk(db),
482 }
483 }
484
485 fn from_chalk(_db: &dyn HirDatabase, _normalize: chalk_ir::AliasEq<Interner>) -> Self {
486 unimplemented!()
487 }
488}
489
490impl ToChalk for Obligation {
491 type Chalk = chalk_ir::DomainGoal<Interner>;
492
493 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::DomainGoal<Interner> {
494 match self {
495 Obligation::Trait(tr) => tr.to_chalk(db).cast(&Interner),
496 Obligation::Projection(pr) => pr.to_chalk(db).cast(&Interner),
497 }
498 }
499
500 fn from_chalk(_db: &dyn HirDatabase, _goal: chalk_ir::DomainGoal<Interner>) -> Self {
501 unimplemented!()
502 }
503}
504
505impl<T> ToChalk for Canonical<T>
506where
507 T: ToChalk,
508 T::Chalk: HasInterner<Interner = Interner>,
509{
510 type Chalk = chalk_ir::Canonical<T::Chalk>;
511
512 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
513 let parameter = chalk_ir::CanonicalVarKind::new(
514 chalk_ir::VariableKind::Ty(chalk_ir::TyKind::General),
515 chalk_ir::UniverseIndex::ROOT,
516 );
517 let value = self.value.to_chalk(db);
518 chalk_ir::Canonical {
519 value,
520 binders: chalk_ir::CanonicalVarKinds::from(&Interner, vec![parameter; self.num_vars]),
521 }
522 }
523
524 fn from_chalk(db: &dyn HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {
525 Canonical {
526 num_vars: canonical.binders.len(&Interner),
527 value: from_chalk(db, canonical.value),
528 }
529 }
530}
531
532impl ToChalk for Arc<TraitEnvironment> {
533 type Chalk = chalk_ir::Environment<Interner>;
534
535 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Environment<Interner> {
536 let mut clauses = Vec::new();
537 for pred in &self.predicates {
538 if pred.is_error() {
539 // for env, we just ignore errors
540 continue;
541 }
542 let program_clause: chalk_ir::ProgramClause<Interner> =
543 pred.clone().to_chalk(db).cast(&Interner);
544 clauses.push(program_clause.into_from_env_clause(&Interner));
545 }
546 chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses)
547 }
548
549 fn from_chalk(
550 _db: &dyn HirDatabase,
551 _env: chalk_ir::Environment<Interner>,
552 ) -> Arc<TraitEnvironment> {
553 unimplemented!()
554 }
555}
556
557impl<T: ToChalk> ToChalk for InEnvironment<T>
558where
559 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>,
560{
561 type Chalk = chalk_ir::InEnvironment<T::Chalk>;
562
563 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
564 chalk_ir::InEnvironment {
565 environment: self.environment.to_chalk(db),
566 goal: self.value.to_chalk(db),
567 }
568 }
569
570 fn from_chalk(
571 db: &dyn HirDatabase,
572 in_env: chalk_ir::InEnvironment<T::Chalk>,
573 ) -> InEnvironment<T> {
574 InEnvironment {
575 environment: from_chalk(db, in_env.environment),
576 value: from_chalk(db, in_env.goal),
577 }
578 }
579}
580
581impl ToChalk for builtin::BuiltinImplData {
582 type Chalk = ImplDatum;
583
584 fn to_chalk(self, db: &dyn HirDatabase) -> ImplDatum {
585 let impl_type = rust_ir::ImplType::External;
586 let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect();
587
588 let impl_datum_bound =
589 rust_ir::ImplDatumBound { trait_ref: self.trait_ref.to_chalk(db), where_clauses };
590 let associated_ty_value_ids =
591 self.assoc_ty_values.into_iter().map(|v| v.to_chalk(db)).collect();
592 rust_ir::ImplDatum {
593 binders: make_binders(impl_datum_bound, self.num_vars),
594 impl_type,
595 polarity: rust_ir::Polarity::Positive,
596 associated_ty_value_ids,
597 }
598 }
599
600 fn from_chalk(_db: &dyn HirDatabase, _data: ImplDatum) -> Self {
601 unimplemented!()
602 }
603}
604
605impl ToChalk for builtin::BuiltinImplAssocTyValueData {
606 type Chalk = AssociatedTyValue;
607
608 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValue {
609 let ty = self.value.to_chalk(db);
610 let value_bound = rust_ir::AssociatedTyValueBound { ty };
611
612 rust_ir::AssociatedTyValue {
613 associated_ty_id: self.assoc_ty_id.to_chalk(db),
614 impl_id: self.impl_.to_chalk(db),
615 value: make_binders(value_bound, self.num_vars),
616 }
617 }
618
619 fn from_chalk(
620 _db: &dyn HirDatabase,
621 _data: AssociatedTyValue,
622 ) -> builtin::BuiltinImplAssocTyValueData {
623 unimplemented!()
624 }
625}
626
627pub(super) fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T>
628where
629 T: HasInterner<Interner = Interner>,
630{
631 chalk_ir::Binders::new(
632 chalk_ir::VariableKinds::from(
633 &Interner,
634 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyKind::General)).take(num_vars),
635 ),
636 value,
637 )
638}
639
640pub(super) fn convert_where_clauses(
641 db: &dyn HirDatabase,
642 def: GenericDefId,
643 substs: &Substs,
644) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
645 let generic_predicates = db.generic_predicates(def);
646 let mut result = Vec::with_capacity(generic_predicates.len());
647 for pred in generic_predicates.iter() {
648 if pred.value.is_error() {
649 // skip errored predicates completely
650 continue;
651 }
652 result.push(pred.clone().subst(substs).to_chalk(db));
653 }
654 result
655}
656
657pub(super) fn generic_predicate_to_inline_bound(
658 db: &dyn HirDatabase,
659 pred: &GenericPredicate,
660 self_ty: &Ty,
661) -> Option<rust_ir::InlineBound<Interner>> {
662 // An InlineBound is like a GenericPredicate, except the self type is left out.
663 // We don't have a special type for this, but Chalk does.
664 match pred {
665 GenericPredicate::Implemented(trait_ref) => {
666 if &trait_ref.substs[0] != self_ty {
667 // we can only convert predicates back to type bounds if they
668 // have the expected self type
669 return None;
670 }
671 let args_no_self = trait_ref.substs[1..]
672 .iter()
673 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
674 .collect();
675 let trait_bound =
676 rust_ir::TraitBound { trait_id: trait_ref.trait_.to_chalk(db), args_no_self };
677 Some(rust_ir::InlineBound::TraitBound(trait_bound))
678 }
679 GenericPredicate::Projection(proj) => {
680 if &proj.projection_ty.parameters[0] != self_ty {
681 return None;
682 }
683 let trait_ = match proj.projection_ty.associated_ty.lookup(db.upcast()).container {
684 AssocContainerId::TraitId(t) => t,
685 _ => panic!("associated type not in trait"),
686 };
687 let args_no_self = proj.projection_ty.parameters[1..]
688 .iter()
689 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
690 .collect();
691 let alias_eq_bound = rust_ir::AliasEqBound {
692 value: proj.ty.clone().to_chalk(db),
693 trait_bound: rust_ir::TraitBound { trait_id: trait_.to_chalk(db), args_no_self },
694 associated_ty_id: proj.projection_ty.associated_ty.to_chalk(db),
695 parameters: Vec::new(), // FIXME we don't support generic associated types yet
696 };
697 Some(rust_ir::InlineBound::AliasEqBound(alias_eq_bound))
698 }
699 GenericPredicate::Error => None,
700 }
701}
diff --git a/crates/ra_hir_ty/src/traits/chalk/tls.rs b/crates/ra_hir_ty/src/traits/chalk/tls.rs
index 4867cb17e..d88828c7c 100644
--- a/crates/ra_hir_ty/src/traits/chalk/tls.rs
+++ b/crates/ra_hir_ty/src/traits/chalk/tls.rs
@@ -1,7 +1,7 @@
1//! Implementation of Chalk debug helper functions using TLS. 1//! Implementation of Chalk debug helper functions using TLS.
2use std::fmt; 2use std::fmt;
3 3
4use chalk_ir::{AliasTy, Goal, Goals, Lifetime, Parameter, ProgramClauseImplication, TypeName}; 4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication, TypeName};
5use itertools::Itertools; 5use itertools::Itertools;
6 6
7use super::{from_chalk, Interner}; 7use super::{from_chalk, Interner};
@@ -15,10 +15,10 @@ pub struct DebugContext<'a>(&'a (dyn HirDatabase + 'a));
15impl DebugContext<'_> { 15impl DebugContext<'_> {
16 pub fn debug_struct_id( 16 pub fn debug_struct_id(
17 &self, 17 &self,
18 id: super::StructId, 18 id: super::AdtId,
19 f: &mut fmt::Formatter<'_>, 19 f: &mut fmt::Formatter<'_>,
20 ) -> Result<(), fmt::Error> { 20 ) -> Result<(), fmt::Error> {
21 let type_ctor: TypeCtor = from_chalk(self.0, TypeName::Struct(id)); 21 let type_ctor: TypeCtor = from_chalk(self.0, TypeName::Adt(id));
22 match type_ctor { 22 match type_ctor {
23 TypeCtor::Bool => write!(f, "bool")?, 23 TypeCtor::Bool => write!(f, "bool")?,
24 TypeCtor::Char => write!(f, "char")?, 24 TypeCtor::Char => write!(f, "char")?,
@@ -188,9 +188,9 @@ impl DebugContext<'_> {
188 write!(fmt, "{:?}", lifetime.data(&Interner)) 188 write!(fmt, "{:?}", lifetime.data(&Interner))
189 } 189 }
190 190
191 pub fn debug_parameter( 191 pub fn debug_generic_arg(
192 &self, 192 &self,
193 parameter: &Parameter<Interner>, 193 parameter: &GenericArg<Interner>,
194 fmt: &mut fmt::Formatter<'_>, 194 fmt: &mut fmt::Formatter<'_>,
195 ) -> Result<(), fmt::Error> { 195 ) -> Result<(), fmt::Error> {
196 write!(fmt, "{:?}", parameter.data(&Interner).inner_debug()) 196 write!(fmt, "{:?}", parameter.data(&Interner).inner_debug())
@@ -244,6 +244,79 @@ impl DebugContext<'_> {
244 ) -> Result<(), fmt::Error> { 244 ) -> Result<(), fmt::Error> {
245 write!(fmt, "{:?}", separator_trait_ref.debug(&Interner)) 245 write!(fmt, "{:?}", separator_trait_ref.debug(&Interner))
246 } 246 }
247
248 pub fn debug_fn_def_id(
249 &self,
250 fn_def_id: chalk_ir::FnDefId<Interner>,
251 fmt: &mut fmt::Formatter<'_>,
252 ) -> Result<(), fmt::Error> {
253 let def: CallableDef = from_chalk(self.0, fn_def_id);
254 let name = match def {
255 CallableDef::FunctionId(ff) => self.0.function_data(ff).name.clone(),
256 CallableDef::StructId(s) => self.0.struct_data(s).name.clone(),
257 CallableDef::EnumVariantId(e) => {
258 let enum_data = self.0.enum_data(e.parent);
259 enum_data.variants[e.local_id].name.clone()
260 }
261 };
262 match def {
263 CallableDef::FunctionId(_) => write!(fmt, "{{fn {}}}", name),
264 CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {
265 write!(fmt, "{{ctor {}}}", name)
266 }
267 }
268 }
269
270 pub fn debug_const(
271 &self,
272 _constant: &chalk_ir::Const<Interner>,
273 fmt: &mut fmt::Formatter<'_>,
274 ) -> fmt::Result {
275 write!(fmt, "const")
276 }
277
278 pub fn debug_variable_kinds(
279 &self,
280 variable_kinds: &chalk_ir::VariableKinds<Interner>,
281 fmt: &mut fmt::Formatter<'_>,
282 ) -> fmt::Result {
283 write!(fmt, "{:?}", variable_kinds.as_slice(&Interner))
284 }
285 pub fn debug_variable_kinds_with_angles(
286 &self,
287 variable_kinds: &chalk_ir::VariableKinds<Interner>,
288 fmt: &mut fmt::Formatter<'_>,
289 ) -> fmt::Result {
290 write!(fmt, "{:?}", variable_kinds.inner_debug(&Interner))
291 }
292 pub fn debug_canonical_var_kinds(
293 &self,
294 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Interner>,
295 fmt: &mut fmt::Formatter<'_>,
296 ) -> fmt::Result {
297 write!(fmt, "{:?}", canonical_var_kinds.as_slice(&Interner))
298 }
299 pub fn debug_program_clause(
300 &self,
301 clause: &chalk_ir::ProgramClause<Interner>,
302 fmt: &mut fmt::Formatter<'_>,
303 ) -> fmt::Result {
304 write!(fmt, "{:?}", clause.data(&Interner))
305 }
306 pub fn debug_program_clauses(
307 &self,
308 clauses: &chalk_ir::ProgramClauses<Interner>,
309 fmt: &mut fmt::Formatter<'_>,
310 ) -> fmt::Result {
311 write!(fmt, "{:?}", clauses.as_slice(&Interner))
312 }
313 pub fn debug_quantified_where_clauses(
314 &self,
315 clauses: &chalk_ir::QuantifiedWhereClauses<Interner>,
316 fmt: &mut fmt::Formatter<'_>,
317 ) -> fmt::Result {
318 write!(fmt, "{:?}", clauses.as_slice(&Interner))
319 }
247} 320}
248 321
249mod unsafe_tls { 322mod unsafe_tls {