Repository: rust-analyzer/rust-analyzer
Pull request #2650 (2019-12-23 05:20:09)

Add macro call support for SourceAnalyzer::type_of


Patch:
diff --git a/Cargo.lock b/Cargo.lock
index e724c1a76b..55afcda7bf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -128,7 +128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 [[package]]
 name = "chalk-derive"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
  "proc-macro2 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
  "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -138,27 +138,27 @@ dependencies = [
 [[package]]
 name = "chalk-engine"
 version = "0.9.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
  "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "chalk-ir"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
- "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
+ "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
  "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "chalk-macros"
 version = "0.1.1"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
  "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
@@ -166,24 +166,24 @@ dependencies = [
 [[package]]
 name = "chalk-rust-ir"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
- "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
+ "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
 ]
 
 [[package]]
 name = "chalk-solve"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5#ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5"
+source = "git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb#151949dece8117d180b5d197a7afa968c3ba14bb"
 dependencies = [
- "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
+ "chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
  "ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -620,7 +620,7 @@ dependencies = [
 
 [[package]]
 name = "lsp-types"
-version = "0.66.0"
+version = "0.65.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -995,9 +995,9 @@ name = "ra_hir_ty"
 version = "0.1.0"
 dependencies = [
  "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
- "chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
+ "chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)",
  "ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "insta 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -1050,7 +1050,7 @@ dependencies = [
  "jod-thread 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
  "lsp-server 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "lsp-types 0.66.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "lsp-types 0.65.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "parking_lot 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "ra_ide 0.1.0",
  "ra_prof 0.1.0",
@@ -1782,12 +1782,12 @@ dependencies = [
 "checksum cargo_metadata 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "46e3374c604fb39d1a2f35ed5e4a4e30e60d01fab49446e08f1b3e9a90aef202"
 "checksum cc 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)" = "f52a465a666ca3d838ebbf08b241383421412fe7ebb463527bba275526d89f76"
 "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
-"checksum chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
-"checksum chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
-"checksum chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
-"checksum chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
-"checksum chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
-"checksum chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5)" = "<none>"
+"checksum chalk-derive 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
+"checksum chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
+"checksum chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
+"checksum chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
+"checksum chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
+"checksum chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=151949dece8117d180b5d197a7afa968c3ba14bb)" = "<none>"
 "checksum clicolors-control 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "90082ee5dcdd64dc4e9e0d37fbf3ee325419e39c0092191e0393df65518f741e"
 "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
 "checksum console 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f5d540c2d34ac9dd0deb5f3b5f54c36c79efa78f6b3ad19106a554d07a7b5d9f"
@@ -1842,7 +1842,7 @@ dependencies = [
 "checksum lock_api 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e57b3997725d2b60dbec1297f6c2e2957cc383db1cebd6be812163f969c7d586"
 "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7"
 "checksum lsp-server 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0ba36405bd742139ab79c246ca5adb7fde2fe1a0f495e2c8e2f607b607dedb12"
-"checksum lsp-types 0.66.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a2dddfe2791cbf4b5eff5a581e45becf47a24b128a62de80e7cc135bf50064"
+"checksum lsp-types 0.65.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1fe9e427e63e6172699737b47f1044bcade7046e2404d59ebd90c459da47cd2b"
 "checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
 "checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e"
 "checksum memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9"
diff --git a/crates/ra_assists/src/assists/add_explicit_type.rs b/crates/ra_assists/src/assists/add_explicit_type.rs
index eeb4ff39f4..2c602a79ee 100644
--- a/crates/ra_assists/src/assists/add_explicit_type.rs
+++ b/crates/ra_assists/src/assists/add_explicit_type.rs
@@ -73,6 +73,24 @@ mod tests {
         );
     }
 
+    #[test]
+    fn add_explicit_type_works_for_macro_call() {
+        check_assist(
+            add_explicit_type,
+            "macro_rules! v { () => {0u64} } fn f() { let a<|> = v!(); }",
+            "macro_rules! v { () => {0u64} } fn f() { let a<|>: u64 = v!(); }",
+        );
+    }
+
+    #[test]
+    fn add_explicit_type_works_for_macro_call_recursive() {
+        check_assist(
+            add_explicit_type,
+            "macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a<|> = v!(); }",
+            "macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a<|>: u64 = v!(); }",
+        );
+    }
+
     #[test]
     fn add_explicit_type_not_applicable_if_ty_not_inferred() {
         check_assist_not_applicable(add_explicit_type, "fn f() { let a<|> = None; }");
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 85b378483c..2c422af8bd 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -215,8 +215,32 @@ impl SourceAnalyzer {
         self.body_source_map.as_ref()?.node_pat(src)
     }
 
+    fn expand_expr(
+        &self,
+        db: &impl HirDatabase,
+        expr: InFile<&ast::Expr>,
+    ) -> Option<InFile<ast::Expr>> {
+        let macro_call = ast::MacroCall::cast(expr.value.syntax().clone())?;
+        let macro_file =
+            self.body_source_map.as_ref()?.node_macro_file(expr.with_value(&macro_call))?;
+        let expanded = db.parse_or_expand(macro_file)?;
+        let kind = expanded.kind();
+        let expr = InFile::new(macro_file, ast::Expr::cast(expanded)?);
+
+        if ast::MacroCall::can_cast(kind) {
+            self.expand_expr(db, expr.as_ref())
+        } else {
+            Some(expr)
+        }
+    }
+
     pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> {
-        let expr_id = self.expr_id(expr)?;
+        let expr_id = if let Some(expr) = self.expand_expr(db, InFile::new(self.file_id, expr)) {
+            self.body_source_map.as_ref()?.node_expr(expr.as_ref())?
+        } else {
+            self.expr_id(expr)?
+        };
+
         let ty = self.infer.as_ref()?[expr_id].clone();
         let environment = TraitEnvironment::lower(db, &self.resolver);
         Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
diff --git a/crates/ra_hir_def/src/body.rs b/crates/ra_hir_def/src/body.rs
index d3e4c50ae0..142c52d358 100644
--- a/crates/ra_hir_def/src/body.rs
+++ b/crates/ra_hir_def/src/body.rs
@@ -163,6 +163,7 @@ pub struct BodySourceMap {
     pat_map: FxHashMap<PatSource, PatId>,
     pat_map_back: ArenaMap<PatId, PatSource>,
     field_map: FxHashMap<(ExprId, usize), AstPtr<ast::RecordField>>,
+    expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
 }
 
 impl Body {
@@ -237,6 +238,11 @@ impl BodySourceMap {
         self.expr_map.get(&src).cloned()
     }
 
+    pub fn node_macro_file(&self, node: InFile<&ast::MacroCall>) -> Option<HirFileId> {
+        let src = node.map(|it| AstPtr::new(it));
+        self.expansions.get(&src).cloned()
+    }
+
     pub fn field_init_shorthand_expr(&self, node: InFile<&ast::RecordField>) -> Option<ExprId> {
         let src = node.map(|it| Either::Right(AstPtr::new(it)));
         self.expr_map.get(&src).cloned()
diff --git a/crates/ra_hir_def/src/body/lower.rs b/crates/ra_hir_def/src/body/lower.rs
index 5323af0972..57c77304cb 100644
--- a/crates/ra_hir_def/src/body/lower.rs
+++ b/crates/ra_hir_def/src/body/lower.rs
@@ -446,14 +446,20 @@ where
                 }
             }
             // FIXME expand to statements in statement position
-            ast::Expr::MacroCall(e) => match self.expander.enter_expand(self.db, e) {
-                Some((mark, expansion)) => {
-                    let id = self.collect_expr(expansion);
-                    self.expander.exit(self.db, mark);
-                    id
+            ast::Expr::MacroCall(e) => {
+                let macro_call = self.expander.to_source(AstPtr::new(&e));
+                match self.expander.enter_expand(self.db, e.clone()) {
+                    Some((mark, expansion)) => {
+                        self.source_map
+                            .expansions
+                            .insert(macro_call, self.expander.current_file_id);
+                        let id = self.collect_expr(expansion);
+                        self.expander.exit(self.db, mark);
+                        id
+                    }
+                    None => self.alloc_expr(Expr::Missing, syntax_ptr),
                 }
-                None => self.alloc_expr(Expr::Missing, syntax_ptr),
-            },
+            }
 
             // FIXME implement HIR for these:
             ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml
index 60793db442..d277bf2bcd 100644
--- a/crates/ra_hir_ty/Cargo.toml
+++ b/crates/ra_hir_ty/Cargo.toml
@@ -21,9 +21,10 @@ ra_prof = { path = "../ra_prof" }
 ra_syntax = { path = "../ra_syntax" }
 test_utils = { path = "../test_utils" }
 
-chalk-solve =   { git = "https://github.com/rust-lang/chalk.git", rev = "ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5" }
-chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5" }
-chalk-ir =      { git = "https://github.com/rust-lang/chalk.git", rev = "ff65b5ac9860f3c36bd892c865ab23d5ff0bbae5" }
+# https://github.com/rust-lang/chalk/pull/294
+chalk-solve =   { git = "https://github.com/rust-lang/chalk.git", rev = "151949dece8117d180b5d197a7afa968c3ba14bb" }
+chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "151949dece8117d180b5d197a7afa968c3ba14bb" }
+chalk-ir =      { git = "https://github.com/rust-lang/chalk.git", rev = "151949dece8117d180b5d197a7afa968c3ba14bb" }
 
 lalrpop-intern = "0.15.1"
 
diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs
index d52f65b836..222a36a9f8 100644
--- a/crates/ra_hir_ty/src/db.rs
+++ b/crates/ra_hir_ty/src/db.rs
@@ -10,7 +10,7 @@ use ra_db::{salsa, CrateId};
 
 use crate::{
     method_resolution::CrateImplBlocks,
-    traits::{chalk, AssocTyValue, Impl},
+    traits::{AssocTyValue, Impl},
     CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, TraitRef, Ty, TyDefId, TypeCtor,
     ValueTyDefId,
 };
@@ -77,24 +77,39 @@ pub trait HirDatabase: DefDatabase {
     #[salsa::interned]
     fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
 
-    #[salsa::invoke(chalk::associated_ty_data_query)]
-    fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>;
+    #[salsa::invoke(crate::traits::chalk::associated_ty_data_query)]
+    fn associated_ty_data(
+        &self,
+        id: chalk_ir::TypeId,
+    ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>;
 
-    #[salsa::invoke(chalk::trait_datum_query)]
-    fn trait_datum(&self, krate: CrateId, trait_id: chalk::TraitId) -> Arc<chalk::TraitDatum>;
+    #[salsa::invoke(crate::traits::chalk::trait_datum_query)]
+    fn trait_datum(
+        &self,
+        krate: CrateId,
+        trait_id: chalk_ir::TraitId,
+    ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>;
 
-    #[salsa::invoke(chalk::struct_datum_query)]
-    fn struct_datum(&self, krate: CrateId, struct_id: chalk::StructId) -> Arc<chalk::StructDatum>;
+    #[salsa::invoke(crate::traits::chalk::struct_datum_query)]
+    fn struct_datum(
+        &self,
+        krate: CrateId,
+        struct_id: chalk_ir::StructId,
+    ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>;
 
     #[salsa::invoke(crate::traits::chalk::impl_datum_query)]
-    fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>;
+    fn impl_datum(
+        &self,
+        krate: CrateId,
+        impl_id: chalk_ir::ImplId,
+    ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>;
 
     #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)]
     fn associated_ty_value(
         &self,
         krate: CrateId,
-        id: chalk::AssociatedTyValueId,
-    ) -> Arc<chalk::AssociatedTyValue>;
+        id: chalk_rust_ir::AssociatedTyValueId,
+    ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>;
 
     #[salsa::invoke(crate::traits::trait_solve_query)]
     fn trait_solve(
diff --git a/crates/ra_hir_ty/src/traits.rs b/crates/ra_hir_ty/src/traits.rs
index c4dc857bc7..d49f8fb4b1 100644
--- a/crates/ra_hir_ty/src/traits.rs
+++ b/crates/ra_hir_ty/src/traits.rs
@@ -1,7 +1,7 @@
 //! Trait solving using Chalk.
 use std::sync::{Arc, Mutex};
 
-use chalk_ir::cast::Cast;
+use chalk_ir::{cast::Cast, family::ChalkIr};
 use hir_def::{expr::ExprId, DefWithBodyId, ImplId, TraitId, TypeAliasId};
 use log::debug;
 use ra_db::{impl_intern_key, salsa, CrateId};
@@ -12,7 +12,7 @@ use crate::db::HirDatabase;
 
 use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk};
 
-use self::chalk::{from_chalk, ToChalk, TypeFamily};
+use self::chalk::{from_chalk, ToChalk};
 
 pub(crate) mod chalk;
 mod builtin;
@@ -20,7 +20,7 @@ mod builtin;
 #[derive(Debug, Clone)]
 pub struct TraitSolver {
     krate: CrateId,
-    inner: Arc<Mutex<chalk_solve::Solver<TypeFamily>>>,
+    inner: Arc<Mutex<chalk_solve::Solver<ChalkIr>>>,
 }
 
 /// We need eq for salsa
@@ -36,8 +36,8 @@ impl TraitSolver {
     fn solve(
         &self,
         db: &impl HirDatabase,
-        goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<TypeFamily>>>,
-    ) -> Option<chalk_solve::Solution<TypeFamily>> {
+        goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<ChalkIr>>>,
+    ) -> Option<chalk_solve::Solution<ChalkIr>> {
         let context = ChalkContext { db, krate: self.krate };
         debug!("solve goal: {:?}", goal);
         let mut solver = match self.inner.lock() {
@@ -201,17 +201,17 @@ pub(crate) fn trait_solve_query(
 
 fn solution_from_chalk(
     db: &impl HirDatabase,
-    solution: chalk_solve::Solution<TypeFamily>,
+    solution: chalk_solve::Solution<ChalkIr>,
 ) -> Solution {
-    let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<TypeFamily>>| {
+    let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<ChalkIr>>| {
         let value = subst
             .value
             .parameters
             .into_iter()
             .map(|p| {
-                let ty = match p.ty() {
-                    Some(ty) => from_chalk(db, ty.clone()),
-                    None => unimplemented!(),
+                let ty = match p {
+                    chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty),
+                    chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(),
                 };
                 ty
             })
@@ -291,7 +291,7 @@ impl FnTrait {
     }
 }
 
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 pub struct ClosureFnTraitImplData {
     def: DefWithBodyId,
     expr: ExprId,
@@ -300,7 +300,7 @@ pub struct ClosureFnTraitImplData {
 
 /// An impl. Usually this comes from an impl block, but some built-in types get
 /// synthetic impls.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 pub enum Impl {
     /// A normal impl from an impl block.
     ImplBlock(ImplId),
diff --git a/crates/ra_hir_ty/src/traits/builtin.rs b/crates/ra_hir_ty/src/traits/builtin.rs
index dd41176f0d..cd587a3382 100644
--- a/crates/ra_hir_ty/src/traits/builtin.rs
+++ b/crates/ra_hir_ty/src/traits/builtin.rs
@@ -28,24 +28,24 @@ pub(super) fn get_builtin_impls(
     trait_: TraitId,
     mut callback: impl FnMut(Impl),
 ) {
-    // Note: since impl_datum needs to be infallible, we need to make sure here
-    // that we have all prerequisites to build the respective impls.
     if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { def, expr }, .. }) = ty {
         for &fn_trait in [super::FnTrait::FnOnce, super::FnTrait::FnMut, super::FnTrait::Fn].iter()
         {
             if let Some(actual_trait) = get_fn_trait(db, krate, fn_trait) {
                 if trait_ == actual_trait {
                     let impl_ = super::ClosureFnTraitImplData { def: *def, expr: *expr, fn_trait };
-                    if check_closure_fn_trait_impl_prerequisites(db, krate, impl_) {
-                        callback(Impl::ClosureFnTraitImpl(impl_));
-                    }
+                    callback(Impl::ClosureFnTraitImpl(impl_));
                 }
             }
         }
     }
 }
 
-pub(super) fn impl_datum(db: &impl HirDatabase, krate: CrateId, impl_: Impl) -> BuiltinImplData {
+pub(super) fn impl_datum(
+    db: &impl HirDatabase,
+    krate: CrateId,
+    impl_: Impl,
+) -> Option<BuiltinImplData> {
     match impl_ {
         Impl::ImplBlock(_) => unreachable!(),
         Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data),
@@ -65,38 +65,21 @@ pub(super) fn associated_ty_value(
     }
 }
 
-fn check_closure_fn_trait_impl_prerequisites(
-    db: &impl HirDatabase,
-    krate: CrateId,
-    data: super::ClosureFnTraitImplData,
-) -> bool {
-    // the respective Fn/FnOnce/FnMut trait needs to exist
-    if get_fn_trait(db, krate, data.fn_trait).is_none() {
-        return false;
-    }
-
-    // FIXME: there are more assumptions that we should probably check here:
-    // the traits having no type params, FnOnce being a supertrait
-
-    // the FnOnce trait needs to exist and have an assoc type named Output
-    let fn_once_trait = match get_fn_trait(db, krate, super::FnTrait::FnOnce) {
-        Some(t) => t,
-        None => return false,
-    };
-    db.trait_data(fn_once_trait).associated_type_by_name(&name![Output]).is_some()
-}
-
 fn closure_fn_trait_impl_datum(
     db: &impl HirDatabase,
     krate: CrateId,
     data: super::ClosureFnTraitImplData,
-) -> BuiltinImplData {
+) -> Option<BuiltinImplData> {
     // for some closure |X, Y| -> Z:
     // impl<T, U, V> Fn<(T, U)> for closure<fn(T, U) -> V> { Output = V }
 
-    let trait_ = get_fn_trait(db, krate, data.fn_trait) // get corresponding fn trait
-        // the existence of the Fn trait has been checked before
-        .expect("fn trait for closure impl missing");
+    let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait
+
+    // validate FnOnce trait, since we need it in the assoc ty value definition
+    // and don't want to return a valid value only to find out later that FnOnce
+    // is broken
+    let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?;
+    let _output = db.trait_data(fn_once_trait).associated_type_by_name(&name![Output])?;
 
     let num_args: u16 = match &db.body(data.def.into())[data.expr] {
         Expr::Lambda { args, .. } => args.len() as u16,
@@ -124,12 +107,12 @@ fn closure_fn_trait_impl_datum(
 
     let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone());
 
-    BuiltinImplData {
+    Some(BuiltinImplData {
         num_vars: num_args as usize + 1,
         trait_ref,
         where_clauses: Vec::new(),
         assoc_ty_values: vec![output_ty_id],
-    }
+    })
 }
 
 fn closure_fn_trait_output_assoc_ty_value(
diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs
index 555930c9bf..5eb032d86a 100644
--- a/crates/ra_hir_ty/src/traits/chalk.rs
+++ b/crates/ra_hir_ty/src/traits/chalk.rs
@@ -1,11 +1,17 @@
 //! Conversion code from/to Chalk.
-use std::{fmt, sync::Arc};
+use std::sync::Arc;
 
 use log::debug;
 
-use chalk_ir::{cast::Cast, Parameter, PlaceholderIndex, TypeName, UniverseIndex};
+use chalk_ir::{
+    cast::Cast, family::ChalkIr, Identifier, Parameter, PlaceholderIndex, TypeId, TypeKindId,
+    TypeName, UniverseIndex,
+};
+use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum};
 
-use hir_def::{AssocContainerId, AssocItemId, GenericDefId, HasModule, Lookup, TypeAliasId};
+use hir_def::{
+    AssocContainerId, AssocItemId, GenericDefId, HasModule, ImplId, Lookup, TraitId, TypeAliasId,
+};
 use ra_db::{
     salsa::{InternId, InternKey},
     CrateId,
@@ -17,83 +23,9 @@ use crate::{
     ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk,
 };
 
-#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
-pub struct TypeFamily {}
-
-impl chalk_ir::family::TypeFamily for TypeFamily {
-    type InternedType = Box<chalk_ir::TyData<Self>>;
-    type InternedLifetime = chalk_ir::LifetimeData<Self>;
-    type InternedParameter = chalk_ir::ParameterData<Self>;
-    type DefId = InternId;
-
-    // FIXME: implement these
-    fn debug_struct_id(
-        _type_kind_id: chalk_ir::StructId<Self>,
-        _fmt: &mut fmt::Formatter<'_>,
-    ) -> Option<fmt::Result> {
-        None
-    }
-
-    fn debug_trait_id(
-        _type_kind_id: chalk_ir::TraitId<Self>,
-        _fmt: &mut fmt::Formatter<'_>,
-    ) -> Option<fmt::Result> {
-        None
-    }
-
-    fn debug_assoc_type_id(
-        _id: chalk_ir::AssocTypeId<Self>,
-        _fmt: &mut fmt::Formatter<'_>,
-    ) -> Option<fmt::Result> {
-        None
-    }
-
-    fn debug_projection(
-        _projection: &chalk_ir::ProjectionTy<Self>,
-        _fmt: &mut fmt::Formatter<'_>,
-    ) -> Option<fmt::Result> {
-        None
-    }
-
-    fn intern_ty(ty: chalk_ir::TyData<Self>) -> Box<chalk_ir::TyData<Self>> {
-        Box::new(ty)
-    }
-
-    fn ty_data(ty: &Box<chalk_ir::TyData<Self>>) -> &chalk_ir::TyData<Self> {
-        ty
-    }
-
-    fn intern_lifetime(lifetime: chalk_ir::LifetimeData<Self>) -> chalk_ir::LifetimeData<Self> {
-        lifetime
-    }
-
-    fn lifetime_data(lifetime: &chalk_ir::LifetimeData<Self>) -> &chalk_ir::LifetimeData<Self> {
-        lifetime
-    }
-
-    fn intern_parameter(parameter: chalk_ir::ParameterData<Self>) -> chalk_ir::ParameterData<Self> {
-        parameter
-    }
-
-    fn parameter_data(parameter: &chalk_ir::ParameterData<Self>) -> &chalk_ir::ParameterData<Self> {
-        parameter
-    }
-}
-
-impl chalk_ir::family::HasTypeFamily for TypeFamily {
-    type TypeFamily = Self;
-}
-
-pub type AssocTypeId = chalk_ir::AssocTypeId<TypeFamily>;
-pub type AssociatedTyDatum = chalk_rust_ir::AssociatedTyDatum<TypeFamily>;
-pub type TraitId = chalk_ir::TraitId<TypeFamily>;
-pub type TraitDatum = chalk_rust_ir::TraitDatum<TypeFamily>;
-pub type StructId = chalk_ir::StructId<TypeFamily>;
-pub type StructDatum = chalk_rust_ir::StructDatum<TypeFamily>;
-pub type ImplId = chalk_ir::ImplId<TypeFamily>;
-pub type ImplDatum = chalk_rust_ir::ImplDatum<TypeFamily>;
-pub type AssociatedTyValueId = chalk_rust_ir::AssociatedTyValueId;
-pub type AssociatedTyValue = chalk_rust_ir::AssociatedTyValue<TypeFamily>;
+/// This represents a trait whose name we could not resolve.
+const UNKNOWN_TRAIT: chalk_ir::TraitId =
+    chalk_ir::TraitId(chalk_ir::RawId { index: u32::max_value() });
 
 pub(super) trait ToChalk {
     type Chalk;
@@ -109,11 +41,21 @@ where
 }
 
 impl ToChalk for Ty {
-    type Chalk = chalk_ir::Ty<TypeFamily>;
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty<TypeFamily> {
+    type Chalk = chalk_ir::Ty<ChalkIr>;
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty<ChalkIr> {
         match self {
             Ty::Apply(apply_ty) => {
-                let name = apply_ty.ctor.to_chalk(db);
+                let name = match apply_ty.ctor {
+                    TypeCtor::AssociatedType(type_alias) => {
+                        let type_id = type_alias.to_chalk(db);
+                        TypeName::AssociatedType(type_id)
+                    }
+                    _ => {
+                        // other TypeCtors get interned and turned into a chalk StructId
+                        let struct_id = apply_ty.ctor.to_chalk(db);
+                        TypeName::TypeKindId(struct_id.into())
+                    }
+                };
                 let parameters = apply_ty.parameters.to_chalk(db);
                 chalk_ir::ApplicationTy { name, parameters }.cast().intern()
             }
@@ -123,30 +65,17 @@ impl ToChalk for Ty {
                 chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern()
             }
             Ty::Param { idx, .. } => {
-                PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }
-                    .to_ty::<TypeFamily>()
+                PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::<ChalkIr>()
             }
             Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(),
             Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
             Ty::Dyn(predicates) => {
-                let where_clauses = predicates
-                    .iter()
-                    .filter(|p| !p.is_error())
-                    .cloned()
-                    .map(|p| p.to_chalk(db))
-                    .collect();
-                let bounded_ty = chalk_ir::BoundedTy { bounds: make_binders(where_clauses, 1) };
-                chalk_ir::TyData::Dyn(bounded_ty).intern()
+                let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect();
+                chalk_ir::TyData::Dyn(make_binders(where_clauses, 1)).intern()
             }
             Ty::Opaque(predicates) => {
-                let where_clauses = predicates
-                    .iter()
-                    .filter(|p| !p.is_error())
-                    .cloned()
-                    .map(|p| p.to_chalk(db))
-                    .collect();
-                let bounded_ty = chalk_ir::BoundedTy { bounds: make_binders(where_clauses, 1) };
-                chalk_ir::TyData::Opaque(bounded_ty).intern()
+                let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect();
+                chalk_ir::TyData::Opaque(make_binders(where_clauses, 1)).intern()
             }
             Ty::Unknown => {
                 let parameters = Vec::new();
@@ -155,19 +84,30 @@ impl ToChalk for Ty {
             }
         }
     }
-    fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty<TypeFamily>) -> Self {
+    fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty<ChalkIr>) -> Self {
         match chalk.data().clone() {
-            chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name {
-                TypeName::Error => Ty::Unknown,
-                _ => {
-                    let ctor = from_chalk(db, apply_ty.name);
-                    let parameters = from_chalk(db, apply_ty.parameters);
-                    Ty::Apply(ApplicationTy { ctor, parameters })
+            chalk_ir::TyData::Apply(apply_ty) => {
+                // FIXME this is kind of hacky due to the fact that
+                // TypeName::Placeholder is a Ty::Param on our side
+                match apply_ty.name {
+                    TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => {
+                        let ctor = from_chalk(db, struct_id);
+                        let parameters = from_chalk(db, apply_ty.parameters);
+                        Ty::Apply(ApplicationTy { ctor, parameters })
+                    }
+                    TypeName::AssociatedType(type_id) => {
+                        let ctor = TypeCtor::AssociatedType(from_chalk(db, type_id));
+                        let parameters = from_chalk(db, apply_ty.parameters);
+                        Ty::Apply(ApplicationTy { ctor, parameters })
+                    }
+                    TypeName::Error => Ty::Unknown,
+                    // FIXME handle TypeKindId::Trait/Type here
+                    TypeName::TypeKindId(_) => unimplemented!(),
+                    TypeName::Placeholder(idx) => {
+                        assert_eq!(idx.ui, UniverseIndex::ROOT);
+                        Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() }
+                    }
                 }
-            },
-            chalk_ir::TyData::Placeholder(idx) => {
-                assert_eq!(idx.ui, UniverseIndex::ROOT);
-                Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() }
             }
             chalk_ir::TyData::Projection(proj) => {
                 let associated_ty = from_chalk(db, proj.associated_ty_id);
@@ -178,15 +118,15 @@ impl ToChalk for Ty {
             chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32),
             chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown,
             chalk_ir::TyData::Dyn(where_clauses) => {
-                assert_eq!(where_clauses.bounds.binders.len(), 1);
+                assert_eq!(where_clauses.binders.len(), 1);
                 let predicates =
-                    where_clauses.bounds.value.into_iter().map(|c| from_chalk(db, c)).collect();
+                    where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect();
                 Ty::Dyn(predicates)
             }
             chalk_ir::TyData::Opaque(where_clauses) => {
-                assert_eq!(where_clauses.bounds.binders.len(), 1);
+                assert_eq!(where_clauses.binders.len(), 1);
                 let predicates =
-                    where_clauses.bounds.value.into_iter().map(|c| from_chalk(db, c)).collect();
+                    where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect();
                 Ty::Opaque(predicates)
             }
         }
@@ -194,21 +134,18 @@ impl ToChalk for Ty {
 }
 
 impl ToChalk for Substs {
-    type Chalk = Vec<chalk_ir::Parameter<TypeFamily>>;
+    type Chalk = Vec<chalk_ir::Parameter<ChalkIr>>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> Vec<Parameter<TypeFamily>> {
+    fn to_chalk(self, db: &impl HirDatabase) -> Vec<Parameter<ChalkIr>> {
         self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect()
     }
 
-    fn from_chalk(
-        db: &impl HirDatabase,
-        parameters: Vec<chalk_ir::Parameter<TypeFamily>>,
-    ) -> Substs {
+    fn from_chalk(db: &impl HirDatabase, parameters: Vec<chalk_ir::Parameter<ChalkIr>>) -> Substs {
         let tys = parameters
             .into_iter()
-            .map(|p| match p.ty() {
-                Some(ty) => from_chalk(db, ty.clone()),
-                None => unimplemented!(),
+            .map(|p| match p {
+                chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty),
+                chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(),
             })
             .collect();
         Substs(tys)
@@ -216,102 +153,88 @@ impl ToChalk for Substs {
 }
 
 impl ToChalk for TraitRef {
-    type Chalk = chalk_ir::TraitRef<TypeFamily>;
+    type Chalk = chalk_ir::TraitRef<ChalkIr>;
 
-    fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef<TypeFamily> {
+    fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef<ChalkIr> {
         let trait_id = self.trait_.to_chalk(db);
         let parameters = self.substs.to_chalk(db);
         chalk_ir::TraitRef { trait_id, parameters }
     }
 
-    fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef<TypeFamily>) -> Self {
+    fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef<ChalkIr>) -> Self {
         let trait_ = from_chalk(db, trait_ref.trait_id);
         let substs = from_chalk(db, trait_ref.parameters);
         TraitRef { trait_, substs }
     }
 }
 
-impl ToChalk for hir_def::TraitId {
-    type Chalk = TraitId;
+impl ToChalk for TraitId {
+    type Chalk = chalk_ir::TraitId;
 
-    fn to_chalk(self, _db: &impl HirDatabase) -> TraitId {
-        chalk_ir::TraitId(self.as_intern_id())
+    fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TraitId {
+        chalk_ir::TraitId(id_to_chalk(self))
     }
 
-    fn from_chalk(_db: &impl HirDatabase, trait_id: TraitId) -> hir_def::TraitId {
-        InternKey::from_intern_id(trait_id.0)
+    fn from_chalk(_db: &impl HirDatabase, trait_id: chalk_ir::TraitId) -> TraitId {
+        id_from_chalk(trait_id.0)
     }
 }
 
 impl ToChalk for TypeCtor {
-    type Chalk = TypeName<TypeFamily>;
+    type Chalk = chalk_ir::StructId;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> TypeName<TypeFamily> {
-        match self {
-            TypeCtor::AssociatedType(type_alias) => {
-                let type_id = type_alias.to_chalk(db);
-                TypeName::AssociatedType(type_id)
-            }
-            _ => {
-                // other TypeCtors get interned and turned into a chalk StructId
-                let struct_id = db.intern_type_ctor(self).into();
-                TypeName::Struct(struct_id)
-            }
-        }
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId {
+        db.intern_type_ctor(self).into()
     }
 
-    fn from_chalk(db: &impl HirDatabase, type_name: TypeName<TypeFamily>) -> TypeCtor {
-        match type_name {
-            TypeName::Struct(struct_id) => db.lookup_intern_type_ctor(struct_id.into()),
-            TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
-            TypeName::Error => {
-                // this should not be reached, since we don't represent TypeName::Error with TypeCtor
-                unreachable!()
-            }
-        }
+    fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor {
+        db.lookup_intern_type_ctor(struct_id.into())
     }
 }
 
 impl ToChalk for Impl {
-    type Chalk = ImplId;
+    type Chalk = chalk_ir::ImplId;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> ImplId {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId {
         db.intern_chalk_impl(self).into()
     }
 
-    fn from_chalk(db: &impl HirDatabase, impl_id: ImplId) -> Impl {
+    fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> Impl {
         db.lookup_intern_chalk_impl(impl_id.into())
     }
 }
 
 impl ToChalk for TypeAliasId {
-    type Chalk = AssocTypeId;
+    type Chalk = chalk_ir::TypeId;
 
-    fn to_chalk(self, _db: &impl HirDatabase) -> AssocTypeId {
-        chalk_ir::AssocTypeId(self.as_intern_id())
+    fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TypeId {
+        chalk_ir::TypeId(id_to_chalk(self))
     }
 
-    fn from_chalk(_db: &impl HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId {
-        InternKey::from_intern_id(type_alias_id.0)
+    fn from_chalk(_db: &impl HirDatabase, type_alias_id: chalk_ir::TypeId) -> TypeAliasId {
+        id_from_chalk(type_alias_id.0)
     }
 }
 
 impl ToChalk for AssocTyValue {
-    type Chalk = AssociatedTyValueId;
+    type Chalk = chalk_rust_ir::AssociatedTyValueId;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> AssociatedTyValueId {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId {
         db.intern_assoc_ty_value(self).into()
     }
 
-    fn from_chalk(db: &impl HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue {
+    fn from_chalk(
+        db: &impl HirDatabase,
+        assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId,
+    ) -> AssocTyValue {
         db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
     }
 }
 
 impl ToChalk for GenericPredicate {
-    type Chalk = chalk_ir::QuantifiedWhereClause<TypeFamily>;
+    type Chalk = chalk_ir::QuantifiedWhereClause<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause<TypeFamily> {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause<ChalkIr> {
         match self {
             GenericPredicate::Implemented(trait_ref) => {
                 make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0)
@@ -323,16 +246,26 @@ impl ToChalk for GenericPredicate {
                 }),
                 0,
             ),
-            GenericPredicate::Error => panic!("tried passing GenericPredicate::Error to Chalk"),
+            GenericPredicate::Error => {
+                let impossible_trait_ref = chalk_ir::TraitRef {
+                    trait_id: UNKNOWN_TRAIT,
+                    parameters: vec![Ty::Unknown.to_chalk(db).cast()],
+                };
+                make_binders(chalk_ir::WhereClause::Implemented(impossible_trait_ref), 0)
+            }
         }
     }
 
     fn from_chalk(
         db: &impl HirDatabase,
-        where_clause: chalk_ir::QuantifiedWhereClause<TypeFamily>,
+        where_clause: chalk_ir::QuantifiedWhereClause<ChalkIr>,
     ) -> GenericPredicate {
         match where_clause.value {
             chalk_ir::WhereClause::Implemented(tr) => {
+                if tr.trait_id == UNKNOWN_TRAIT {
+                    // FIXME we need an Error enum on the Chalk side to avoid this
+                    return GenericPredicate::Error;
+                }
                 GenericPredicate::Implemented(from_chalk(db, tr))
             }
             chalk_ir::WhereClause::ProjectionEq(projection_eq) => {
@@ -345,9 +278,9 @@ impl ToChalk for GenericPredicate {
 }
 
 impl ToChalk for ProjectionTy {
-    type Chalk = chalk_ir::ProjectionTy<TypeFamily>;
+    type Chalk = chalk_ir::ProjectionTy<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ProjectionTy<TypeFamily> {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ProjectionTy<ChalkIr> {
         chalk_ir::ProjectionTy {
             associated_ty_id: self.associated_ty.to_chalk(db),
             parameters: self.parameters.to_chalk(db),
@@ -356,7 +289,7 @@ impl ToChalk for ProjectionTy {
 
     fn from_chalk(
         db: &impl HirDatabase,
-        projection_ty: chalk_ir::ProjectionTy<TypeFamily>,
+        projection_ty: chalk_ir::ProjectionTy<ChalkIr>,
     ) -> ProjectionTy {
         ProjectionTy {
             associated_ty: from_chalk(db, projection_ty.associated_ty_id),
@@ -366,31 +299,31 @@ impl ToChalk for ProjectionTy {
 }
 
 impl ToChalk for super::ProjectionPredicate {
-    type Chalk = chalk_ir::Normalize<TypeFamily>;
+    type Chalk = chalk_ir::Normalize<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize<TypeFamily> {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize<ChalkIr> {
         chalk_ir::Normalize {
             projection: self.projection_ty.to_chalk(db),
             ty: self.ty.to_chalk(db),
         }
     }
 
-    fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize<TypeFamily>) -> Self {
+    fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize<ChalkIr>) -> Self {
         unimplemented!()
     }
 }
 
 impl ToChalk for Obligation {
-    type Chalk = chalk_ir::DomainGoal<TypeFamily>;
+    type Chalk = chalk_ir::DomainGoal<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal<TypeFamily> {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal<ChalkIr> {
         match self {
             Obligation::Trait(tr) => tr.to_chalk(db).cast(),
             Obligation::Projection(pr) => pr.to_chalk(db).cast(),
         }
     }
 
-    fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal<TypeFamily>) -> Self {
+    fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal<ChalkIr>) -> Self {
         unimplemented!()
     }
 }
@@ -414,17 +347,16 @@ where
 }
 
 impl ToChalk for Arc<super::TraitEnvironment> {
-    type Chalk = chalk_ir::Environment<TypeFamily>;
+    type Chalk = chalk_ir::Environment<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment<TypeFamily> {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment<ChalkIr> {
         let mut clauses = Vec::new();
         for pred in &self.predicates {
             if pred.is_error() {
                 // for env, we just ignore errors
                 continue;
             }
-            let program_clause: chalk_ir::ProgramClause<TypeFamily> =
-                pred.clone().to_chalk(db).cast();
+            let program_clause: chalk_ir::ProgramClause<ChalkIr> = pred.clone().to_chalk(db).cast();
             clauses.push(program_clause.into_from_env_clause());
         }
         chalk_ir::Environment::new().add_clauses(clauses)
@@ -432,7 +364,7 @@ impl ToChalk for Arc<super::TraitEnvironment> {
 
     fn from_chalk(
         _db: &impl HirDatabase,
-        _env: chalk_ir::Environment<TypeFamily>,
+        _env: chalk_ir::Environment<ChalkIr>,
     ) -> Arc<super::TraitEnvironment> {
         unimplemented!()
     }
@@ -440,7 +372,7 @@ impl ToChalk for Arc<super::TraitEnvironment> {
 
 impl<T: ToChalk> ToChalk for super::InEnvironment<T>
 where
-    T::Chalk: chalk_ir::family::HasTypeFamily<TypeFamily = TypeFamily>,
+    T::Chalk: chalk_ir::family::HasTypeFamily<TypeFamily = ChalkIr>,
 {
     type Chalk = chalk_ir::InEnvironment<T::Chalk>;
 
@@ -463,9 +395,9 @@ where
 }
 
 impl ToChalk for builtin::BuiltinImplData {
-    type Chalk = ImplDatum;
+    type Chalk = chalk_rust_ir::ImplDatum<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> ImplDatum {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::ImplDatum<ChalkIr> {
         let impl_type = chalk_rust_ir::ImplType::External;
         let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect();
 
@@ -481,15 +413,15 @@ impl ToChalk for builtin::BuiltinImplData {
         }
     }
 
-    fn from_chalk(_db: &impl HirDatabase, _data: ImplDatum) -> Self {
+    fn from_chalk(_db: &impl HirDatabase, _data: chalk_rust_ir::ImplDatum<ChalkIr>) -> Self {
         unimplemented!()
     }
 }
 
 impl ToChalk for builtin::BuiltinImplAssocTyValueData {
-    type Chalk = AssociatedTyValue;
+    type Chalk = chalk_rust_ir::AssociatedTyValue<ChalkIr>;
 
-    fn to_chalk(self, db: &impl HirDatabase) -> AssociatedTyValue {
+    fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValue<ChalkIr> {
         let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: self.value.to_chalk(db) };
 
         chalk_rust_ir::AssociatedTyValue {
@@ -501,7 +433,7 @@ impl ToChalk for builtin::BuiltinImplAssocTyValueData {
 
     fn from_chalk(
         _db: &impl HirDatabase,
-        _data: AssociatedTyValue,
+        _data: chalk_rust_ir::AssociatedTyValue<ChalkIr>,
     ) -> builtin::BuiltinImplAssocTyValueData {
         unimplemented!()
     }
@@ -518,46 +450,46 @@ fn convert_where_clauses(
     db: &impl HirDatabase,
     def: GenericDefId,
     substs: &Substs,
-) -> Vec<chalk_ir::QuantifiedWhereClause<TypeFamily>> {
+) -> Vec<chalk_ir::QuantifiedWhereClause<ChalkIr>> {
     let generic_predicates = db.generic_predicates(def);
     let mut result = Vec::with_capacity(generic_predicates.len());
     for pred in generic_predicates.iter() {
         if pred.is_error() {
-            // skip errored predicates completely
-            continue;
+            // HACK: Return just the single predicate (which is always false
+            // anyway), otherwise Chalk can easily get into slow situations
+            return vec![pred.clone().subst(substs).to_chalk(db)];
         }
         result.push(pred.clone().subst(substs).to_chalk(db));
     }
     result
 }
 
-impl<'a, DB> chalk_solve::RustIrDatabase<TypeFamily> for ChalkContext<'a, DB>
+impl<'a, DB> chalk_solve::RustIrDatabase<ChalkIr> for ChalkContext<'a, DB>
 where
     DB: HirDatabase,
 {
-    fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
+    fn associated_ty_data(&self, id: TypeId) -> Arc<AssociatedTyDatum<ChalkIr>> {
         self.db.associated_ty_data(id)
     }
-    fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
+    fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc<TraitDatum<ChalkIr>> {
         self.db.trait_datum(self.krate, trait_id)
     }
-    fn struct_datum(&self, struct_id: StructId) -> Arc<StructDatum> {
+    fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc<StructDatum<ChalkIr>> {
         self.db.struct_datum(self.krate, struct_id)
     }
-    fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
+    fn impl_datum(&self, impl_id: chalk_ir::ImplId) -> Arc<ImplDatum<ChalkIr>> {
         self.db.impl_datum(self.krate, impl_id)
     }
     fn impls_for_trait(
         &self,
-        trait_id: TraitId,
-        parameters: &[Parameter<TypeFamily>],
-    ) -> Vec<ImplId> {
+        trait_id: chalk_ir::TraitId,
+        parameters: &[Parameter<ChalkIr>],
+    ) -> Vec<chalk_ir::ImplId> {
         debug!("impls_for_trait {:?}", trait_id);
-        let trait_: hir_def::TraitId = from_chalk(self.db, trait_id);
-
-        // Note: Since we're using impls_for_trait, only impls where the trait
-        // can be resolved should ever reach Chalk. `impl_datum` relies on that
-        // and will panic if the trait can't be resolved.
+        if trait_id == UNKNOWN_TRAIT {
+            return Vec::new();
+        }
+        let trait_: TraitId = from_chalk(self.db, trait_id);
         let mut result: Vec<_> = self
             .db
             .impls_for_trait(self.krate, trait_.into())
@@ -576,32 +508,39 @@ where
         debug!("impls_for_trait returned {} impls", result.len());
         result
     }
-    fn impl_provided_for(&self, auto_trait_id: TraitId, struct_id: StructId) -> bool {
+    fn impl_provided_for(
+        &self,
+        auto_trait_id: chalk_ir::TraitId,
+        struct_id: chalk_ir::StructId,
+    ) -> bool {
         debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id);
         false // FIXME
     }
-    fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
+    fn type_name(&self, _id: TypeKindId) -> Identifier {
+        unimplemented!()
+    }
+    fn associated_ty_value(
+        &self,
+        id: chalk_rust_ir::AssociatedTyValueId,
+    ) -> Arc<AssociatedTyValue<ChalkIr>> {
         self.db.associated_ty_value(self.krate.into(), id)
     }
-    fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<TypeFamily>> {
+    fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<ChalkIr>> {
         vec![]
     }
-    fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId> {
+    fn local_impls_to_coherence_check(
+        &self,
+        _trait_id: chalk_ir::TraitId,
+    ) -> Vec<chalk_ir::ImplId> {
         // We don't do coherence checking (yet)
         unimplemented!()
     }
-    fn as_struct_id(&self, id: &TypeName<TypeFamily>) -> Option<StructId> {
-        match id {
-            TypeName::Struct(struct_id) => Some(*struct_id),
-            _ => None,
-        }
-    }
 }
 
 pub(crate) fn associated_ty_data_query(
     db: &impl HirDatabase,
-    id: AssocTypeId,
-) -> Arc<AssociatedTyDatum> {
+    id: TypeId,
+) -> Arc<AssociatedTyDatum<ChalkIr>> {
     debug!("associated_ty_data {:?}", id);
     let type_alias: TypeAliasId = from_chalk(db, id);
     let trait_ = match type_alias.lookup(db).container {
@@ -626,10 +565,28 @@ pub(crate) fn associated_ty_data_query(
 pub(crate) fn trait_datum_query(
     db: &impl HirDatabase,
     krate: CrateId,
-    trait_id: TraitId,
-) -> Arc<TraitDatum> {
+    trait_id: chalk_ir::TraitId,
+) -> Arc<TraitDatum<ChalkIr>> {
     debug!("trait_datum {:?}", trait_id);
-    let trait_: hir_def::TraitId = from_chalk(db, trait_id);
+    if trait_id == UNKNOWN_TRAIT {
+        let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() };
+
+        let flags = chalk_rust_ir::TraitFlags {
+            auto: false,
+            marker: false,
+            upstream: true,
+            fundamental: false,
+            non_enumerable: true,
+            coinductive: false,
+        };
+        return Arc::new(TraitDatum {
+            id: trait_id,
+            binders: make_binders(trait_datum_bound, 1),
+            flags,
+            associated_ty_ids: vec![],
+        });
+    }
+    let trait_: TraitId = from_chalk(db, trait_id);
     let trait_data = db.trait_data(trait_);
     debug!("trait {:?} = {:?}", trait_id, trait_data.name);
     let generic_params = generics(db, trait_.into());
@@ -659,10 +616,10 @@ pub(crate) fn trait_datum_query(
 pub(crate) fn struct_datum_query(
     db: &impl HirDatabase,
     krate: CrateId,
-    struct_id: StructId,
-) -> Arc<StructDatum> {
+    struct_id: chalk_ir::StructId,
+) -> Arc<StructDatum<ChalkIr>> {
     debug!("struct_datum {:?}", struct_id);
-    let type_ctor: TypeCtor = from_chalk(db, TypeName::Struct(struct_id));
+    let type_ctor: TypeCtor = from_chalk(db, struct_id);
     debug!("struct {:?} = {:?}", struct_id, type_ctor);
     let num_params = type_ctor.num_ty_params(db);
     let upstream = type_ctor.krate(db) != Some(krate);
@@ -691,27 +648,25 @@ pub(crate) fn struct_datum_query(
 pub(crate) fn impl_datum_query(
     db: &impl HirDatabase,
     krate: CrateId,
-    impl_id: ImplId,
-) -> Arc<ImplDatum> {
+    impl_id: chalk_ir::ImplId,
+) -> Arc<ImplDatum<ChalkIr>> {
     let _p = ra_prof::profile("impl_datum");
     debug!("impl_datum {:?}", impl_id);
     let impl_: Impl = from_chalk(db, impl_id);
     match impl_ {
         Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block),
-        _ => Arc::new(builtin::impl_datum(db, krate, impl_).to_chalk(db)),
+        _ => builtin::impl_datum(db, krate, impl_).map(|d| Arc::new(d.to_chalk(db))),
     }
+    .unwrap_or_else(invalid_impl_datum)
 }
 
 fn impl_block_datum(
     db: &impl HirDatabase,
     krate: CrateId,
-    chalk_id: ImplId,
-    impl_id: hir_def::ImplId,
-) -> Arc<ImplDatum> {
-    let trait_ref = db
-        .impl_trait(impl_id)
-        // ImplIds for impls where the trait ref can't be resolved should never reach Chalk
-        .expect("invalid impl passed to Chalk");
+    chalk_id: chalk_ir::ImplId,
+    impl_id: ImplId,
+) -> Option<Arc<ImplDatum<ChalkIr>>> {
+    let trait_ref = db.impl_trait(impl_id)?;
     let impl_data = db.impl_data(impl_id);
 
     let generic_params = generics(db, impl_id.into());
@@ -763,14 +718,29 @@ fn impl_block_datum(
         polarity,
         associated_ty_value_ids,
     };
+    Some(Arc::new(impl_datum))
+}
+
+fn invalid_impl_datum() -> Arc<ImplDatum<ChalkIr>> {
+    let trait_ref = chalk_ir::TraitRef {
+        trait_id: UNKNOWN_TRAIT,
+        parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()],
+    };
+    let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() };
+    let impl_datum = ImplDatum {
+        binders: make_binders(impl_datum_bound, 1),
+        impl_type: chalk_rust_ir::ImplType::External,
+        polarity: chalk_rust_ir::Polarity::Positive,
+        associated_ty_value_ids: Vec::new(),
+    };
     Arc::new(impl_datum)
 }
 
 pub(crate) fn associated_ty_value_query(
     db: &impl HirDatabase,
     krate: CrateId,
-    id: AssociatedTyValueId,
-) -> Arc<AssociatedTyValue> {
+    id: chalk_rust_ir::AssociatedTyValueId,
+) -> Arc<chalk_rust_ir::AssociatedTyValue<ChalkIr>> {
     let data: AssocTyValue = from_chalk(db, id);
     match data {
         AssocTyValue::TypeAlias(type_alias) => {
@@ -784,7 +754,7 @@ fn type_alias_associated_ty_value(
     db: &impl HirDatabase,
     _krate: CrateId,
     type_alias: TypeAliasId,
-) -> Arc<AssociatedTyValue> {
+) -> Arc<AssociatedTyValue<ChalkIr>> {
     let type_alias_data = db.type_alias_data(type_alias);
     let impl_id = match type_alias.lookup(db).container {
         AssocContainerId::ImplId(it) => it,
@@ -816,27 +786,27 @@ fn id_to_chalk<T: InternKey>(salsa_id: T) -> chalk_ir::RawId {
     chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() }
 }
 
-impl From<StructId> for crate::TypeCtorId {
-    fn from(struct_id: StructId) -> Self {
-        InternKey::from_intern_id(struct_id.0)
+impl From<chalk_ir::StructId> for crate::TypeCtorId {
+    fn from(struct_id: chalk_ir::StructId) -> Self {
+        id_from_chalk(struct_id.0)
     }
 }
 
-impl From<crate::TypeCtorId> for StructId {
+impl From<crate::TypeCtorId> for chalk_ir::StructId {
     fn from(type_ctor_id: crate::TypeCtorId) -> Self {
-        chalk_ir::StructId(type_ctor_id.as_intern_id())
+        chalk_ir::StructId(id_to_chalk(type_ctor_id))
     }
 }
 
-impl From<ImplId> for crate::traits::GlobalImplId {
-    fn from(impl_id: ImplId) -> Self {
-        InternKey::from_intern_id(impl_id.0)
+impl From<chalk_ir::ImplId> for crate::traits::GlobalImplId {
+    fn from(impl_id: chalk_ir::ImplId) -> Self {
+        id_from_chalk(impl_id.0)
     }
 }
 
-impl From<crate::traits::GlobalImplId> for ImplId {
+impl From<crate::traits::GlobalImplId> for chalk_ir::ImplId {
     fn from(impl_id: crate::traits::GlobalImplId) -> Self {
-        chalk_ir::ImplId(impl_id.as_intern_id())
+        chalk_ir::ImplId(id_to_chalk(impl_id))
     }
 }
 
diff --git a/crates/ra_lsp_server/Cargo.toml b/crates/ra_lsp_server/Cargo.toml
index 60cbc38a95..e826c10ef0 100644
--- a/crates/ra_lsp_server/Cargo.toml
+++ b/crates/ra_lsp_server/Cargo.toml
@@ -14,7 +14,7 @@ serde_json = "1.0.34"
 serde = { version = "1.0.83", features = ["derive"] }
 crossbeam-channel = "0.4"
 log = "0.4.3"
-lsp-types = { version = "0.66.0", features = ["proposed"] }
+lsp-types = { version = "0.65.0", features = ["proposed"] }
 rustc-hash = "1.0"
 parking_lot = "0.10.0"
 jod-thread = "0.1.0"


Test patch:
diff --git a/crates/ra_hir_ty/src/tests/method_resolution.rs b/crates/ra_hir_ty/src/tests/method_resolution.rs
index ce9a06fde4..45164c9e96 100644
--- a/crates/ra_hir_ty/src/tests/method_resolution.rs
+++ b/crates/ra_hir_ty/src/tests/method_resolution.rs
@@ -865,7 +865,7 @@ mod foo {
 
 #[test]
 fn method_resolution_where_clause_for_unknown_trait() {
-    // The blanket impl currently applies because we ignore the unresolved where clause
+    // The blanket impl shouldn't apply because we can't even resolve UnknownTrait
     let t = type_at(
         r#"
 //- /main.rs
@@ -875,7 +875,7 @@ impl<T> Trait for T where T: UnknownTrait {}
 fn test() { (&S).foo()<|>; }
 "#,
     );
-    assert_eq!(t, "u128");
+    assert_eq!(t, "{unknown}");
 }
 
 #[test]
diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs
index ae316922bd..76e2198b66 100644
--- a/crates/ra_hir_ty/src/tests/traits.rs
+++ b/crates/ra_hir_ty/src/tests/traits.rs
@@ -958,23 +958,6 @@ fn test() {
     );
 }
 
-#[test]
-fn error_bound_chalk() {
-    let t = type_at(
-        r#"
-//- /main.rs
-trait Trait {
-    fn foo(&self) -> u32 {}
-}
-
-fn test(x: (impl Trait + UnknownTrait)) {
-    x.foo()<|>;
-}
-"#,
-    );
-    assert_eq!(t, "u32");
-}
-
 #[test]
 fn assoc_type_bindings() {
     assert_snapshot!(