aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-03-13 15:05:46 +0000
committerAleksey Kladov <[email protected]>2020-03-16 16:42:30 +0000
commit9faea2364dee4fbc9391ad233c570b70256ef002 (patch)
tree160af959553ce57fdfcbc0a6c79bafcc3611aeea /crates
parent648df02953a6ebf87a5876668eceba208687e8a7 (diff)
Use `dyn Trait` for working with databse
It improves compile time in `--release` mode quite a bit, it doesn't really slow things down and, conceptually, it seems closer to what we want the physical architecture to look like (we don't want to monomorphise EVERYTHING in a single leaf crate).
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_db/src/lib.rs4
-rw-r--r--crates/ra_hir/src/code_model.rs329
-rw-r--r--crates/ra_hir/src/has_source.rs64
-rw-r--r--crates/ra_hir/src/semantics.rs22
-rw-r--r--crates/ra_hir/src/semantics/source_to_def.rs23
-rw-r--r--crates/ra_hir/src/source_analyzer.rs89
-rw-r--r--crates/ra_hir_def/src/adt.rs16
-rw-r--r--crates/ra_hir_def/src/attr.rs14
-rw-r--r--crates/ra_hir_def/src/body.rs22
-rw-r--r--crates/ra_hir_def/src/body/lower.rs11
-rw-r--r--crates/ra_hir_def/src/body/scope.rs2
-rw-r--r--crates/ra_hir_def/src/child_by_source.rs20
-rw-r--r--crates/ra_hir_def/src/data.rs18
-rw-r--r--crates/ra_hir_def/src/db.rs10
-rw-r--r--crates/ra_hir_def/src/docs.rs4
-rw-r--r--crates/ra_hir_def/src/find_path.rs8
-rw-r--r--crates/ra_hir_def/src/generics.rs8
-rw-r--r--crates/ra_hir_def/src/lang_item.rs10
-rw-r--r--crates/ra_hir_def/src/lib.rs48
-rw-r--r--crates/ra_hir_def/src/nameres.rs25
-rw-r--r--crates/ra_hir_def/src/nameres/collector.rs22
-rw-r--r--crates/ra_hir_def/src/nameres/mod_resolution.rs4
-rw-r--r--crates/ra_hir_def/src/nameres/path_resolution.rs8
-rw-r--r--crates/ra_hir_def/src/nameres/raw.rs8
-rw-r--r--crates/ra_hir_def/src/resolver.rs62
-rw-r--r--crates/ra_hir_def/src/src.rs12
-rw-r--r--crates/ra_hir_def/src/test_db.rs18
-rw-r--r--crates/ra_hir_def/src/visibility.rs12
-rw-r--r--crates/ra_hir_expand/src/db.rs2
-rw-r--r--crates/ra_hir_expand/src/eager.rs6
-rw-r--r--crates/ra_hir_expand/src/hygiene.rs2
-rw-r--r--crates/ra_hir_expand/src/lib.rs6
-rw-r--r--crates/ra_hir_ty/src/autoderef.rs8
-rw-r--r--crates/ra_hir_ty/src/db.rs4
-rw-r--r--crates/ra_hir_ty/src/display.rs50
-rw-r--r--crates/ra_hir_ty/src/expr.rs19
-rw-r--r--crates/ra_hir_ty/src/infer.rs38
-rw-r--r--crates/ra_hir_ty/src/infer/coerce.rs8
-rw-r--r--crates/ra_hir_ty/src/infer/expr.rs23
-rw-r--r--crates/ra_hir_ty/src/infer/pat.rs8
-rw-r--r--crates/ra_hir_ty/src/infer/path.rs15
-rw-r--r--crates/ra_hir_ty/src/infer/unify.rs18
-rw-r--r--crates/ra_hir_ty/src/lib.rs36
-rw-r--r--crates/ra_hir_ty/src/lower.rs220
-rw-r--r--crates/ra_hir_ty/src/method_resolution.rs43
-rw-r--r--crates/ra_hir_ty/src/test_db.rs18
-rw-r--r--crates/ra_hir_ty/src/traits.rs12
-rw-r--r--crates/ra_hir_ty/src/traits/builtin.rs36
-rw-r--r--crates/ra_hir_ty/src/traits/chalk.rs111
-rw-r--r--crates/ra_hir_ty/src/utils.rs16
-rw-r--r--crates/ra_ide_db/src/lib.rs15
51 files changed, 813 insertions, 794 deletions
diff --git a/crates/ra_db/src/lib.rs b/crates/ra_db/src/lib.rs
index d500d5e85..bac24e218 100644
--- a/crates/ra_db/src/lib.rs
+++ b/crates/ra_db/src/lib.rs
@@ -32,6 +32,10 @@ macro_rules! impl_intern_key {
32 }; 32 };
33} 33}
34 34
35pub trait Upcast<T: ?Sized> {
36 fn upcast(&self) -> &T;
37}
38
35pub trait CheckCanceled { 39pub trait CheckCanceled {
36 /// Aborts current query if there are pending changes. 40 /// Aborts current query if there are pending changes.
37 /// 41 ///
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index ff041150b..45e31095c 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -33,11 +33,7 @@ use ra_syntax::{
33}; 33};
34use rustc_hash::FxHashSet; 34use rustc_hash::FxHashSet;
35 35
36use crate::{ 36use crate::{db::HirDatabase, has_source::HasSource, CallableDef, HirDisplay, InFile, Name};
37 db::{DefDatabase, HirDatabase},
38 has_source::HasSource,
39 CallableDef, HirDisplay, InFile, Name,
40};
41 37
42/// hir::Crate describes a single crate. It's the main interface with which 38/// hir::Crate describes a single crate. It's the main interface with which
43/// a crate's dependencies interact. Mostly, it should be just a proxy for the 39/// a crate's dependencies interact. Mostly, it should be just a proxy for the
@@ -54,7 +50,7 @@ pub struct CrateDependency {
54} 50}
55 51
56impl Crate { 52impl Crate {
57 pub fn dependencies(self, db: &impl DefDatabase) -> Vec<CrateDependency> { 53 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
58 db.crate_graph()[self.id] 54 db.crate_graph()[self.id]
59 .dependencies 55 .dependencies
60 .iter() 56 .iter()
@@ -67,7 +63,7 @@ impl Crate {
67 } 63 }
68 64
69 // FIXME: add `transitive_reverse_dependencies`. 65 // FIXME: add `transitive_reverse_dependencies`.
70 pub fn reverse_dependencies(self, db: &impl DefDatabase) -> Vec<Crate> { 66 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
71 let crate_graph = db.crate_graph(); 67 let crate_graph = db.crate_graph();
72 crate_graph 68 crate_graph
73 .iter() 69 .iter()
@@ -78,20 +74,20 @@ impl Crate {
78 .collect() 74 .collect()
79 } 75 }
80 76
81 pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> { 77 pub fn root_module(self, db: &dyn HirDatabase) -> Option<Module> {
82 let module_id = db.crate_def_map(self.id).root; 78 let module_id = db.crate_def_map(self.id).root;
83 Some(Module::new(self, module_id)) 79 Some(Module::new(self, module_id))
84 } 80 }
85 81
86 pub fn root_file(self, db: &impl DefDatabase) -> FileId { 82 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
87 db.crate_graph()[self.id].root_file_id 83 db.crate_graph()[self.id].root_file_id
88 } 84 }
89 85
90 pub fn edition(self, db: &impl DefDatabase) -> Edition { 86 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
91 db.crate_graph()[self.id].edition 87 db.crate_graph()[self.id].edition
92 } 88 }
93 89
94 pub fn all(db: &impl DefDatabase) -> Vec<Crate> { 90 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
95 db.crate_graph().iter().map(|id| Crate { id }).collect() 91 db.crate_graph().iter().map(|id| Crate { id }).collect()
96 } 92 }
97} 93}
@@ -128,7 +124,7 @@ impl_froms!(
128); 124);
129 125
130impl ModuleDef { 126impl ModuleDef {
131 pub fn module(self, db: &impl HirDatabase) -> Option<Module> { 127 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
132 match self { 128 match self {
133 ModuleDef::Module(it) => it.parent(db), 129 ModuleDef::Module(it) => it.parent(db),
134 ModuleDef::Function(it) => Some(it.module(db)), 130 ModuleDef::Function(it) => Some(it.module(db)),
@@ -153,7 +149,7 @@ impl Module {
153 } 149 }
154 150
155 /// Name of this module. 151 /// Name of this module.
156 pub fn name(self, db: &impl DefDatabase) -> Option<Name> { 152 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
157 let def_map = db.crate_def_map(self.id.krate); 153 let def_map = db.crate_def_map(self.id.krate);
158 let parent = def_map[self.id.local_id].parent?; 154 let parent = def_map[self.id.local_id].parent?;
159 def_map[parent].children.iter().find_map(|(name, module_id)| { 155 def_map[parent].children.iter().find_map(|(name, module_id)| {
@@ -173,13 +169,13 @@ impl Module {
173 /// Topmost parent of this module. Every module has a `crate_root`, but some 169 /// Topmost parent of this module. Every module has a `crate_root`, but some
174 /// might be missing `krate`. This can happen if a module's file is not included 170 /// might be missing `krate`. This can happen if a module's file is not included
175 /// in the module tree of any target in `Cargo.toml`. 171 /// in the module tree of any target in `Cargo.toml`.
176 pub fn crate_root(self, db: &impl DefDatabase) -> Module { 172 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
177 let def_map = db.crate_def_map(self.id.krate); 173 let def_map = db.crate_def_map(self.id.krate);
178 self.with_module_id(def_map.root) 174 self.with_module_id(def_map.root)
179 } 175 }
180 176
181 /// Iterates over all child modules. 177 /// Iterates over all child modules.
182 pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { 178 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
183 let def_map = db.crate_def_map(self.id.krate); 179 let def_map = db.crate_def_map(self.id.krate);
184 let children = def_map[self.id.local_id] 180 let children = def_map[self.id.local_id]
185 .children 181 .children
@@ -190,13 +186,13 @@ impl Module {
190 } 186 }
191 187
192 /// Finds a parent module. 188 /// Finds a parent module.
193 pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { 189 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
194 let def_map = db.crate_def_map(self.id.krate); 190 let def_map = db.crate_def_map(self.id.krate);
195 let parent_id = def_map[self.id.local_id].parent?; 191 let parent_id = def_map[self.id.local_id].parent?;
196 Some(self.with_module_id(parent_id)) 192 Some(self.with_module_id(parent_id))
197 } 193 }
198 194
199 pub fn path_to_root(self, db: &impl HirDatabase) -> Vec<Module> { 195 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
200 let mut res = vec![self]; 196 let mut res = vec![self];
201 let mut curr = self; 197 let mut curr = self;
202 while let Some(next) = curr.parent(db) { 198 while let Some(next) = curr.parent(db) {
@@ -209,7 +205,7 @@ impl Module {
209 /// Returns a `ModuleScope`: a set of items, visible in this module. 205 /// Returns a `ModuleScope`: a set of items, visible in this module.
210 pub fn scope( 206 pub fn scope(
211 self, 207 self,
212 db: &impl HirDatabase, 208 db: &dyn HirDatabase,
213 visible_from: Option<Module>, 209 visible_from: Option<Module>,
214 ) -> Vec<(Name, ScopeDef)> { 210 ) -> Vec<(Name, ScopeDef)> {
215 db.crate_def_map(self.id.krate)[self.id.local_id] 211 db.crate_def_map(self.id.krate)[self.id.local_id]
@@ -217,7 +213,8 @@ impl Module {
217 .entries() 213 .entries()
218 .filter_map(|(name, def)| { 214 .filter_map(|(name, def)| {
219 if let Some(m) = visible_from { 215 if let Some(m) = visible_from {
220 let filtered = def.filter_visibility(|vis| vis.is_visible_from(db, m.id)); 216 let filtered =
217 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
221 if filtered.is_none() && !def.is_none() { 218 if filtered.is_none() && !def.is_none() {
222 None 219 None
223 } else { 220 } else {
@@ -233,10 +230,10 @@ impl Module {
233 .collect() 230 .collect()
234 } 231 }
235 232
236 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { 233 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
237 let _p = profile("Module::diagnostics"); 234 let _p = profile("Module::diagnostics");
238 let crate_def_map = db.crate_def_map(self.id.krate); 235 let crate_def_map = db.crate_def_map(self.id.krate);
239 crate_def_map.add_diagnostics(db, self.id.local_id, sink); 236 crate_def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
240 for decl in self.declarations(db) { 237 for decl in self.declarations(db) {
241 match decl { 238 match decl {
242 crate::ModuleDef::Function(f) => f.diagnostics(db, sink), 239 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
@@ -259,12 +256,12 @@ impl Module {
259 } 256 }
260 } 257 }
261 258
262 pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { 259 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
263 let def_map = db.crate_def_map(self.id.krate); 260 let def_map = db.crate_def_map(self.id.krate);
264 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect() 261 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
265 } 262 }
266 263
267 pub fn impl_defs(self, db: &impl DefDatabase) -> Vec<ImplDef> { 264 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<ImplDef> {
268 let def_map = db.crate_def_map(self.id.krate); 265 let def_map = db.crate_def_map(self.id.krate);
269 def_map[self.id.local_id].scope.impls().map(ImplDef::from).collect() 266 def_map[self.id.local_id].scope.impls().map(ImplDef::from).collect()
270 } 267 }
@@ -277,11 +274,11 @@ impl Module {
277 /// this module, if possible. 274 /// this module, if possible.
278 pub fn find_use_path( 275 pub fn find_use_path(
279 self, 276 self,
280 db: &impl DefDatabase, 277 db: &dyn HirDatabase,
281 item: ModuleDef, 278 item: ModuleDef,
282 ) -> Option<hir_def::path::ModPath> { 279 ) -> Option<hir_def::path::ModPath> {
283 // FIXME expose namespace choice 280 // FIXME expose namespace choice
284 hir_def::find_path::find_path(db, determine_item_namespace(item), self.into()) 281 hir_def::find_path::find_path(db.upcast(), determine_item_namespace(item), self.into())
285 } 282 }
286} 283}
287 284
@@ -307,7 +304,7 @@ pub enum FieldSource {
307} 304}
308 305
309impl StructField { 306impl StructField {
310 pub fn name(&self, db: &impl HirDatabase) -> Name { 307 pub fn name(&self, db: &dyn HirDatabase) -> Name {
311 self.parent.variant_data(db).fields()[self.id].name.clone() 308 self.parent.variant_data(db).fields()[self.id].name.clone()
312 } 309 }
313 310
@@ -315,7 +312,7 @@ impl StructField {
315 /// placeholder types for type parameters). This is good for showing 312 /// placeholder types for type parameters). This is good for showing
316 /// signature help, but not so good to actually get the type of the field 313 /// signature help, but not so good to actually get the type of the field
317 /// when you actually have a variable of the struct. 314 /// when you actually have a variable of the struct.
318 pub fn signature_ty(&self, db: &impl HirDatabase) -> Type { 315 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
319 let var_id = self.parent.into(); 316 let var_id = self.parent.into();
320 let generic_def_id: GenericDefId = match self.parent { 317 let generic_def_id: GenericDefId = match self.parent {
321 VariantDef::Struct(it) => it.id.into(), 318 VariantDef::Struct(it) => it.id.into(),
@@ -327,17 +324,17 @@ impl StructField {
327 Type::new(db, self.parent.module(db).id.krate, var_id, ty) 324 Type::new(db, self.parent.module(db).id.krate, var_id, ty)
328 } 325 }
329 326
330 pub fn parent_def(&self, _db: &impl HirDatabase) -> VariantDef { 327 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
331 self.parent 328 self.parent
332 } 329 }
333} 330}
334 331
335impl HasVisibility for StructField { 332impl HasVisibility for StructField {
336 fn visibility(&self, db: &impl HirDatabase) -> Visibility { 333 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
337 let variant_data = self.parent.variant_data(db); 334 let variant_data = self.parent.variant_data(db);
338 let visibility = &variant_data.fields()[self.id].visibility; 335 let visibility = &variant_data.fields()[self.id].visibility;
339 let parent_id: hir_def::VariantId = self.parent.into(); 336 let parent_id: hir_def::VariantId = self.parent.into();
340 visibility.resolve(db, &parent_id.resolver(db)) 337 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
341 } 338 }
342} 339}
343 340
@@ -347,19 +344,19 @@ pub struct Struct {
347} 344}
348 345
349impl Struct { 346impl Struct {
350 pub fn module(self, db: &impl DefDatabase) -> Module { 347 pub fn module(self, db: &dyn HirDatabase) -> Module {
351 Module { id: self.id.lookup(db).container.module(db) } 348 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
352 } 349 }
353 350
354 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 351 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
355 Some(self.module(db).krate()) 352 Some(self.module(db).krate())
356 } 353 }
357 354
358 pub fn name(self, db: &impl DefDatabase) -> Name { 355 pub fn name(self, db: &dyn HirDatabase) -> Name {
359 db.struct_data(self.id).name.clone() 356 db.struct_data(self.id).name.clone()
360 } 357 }
361 358
362 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { 359 pub fn fields(self, db: &dyn HirDatabase) -> Vec<StructField> {
363 db.struct_data(self.id) 360 db.struct_data(self.id)
364 .variant_data 361 .variant_data
365 .fields() 362 .fields()
@@ -368,11 +365,11 @@ impl Struct {
368 .collect() 365 .collect()
369 } 366 }
370 367
371 pub fn ty(self, db: &impl HirDatabase) -> Type { 368 pub fn ty(self, db: &dyn HirDatabase) -> Type {
372 Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id) 369 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
373 } 370 }
374 371
375 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 372 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
376 db.struct_data(self.id).variant_data.clone() 373 db.struct_data(self.id).variant_data.clone()
377 } 374 }
378} 375}
@@ -383,19 +380,19 @@ pub struct Union {
383} 380}
384 381
385impl Union { 382impl Union {
386 pub fn name(self, db: &impl DefDatabase) -> Name { 383 pub fn name(self, db: &dyn HirDatabase) -> Name {
387 db.union_data(self.id).name.clone() 384 db.union_data(self.id).name.clone()
388 } 385 }
389 386
390 pub fn module(self, db: &impl DefDatabase) -> Module { 387 pub fn module(self, db: &dyn HirDatabase) -> Module {
391 Module { id: self.id.lookup(db).container.module(db) } 388 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
392 } 389 }
393 390
394 pub fn ty(self, db: &impl HirDatabase) -> Type { 391 pub fn ty(self, db: &dyn HirDatabase) -> Type {
395 Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id) 392 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
396 } 393 }
397 394
398 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { 395 pub fn fields(self, db: &dyn HirDatabase) -> Vec<StructField> {
399 db.union_data(self.id) 396 db.union_data(self.id)
400 .variant_data 397 .variant_data
401 .fields() 398 .fields()
@@ -404,7 +401,7 @@ impl Union {
404 .collect() 401 .collect()
405 } 402 }
406 403
407 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 404 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
408 db.union_data(self.id).variant_data.clone() 405 db.union_data(self.id).variant_data.clone()
409 } 406 }
410} 407}
@@ -415,19 +412,19 @@ pub struct Enum {
415} 412}
416 413
417impl Enum { 414impl Enum {
418 pub fn module(self, db: &impl DefDatabase) -> Module { 415 pub fn module(self, db: &dyn HirDatabase) -> Module {
419 Module { id: self.id.lookup(db).container.module(db) } 416 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
420 } 417 }
421 418
422 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 419 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
423 Some(self.module(db).krate()) 420 Some(self.module(db).krate())
424 } 421 }
425 422
426 pub fn name(self, db: &impl DefDatabase) -> Name { 423 pub fn name(self, db: &dyn HirDatabase) -> Name {
427 db.enum_data(self.id).name.clone() 424 db.enum_data(self.id).name.clone()
428 } 425 }
429 426
430 pub fn variants(self, db: &impl DefDatabase) -> Vec<EnumVariant> { 427 pub fn variants(self, db: &dyn HirDatabase) -> Vec<EnumVariant> {
431 db.enum_data(self.id) 428 db.enum_data(self.id)
432 .variants 429 .variants
433 .iter() 430 .iter()
@@ -435,8 +432,8 @@ impl Enum {
435 .collect() 432 .collect()
436 } 433 }
437 434
438 pub fn ty(self, db: &impl HirDatabase) -> Type { 435 pub fn ty(self, db: &dyn HirDatabase) -> Type {
439 Type::from_def(db, self.id.lookup(db).container.module(db).krate, self.id) 436 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
440 } 437 }
441} 438}
442 439
@@ -447,18 +444,18 @@ pub struct EnumVariant {
447} 444}
448 445
449impl EnumVariant { 446impl EnumVariant {
450 pub fn module(self, db: &impl HirDatabase) -> Module { 447 pub fn module(self, db: &dyn HirDatabase) -> Module {
451 self.parent.module(db) 448 self.parent.module(db)
452 } 449 }
453 pub fn parent_enum(self, _db: &impl DefDatabase) -> Enum { 450 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
454 self.parent 451 self.parent
455 } 452 }
456 453
457 pub fn name(self, db: &impl DefDatabase) -> Name { 454 pub fn name(self, db: &dyn HirDatabase) -> Name {
458 db.enum_data(self.parent.id).variants[self.id].name.clone() 455 db.enum_data(self.parent.id).variants[self.id].name.clone()
459 } 456 }
460 457
461 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { 458 pub fn fields(self, db: &dyn HirDatabase) -> Vec<StructField> {
462 self.variant_data(db) 459 self.variant_data(db)
463 .fields() 460 .fields()
464 .iter() 461 .iter()
@@ -466,11 +463,11 @@ impl EnumVariant {
466 .collect() 463 .collect()
467 } 464 }
468 465
469 pub fn kind(self, db: &impl HirDatabase) -> StructKind { 466 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
470 self.variant_data(db).kind() 467 self.variant_data(db).kind()
471 } 468 }
472 469
473 pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 470 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
474 db.enum_data(self.parent.id).variants[self.id].variant_data.clone() 471 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
475 } 472 }
476} 473}
@@ -485,7 +482,7 @@ pub enum Adt {
485impl_froms!(Adt: Struct, Union, Enum); 482impl_froms!(Adt: Struct, Union, Enum);
486 483
487impl Adt { 484impl Adt {
488 pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool { 485 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
489 let subst = db.generic_defaults(self.into()); 486 let subst = db.generic_defaults(self.into());
490 subst.iter().any(|ty| ty == &Ty::Unknown) 487 subst.iter().any(|ty| ty == &Ty::Unknown)
491 } 488 }
@@ -493,12 +490,12 @@ impl Adt {
493 /// Turns this ADT into a type. Any type parameters of the ADT will be 490 /// Turns this ADT into a type. Any type parameters of the ADT will be
494 /// turned into unknown types, which is good for e.g. finding the most 491 /// turned into unknown types, which is good for e.g. finding the most
495 /// general set of completions, but will not look very nice when printed. 492 /// general set of completions, but will not look very nice when printed.
496 pub fn ty(self, db: &impl HirDatabase) -> Type { 493 pub fn ty(self, db: &dyn HirDatabase) -> Type {
497 let id = AdtId::from(self); 494 let id = AdtId::from(self);
498 Type::from_def(db, id.module(db).krate, id) 495 Type::from_def(db, id.module(db.upcast()).krate, id)
499 } 496 }
500 497
501 pub fn module(self, db: &impl DefDatabase) -> Module { 498 pub fn module(self, db: &dyn HirDatabase) -> Module {
502 match self { 499 match self {
503 Adt::Struct(s) => s.module(db), 500 Adt::Struct(s) => s.module(db),
504 Adt::Union(s) => s.module(db), 501 Adt::Union(s) => s.module(db),
@@ -506,11 +503,11 @@ impl Adt {
506 } 503 }
507 } 504 }
508 505
509 pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> { 506 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
510 Some(self.module(db).krate()) 507 Some(self.module(db).krate())
511 } 508 }
512 509
513 pub fn name(&self, db: &impl HirDatabase) -> Name { 510 pub fn name(&self, db: &dyn HirDatabase) -> Name {
514 match self { 511 match self {
515 Adt::Struct(s) => s.name(db), 512 Adt::Struct(s) => s.name(db),
516 Adt::Union(u) => u.name(db), 513 Adt::Union(u) => u.name(db),
@@ -528,7 +525,7 @@ pub enum VariantDef {
528impl_froms!(VariantDef: Struct, Union, EnumVariant); 525impl_froms!(VariantDef: Struct, Union, EnumVariant);
529 526
530impl VariantDef { 527impl VariantDef {
531 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { 528 pub fn fields(self, db: &dyn HirDatabase) -> Vec<StructField> {
532 match self { 529 match self {
533 VariantDef::Struct(it) => it.fields(db), 530 VariantDef::Struct(it) => it.fields(db),
534 VariantDef::Union(it) => it.fields(db), 531 VariantDef::Union(it) => it.fields(db),
@@ -536,7 +533,7 @@ impl VariantDef {
536 } 533 }
537 } 534 }
538 535
539 pub fn module(self, db: &impl HirDatabase) -> Module { 536 pub fn module(self, db: &dyn HirDatabase) -> Module {
540 match self { 537 match self {
541 VariantDef::Struct(it) => it.module(db), 538 VariantDef::Struct(it) => it.module(db),
542 VariantDef::Union(it) => it.module(db), 539 VariantDef::Union(it) => it.module(db),
@@ -544,7 +541,7 @@ impl VariantDef {
544 } 541 }
545 } 542 }
546 543
547 pub fn name(&self, db: &impl HirDatabase) -> Name { 544 pub fn name(&self, db: &dyn HirDatabase) -> Name {
548 match self { 545 match self {
549 VariantDef::Struct(s) => s.name(db), 546 VariantDef::Struct(s) => s.name(db),
550 VariantDef::Union(u) => u.name(db), 547 VariantDef::Union(u) => u.name(db),
@@ -552,7 +549,7 @@ impl VariantDef {
552 } 549 }
553 } 550 }
554 551
555 pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 552 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
556 match self { 553 match self {
557 VariantDef::Struct(it) => it.variant_data(db), 554 VariantDef::Struct(it) => it.variant_data(db),
558 VariantDef::Union(it) => it.variant_data(db), 555 VariantDef::Union(it) => it.variant_data(db),
@@ -572,7 +569,7 @@ pub enum DefWithBody {
572impl_froms!(DefWithBody: Function, Const, Static); 569impl_froms!(DefWithBody: Function, Const, Static);
573 570
574impl DefWithBody { 571impl DefWithBody {
575 pub fn module(self, db: &impl HirDatabase) -> Module { 572 pub fn module(self, db: &dyn HirDatabase) -> Module {
576 match self { 573 match self {
577 DefWithBody::Const(c) => c.module(db), 574 DefWithBody::Const(c) => c.module(db),
578 DefWithBody::Function(f) => f.module(db), 575 DefWithBody::Function(f) => f.module(db),
@@ -580,7 +577,7 @@ impl DefWithBody {
580 } 577 }
581 } 578 }
582 579
583 pub fn name(self, db: &impl HirDatabase) -> Option<Name> { 580 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
584 match self { 581 match self {
585 DefWithBody::Function(f) => Some(f.name(db)), 582 DefWithBody::Function(f) => Some(f.name(db)),
586 DefWithBody::Static(s) => s.name(db), 583 DefWithBody::Static(s) => s.name(db),
@@ -595,27 +592,27 @@ pub struct Function {
595} 592}
596 593
597impl Function { 594impl Function {
598 pub fn module(self, db: &impl DefDatabase) -> Module { 595 pub fn module(self, db: &dyn HirDatabase) -> Module {
599 self.id.lookup(db).module(db).into() 596 self.id.lookup(db.upcast()).module(db.upcast()).into()
600 } 597 }
601 598
602 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 599 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
603 Some(self.module(db).krate()) 600 Some(self.module(db).krate())
604 } 601 }
605 602
606 pub fn name(self, db: &impl HirDatabase) -> Name { 603 pub fn name(self, db: &dyn HirDatabase) -> Name {
607 db.function_data(self.id).name.clone() 604 db.function_data(self.id).name.clone()
608 } 605 }
609 606
610 pub fn has_self_param(self, db: &impl HirDatabase) -> bool { 607 pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
611 db.function_data(self.id).has_self_param 608 db.function_data(self.id).has_self_param
612 } 609 }
613 610
614 pub fn params(self, db: &impl HirDatabase) -> Vec<TypeRef> { 611 pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeRef> {
615 db.function_data(self.id).params.clone() 612 db.function_data(self.id).params.clone()
616 } 613 }
617 614
618 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { 615 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
619 let _p = profile("Function::diagnostics"); 616 let _p = profile("Function::diagnostics");
620 let infer = db.infer(self.id.into()); 617 let infer = db.infer(self.id.into());
621 infer.add_diagnostics(db, self.id, sink); 618 infer.add_diagnostics(db, self.id, sink);
@@ -625,10 +622,10 @@ impl Function {
625} 622}
626 623
627impl HasVisibility for Function { 624impl HasVisibility for Function {
628 fn visibility(&self, db: &impl HirDatabase) -> Visibility { 625 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
629 let function_data = db.function_data(self.id); 626 let function_data = db.function_data(self.id);
630 let visibility = &function_data.visibility; 627 let visibility = &function_data.visibility;
631 visibility.resolve(db, &self.id.resolver(db)) 628 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
632 } 629 }
633} 630}
634 631
@@ -638,24 +635,24 @@ pub struct Const {
638} 635}
639 636
640impl Const { 637impl Const {
641 pub fn module(self, db: &impl DefDatabase) -> Module { 638 pub fn module(self, db: &dyn HirDatabase) -> Module {
642 Module { id: self.id.lookup(db).module(db) } 639 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
643 } 640 }
644 641
645 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 642 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
646 Some(self.module(db).krate()) 643 Some(self.module(db).krate())
647 } 644 }
648 645
649 pub fn name(self, db: &impl HirDatabase) -> Option<Name> { 646 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
650 db.const_data(self.id).name.clone() 647 db.const_data(self.id).name.clone()
651 } 648 }
652} 649}
653 650
654impl HasVisibility for Const { 651impl HasVisibility for Const {
655 fn visibility(&self, db: &impl HirDatabase) -> Visibility { 652 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
656 let function_data = db.const_data(self.id); 653 let function_data = db.const_data(self.id);
657 let visibility = &function_data.visibility; 654 let visibility = &function_data.visibility;
658 visibility.resolve(db, &self.id.resolver(db)) 655 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
659 } 656 }
660} 657}
661 658
@@ -665,15 +662,15 @@ pub struct Static {
665} 662}
666 663
667impl Static { 664impl Static {
668 pub fn module(self, db: &impl DefDatabase) -> Module { 665 pub fn module(self, db: &dyn HirDatabase) -> Module {
669 Module { id: self.id.lookup(db).module(db) } 666 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
670 } 667 }
671 668
672 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 669 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
673 Some(self.module(db).krate()) 670 Some(self.module(db).krate())
674 } 671 }
675 672
676 pub fn name(self, db: &impl HirDatabase) -> Option<Name> { 673 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
677 db.static_data(self.id).name.clone() 674 db.static_data(self.id).name.clone()
678 } 675 }
679} 676}
@@ -684,19 +681,19 @@ pub struct Trait {
684} 681}
685 682
686impl Trait { 683impl Trait {
687 pub fn module(self, db: &impl DefDatabase) -> Module { 684 pub fn module(self, db: &dyn HirDatabase) -> Module {
688 Module { id: self.id.lookup(db).container.module(db) } 685 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
689 } 686 }
690 687
691 pub fn name(self, db: &impl DefDatabase) -> Name { 688 pub fn name(self, db: &dyn HirDatabase) -> Name {
692 db.trait_data(self.id).name.clone() 689 db.trait_data(self.id).name.clone()
693 } 690 }
694 691
695 pub fn items(self, db: &impl DefDatabase) -> Vec<AssocItem> { 692 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
696 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect() 693 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
697 } 694 }
698 695
699 pub fn is_auto(self, db: &impl DefDatabase) -> bool { 696 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
700 db.trait_data(self.id).auto 697 db.trait_data(self.id).auto
701 } 698 }
702} 699}
@@ -707,37 +704,37 @@ pub struct TypeAlias {
707} 704}
708 705
709impl TypeAlias { 706impl TypeAlias {
710 pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool { 707 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
711 let subst = db.generic_defaults(self.id.into()); 708 let subst = db.generic_defaults(self.id.into());
712 subst.iter().any(|ty| ty == &Ty::Unknown) 709 subst.iter().any(|ty| ty == &Ty::Unknown)
713 } 710 }
714 711
715 pub fn module(self, db: &impl DefDatabase) -> Module { 712 pub fn module(self, db: &dyn HirDatabase) -> Module {
716 Module { id: self.id.lookup(db).module(db) } 713 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
717 } 714 }
718 715
719 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 716 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
720 Some(self.module(db).krate()) 717 Some(self.module(db).krate())
721 } 718 }
722 719
723 pub fn type_ref(self, db: &impl DefDatabase) -> Option<TypeRef> { 720 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
724 db.type_alias_data(self.id).type_ref.clone() 721 db.type_alias_data(self.id).type_ref.clone()
725 } 722 }
726 723
727 pub fn ty(self, db: &impl HirDatabase) -> Type { 724 pub fn ty(self, db: &dyn HirDatabase) -> Type {
728 Type::from_def(db, self.id.lookup(db).module(db).krate, self.id) 725 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate, self.id)
729 } 726 }
730 727
731 pub fn name(self, db: &impl DefDatabase) -> Name { 728 pub fn name(self, db: &dyn HirDatabase) -> Name {
732 db.type_alias_data(self.id).name.clone() 729 db.type_alias_data(self.id).name.clone()
733 } 730 }
734} 731}
735 732
736impl HasVisibility for TypeAlias { 733impl HasVisibility for TypeAlias {
737 fn visibility(&self, db: &impl HirDatabase) -> Visibility { 734 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
738 let function_data = db.type_alias_data(self.id); 735 let function_data = db.type_alias_data(self.id);
739 let visibility = &function_data.visibility; 736 let visibility = &function_data.visibility;
740 visibility.resolve(db, &self.id.resolver(db)) 737 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
741 } 738 }
742} 739}
743 740
@@ -750,14 +747,14 @@ impl MacroDef {
750 /// FIXME: right now, this just returns the root module of the crate that 747 /// FIXME: right now, this just returns the root module of the crate that
751 /// defines this macro. The reasons for this is that macros are expanded 748 /// defines this macro. The reasons for this is that macros are expanded
752 /// early, in `ra_hir_expand`, where modules simply do not exist yet. 749 /// early, in `ra_hir_expand`, where modules simply do not exist yet.
753 pub fn module(self, db: &impl HirDatabase) -> Option<Module> { 750 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
754 let krate = self.id.krate?; 751 let krate = self.id.krate?;
755 let module_id = db.crate_def_map(krate).root; 752 let module_id = db.crate_def_map(krate).root;
756 Some(Module::new(Crate { id: krate }, module_id)) 753 Some(Module::new(Crate { id: krate }, module_id))
757 } 754 }
758 755
759 /// XXX: this parses the file 756 /// XXX: this parses the file
760 pub fn name(self, db: &impl HirDatabase) -> Option<Name> { 757 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
761 self.source(db).value.name().map(|it| it.as_name()) 758 self.source(db).value.name().map(|it| it.as_name())
762 } 759 }
763} 760}
@@ -775,50 +772,50 @@ pub enum AssocItemContainer {
775 ImplDef(ImplDef), 772 ImplDef(ImplDef),
776} 773}
777pub trait AsAssocItem { 774pub trait AsAssocItem {
778 fn as_assoc_item(self, db: &impl DefDatabase) -> Option<AssocItem>; 775 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
779} 776}
780 777
781impl AsAssocItem for Function { 778impl AsAssocItem for Function {
782 fn as_assoc_item(self, db: &impl DefDatabase) -> Option<AssocItem> { 779 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
783 as_assoc_item(db, AssocItem::Function, self.id) 780 as_assoc_item(db, AssocItem::Function, self.id)
784 } 781 }
785} 782}
786impl AsAssocItem for Const { 783impl AsAssocItem for Const {
787 fn as_assoc_item(self, db: &impl DefDatabase) -> Option<AssocItem> { 784 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
788 as_assoc_item(db, AssocItem::Const, self.id) 785 as_assoc_item(db, AssocItem::Const, self.id)
789 } 786 }
790} 787}
791impl AsAssocItem for TypeAlias { 788impl AsAssocItem for TypeAlias {
792 fn as_assoc_item(self, db: &impl DefDatabase) -> Option<AssocItem> { 789 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
793 as_assoc_item(db, AssocItem::TypeAlias, self.id) 790 as_assoc_item(db, AssocItem::TypeAlias, self.id)
794 } 791 }
795} 792}
796fn as_assoc_item<ID, DEF, CTOR, AST>(db: &impl DefDatabase, ctor: CTOR, id: ID) -> Option<AssocItem> 793fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
797where 794where
798 ID: Lookup<Data = AssocItemLoc<AST>>, 795 ID: Lookup<Data = AssocItemLoc<AST>>,
799 DEF: From<ID>, 796 DEF: From<ID>,
800 CTOR: FnOnce(DEF) -> AssocItem, 797 CTOR: FnOnce(DEF) -> AssocItem,
801 AST: AstNode, 798 AST: AstNode,
802{ 799{
803 match id.lookup(db).container { 800 match id.lookup(db.upcast()).container {
804 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))), 801 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
805 AssocContainerId::ContainerId(_) => None, 802 AssocContainerId::ContainerId(_) => None,
806 } 803 }
807} 804}
808 805
809impl AssocItem { 806impl AssocItem {
810 pub fn module(self, db: &impl DefDatabase) -> Module { 807 pub fn module(self, db: &dyn HirDatabase) -> Module {
811 match self { 808 match self {
812 AssocItem::Function(f) => f.module(db), 809 AssocItem::Function(f) => f.module(db),
813 AssocItem::Const(c) => c.module(db), 810 AssocItem::Const(c) => c.module(db),
814 AssocItem::TypeAlias(t) => t.module(db), 811 AssocItem::TypeAlias(t) => t.module(db),
815 } 812 }
816 } 813 }
817 pub fn container(self, db: &impl DefDatabase) -> AssocItemContainer { 814 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
818 let container = match self { 815 let container = match self {
819 AssocItem::Function(it) => it.id.lookup(db).container, 816 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
820 AssocItem::Const(it) => it.id.lookup(db).container, 817 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
821 AssocItem::TypeAlias(it) => it.id.lookup(db).container, 818 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
822 }; 819 };
823 match container { 820 match container {
824 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()), 821 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
@@ -829,7 +826,7 @@ impl AssocItem {
829} 826}
830 827
831impl HasVisibility for AssocItem { 828impl HasVisibility for AssocItem {
832 fn visibility(&self, db: &impl HirDatabase) -> Visibility { 829 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
833 match self { 830 match self {
834 AssocItem::Function(f) => f.visibility(db), 831 AssocItem::Function(f) => f.visibility(db),
835 AssocItem::Const(c) => c.visibility(db), 832 AssocItem::Const(c) => c.visibility(db),
@@ -862,7 +859,7 @@ impl_froms!(
862); 859);
863 860
864impl GenericDef { 861impl GenericDef {
865 pub fn params(self, db: &impl HirDatabase) -> Vec<TypeParam> { 862 pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
866 let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into()); 863 let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into());
867 generics 864 generics
868 .types 865 .types
@@ -880,7 +877,7 @@ pub struct Local {
880 877
881impl Local { 878impl Local {
882 // FIXME: why is this an option? It shouldn't be? 879 // FIXME: why is this an option? It shouldn't be?
883 pub fn name(self, db: &impl HirDatabase) -> Option<Name> { 880 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
884 let body = db.body(self.parent.into()); 881 let body = db.body(self.parent.into());
885 match &body[self.pat_id] { 882 match &body[self.pat_id] {
886 Pat::Bind { name, .. } => Some(name.clone()), 883 Pat::Bind { name, .. } => Some(name.clone()),
@@ -888,11 +885,11 @@ impl Local {
888 } 885 }
889 } 886 }
890 887
891 pub fn is_self(self, db: &impl HirDatabase) -> bool { 888 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
892 self.name(db) == Some(name![self]) 889 self.name(db) == Some(name![self])
893 } 890 }
894 891
895 pub fn is_mut(self, db: &impl HirDatabase) -> bool { 892 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
896 let body = db.body(self.parent.into()); 893 let body = db.body(self.parent.into());
897 match &body[self.pat_id] { 894 match &body[self.pat_id] {
898 Pat::Bind { mode, .. } => match mode { 895 Pat::Bind { mode, .. } => match mode {
@@ -903,28 +900,28 @@ impl Local {
903 } 900 }
904 } 901 }
905 902
906 pub fn parent(self, _db: &impl HirDatabase) -> DefWithBody { 903 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
907 self.parent.into() 904 self.parent.into()
908 } 905 }
909 906
910 pub fn module(self, db: &impl HirDatabase) -> Module { 907 pub fn module(self, db: &dyn HirDatabase) -> Module {
911 self.parent(db).module(db) 908 self.parent(db).module(db)
912 } 909 }
913 910
914 pub fn ty(self, db: &impl HirDatabase) -> Type { 911 pub fn ty(self, db: &dyn HirDatabase) -> Type {
915 let def = DefWithBodyId::from(self.parent); 912 let def = DefWithBodyId::from(self.parent);
916 let infer = db.infer(def); 913 let infer = db.infer(def);
917 let ty = infer[self.pat_id].clone(); 914 let ty = infer[self.pat_id].clone();
918 let resolver = def.resolver(db); 915 let resolver = def.resolver(db.upcast());
919 let krate = def.module(db).krate; 916 let krate = def.module(db.upcast()).krate;
920 let environment = TraitEnvironment::lower(db, &resolver); 917 let environment = TraitEnvironment::lower(db, &resolver);
921 Type { krate, ty: InEnvironment { value: ty, environment } } 918 Type { krate, ty: InEnvironment { value: ty, environment } }
922 } 919 }
923 920
924 pub fn source(self, db: &impl HirDatabase) -> InFile<Either<ast::BindPat, ast::SelfParam>> { 921 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::BindPat, ast::SelfParam>> {
925 let (_body, source_map) = db.body_with_source_map(self.parent.into()); 922 let (_body, source_map) = db.body_with_source_map(self.parent.into());
926 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm... 923 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
927 let root = src.file_syntax(db); 924 let root = src.file_syntax(db.upcast());
928 src.map(|ast| { 925 src.map(|ast| {
929 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root)) 926 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
930 }) 927 })
@@ -937,13 +934,13 @@ pub struct TypeParam {
937} 934}
938 935
939impl TypeParam { 936impl TypeParam {
940 pub fn name(self, db: &impl HirDatabase) -> Name { 937 pub fn name(self, db: &dyn HirDatabase) -> Name {
941 let params = db.generic_params(self.id.parent); 938 let params = db.generic_params(self.id.parent);
942 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing) 939 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
943 } 940 }
944 941
945 pub fn module(self, db: &impl HirDatabase) -> Module { 942 pub fn module(self, db: &dyn HirDatabase) -> Module {
946 self.id.parent.module(db).into() 943 self.id.parent.module(db.upcast()).into()
947 } 944 }
948} 945}
949 946
@@ -954,55 +951,55 @@ pub struct ImplDef {
954} 951}
955 952
956impl ImplDef { 953impl ImplDef {
957 pub fn all_in_crate(db: &impl HirDatabase, krate: Crate) -> Vec<ImplDef> { 954 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<ImplDef> {
958 let impls = db.impls_in_crate(krate.id); 955 let impls = db.impls_in_crate(krate.id);
959 impls.all_impls().map(Self::from).collect() 956 impls.all_impls().map(Self::from).collect()
960 } 957 }
961 pub fn for_trait(db: &impl HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplDef> { 958 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplDef> {
962 let impls = db.impls_in_crate(krate.id); 959 let impls = db.impls_in_crate(krate.id);
963 impls.lookup_impl_defs_for_trait(trait_.id).map(Self::from).collect() 960 impls.lookup_impl_defs_for_trait(trait_.id).map(Self::from).collect()
964 } 961 }
965 962
966 pub fn target_trait(&self, db: &impl DefDatabase) -> Option<TypeRef> { 963 pub fn target_trait(&self, db: &dyn HirDatabase) -> Option<TypeRef> {
967 db.impl_data(self.id).target_trait.clone() 964 db.impl_data(self.id).target_trait.clone()
968 } 965 }
969 966
970 pub fn target_type(&self, db: &impl DefDatabase) -> TypeRef { 967 pub fn target_type(&self, db: &dyn HirDatabase) -> TypeRef {
971 db.impl_data(self.id).target_type.clone() 968 db.impl_data(self.id).target_type.clone()
972 } 969 }
973 970
974 pub fn target_ty(&self, db: &impl HirDatabase) -> Type { 971 pub fn target_ty(&self, db: &dyn HirDatabase) -> Type {
975 let impl_data = db.impl_data(self.id); 972 let impl_data = db.impl_data(self.id);
976 let resolver = self.id.resolver(db); 973 let resolver = self.id.resolver(db.upcast());
977 let ctx = hir_ty::TyLoweringContext::new(db, &resolver); 974 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
978 let environment = TraitEnvironment::lower(db, &resolver); 975 let environment = TraitEnvironment::lower(db, &resolver);
979 let ty = Ty::from_hir(&ctx, &impl_data.target_type); 976 let ty = Ty::from_hir(&ctx, &impl_data.target_type);
980 Type { 977 Type {
981 krate: self.id.lookup(db).container.module(db).krate, 978 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate,
982 ty: InEnvironment { value: ty, environment }, 979 ty: InEnvironment { value: ty, environment },
983 } 980 }
984 } 981 }
985 982
986 pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { 983 pub fn items(&self, db: &dyn HirDatabase) -> Vec<AssocItem> {
987 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect() 984 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
988 } 985 }
989 986
990 pub fn is_negative(&self, db: &impl DefDatabase) -> bool { 987 pub fn is_negative(&self, db: &dyn HirDatabase) -> bool {
991 db.impl_data(self.id).is_negative 988 db.impl_data(self.id).is_negative
992 } 989 }
993 990
994 pub fn module(&self, db: &impl DefDatabase) -> Module { 991 pub fn module(&self, db: &dyn HirDatabase) -> Module {
995 self.id.lookup(db).container.module(db).into() 992 self.id.lookup(db.upcast()).container.module(db.upcast()).into()
996 } 993 }
997 994
998 pub fn krate(&self, db: &impl DefDatabase) -> Crate { 995 pub fn krate(&self, db: &dyn HirDatabase) -> Crate {
999 Crate { id: self.module(db).id.krate } 996 Crate { id: self.module(db).id.krate }
1000 } 997 }
1001 998
1002 pub fn is_builtin_derive(&self, db: &impl DefDatabase) -> Option<InFile<ast::Attr>> { 999 pub fn is_builtin_derive(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1003 let src = self.source(db); 1000 let src = self.source(db);
1004 let item = src.file_id.is_builtin_derive(db)?; 1001 let item = src.file_id.is_builtin_derive(db.upcast())?;
1005 let hygenic = hir_expand::hygiene::Hygiene::new(db, item.file_id); 1002 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1006 1003
1007 let attr = item 1004 let attr = item
1008 .value 1005 .value
@@ -1028,14 +1025,14 @@ pub struct Type {
1028} 1025}
1029 1026
1030impl Type { 1027impl Type {
1031 fn new(db: &impl HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type { 1028 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1032 let resolver = lexical_env.resolver(db); 1029 let resolver = lexical_env.resolver(db.upcast());
1033 let environment = TraitEnvironment::lower(db, &resolver); 1030 let environment = TraitEnvironment::lower(db, &resolver);
1034 Type { krate, ty: InEnvironment { value: ty, environment } } 1031 Type { krate, ty: InEnvironment { value: ty, environment } }
1035 } 1032 }
1036 1033
1037 fn from_def( 1034 fn from_def(
1038 db: &impl HirDatabase, 1035 db: &dyn HirDatabase,
1039 krate: CrateId, 1036 krate: CrateId,
1040 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>, 1037 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1041 ) -> Type { 1038 ) -> Type {
@@ -1073,7 +1070,7 @@ impl Type {
1073 1070
1074 /// Checks that particular type `ty` implements `std::future::Future`. 1071 /// Checks that particular type `ty` implements `std::future::Future`.
1075 /// This function is used in `.await` syntax completion. 1072 /// This function is used in `.await` syntax completion.
1076 pub fn impls_future(&self, db: &impl HirDatabase) -> bool { 1073 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1077 let krate = self.krate; 1074 let krate = self.krate;
1078 1075
1079 let std_future_trait = 1076 let std_future_trait =
@@ -1110,7 +1107,7 @@ impl Type {
1110 } 1107 }
1111 } 1108 }
1112 1109
1113 pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> { 1110 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(StructField, Type)> {
1114 if let Ty::Apply(a_ty) = &self.ty.value { 1111 if let Ty::Apply(a_ty) = &self.ty.value {
1115 if let TypeCtor::Adt(AdtId::StructId(s)) = a_ty.ctor { 1112 if let TypeCtor::Adt(AdtId::StructId(s)) = a_ty.ctor {
1116 let var_def = s.into(); 1113 let var_def = s.into();
@@ -1128,7 +1125,7 @@ impl Type {
1128 Vec::new() 1125 Vec::new()
1129 } 1126 }
1130 1127
1131 pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec<Type> { 1128 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1132 let mut res = Vec::new(); 1129 let mut res = Vec::new();
1133 if let Ty::Apply(a_ty) = &self.ty.value { 1130 if let Ty::Apply(a_ty) = &self.ty.value {
1134 if let TypeCtor::Tuple { .. } = a_ty.ctor { 1131 if let TypeCtor::Tuple { .. } = a_ty.ctor {
@@ -1143,7 +1140,7 @@ impl Type {
1143 1140
1144 pub fn variant_fields( 1141 pub fn variant_fields(
1145 &self, 1142 &self,
1146 db: &impl HirDatabase, 1143 db: &dyn HirDatabase,
1147 def: VariantDef, 1144 def: VariantDef,
1148 ) -> Vec<(StructField, Type)> { 1145 ) -> Vec<(StructField, Type)> {
1149 // FIXME: check that ty and def match 1146 // FIXME: check that ty and def match
@@ -1162,7 +1159,7 @@ impl Type {
1162 } 1159 }
1163 } 1160 }
1164 1161
1165 pub fn autoderef<'a>(&'a self, db: &'a impl HirDatabase) -> impl Iterator<Item = Type> + 'a { 1162 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1166 // There should be no inference vars in types passed here 1163 // There should be no inference vars in types passed here
1167 // FIXME check that? 1164 // FIXME check that?
1168 let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 }; 1165 let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
@@ -1177,7 +1174,7 @@ impl Type {
1177 // lifetime problems, because we need to borrow temp `CrateImplDefs`. 1174 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1178 pub fn iterate_impl_items<T>( 1175 pub fn iterate_impl_items<T>(
1179 self, 1176 self,
1180 db: &impl HirDatabase, 1177 db: &dyn HirDatabase,
1181 krate: Crate, 1178 krate: Crate,
1182 mut callback: impl FnMut(AssocItem) -> Option<T>, 1179 mut callback: impl FnMut(AssocItem) -> Option<T>,
1183 ) -> Option<T> { 1180 ) -> Option<T> {
@@ -1197,7 +1194,7 @@ impl Type {
1197 1194
1198 pub fn iterate_method_candidates<T>( 1195 pub fn iterate_method_candidates<T>(
1199 &self, 1196 &self,
1200 db: &impl HirDatabase, 1197 db: &dyn HirDatabase,
1201 krate: Crate, 1198 krate: Crate,
1202 traits_in_scope: &FxHashSet<TraitId>, 1199 traits_in_scope: &FxHashSet<TraitId>,
1203 name: Option<&Name>, 1200 name: Option<&Name>,
@@ -1228,7 +1225,7 @@ impl Type {
1228 1225
1229 pub fn iterate_path_candidates<T>( 1226 pub fn iterate_path_candidates<T>(
1230 &self, 1227 &self,
1231 db: &impl HirDatabase, 1228 db: &dyn HirDatabase,
1232 krate: Crate, 1229 krate: Crate,
1233 traits_in_scope: &FxHashSet<TraitId>, 1230 traits_in_scope: &FxHashSet<TraitId>,
1234 name: Option<&Name>, 1231 name: Option<&Name>,
@@ -1283,7 +1280,7 @@ impl Type {
1283} 1280}
1284 1281
1285impl HirDisplay for Type { 1282impl HirDisplay for Type {
1286 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> std::fmt::Result { 1283 fn hir_fmt(&self, f: &mut HirFormatter) -> std::fmt::Result {
1287 self.ty.value.hir_fmt(f) 1284 self.ty.value.hir_fmt(f)
1288 } 1285 }
1289} 1286}
@@ -1360,30 +1357,30 @@ impl_froms!(
1360); 1357);
1361 1358
1362pub trait HasAttrs { 1359pub trait HasAttrs {
1363 fn attrs(self, db: &impl DefDatabase) -> Attrs; 1360 fn attrs(self, db: &dyn HirDatabase) -> Attrs;
1364} 1361}
1365 1362
1366impl<T: Into<AttrDef>> HasAttrs for T { 1363impl<T: Into<AttrDef>> HasAttrs for T {
1367 fn attrs(self, db: &impl DefDatabase) -> Attrs { 1364 fn attrs(self, db: &dyn HirDatabase) -> Attrs {
1368 let def: AttrDef = self.into(); 1365 let def: AttrDef = self.into();
1369 db.attrs(def.into()) 1366 db.attrs(def.into())
1370 } 1367 }
1371} 1368}
1372 1369
1373pub trait Docs { 1370pub trait Docs {
1374 fn docs(&self, db: &impl HirDatabase) -> Option<Documentation>; 1371 fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation>;
1375} 1372}
1376impl<T: Into<AttrDef> + Copy> Docs for T { 1373impl<T: Into<AttrDef> + Copy> Docs for T {
1377 fn docs(&self, db: &impl HirDatabase) -> Option<Documentation> { 1374 fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation> {
1378 let def: AttrDef = (*self).into(); 1375 let def: AttrDef = (*self).into();
1379 db.documentation(def.into()) 1376 db.documentation(def.into())
1380 } 1377 }
1381} 1378}
1382 1379
1383pub trait HasVisibility { 1380pub trait HasVisibility {
1384 fn visibility(&self, db: &impl HirDatabase) -> Visibility; 1381 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
1385 fn is_visible_from(&self, db: &impl HirDatabase, module: Module) -> bool { 1382 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
1386 let vis = self.visibility(db); 1383 let vis = self.visibility(db);
1387 vis.is_visible_from(db, module.id) 1384 vis.is_visible_from(db.upcast(), module.id)
1388 } 1385 }
1389} 1386}
diff --git a/crates/ra_hir/src/has_source.rs b/crates/ra_hir/src/has_source.rs
index f121e1eff..129764e0a 100644
--- a/crates/ra_hir/src/has_source.rs
+++ b/crates/ra_hir/src/has_source.rs
@@ -9,7 +9,7 @@ use hir_def::{
9use ra_syntax::ast; 9use ra_syntax::ast;
10 10
11use crate::{ 11use crate::{
12 db::DefDatabase, Const, Enum, EnumVariant, FieldSource, Function, ImplDef, MacroDef, Module, 12 db::HirDatabase, Const, Enum, EnumVariant, FieldSource, Function, ImplDef, MacroDef, Module,
13 Static, Struct, StructField, Trait, TypeAlias, TypeParam, Union, 13 Static, Struct, StructField, Trait, TypeAlias, TypeParam, Union,
14}; 14};
15 15
@@ -17,31 +17,31 @@ pub use hir_expand::InFile;
17 17
18pub trait HasSource { 18pub trait HasSource {
19 type Ast; 19 type Ast;
20 fn source(self, db: &impl DefDatabase) -> InFile<Self::Ast>; 20 fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast>;
21} 21}
22 22
23/// NB: Module is !HasSource, because it has two source nodes at the same time: 23/// NB: Module is !HasSource, because it has two source nodes at the same time:
24/// definition and declaration. 24/// definition and declaration.
25impl Module { 25impl Module {
26 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. 26 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
27 pub fn definition_source(self, db: &impl DefDatabase) -> InFile<ModuleSource> { 27 pub fn definition_source(self, db: &dyn HirDatabase) -> InFile<ModuleSource> {
28 let def_map = db.crate_def_map(self.id.krate); 28 let def_map = db.crate_def_map(self.id.krate);
29 def_map[self.id.local_id].definition_source(db) 29 def_map[self.id.local_id].definition_source(db.upcast())
30 } 30 }
31 31
32 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`. 32 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
33 /// `None` for the crate root. 33 /// `None` for the crate root.
34 pub fn declaration_source(self, db: &impl DefDatabase) -> Option<InFile<ast::Module>> { 34 pub fn declaration_source(self, db: &dyn HirDatabase) -> Option<InFile<ast::Module>> {
35 let def_map = db.crate_def_map(self.id.krate); 35 let def_map = db.crate_def_map(self.id.krate);
36 def_map[self.id.local_id].declaration_source(db) 36 def_map[self.id.local_id].declaration_source(db.upcast())
37 } 37 }
38} 38}
39 39
40impl HasSource for StructField { 40impl HasSource for StructField {
41 type Ast = FieldSource; 41 type Ast = FieldSource;
42 fn source(self, db: &impl DefDatabase) -> InFile<FieldSource> { 42 fn source(self, db: &dyn HirDatabase) -> InFile<FieldSource> {
43 let var = VariantId::from(self.parent); 43 let var = VariantId::from(self.parent);
44 let src = var.child_source(db); 44 let src = var.child_source(db.upcast());
45 src.map(|it| match it[self.id].clone() { 45 src.map(|it| match it[self.id].clone() {
46 Either::Left(it) => FieldSource::Pos(it), 46 Either::Left(it) => FieldSource::Pos(it),
47 Either::Right(it) => FieldSource::Named(it), 47 Either::Right(it) => FieldSource::Named(it),
@@ -50,78 +50,78 @@ impl HasSource for StructField {
50} 50}
51impl HasSource for Struct { 51impl HasSource for Struct {
52 type Ast = ast::StructDef; 52 type Ast = ast::StructDef;
53 fn source(self, db: &impl DefDatabase) -> InFile<ast::StructDef> { 53 fn source(self, db: &dyn HirDatabase) -> InFile<ast::StructDef> {
54 self.id.lookup(db).source(db) 54 self.id.lookup(db.upcast()).source(db.upcast())
55 } 55 }
56} 56}
57impl HasSource for Union { 57impl HasSource for Union {
58 type Ast = ast::UnionDef; 58 type Ast = ast::UnionDef;
59 fn source(self, db: &impl DefDatabase) -> InFile<ast::UnionDef> { 59 fn source(self, db: &dyn HirDatabase) -> InFile<ast::UnionDef> {
60 self.id.lookup(db).source(db) 60 self.id.lookup(db.upcast()).source(db.upcast())
61 } 61 }
62} 62}
63impl HasSource for Enum { 63impl HasSource for Enum {
64 type Ast = ast::EnumDef; 64 type Ast = ast::EnumDef;
65 fn source(self, db: &impl DefDatabase) -> InFile<ast::EnumDef> { 65 fn source(self, db: &dyn HirDatabase) -> InFile<ast::EnumDef> {
66 self.id.lookup(db).source(db) 66 self.id.lookup(db.upcast()).source(db.upcast())
67 } 67 }
68} 68}
69impl HasSource for EnumVariant { 69impl HasSource for EnumVariant {
70 type Ast = ast::EnumVariant; 70 type Ast = ast::EnumVariant;
71 fn source(self, db: &impl DefDatabase) -> InFile<ast::EnumVariant> { 71 fn source(self, db: &dyn HirDatabase) -> InFile<ast::EnumVariant> {
72 self.parent.id.child_source(db).map(|map| map[self.id].clone()) 72 self.parent.id.child_source(db.upcast()).map(|map| map[self.id].clone())
73 } 73 }
74} 74}
75impl HasSource for Function { 75impl HasSource for Function {
76 type Ast = ast::FnDef; 76 type Ast = ast::FnDef;
77 fn source(self, db: &impl DefDatabase) -> InFile<ast::FnDef> { 77 fn source(self, db: &dyn HirDatabase) -> InFile<ast::FnDef> {
78 self.id.lookup(db).source(db) 78 self.id.lookup(db.upcast()).source(db.upcast())
79 } 79 }
80} 80}
81impl HasSource for Const { 81impl HasSource for Const {
82 type Ast = ast::ConstDef; 82 type Ast = ast::ConstDef;
83 fn source(self, db: &impl DefDatabase) -> InFile<ast::ConstDef> { 83 fn source(self, db: &dyn HirDatabase) -> InFile<ast::ConstDef> {
84 self.id.lookup(db).source(db) 84 self.id.lookup(db.upcast()).source(db.upcast())
85 } 85 }
86} 86}
87impl HasSource for Static { 87impl HasSource for Static {
88 type Ast = ast::StaticDef; 88 type Ast = ast::StaticDef;
89 fn source(self, db: &impl DefDatabase) -> InFile<ast::StaticDef> { 89 fn source(self, db: &dyn HirDatabase) -> InFile<ast::StaticDef> {
90 self.id.lookup(db).source(db) 90 self.id.lookup(db.upcast()).source(db.upcast())
91 } 91 }
92} 92}
93impl HasSource for Trait { 93impl HasSource for Trait {
94 type Ast = ast::TraitDef; 94 type Ast = ast::TraitDef;
95 fn source(self, db: &impl DefDatabase) -> InFile<ast::TraitDef> { 95 fn source(self, db: &dyn HirDatabase) -> InFile<ast::TraitDef> {
96 self.id.lookup(db).source(db) 96 self.id.lookup(db.upcast()).source(db.upcast())
97 } 97 }
98} 98}
99impl HasSource for TypeAlias { 99impl HasSource for TypeAlias {
100 type Ast = ast::TypeAliasDef; 100 type Ast = ast::TypeAliasDef;
101 fn source(self, db: &impl DefDatabase) -> InFile<ast::TypeAliasDef> { 101 fn source(self, db: &dyn HirDatabase) -> InFile<ast::TypeAliasDef> {
102 self.id.lookup(db).source(db) 102 self.id.lookup(db.upcast()).source(db.upcast())
103 } 103 }
104} 104}
105impl HasSource for MacroDef { 105impl HasSource for MacroDef {
106 type Ast = ast::MacroCall; 106 type Ast = ast::MacroCall;
107 fn source(self, db: &impl DefDatabase) -> InFile<ast::MacroCall> { 107 fn source(self, db: &dyn HirDatabase) -> InFile<ast::MacroCall> {
108 InFile { 108 InFile {
109 file_id: self.id.ast_id.expect("MacroDef without ast_id").file_id, 109 file_id: self.id.ast_id.expect("MacroDef without ast_id").file_id,
110 value: self.id.ast_id.expect("MacroDef without ast_id").to_node(db), 110 value: self.id.ast_id.expect("MacroDef without ast_id").to_node(db.upcast()),
111 } 111 }
112 } 112 }
113} 113}
114impl HasSource for ImplDef { 114impl HasSource for ImplDef {
115 type Ast = ast::ImplDef; 115 type Ast = ast::ImplDef;
116 fn source(self, db: &impl DefDatabase) -> InFile<ast::ImplDef> { 116 fn source(self, db: &dyn HirDatabase) -> InFile<ast::ImplDef> {
117 self.id.lookup(db).source(db) 117 self.id.lookup(db.upcast()).source(db.upcast())
118 } 118 }
119} 119}
120 120
121impl HasSource for TypeParam { 121impl HasSource for TypeParam {
122 type Ast = Either<ast::TraitDef, ast::TypeParam>; 122 type Ast = Either<ast::TraitDef, ast::TypeParam>;
123 fn source(self, db: &impl DefDatabase) -> InFile<Self::Ast> { 123 fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast> {
124 let child_source = self.id.parent.child_source(db); 124 let child_source = self.id.parent.child_source(db.upcast());
125 child_source.map(|it| it[self.id.local_id].clone()) 125 child_source.map(|it| it[self.id.local_id].clone())
126 } 126 }
127} 127}
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
index 788bb3eb7..55e634528 100644
--- a/crates/ra_hir/src/semantics.rs
+++ b/crates/ra_hir/src/semantics.rs
@@ -190,7 +190,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
190 T::to_def(self, src) 190 T::to_def(self, src)
191 } 191 }
192 192
193 fn with_ctx<F: FnOnce(&mut SourceToDefCtx<&DB>) -> T, T>(&self, f: F) -> T { 193 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
194 let mut cache = self.s2d_cache.borrow_mut(); 194 let mut cache = self.s2d_cache.borrow_mut();
195 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache }; 195 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
196 f(&mut ctx) 196 f(&mut ctx)
@@ -369,35 +369,35 @@ impl<'a, DB: HirDatabase> SemanticsScope<'a, DB> {
369} 369}
370 370
371// FIXME: Change `HasSource` trait to work with `Semantics` and remove this? 371// FIXME: Change `HasSource` trait to work with `Semantics` and remove this?
372pub fn original_range(db: &impl HirDatabase, node: InFile<&SyntaxNode>) -> FileRange { 372pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange {
373 if let Some(range) = original_range_opt(db, node) { 373 if let Some(range) = original_range_opt(db, node) {
374 let original_file = range.file_id.original_file(db); 374 let original_file = range.file_id.original_file(db.upcast());
375 if range.file_id == original_file.into() { 375 if range.file_id == original_file.into() {
376 return FileRange { file_id: original_file, range: range.value }; 376 return FileRange { file_id: original_file, range: range.value };
377 } 377 }
378 378
379 log::error!("Fail to mapping up more for {:?}", range); 379 log::error!("Fail to mapping up more for {:?}", range);
380 return FileRange { file_id: range.file_id.original_file(db), range: range.value }; 380 return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value };
381 } 381 }
382 382
383 // Fall back to whole macro call 383 // Fall back to whole macro call
384 if let Some(expansion) = node.file_id.expansion_info(db) { 384 if let Some(expansion) = node.file_id.expansion_info(db.upcast()) {
385 if let Some(call_node) = expansion.call_node() { 385 if let Some(call_node) = expansion.call_node() {
386 return FileRange { 386 return FileRange {
387 file_id: call_node.file_id.original_file(db), 387 file_id: call_node.file_id.original_file(db.upcast()),
388 range: call_node.value.text_range(), 388 range: call_node.value.text_range(),
389 }; 389 };
390 } 390 }
391 } 391 }
392 392
393 FileRange { file_id: node.file_id.original_file(db), range: node.value.text_range() } 393 FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() }
394} 394}
395 395
396fn original_range_opt( 396fn original_range_opt(
397 db: &impl HirDatabase, 397 db: &dyn HirDatabase,
398 node: InFile<&SyntaxNode>, 398 node: InFile<&SyntaxNode>,
399) -> Option<InFile<TextRange>> { 399) -> Option<InFile<TextRange>> {
400 let expansion = node.file_id.expansion_info(db)?; 400 let expansion = node.file_id.expansion_info(db.upcast())?;
401 401
402 // the input node has only one token ? 402 // the input node has only one token ?
403 let single = skip_trivia_token(node.value.first_token()?, Direction::Next)? 403 let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
@@ -419,7 +419,7 @@ fn original_range_opt(
419} 419}
420 420
421fn ascend_call_token( 421fn ascend_call_token(
422 db: &impl HirDatabase, 422 db: &dyn HirDatabase,
423 expansion: &ExpansionInfo, 423 expansion: &ExpansionInfo,
424 token: InFile<SyntaxToken>, 424 token: InFile<SyntaxToken>,
425) -> Option<InFile<SyntaxToken>> { 425) -> Option<InFile<SyntaxToken>> {
@@ -427,7 +427,7 @@ fn ascend_call_token(
427 if origin != Origin::Call { 427 if origin != Origin::Call {
428 return None; 428 return None;
429 } 429 }
430 if let Some(info) = mapped.file_id.expansion_info(db) { 430 if let Some(info) = mapped.file_id.expansion_info(db.upcast()) {
431 return ascend_call_token(db, &info, mapped); 431 return ascend_call_token(db, &info, mapped);
432 } 432 }
433 Some(mapped) 433 Some(mapped)
diff --git a/crates/ra_hir/src/semantics/source_to_def.rs b/crates/ra_hir/src/semantics/source_to_def.rs
index 67b243222..8843f2835 100644
--- a/crates/ra_hir/src/semantics/source_to_def.rs
+++ b/crates/ra_hir/src/semantics/source_to_def.rs
@@ -21,12 +21,12 @@ use crate::{db::HirDatabase, InFile, MacroDefId};
21 21
22pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>; 22pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>;
23 23
24pub(super) struct SourceToDefCtx<'a, DB> { 24pub(super) struct SourceToDefCtx<'a, 'b> {
25 pub(super) db: DB, 25 pub(super) db: &'b dyn HirDatabase,
26 pub(super) cache: &'a mut SourceToDefCache, 26 pub(super) cache: &'a mut SourceToDefCache,
27} 27}
28 28
29impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> { 29impl SourceToDefCtx<'_, '_> {
30 pub(super) fn file_to_def(&mut self, file: FileId) -> Option<ModuleId> { 30 pub(super) fn file_to_def(&mut self, file: FileId) -> Option<ModuleId> {
31 let _p = profile("SourceBinder::to_module_def"); 31 let _p = profile("SourceBinder::to_module_def");
32 let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| { 32 let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| {
@@ -43,7 +43,7 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
43 .as_ref() 43 .as_ref()
44 .map(|it| it.syntax()) 44 .map(|it| it.syntax())
45 .cloned() 45 .cloned()
46 .ancestors_with_macros(self.db) 46 .ancestors_with_macros(self.db.upcast())
47 .skip(1) 47 .skip(1)
48 .find_map(|it| { 48 .find_map(|it| {
49 let m = ast::Module::cast(it.value.clone())?; 49 let m = ast::Module::cast(it.value.clone())?;
@@ -53,7 +53,7 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
53 let parent_module = match parent_declaration { 53 let parent_module = match parent_declaration {
54 Some(parent_declaration) => self.module_to_def(parent_declaration), 54 Some(parent_declaration) => self.module_to_def(parent_declaration),
55 None => { 55 None => {
56 let file_id = src.file_id.original_file(self.db); 56 let file_id = src.file_id.original_file(self.db.upcast());
57 self.file_to_def(file_id) 57 self.file_to_def(file_id)
58 } 58 }
59 }?; 59 }?;
@@ -147,7 +147,7 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
147 // FIXME: use DynMap as well? 147 // FIXME: use DynMap as well?
148 pub(super) fn macro_call_to_def(&mut self, src: InFile<ast::MacroCall>) -> Option<MacroDefId> { 148 pub(super) fn macro_call_to_def(&mut self, src: InFile<ast::MacroCall>) -> Option<MacroDefId> {
149 let kind = MacroDefKind::Declarative; 149 let kind = MacroDefKind::Declarative;
150 let file_id = src.file_id.original_file(self.db); 150 let file_id = src.file_id.original_file(self.db.upcast());
151 let krate = self.file_to_def(file_id)?.krate; 151 let krate = self.file_to_def(file_id)?.krate;
152 let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value); 152 let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
153 let ast_id = Some(AstId::new(src.file_id, file_ast_id)); 153 let ast_id = Some(AstId::new(src.file_id, file_ast_id));
@@ -155,7 +155,7 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
155 } 155 }
156 156
157 pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> { 157 pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
158 for container in src.cloned().ancestors_with_macros(self.db).skip(1) { 158 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
159 let res: ChildContainer = match_ast! { 159 let res: ChildContainer = match_ast! {
160 match (container.value) { 160 match (container.value) {
161 ast::Module(it) => { 161 ast::Module(it) => {
@@ -200,12 +200,12 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
200 return Some(res); 200 return Some(res);
201 } 201 }
202 202
203 let def = self.file_to_def(src.file_id.original_file(self.db))?; 203 let def = self.file_to_def(src.file_id.original_file(self.db.upcast()))?;
204 Some(def.into()) 204 Some(def.into())
205 } 205 }
206 206
207 fn find_type_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> { 207 fn find_type_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
208 for container in src.cloned().ancestors_with_macros(self.db).skip(1) { 208 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
209 let res: GenericDefId = match_ast! { 209 let res: GenericDefId = match_ast! {
210 match (container.value) { 210 match (container.value) {
211 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() }, 211 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() },
@@ -223,7 +223,7 @@ impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
223 } 223 }
224 224
225 fn find_pat_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> { 225 fn find_pat_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
226 for container in src.cloned().ancestors_with_macros(self.db).skip(1) { 226 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
227 let res: DefWithBodyId = match_ast! { 227 let res: DefWithBodyId = match_ast! {
228 match (container.value) { 228 match (container.value) {
229 ast::ConstDef(it) => { self.const_to_def(container.with_value(it))?.into() }, 229 ast::ConstDef(it) => { self.const_to_def(container.with_value(it))?.into() },
@@ -262,7 +262,8 @@ impl_froms! {
262} 262}
263 263
264impl ChildContainer { 264impl ChildContainer {
265 fn child_by_source(self, db: &impl HirDatabase) -> DynMap { 265 fn child_by_source(self, db: &dyn HirDatabase) -> DynMap {
266 let db = db.upcast();
266 match self { 267 match self {
267 ChildContainer::DefWithBodyId(it) => it.child_by_source(db), 268 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
268 ChildContainer::ModuleId(it) => it.child_by_source(db), 269 ChildContainer::ModuleId(it) => it.child_by_source(db),
diff --git a/crates/ra_hir/src/source_analyzer.rs b/crates/ra_hir/src/source_analyzer.rs
index 331ecdd9c..e8afef328 100644
--- a/crates/ra_hir/src/source_analyzer.rs
+++ b/crates/ra_hir/src/source_analyzer.rs
@@ -42,7 +42,7 @@ pub(crate) struct SourceAnalyzer {
42 42
43impl SourceAnalyzer { 43impl SourceAnalyzer {
44 pub(crate) fn new_for_body( 44 pub(crate) fn new_for_body(
45 db: &impl HirDatabase, 45 db: &dyn HirDatabase,
46 def: DefWithBodyId, 46 def: DefWithBodyId,
47 node: InFile<&SyntaxNode>, 47 node: InFile<&SyntaxNode>,
48 offset: Option<TextUnit>, 48 offset: Option<TextUnit>,
@@ -53,7 +53,7 @@ impl SourceAnalyzer {
53 None => scope_for(&scopes, &source_map, node), 53 None => scope_for(&scopes, &source_map, node),
54 Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)), 54 Some(offset) => scope_for_offset(&scopes, &source_map, node.with_value(offset)),
55 }; 55 };
56 let resolver = resolver_for_scope(db, def, scope); 56 let resolver = resolver_for_scope(db.upcast(), def, scope);
57 SourceAnalyzer { 57 SourceAnalyzer {
58 resolver, 58 resolver,
59 body: Some(body), 59 body: Some(body),
@@ -90,7 +90,7 @@ impl SourceAnalyzer {
90 90
91 fn expand_expr( 91 fn expand_expr(
92 &self, 92 &self,
93 db: &impl HirDatabase, 93 db: &dyn HirDatabase,
94 expr: InFile<ast::MacroCall>, 94 expr: InFile<ast::MacroCall>,
95 ) -> Option<InFile<ast::Expr>> { 95 ) -> Option<InFile<ast::Expr>> {
96 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?; 96 let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?;
@@ -103,11 +103,11 @@ impl SourceAnalyzer {
103 Some(res) 103 Some(res)
104 } 104 }
105 105
106 fn trait_env(&self, db: &impl HirDatabase) -> Arc<TraitEnvironment> { 106 fn trait_env(&self, db: &dyn HirDatabase) -> Arc<TraitEnvironment> {
107 TraitEnvironment::lower(db, &self.resolver) 107 TraitEnvironment::lower(db, &self.resolver)
108 } 108 }
109 109
110 pub(crate) fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> { 110 pub(crate) fn type_of(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> {
111 let expr_id = match expr { 111 let expr_id = match expr {
112 ast::Expr::MacroCall(call) => { 112 ast::Expr::MacroCall(call) => {
113 let expr = self.expand_expr(db, InFile::new(self.file_id, call.clone()))?; 113 let expr = self.expand_expr(db, InFile::new(self.file_id, call.clone()))?;
@@ -121,7 +121,7 @@ impl SourceAnalyzer {
121 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) 121 Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
122 } 122 }
123 123
124 pub(crate) fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> { 124 pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> {
125 let pat_id = self.pat_id(pat)?; 125 let pat_id = self.pat_id(pat)?;
126 let ty = self.infer.as_ref()?[pat_id].clone(); 126 let ty = self.infer.as_ref()?[pat_id].clone();
127 let environment = self.trait_env(db); 127 let environment = self.trait_env(db);
@@ -140,7 +140,7 @@ impl SourceAnalyzer {
140 140
141 pub(crate) fn resolve_record_field( 141 pub(crate) fn resolve_record_field(
142 &self, 142 &self,
143 db: &impl HirDatabase, 143 db: &dyn HirDatabase,
144 field: &ast::RecordField, 144 field: &ast::RecordField,
145 ) -> Option<(crate::StructField, Option<Local>)> { 145 ) -> Option<(crate::StructField, Option<Local>)> {
146 let (expr_id, local) = match field.expr() { 146 let (expr_id, local) = match field.expr() {
@@ -150,7 +150,7 @@ impl SourceAnalyzer {
150 let expr_id = self.body_source_map.as_ref()?.field_init_shorthand_expr(src)?; 150 let expr_id = self.body_source_map.as_ref()?.field_init_shorthand_expr(src)?;
151 let local_name = field.name_ref()?.as_name(); 151 let local_name = field.name_ref()?.as_name();
152 let path = ModPath::from_segments(PathKind::Plain, once(local_name)); 152 let path = ModPath::from_segments(PathKind::Plain, once(local_name));
153 let local = match self.resolver.resolve_path_in_value_ns_fully(db, &path) { 153 let local = match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
154 Some(ValueNs::LocalBinding(pat_id)) => { 154 Some(ValueNs::LocalBinding(pat_id)) => {
155 Some(Local { pat_id, parent: self.resolver.body_owner()? }) 155 Some(Local { pat_id, parent: self.resolver.body_owner()? })
156 } 156 }
@@ -181,17 +181,17 @@ impl SourceAnalyzer {
181 181
182 pub(crate) fn resolve_macro_call( 182 pub(crate) fn resolve_macro_call(
183 &self, 183 &self,
184 db: &impl HirDatabase, 184 db: &dyn HirDatabase,
185 macro_call: InFile<&ast::MacroCall>, 185 macro_call: InFile<&ast::MacroCall>,
186 ) -> Option<MacroDef> { 186 ) -> Option<MacroDef> {
187 let hygiene = Hygiene::new(db, macro_call.file_id); 187 let hygiene = Hygiene::new(db.upcast(), macro_call.file_id);
188 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; 188 let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?;
189 self.resolver.resolve_path_as_macro(db, path.mod_path()).map(|it| it.into()) 189 self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into())
190 } 190 }
191 191
192 pub(crate) fn resolve_bind_pat_to_const( 192 pub(crate) fn resolve_bind_pat_to_const(
193 &self, 193 &self,
194 db: &impl HirDatabase, 194 db: &dyn HirDatabase,
195 pat: &ast::BindPat, 195 pat: &ast::BindPat,
196 ) -> Option<ModuleDef> { 196 ) -> Option<ModuleDef> {
197 let pat_id = self.pat_id(&pat.clone().into())?; 197 let pat_id = self.pat_id(&pat.clone().into())?;
@@ -209,7 +209,7 @@ impl SourceAnalyzer {
209 209
210 pub(crate) fn resolve_path( 210 pub(crate) fn resolve_path(
211 &self, 211 &self,
212 db: &impl HirDatabase, 212 db: &dyn HirDatabase,
213 path: &ast::Path, 213 path: &ast::Path,
214 ) -> Option<PathResolution> { 214 ) -> Option<PathResolution> {
215 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { 215 if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) {
@@ -231,11 +231,12 @@ impl SourceAnalyzer {
231 231
232 pub(crate) fn expand( 232 pub(crate) fn expand(
233 &self, 233 &self,
234 db: &impl HirDatabase, 234 db: &dyn HirDatabase,
235 macro_call: InFile<&ast::MacroCall>, 235 macro_call: InFile<&ast::MacroCall>,
236 ) -> Option<HirFileId> { 236 ) -> Option<HirFileId> {
237 let macro_call_id = 237 let macro_call_id = macro_call.as_call_id(db.upcast(), |path| {
238 macro_call.as_call_id(db, |path| self.resolver.resolve_path_as_macro(db, &path))?; 238 self.resolver.resolve_path_as_macro(db.upcast(), &path)
239 })?;
239 Some(macro_call_id.as_file()) 240 Some(macro_call_id.as_file())
240 } 241 }
241} 242}
@@ -283,42 +284,46 @@ fn scope_for_offset(
283} 284}
284 285
285pub(crate) fn resolve_hir_path( 286pub(crate) fn resolve_hir_path(
286 db: &impl HirDatabase, 287 db: &dyn HirDatabase,
287 resolver: &Resolver, 288 resolver: &Resolver,
288 path: &crate::Path, 289 path: &crate::Path,
289) -> Option<PathResolution> { 290) -> Option<PathResolution> {
290 let types = resolver.resolve_path_in_type_ns_fully(db, path.mod_path()).map(|ty| match ty { 291 let types =
291 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), 292 resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty {
292 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }), 293 TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
293 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()), 294 TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }),
294 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), 295 TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
295 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()), 296 PathResolution::Def(Adt::from(it).into())
296 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
297 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
298 });
299 let body_owner = resolver.body_owner();
300 let values = resolver.resolve_path_in_value_ns_fully(db, path.mod_path()).and_then(|val| {
301 let res = match val {
302 ValueNs::LocalBinding(pat_id) => {
303 let var = Local { parent: body_owner?.into(), pat_id };
304 PathResolution::Local(var)
305 } 297 }
306 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()), 298 TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
307 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()), 299 TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
308 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()), 300 TypeNs::BuiltinType(it) => PathResolution::Def(it.into()),
309 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()), 301 TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
310 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), 302 });
311 }; 303 let body_owner = resolver.body_owner();
312 Some(res) 304 let values =
313 }); 305 resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| {
306 let res = match val {
307 ValueNs::LocalBinding(pat_id) => {
308 let var = Local { parent: body_owner?.into(), pat_id };
309 PathResolution::Local(var)
310 }
311 ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
312 ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
313 ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
314 ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
315 ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
316 };
317 Some(res)
318 });
314 319
315 let items = resolver 320 let items = resolver
316 .resolve_module_path_in_items(db, path.mod_path()) 321 .resolve_module_path_in_items(db.upcast(), path.mod_path())
317 .take_types() 322 .take_types()
318 .map(|it| PathResolution::Def(it.into())); 323 .map(|it| PathResolution::Def(it.into()));
319 types.or(values).or(items).or_else(|| { 324 types.or(values).or(items).or_else(|| {
320 resolver 325 resolver
321 .resolve_path_as_macro(db, path.mod_path()) 326 .resolve_path_as_macro(db.upcast(), path.mod_path())
322 .map(|def| PathResolution::Macro(def.into())) 327 .map(|def| PathResolution::Macro(def.into()))
323 }) 328 })
324} 329}
diff --git a/crates/ra_hir_def/src/adt.rs b/crates/ra_hir_def/src/adt.rs
index 2bdfc2b8d..d55c49938 100644
--- a/crates/ra_hir_def/src/adt.rs
+++ b/crates/ra_hir_def/src/adt.rs
@@ -52,14 +52,14 @@ pub struct StructFieldData {
52} 52}
53 53
54impl StructData { 54impl StructData {
55 pub(crate) fn struct_data_query(db: &impl DefDatabase, id: StructId) -> Arc<StructData> { 55 pub(crate) fn struct_data_query(db: &dyn DefDatabase, id: StructId) -> Arc<StructData> {
56 let src = id.lookup(db).source(db); 56 let src = id.lookup(db).source(db);
57 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name()); 57 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
58 let variant_data = VariantData::new(db, src.map(|s| s.kind())); 58 let variant_data = VariantData::new(db, src.map(|s| s.kind()));
59 let variant_data = Arc::new(variant_data); 59 let variant_data = Arc::new(variant_data);
60 Arc::new(StructData { name, variant_data }) 60 Arc::new(StructData { name, variant_data })
61 } 61 }
62 pub(crate) fn union_data_query(db: &impl DefDatabase, id: UnionId) -> Arc<StructData> { 62 pub(crate) fn union_data_query(db: &dyn DefDatabase, id: UnionId) -> Arc<StructData> {
63 let src = id.lookup(db).source(db); 63 let src = id.lookup(db).source(db);
64 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name()); 64 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
65 let variant_data = VariantData::new( 65 let variant_data = VariantData::new(
@@ -76,7 +76,7 @@ impl StructData {
76} 76}
77 77
78impl EnumData { 78impl EnumData {
79 pub(crate) fn enum_data_query(db: &impl DefDatabase, e: EnumId) -> Arc<EnumData> { 79 pub(crate) fn enum_data_query(db: &dyn DefDatabase, e: EnumId) -> Arc<EnumData> {
80 let _p = profile("enum_data_query"); 80 let _p = profile("enum_data_query");
81 let src = e.lookup(db).source(db); 81 let src = e.lookup(db).source(db);
82 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name()); 82 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
@@ -94,7 +94,7 @@ impl EnumData {
94impl HasChildSource for EnumId { 94impl HasChildSource for EnumId {
95 type ChildId = LocalEnumVariantId; 95 type ChildId = LocalEnumVariantId;
96 type Value = ast::EnumVariant; 96 type Value = ast::EnumVariant;
97 fn child_source(&self, db: &impl DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>> { 97 fn child_source(&self, db: &dyn DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>> {
98 let src = self.lookup(db).source(db); 98 let src = self.lookup(db).source(db);
99 let mut trace = Trace::new_for_map(); 99 let mut trace = Trace::new_for_map();
100 lower_enum(db, &mut trace, &src); 100 lower_enum(db, &mut trace, &src);
@@ -103,7 +103,7 @@ impl HasChildSource for EnumId {
103} 103}
104 104
105fn lower_enum( 105fn lower_enum(
106 db: &impl DefDatabase, 106 db: &dyn DefDatabase,
107 trace: &mut Trace<LocalEnumVariantId, EnumVariantData, ast::EnumVariant>, 107 trace: &mut Trace<LocalEnumVariantId, EnumVariantData, ast::EnumVariant>,
108 ast: &InFile<ast::EnumDef>, 108 ast: &InFile<ast::EnumDef>,
109) { 109) {
@@ -119,7 +119,7 @@ fn lower_enum(
119} 119}
120 120
121impl VariantData { 121impl VariantData {
122 fn new(db: &impl DefDatabase, flavor: InFile<ast::StructKind>) -> Self { 122 fn new(db: &dyn DefDatabase, flavor: InFile<ast::StructKind>) -> Self {
123 let mut trace = Trace::new_for_arena(); 123 let mut trace = Trace::new_for_arena();
124 match lower_struct(db, &mut trace, &flavor) { 124 match lower_struct(db, &mut trace, &flavor) {
125 StructKind::Tuple => VariantData::Tuple(trace.into_arena()), 125 StructKind::Tuple => VariantData::Tuple(trace.into_arena()),
@@ -153,7 +153,7 @@ impl HasChildSource for VariantId {
153 type ChildId = LocalStructFieldId; 153 type ChildId = LocalStructFieldId;
154 type Value = Either<ast::TupleFieldDef, ast::RecordFieldDef>; 154 type Value = Either<ast::TupleFieldDef, ast::RecordFieldDef>;
155 155
156 fn child_source(&self, db: &impl DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>> { 156 fn child_source(&self, db: &dyn DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>> {
157 let src = match self { 157 let src = match self {
158 VariantId::EnumVariantId(it) => { 158 VariantId::EnumVariantId(it) => {
159 // I don't really like the fact that we call into parent source 159 // I don't really like the fact that we call into parent source
@@ -182,7 +182,7 @@ pub enum StructKind {
182} 182}
183 183
184fn lower_struct( 184fn lower_struct(
185 db: &impl DefDatabase, 185 db: &dyn DefDatabase,
186 trace: &mut Trace< 186 trace: &mut Trace<
187 LocalStructFieldId, 187 LocalStructFieldId,
188 StructFieldData, 188 StructFieldData,
diff --git a/crates/ra_hir_def/src/attr.rs b/crates/ra_hir_def/src/attr.rs
index 9efa4970c..71a18f5e1 100644
--- a/crates/ra_hir_def/src/attr.rs
+++ b/crates/ra_hir_def/src/attr.rs
@@ -32,7 +32,7 @@ impl ops::Deref for Attrs {
32} 32}
33 33
34impl Attrs { 34impl Attrs {
35 pub(crate) fn attrs_query(db: &impl DefDatabase, def: AttrDefId) -> Attrs { 35 pub(crate) fn attrs_query(db: &dyn DefDatabase, def: AttrDefId) -> Attrs {
36 match def { 36 match def {
37 AttrDefId::ModuleId(module) => { 37 AttrDefId::ModuleId(module) => {
38 let def_map = db.crate_def_map(module.krate); 38 let def_map = db.crate_def_map(module.krate);
@@ -71,8 +71,8 @@ impl Attrs {
71 } 71 }
72 } 72 }
73 73
74 fn from_attrs_owner(db: &impl DefDatabase, owner: InFile<&dyn AttrsOwner>) -> Attrs { 74 fn from_attrs_owner(db: &dyn DefDatabase, owner: InFile<&dyn AttrsOwner>) -> Attrs {
75 let hygiene = Hygiene::new(db, owner.file_id); 75 let hygiene = Hygiene::new(db.upcast(), owner.file_id);
76 Attrs::new(owner.value, &hygiene) 76 Attrs::new(owner.value, &hygiene)
77 } 77 }
78 78
@@ -155,20 +155,18 @@ impl<'a> AttrQuery<'a> {
155 } 155 }
156} 156}
157 157
158fn attrs_from_ast<D, N>(src: AstId<N>, db: &D) -> Attrs 158fn attrs_from_ast<N>(src: AstId<N>, db: &dyn DefDatabase) -> Attrs
159where 159where
160 N: ast::AttrsOwner, 160 N: ast::AttrsOwner,
161 D: DefDatabase,
162{ 161{
163 let src = InFile::new(src.file_id, src.to_node(db)); 162 let src = InFile::new(src.file_id, src.to_node(db.upcast()));
164 Attrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn AttrsOwner)) 163 Attrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn AttrsOwner))
165} 164}
166 165
167fn attrs_from_loc<T, D>(node: T, db: &D) -> Attrs 166fn attrs_from_loc<T>(node: T, db: &dyn DefDatabase) -> Attrs
168where 167where
169 T: HasSource, 168 T: HasSource,
170 T::Value: ast::AttrsOwner, 169 T::Value: ast::AttrsOwner,
171 D: DefDatabase,
172{ 170{
173 let src = node.source(db); 171 let src = node.source(db);
174 Attrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn AttrsOwner)) 172 Attrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn AttrsOwner))
diff --git a/crates/ra_hir_def/src/body.rs b/crates/ra_hir_def/src/body.rs
index 2bc405a59..34561ee73 100644
--- a/crates/ra_hir_def/src/body.rs
+++ b/crates/ra_hir_def/src/body.rs
@@ -34,19 +34,19 @@ pub(crate) struct Expander {
34 34
35impl Expander { 35impl Expander {
36 pub(crate) fn new( 36 pub(crate) fn new(
37 db: &impl DefDatabase, 37 db: &dyn DefDatabase,
38 current_file_id: HirFileId, 38 current_file_id: HirFileId,
39 module: ModuleId, 39 module: ModuleId,
40 ) -> Expander { 40 ) -> Expander {
41 let crate_def_map = db.crate_def_map(module.krate); 41 let crate_def_map = db.crate_def_map(module.krate);
42 let hygiene = Hygiene::new(db, current_file_id); 42 let hygiene = Hygiene::new(db.upcast(), current_file_id);
43 let ast_id_map = db.ast_id_map(current_file_id); 43 let ast_id_map = db.ast_id_map(current_file_id);
44 Expander { crate_def_map, current_file_id, hygiene, ast_id_map, module } 44 Expander { crate_def_map, current_file_id, hygiene, ast_id_map, module }
45 } 45 }
46 46
47 pub(crate) fn enter_expand<T: ast::AstNode, DB: DefDatabase>( 47 pub(crate) fn enter_expand<T: ast::AstNode>(
48 &mut self, 48 &mut self,
49 db: &DB, 49 db: &dyn DefDatabase,
50 local_scope: Option<&ItemScope>, 50 local_scope: Option<&ItemScope>,
51 macro_call: ast::MacroCall, 51 macro_call: ast::MacroCall,
52 ) -> Option<(Mark, T)> { 52 ) -> Option<(Mark, T)> {
@@ -70,7 +70,7 @@ impl Expander {
70 ast_id_map: mem::take(&mut self.ast_id_map), 70 ast_id_map: mem::take(&mut self.ast_id_map),
71 bomb: DropBomb::new("expansion mark dropped"), 71 bomb: DropBomb::new("expansion mark dropped"),
72 }; 72 };
73 self.hygiene = Hygiene::new(db, file_id); 73 self.hygiene = Hygiene::new(db.upcast(), file_id);
74 self.current_file_id = file_id; 74 self.current_file_id = file_id;
75 self.ast_id_map = db.ast_id_map(file_id); 75 self.ast_id_map = db.ast_id_map(file_id);
76 76
@@ -84,8 +84,8 @@ impl Expander {
84 None 84 None
85 } 85 }
86 86
87 pub(crate) fn exit(&mut self, db: &impl DefDatabase, mut mark: Mark) { 87 pub(crate) fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {
88 self.hygiene = Hygiene::new(db, mark.file_id); 88 self.hygiene = Hygiene::new(db.upcast(), mark.file_id);
89 self.current_file_id = mark.file_id; 89 self.current_file_id = mark.file_id;
90 self.ast_id_map = mem::take(&mut mark.ast_id_map); 90 self.ast_id_map = mem::take(&mut mark.ast_id_map);
91 mark.bomb.defuse(); 91 mark.bomb.defuse();
@@ -99,7 +99,7 @@ impl Expander {
99 Path::from_src(path, &self.hygiene) 99 Path::from_src(path, &self.hygiene)
100 } 100 }
101 101
102 fn resolve_path_as_macro(&self, db: &impl DefDatabase, path: &ModPath) -> Option<MacroDefId> { 102 fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
103 self.crate_def_map 103 self.crate_def_map
104 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other) 104 .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
105 .0 105 .0
@@ -167,7 +167,7 @@ pub struct SyntheticSyntax;
167 167
168impl Body { 168impl Body {
169 pub(crate) fn body_with_source_map_query( 169 pub(crate) fn body_with_source_map_query(
170 db: &impl DefDatabase, 170 db: &dyn DefDatabase,
171 def: DefWithBodyId, 171 def: DefWithBodyId,
172 ) -> (Arc<Body>, Arc<BodySourceMap>) { 172 ) -> (Arc<Body>, Arc<BodySourceMap>) {
173 let _p = profile("body_with_source_map_query"); 173 let _p = profile("body_with_source_map_query");
@@ -196,12 +196,12 @@ impl Body {
196 (Arc::new(body), Arc::new(source_map)) 196 (Arc::new(body), Arc::new(source_map))
197 } 197 }
198 198
199 pub(crate) fn body_query(db: &impl DefDatabase, def: DefWithBodyId) -> Arc<Body> { 199 pub(crate) fn body_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<Body> {
200 db.body_with_source_map(def).0 200 db.body_with_source_map(def).0
201 } 201 }
202 202
203 fn new( 203 fn new(
204 db: &impl DefDatabase, 204 db: &dyn DefDatabase,
205 def: DefWithBodyId, 205 def: DefWithBodyId,
206 expander: Expander, 206 expander: Expander,
207 params: Option<ast::ParamList>, 207 params: Option<ast::ParamList>,
diff --git a/crates/ra_hir_def/src/body/lower.rs b/crates/ra_hir_def/src/body/lower.rs
index 54b5591d3..6238de606 100644
--- a/crates/ra_hir_def/src/body/lower.rs
+++ b/crates/ra_hir_def/src/body/lower.rs
@@ -36,7 +36,7 @@ use crate::{
36}; 36};
37 37
38pub(super) fn lower( 38pub(super) fn lower(
39 db: &impl DefDatabase, 39 db: &dyn DefDatabase,
40 def: DefWithBodyId, 40 def: DefWithBodyId,
41 expander: Expander, 41 expander: Expander,
42 params: Option<ast::ParamList>, 42 params: Option<ast::ParamList>,
@@ -58,8 +58,8 @@ pub(super) fn lower(
58 .collect(params, body) 58 .collect(params, body)
59} 59}
60 60
61struct ExprCollector<DB> { 61struct ExprCollector<'a> {
62 db: DB, 62 db: &'a dyn DefDatabase,
63 def: DefWithBodyId, 63 def: DefWithBodyId,
64 expander: Expander, 64 expander: Expander,
65 65
@@ -67,10 +67,7 @@ struct ExprCollector<DB> {
67 source_map: BodySourceMap, 67 source_map: BodySourceMap,
68} 68}
69 69
70impl<'a, DB> ExprCollector<&'a DB> 70impl ExprCollector<'_> {
71where
72 DB: DefDatabase,
73{
74 fn collect( 71 fn collect(
75 mut self, 72 mut self,
76 param_list: Option<ast::ParamList>, 73 param_list: Option<ast::ParamList>,
diff --git a/crates/ra_hir_def/src/body/scope.rs b/crates/ra_hir_def/src/body/scope.rs
index a58a7b21f..7c3db8869 100644
--- a/crates/ra_hir_def/src/body/scope.rs
+++ b/crates/ra_hir_def/src/body/scope.rs
@@ -45,7 +45,7 @@ pub struct ScopeData {
45} 45}
46 46
47impl ExprScopes { 47impl ExprScopes {
48 pub(crate) fn expr_scopes_query(db: &impl DefDatabase, def: DefWithBodyId) -> Arc<ExprScopes> { 48 pub(crate) fn expr_scopes_query(db: &dyn DefDatabase, def: DefWithBodyId) -> Arc<ExprScopes> {
49 let body = db.body(def); 49 let body = db.body(def);
50 Arc::new(ExprScopes::new(&*body)) 50 Arc::new(ExprScopes::new(&*body))
51 } 51 }
diff --git a/crates/ra_hir_def/src/child_by_source.rs b/crates/ra_hir_def/src/child_by_source.rs
index 8b6c773ee..7009f21d1 100644
--- a/crates/ra_hir_def/src/child_by_source.rs
+++ b/crates/ra_hir_def/src/child_by_source.rs
@@ -17,11 +17,11 @@ use crate::{
17}; 17};
18 18
19pub trait ChildBySource { 19pub trait ChildBySource {
20 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap; 20 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap;
21} 21}
22 22
23impl ChildBySource for TraitId { 23impl ChildBySource for TraitId {
24 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 24 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
25 let mut res = DynMap::default(); 25 let mut res = DynMap::default();
26 26
27 let data = db.trait_data(*self); 27 let data = db.trait_data(*self);
@@ -47,7 +47,7 @@ impl ChildBySource for TraitId {
47} 47}
48 48
49impl ChildBySource for ImplId { 49impl ChildBySource for ImplId {
50 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 50 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
51 let mut res = DynMap::default(); 51 let mut res = DynMap::default();
52 52
53 let data = db.impl_data(*self); 53 let data = db.impl_data(*self);
@@ -73,7 +73,7 @@ impl ChildBySource for ImplId {
73} 73}
74 74
75impl ChildBySource for ModuleId { 75impl ChildBySource for ModuleId {
76 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 76 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
77 let crate_def_map = db.crate_def_map(self.krate); 77 let crate_def_map = db.crate_def_map(self.krate);
78 let module_data = &crate_def_map[self.local_id]; 78 let module_data = &crate_def_map[self.local_id];
79 module_data.scope.child_by_source(db) 79 module_data.scope.child_by_source(db)
@@ -81,13 +81,13 @@ impl ChildBySource for ModuleId {
81} 81}
82 82
83impl ChildBySource for ItemScope { 83impl ChildBySource for ItemScope {
84 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 84 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
85 let mut res = DynMap::default(); 85 let mut res = DynMap::default();
86 self.declarations().for_each(|item| add_module_def(db, &mut res, item)); 86 self.declarations().for_each(|item| add_module_def(db, &mut res, item));
87 self.impls().for_each(|imp| add_impl(db, &mut res, imp)); 87 self.impls().for_each(|imp| add_impl(db, &mut res, imp));
88 return res; 88 return res;
89 89
90 fn add_module_def(db: &impl DefDatabase, map: &mut DynMap, item: ModuleDefId) { 90 fn add_module_def(db: &dyn DefDatabase, map: &mut DynMap, item: ModuleDefId) {
91 match item { 91 match item {
92 ModuleDefId::FunctionId(func) => { 92 ModuleDefId::FunctionId(func) => {
93 let src = func.lookup(db).source(db); 93 let src = func.lookup(db).source(db);
@@ -126,7 +126,7 @@ impl ChildBySource for ItemScope {
126 _ => (), 126 _ => (),
127 } 127 }
128 } 128 }
129 fn add_impl(db: &impl DefDatabase, map: &mut DynMap, imp: ImplId) { 129 fn add_impl(db: &dyn DefDatabase, map: &mut DynMap, imp: ImplId) {
130 let src = imp.lookup(db).source(db); 130 let src = imp.lookup(db).source(db);
131 map[keys::IMPL].insert(src, imp) 131 map[keys::IMPL].insert(src, imp)
132 } 132 }
@@ -134,7 +134,7 @@ impl ChildBySource for ItemScope {
134} 134}
135 135
136impl ChildBySource for VariantId { 136impl ChildBySource for VariantId {
137 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 137 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
138 let mut res = DynMap::default(); 138 let mut res = DynMap::default();
139 139
140 let arena_map = self.child_source(db); 140 let arena_map = self.child_source(db);
@@ -155,7 +155,7 @@ impl ChildBySource for VariantId {
155} 155}
156 156
157impl ChildBySource for EnumId { 157impl ChildBySource for EnumId {
158 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 158 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
159 let mut res = DynMap::default(); 159 let mut res = DynMap::default();
160 160
161 let arena_map = self.child_source(db); 161 let arena_map = self.child_source(db);
@@ -170,7 +170,7 @@ impl ChildBySource for EnumId {
170} 170}
171 171
172impl ChildBySource for DefWithBodyId { 172impl ChildBySource for DefWithBodyId {
173 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 173 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
174 let body = db.body(*self); 174 let body = db.body(*self);
175 body.item_scope.child_by_source(db) 175 body.item_scope.child_by_source(db)
176 } 176 }
diff --git a/crates/ra_hir_def/src/data.rs b/crates/ra_hir_def/src/data.rs
index c0b16b7fa..04bd4a305 100644
--- a/crates/ra_hir_def/src/data.rs
+++ b/crates/ra_hir_def/src/data.rs
@@ -105,7 +105,7 @@ pub struct TypeAliasData {
105 105
106impl TypeAliasData { 106impl TypeAliasData {
107 pub(crate) fn type_alias_data_query( 107 pub(crate) fn type_alias_data_query(
108 db: &impl DefDatabase, 108 db: &dyn DefDatabase,
109 typ: TypeAliasId, 109 typ: TypeAliasId,
110 ) -> Arc<TypeAliasData> { 110 ) -> Arc<TypeAliasData> {
111 let loc = typ.lookup(db); 111 let loc = typ.lookup(db);
@@ -127,7 +127,7 @@ pub struct TraitData {
127} 127}
128 128
129impl TraitData { 129impl TraitData {
130 pub(crate) fn trait_data_query(db: &impl DefDatabase, tr: TraitId) -> Arc<TraitData> { 130 pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
131 let src = tr.lookup(db).source(db); 131 let src = tr.lookup(db).source(db);
132 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name()); 132 let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
133 let auto = src.value.is_auto(); 133 let auto = src.value.is_auto();
@@ -200,7 +200,7 @@ pub struct ImplData {
200} 200}
201 201
202impl ImplData { 202impl ImplData {
203 pub(crate) fn impl_data_query(db: &impl DefDatabase, id: ImplId) -> Arc<ImplData> { 203 pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
204 let _p = profile("impl_data_query"); 204 let _p = profile("impl_data_query");
205 let impl_loc = id.lookup(db); 205 let impl_loc = id.lookup(db);
206 let src = impl_loc.source(db); 206 let src = impl_loc.source(db);
@@ -235,20 +235,20 @@ pub struct ConstData {
235} 235}
236 236
237impl ConstData { 237impl ConstData {
238 pub(crate) fn const_data_query(db: &impl DefDatabase, konst: ConstId) -> Arc<ConstData> { 238 pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
239 let loc = konst.lookup(db); 239 let loc = konst.lookup(db);
240 let node = loc.source(db); 240 let node = loc.source(db);
241 let vis_default = RawVisibility::default_for_container(loc.container); 241 let vis_default = RawVisibility::default_for_container(loc.container);
242 Arc::new(ConstData::new(db, vis_default, node)) 242 Arc::new(ConstData::new(db, vis_default, node))
243 } 243 }
244 244
245 pub(crate) fn static_data_query(db: &impl DefDatabase, konst: StaticId) -> Arc<ConstData> { 245 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<ConstData> {
246 let node = konst.lookup(db).source(db); 246 let node = konst.lookup(db).source(db);
247 Arc::new(ConstData::new(db, RawVisibility::private(), node)) 247 Arc::new(ConstData::new(db, RawVisibility::private(), node))
248 } 248 }
249 249
250 fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>( 250 fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>(
251 db: &impl DefDatabase, 251 db: &dyn DefDatabase,
252 vis_default: RawVisibility, 252 vis_default: RawVisibility,
253 node: InFile<N>, 253 node: InFile<N>,
254 ) -> ConstData { 254 ) -> ConstData {
@@ -261,7 +261,7 @@ impl ConstData {
261} 261}
262 262
263fn collect_impl_items_in_macros( 263fn collect_impl_items_in_macros(
264 db: &impl DefDatabase, 264 db: &dyn DefDatabase,
265 module_id: ModuleId, 265 module_id: ModuleId,
266 impl_def: &InFile<ast::ItemList>, 266 impl_def: &InFile<ast::ItemList>,
267 id: ImplId, 267 id: ImplId,
@@ -280,7 +280,7 @@ fn collect_impl_items_in_macros(
280} 280}
281 281
282fn collect_impl_items_in_macro( 282fn collect_impl_items_in_macro(
283 db: &impl DefDatabase, 283 db: &dyn DefDatabase,
284 expander: &mut Expander, 284 expander: &mut Expander,
285 m: ast::MacroCall, 285 m: ast::MacroCall,
286 id: ImplId, 286 id: ImplId,
@@ -312,7 +312,7 @@ fn collect_impl_items_in_macro(
312} 312}
313 313
314fn collect_impl_items( 314fn collect_impl_items(
315 db: &impl DefDatabase, 315 db: &dyn DefDatabase,
316 impl_items: impl Iterator<Item = ImplItem>, 316 impl_items: impl Iterator<Item = ImplItem>,
317 file_id: crate::HirFileId, 317 file_id: crate::HirFileId,
318 id: ImplId, 318 id: ImplId,
diff --git a/crates/ra_hir_def/src/db.rs b/crates/ra_hir_def/src/db.rs
index dcd377aae..7f8c1ea21 100644
--- a/crates/ra_hir_def/src/db.rs
+++ b/crates/ra_hir_def/src/db.rs
@@ -2,7 +2,7 @@
2use std::sync::Arc; 2use std::sync::Arc;
3 3
4use hir_expand::{db::AstDatabase, HirFileId}; 4use hir_expand::{db::AstDatabase, HirFileId};
5use ra_db::{salsa, CrateId, SourceDatabase}; 5use ra_db::{salsa, CrateId, SourceDatabase, Upcast};
6use ra_prof::profile; 6use ra_prof::profile;
7use ra_syntax::SmolStr; 7use ra_syntax::SmolStr;
8 8
@@ -43,7 +43,7 @@ pub trait InternDatabase: SourceDatabase {
43} 43}
44 44
45#[salsa::query_group(DefDatabaseStorage)] 45#[salsa::query_group(DefDatabaseStorage)]
46pub trait DefDatabase: InternDatabase + AstDatabase { 46pub trait DefDatabase: InternDatabase + AstDatabase + Upcast<dyn AstDatabase> {
47 #[salsa::invoke(RawItems::raw_items_query)] 47 #[salsa::invoke(RawItems::raw_items_query)]
48 fn raw_items(&self, file_id: HirFileId) -> Arc<RawItems>; 48 fn raw_items(&self, file_id: HirFileId) -> Arc<RawItems>;
49 49
@@ -109,6 +109,12 @@ pub trait DefDatabase: InternDatabase + AstDatabase {
109 fn documentation(&self, def: AttrDefId) -> Option<Documentation>; 109 fn documentation(&self, def: AttrDefId) -> Option<Documentation>;
110} 110}
111 111
112// impl<T: DefDatabase> Upcast<dyn AstDatabase> for T {
113// fn upcast(&self) -> &dyn AstDatabase {
114// &*self
115// }
116// }
117
112fn crate_def_map_wait(db: &impl DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { 118fn crate_def_map_wait(db: &impl DefDatabase, krate: CrateId) -> Arc<CrateDefMap> {
113 let _p = profile("crate_def_map:wait"); 119 let _p = profile("crate_def_map:wait");
114 db.crate_def_map_query(krate) 120 db.crate_def_map_query(krate)
diff --git a/crates/ra_hir_def/src/docs.rs b/crates/ra_hir_def/src/docs.rs
index b29f142e3..0539a77d4 100644
--- a/crates/ra_hir_def/src/docs.rs
+++ b/crates/ra_hir_def/src/docs.rs
@@ -34,7 +34,7 @@ impl Documentation {
34 } 34 }
35 35
36 pub(crate) fn documentation_query( 36 pub(crate) fn documentation_query(
37 db: &impl DefDatabase, 37 db: &dyn DefDatabase,
38 def: AttrDefId, 38 def: AttrDefId,
39 ) -> Option<Documentation> { 39 ) -> Option<Documentation> {
40 match def { 40 match def {
@@ -60,7 +60,7 @@ impl Documentation {
60 docs_from_ast(&src.value[it.local_id]) 60 docs_from_ast(&src.value[it.local_id])
61 } 61 }
62 AttrDefId::TraitId(it) => docs_from_ast(&it.lookup(db).source(db).value), 62 AttrDefId::TraitId(it) => docs_from_ast(&it.lookup(db).source(db).value),
63 AttrDefId::MacroDefId(it) => docs_from_ast(&it.ast_id?.to_node(db)), 63 AttrDefId::MacroDefId(it) => docs_from_ast(&it.ast_id?.to_node(db.upcast())),
64 AttrDefId::ConstId(it) => docs_from_ast(&it.lookup(db).source(db).value), 64 AttrDefId::ConstId(it) => docs_from_ast(&it.lookup(db).source(db).value),
65 AttrDefId::StaticId(it) => docs_from_ast(&it.lookup(db).source(db).value), 65 AttrDefId::StaticId(it) => docs_from_ast(&it.lookup(db).source(db).value),
66 AttrDefId::FunctionId(it) => docs_from_ast(&it.lookup(db).source(db).value), 66 AttrDefId::FunctionId(it) => docs_from_ast(&it.lookup(db).source(db).value),
diff --git a/crates/ra_hir_def/src/find_path.rs b/crates/ra_hir_def/src/find_path.rs
index 07ca74ec3..d58ac6ba5 100644
--- a/crates/ra_hir_def/src/find_path.rs
+++ b/crates/ra_hir_def/src/find_path.rs
@@ -44,12 +44,12 @@ impl ModPath {
44 44
45/// Find a path that can be used to refer to a certain item. This can depend on 45/// Find a path that can be used to refer to a certain item. This can depend on
46/// *from where* you're referring to the item, hence the `from` parameter. 46/// *from where* you're referring to the item, hence the `from` parameter.
47pub fn find_path(db: &impl DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> { 47pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
48 find_path_inner(db, item, from, MAX_PATH_LEN) 48 find_path_inner(db, item, from, MAX_PATH_LEN)
49} 49}
50 50
51fn find_path_inner( 51fn find_path_inner(
52 db: &impl DefDatabase, 52 db: &dyn DefDatabase,
53 item: ItemInNs, 53 item: ItemInNs,
54 from: ModuleId, 54 from: ModuleId,
55 max_len: usize, 55 max_len: usize,
@@ -165,7 +165,7 @@ fn select_best_path(old_path: ModPath, new_path: ModPath) -> ModPath {
165} 165}
166 166
167fn find_importable_locations( 167fn find_importable_locations(
168 db: &impl DefDatabase, 168 db: &dyn DefDatabase,
169 item: ItemInNs, 169 item: ItemInNs,
170 from: ModuleId, 170 from: ModuleId,
171) -> Vec<(ModuleId, Name)> { 171) -> Vec<(ModuleId, Name)> {
@@ -195,7 +195,7 @@ fn find_importable_locations(
195/// Note that the crate doesn't need to be the one in which the item is defined; 195/// Note that the crate doesn't need to be the one in which the item is defined;
196/// it might be re-exported in other crates. 196/// it might be re-exported in other crates.
197fn importable_locations_in_crate( 197fn importable_locations_in_crate(
198 db: &impl DefDatabase, 198 db: &dyn DefDatabase,
199 item: ItemInNs, 199 item: ItemInNs,
200 krate: CrateId, 200 krate: CrateId,
201) -> Vec<(ModuleId, Name, Visibility)> { 201) -> Vec<(ModuleId, Name, Visibility)> {
diff --git a/crates/ra_hir_def/src/generics.rs b/crates/ra_hir_def/src/generics.rs
index 519c60de0..24adc8153 100644
--- a/crates/ra_hir_def/src/generics.rs
+++ b/crates/ra_hir_def/src/generics.rs
@@ -69,7 +69,7 @@ type SourceMap = ArenaMap<LocalTypeParamId, Either<ast::TraitDef, ast::TypeParam
69 69
70impl GenericParams { 70impl GenericParams {
71 pub(crate) fn generic_params_query( 71 pub(crate) fn generic_params_query(
72 db: &impl DefDatabase, 72 db: &dyn DefDatabase,
73 def: GenericDefId, 73 def: GenericDefId,
74 ) -> Arc<GenericParams> { 74 ) -> Arc<GenericParams> {
75 let _p = profile("generic_params_query"); 75 let _p = profile("generic_params_query");
@@ -77,7 +77,7 @@ impl GenericParams {
77 Arc::new(params) 77 Arc::new(params)
78 } 78 }
79 79
80 fn new(db: &impl DefDatabase, def: GenericDefId) -> (GenericParams, InFile<SourceMap>) { 80 fn new(db: &dyn DefDatabase, def: GenericDefId) -> (GenericParams, InFile<SourceMap>) {
81 let mut generics = GenericParams { types: Arena::default(), where_predicates: Vec::new() }; 81 let mut generics = GenericParams { types: Arena::default(), where_predicates: Vec::new() };
82 let mut sm = ArenaMap::default(); 82 let mut sm = ArenaMap::default();
83 // FIXME: add `: Sized` bound for everything except for `Self` in traits 83 // FIXME: add `: Sized` bound for everything except for `Self` in traits
@@ -242,14 +242,14 @@ impl GenericParams {
242impl HasChildSource for GenericDefId { 242impl HasChildSource for GenericDefId {
243 type ChildId = LocalTypeParamId; 243 type ChildId = LocalTypeParamId;
244 type Value = Either<ast::TraitDef, ast::TypeParam>; 244 type Value = Either<ast::TraitDef, ast::TypeParam>;
245 fn child_source(&self, db: &impl DefDatabase) -> InFile<SourceMap> { 245 fn child_source(&self, db: &dyn DefDatabase) -> InFile<SourceMap> {
246 let (_, sm) = GenericParams::new(db, *self); 246 let (_, sm) = GenericParams::new(db, *self);
247 sm 247 sm
248 } 248 }
249} 249}
250 250
251impl ChildBySource for GenericDefId { 251impl ChildBySource for GenericDefId {
252 fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { 252 fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
253 let mut res = DynMap::default(); 253 let mut res = DynMap::default();
254 let arena_map = self.child_source(db); 254 let arena_map = self.child_source(db);
255 let arena_map = arena_map.as_ref(); 255 let arena_map = arena_map.as_ref();
diff --git a/crates/ra_hir_def/src/lang_item.rs b/crates/ra_hir_def/src/lang_item.rs
index 6de49730e..01b367278 100644
--- a/crates/ra_hir_def/src/lang_item.rs
+++ b/crates/ra_hir_def/src/lang_item.rs
@@ -77,7 +77,7 @@ impl LangItems {
77 } 77 }
78 78
79 /// Salsa query. This will look for lang items in a specific crate. 79 /// Salsa query. This will look for lang items in a specific crate.
80 pub(crate) fn crate_lang_items_query(db: &impl DefDatabase, krate: CrateId) -> Arc<LangItems> { 80 pub(crate) fn crate_lang_items_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<LangItems> {
81 let mut lang_items = LangItems::default(); 81 let mut lang_items = LangItems::default();
82 82
83 let crate_def_map = db.crate_def_map(krate); 83 let crate_def_map = db.crate_def_map(krate);
@@ -92,7 +92,7 @@ impl LangItems {
92 } 92 }
93 93
94 pub(crate) fn module_lang_items_query( 94 pub(crate) fn module_lang_items_query(
95 db: &impl DefDatabase, 95 db: &dyn DefDatabase,
96 module: ModuleId, 96 module: ModuleId,
97 ) -> Option<Arc<LangItems>> { 97 ) -> Option<Arc<LangItems>> {
98 let mut lang_items = LangItems::default(); 98 let mut lang_items = LangItems::default();
@@ -107,7 +107,7 @@ impl LangItems {
107 /// Salsa query. Look for a lang item, starting from the specified crate and recursively 107 /// Salsa query. Look for a lang item, starting from the specified crate and recursively
108 /// traversing its dependencies. 108 /// traversing its dependencies.
109 pub(crate) fn lang_item_query( 109 pub(crate) fn lang_item_query(
110 db: &impl DefDatabase, 110 db: &dyn DefDatabase,
111 start_crate: CrateId, 111 start_crate: CrateId,
112 item: SmolStr, 112 item: SmolStr,
113 ) -> Option<LangItemTarget> { 113 ) -> Option<LangItemTarget> {
@@ -122,7 +122,7 @@ impl LangItems {
122 .find_map(|dep| db.lang_item(dep.crate_id, item.clone())) 122 .find_map(|dep| db.lang_item(dep.crate_id, item.clone()))
123 } 123 }
124 124
125 fn collect_lang_items(&mut self, db: &impl DefDatabase, module: ModuleId) { 125 fn collect_lang_items(&mut self, db: &dyn DefDatabase, module: ModuleId) {
126 // Look for impl targets 126 // Look for impl targets
127 let def_map = db.crate_def_map(module.krate); 127 let def_map = db.crate_def_map(module.krate);
128 let module_data = &def_map[module.local_id]; 128 let module_data = &def_map[module.local_id];
@@ -152,7 +152,7 @@ impl LangItems {
152 152
153 fn collect_lang_item<T>( 153 fn collect_lang_item<T>(
154 &mut self, 154 &mut self,
155 db: &impl DefDatabase, 155 db: &dyn DefDatabase,
156 item: T, 156 item: T,
157 constructor: fn(T) -> LangItemTarget, 157 constructor: fn(T) -> LangItemTarget,
158 ) where 158 ) where
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
index a3d617e1f..24f9eb9e0 100644
--- a/crates/ra_hir_def/src/lib.rs
+++ b/crates/ra_hir_def/src/lib.rs
@@ -47,8 +47,8 @@ mod marks;
47use std::hash::Hash; 47use std::hash::Hash;
48 48
49use hir_expand::{ 49use hir_expand::{
50 ast_id_map::FileAstId, db::AstDatabase, eager::expand_eager_macro, hygiene::Hygiene, AstId, 50 ast_id_map::FileAstId, eager::expand_eager_macro, hygiene::Hygiene, AstId, HirFileId, InFile,
51 HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, 51 MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
52}; 52};
53use ra_arena::{impl_arena_id, RawId}; 53use ra_arena::{impl_arena_id, RawId};
54use ra_db::{impl_intern_key, salsa, CrateId}; 54use ra_db::{impl_intern_key, salsa, CrateId};
@@ -87,14 +87,14 @@ macro_rules! impl_intern {
87 87
88 impl Intern for $loc { 88 impl Intern for $loc {
89 type ID = $id; 89 type ID = $id;
90 fn intern(self, db: &impl db::DefDatabase) -> $id { 90 fn intern(self, db: &dyn db::DefDatabase) -> $id {
91 db.$intern(self) 91 db.$intern(self)
92 } 92 }
93 } 93 }
94 94
95 impl Lookup for $id { 95 impl Lookup for $id {
96 type Data = $loc; 96 type Data = $loc;
97 fn lookup(&self, db: &impl db::DefDatabase) -> $loc { 97 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
98 db.$lookup(*self) 98 db.$lookup(*self)
99 } 99 }
100 } 100 }
@@ -339,20 +339,20 @@ impl_froms!(VariantId: EnumVariantId, StructId, UnionId);
339 339
340trait Intern { 340trait Intern {
341 type ID; 341 type ID;
342 fn intern(self, db: &impl db::DefDatabase) -> Self::ID; 342 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
343} 343}
344 344
345pub trait Lookup { 345pub trait Lookup {
346 type Data; 346 type Data;
347 fn lookup(&self, db: &impl db::DefDatabase) -> Self::Data; 347 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
348} 348}
349 349
350pub trait HasModule { 350pub trait HasModule {
351 fn module(&self, db: &impl db::DefDatabase) -> ModuleId; 351 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
352} 352}
353 353
354impl HasModule for ContainerId { 354impl HasModule for ContainerId {
355 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 355 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
356 match *self { 356 match *self {
357 ContainerId::ModuleId(it) => it, 357 ContainerId::ModuleId(it) => it,
358 ContainerId::DefWithBodyId(it) => it.module(db), 358 ContainerId::DefWithBodyId(it) => it.module(db),
@@ -361,7 +361,7 @@ impl HasModule for ContainerId {
361} 361}
362 362
363impl HasModule for AssocContainerId { 363impl HasModule for AssocContainerId {
364 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 364 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
365 match *self { 365 match *self {
366 AssocContainerId::ContainerId(it) => it.module(db), 366 AssocContainerId::ContainerId(it) => it.module(db),
367 AssocContainerId::ImplId(it) => it.lookup(db).container.module(db), 367 AssocContainerId::ImplId(it) => it.lookup(db).container.module(db),
@@ -371,13 +371,13 @@ impl HasModule for AssocContainerId {
371} 371}
372 372
373impl<N: AstNode> HasModule for AssocItemLoc<N> { 373impl<N: AstNode> HasModule for AssocItemLoc<N> {
374 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 374 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
375 self.container.module(db) 375 self.container.module(db)
376 } 376 }
377} 377}
378 378
379impl HasModule for AdtId { 379impl HasModule for AdtId {
380 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 380 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
381 match self { 381 match self {
382 AdtId::StructId(it) => it.lookup(db).container, 382 AdtId::StructId(it) => it.lookup(db).container,
383 AdtId::UnionId(it) => it.lookup(db).container, 383 AdtId::UnionId(it) => it.lookup(db).container,
@@ -388,7 +388,7 @@ impl HasModule for AdtId {
388} 388}
389 389
390impl HasModule for DefWithBodyId { 390impl HasModule for DefWithBodyId {
391 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 391 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
392 match self { 392 match self {
393 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db), 393 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
394 DefWithBodyId::StaticId(it) => it.lookup(db).module(db), 394 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
@@ -398,7 +398,7 @@ impl HasModule for DefWithBodyId {
398} 398}
399 399
400impl HasModule for GenericDefId { 400impl HasModule for GenericDefId {
401 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 401 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
402 match self { 402 match self {
403 GenericDefId::FunctionId(it) => it.lookup(db).module(db), 403 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
404 GenericDefId::AdtId(it) => it.module(db), 404 GenericDefId::AdtId(it) => it.module(db),
@@ -412,7 +412,7 @@ impl HasModule for GenericDefId {
412} 412}
413 413
414impl HasModule for StaticLoc { 414impl HasModule for StaticLoc {
415 fn module(&self, db: &impl db::DefDatabase) -> ModuleId { 415 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
416 self.container.module(db) 416 self.container.module(db)
417 } 417 }
418} 418}
@@ -421,7 +421,7 @@ impl HasModule for StaticLoc {
421pub trait AsMacroCall { 421pub trait AsMacroCall {
422 fn as_call_id( 422 fn as_call_id(
423 &self, 423 &self,
424 db: &(impl db::DefDatabase + AstDatabase), 424 db: &dyn db::DefDatabase,
425 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 425 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
426 ) -> Option<MacroCallId>; 426 ) -> Option<MacroCallId>;
427} 427}
@@ -429,11 +429,11 @@ pub trait AsMacroCall {
429impl AsMacroCall for InFile<&ast::MacroCall> { 429impl AsMacroCall for InFile<&ast::MacroCall> {
430 fn as_call_id( 430 fn as_call_id(
431 &self, 431 &self,
432 db: &(impl db::DefDatabase + AstDatabase), 432 db: &dyn db::DefDatabase,
433 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 433 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
434 ) -> Option<MacroCallId> { 434 ) -> Option<MacroCallId> {
435 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value)); 435 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
436 let h = Hygiene::new(db, self.file_id); 436 let h = Hygiene::new(db.upcast(), self.file_id);
437 let path = path::ModPath::from_src(self.value.path()?, &h)?; 437 let path = path::ModPath::from_src(self.value.path()?, &h)?;
438 438
439 AstIdWithPath::new(ast_id.file_id, ast_id.value, path).as_call_id(db, resolver) 439 AstIdWithPath::new(ast_id.file_id, ast_id.value, path).as_call_id(db, resolver)
@@ -456,23 +456,23 @@ impl<T: ast::AstNode> AstIdWithPath<T> {
456impl AsMacroCall for AstIdWithPath<ast::MacroCall> { 456impl AsMacroCall for AstIdWithPath<ast::MacroCall> {
457 fn as_call_id( 457 fn as_call_id(
458 &self, 458 &self,
459 db: &impl AstDatabase, 459 db: &dyn db::DefDatabase,
460 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 460 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
461 ) -> Option<MacroCallId> { 461 ) -> Option<MacroCallId> {
462 let def: MacroDefId = resolver(self.path.clone())?; 462 let def: MacroDefId = resolver(self.path.clone())?;
463 463
464 if let MacroDefKind::BuiltInEager(_) = def.kind { 464 if let MacroDefKind::BuiltInEager(_) = def.kind {
465 let macro_call = InFile::new(self.ast_id.file_id, self.ast_id.to_node(db)); 465 let macro_call = InFile::new(self.ast_id.file_id, self.ast_id.to_node(db.upcast()));
466 let hygiene = Hygiene::new(db, self.ast_id.file_id); 466 let hygiene = Hygiene::new(db.upcast(), self.ast_id.file_id);
467 467
468 Some( 468 Some(
469 expand_eager_macro(db, macro_call, def, &|path: ast::Path| { 469 expand_eager_macro(db.upcast(), macro_call, def, &|path: ast::Path| {
470 resolver(path::ModPath::from_src(path, &hygiene)?) 470 resolver(path::ModPath::from_src(path, &hygiene)?)
471 })? 471 })?
472 .into(), 472 .into(),
473 ) 473 )
474 } else { 474 } else {
475 Some(def.as_lazy_macro(db, MacroCallKind::FnLike(self.ast_id)).into()) 475 Some(def.as_lazy_macro(db.upcast(), MacroCallKind::FnLike(self.ast_id)).into())
476 } 476 }
477 } 477 }
478} 478}
@@ -480,10 +480,10 @@ impl AsMacroCall for AstIdWithPath<ast::MacroCall> {
480impl AsMacroCall for AstIdWithPath<ast::ModuleItem> { 480impl AsMacroCall for AstIdWithPath<ast::ModuleItem> {
481 fn as_call_id( 481 fn as_call_id(
482 &self, 482 &self,
483 db: &impl AstDatabase, 483 db: &dyn db::DefDatabase,
484 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>, 484 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
485 ) -> Option<MacroCallId> { 485 ) -> Option<MacroCallId> {
486 let def = resolver(self.path.clone())?; 486 let def = resolver(self.path.clone())?;
487 Some(def.as_lazy_macro(db, MacroCallKind::Attr(self.ast_id)).into()) 487 Some(def.as_lazy_macro(db.upcast(), MacroCallKind::Attr(self.ast_id)).into())
488 } 488 }
489} 489}
diff --git a/crates/ra_hir_def/src/nameres.rs b/crates/ra_hir_def/src/nameres.rs
index 03515309e..be53313ee 100644
--- a/crates/ra_hir_def/src/nameres.rs
+++ b/crates/ra_hir_def/src/nameres.rs
@@ -151,16 +151,17 @@ impl ModuleOrigin {
151 151
152 /// Returns a node which defines this module. 152 /// Returns a node which defines this module.
153 /// That is, a file or a `mod foo {}` with items. 153 /// That is, a file or a `mod foo {}` with items.
154 fn definition_source(&self, db: &impl DefDatabase) -> InFile<ModuleSource> { 154 fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
155 match self { 155 match self {
156 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => { 156 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
157 let file_id = *definition; 157 let file_id = *definition;
158 let sf = db.parse(file_id).tree(); 158 let sf = db.parse(file_id).tree();
159 InFile::new(file_id.into(), ModuleSource::SourceFile(sf)) 159 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
160 } 160 }
161 ModuleOrigin::Inline { definition } => { 161 ModuleOrigin::Inline { definition } => InFile::new(
162 InFile::new(definition.file_id, ModuleSource::Module(definition.to_node(db))) 162 definition.file_id,
163 } 163 ModuleSource::Module(definition.to_node(db.upcast())),
164 ),
164 } 165 }
165 } 166 }
166} 167}
@@ -176,7 +177,7 @@ pub struct ModuleData {
176} 177}
177 178
178impl CrateDefMap { 179impl CrateDefMap {
179 pub(crate) fn crate_def_map_query(db: &impl DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { 180 pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<CrateDefMap> {
180 let _p = profile("crate_def_map_query").detail(|| { 181 let _p = profile("crate_def_map_query").detail(|| {
181 db.crate_graph()[krate] 182 db.crate_graph()[krate]
182 .display_name 183 .display_name
@@ -204,7 +205,7 @@ impl CrateDefMap {
204 205
205 pub fn add_diagnostics( 206 pub fn add_diagnostics(
206 &self, 207 &self,
207 db: &impl DefDatabase, 208 db: &dyn DefDatabase,
208 module: LocalModuleId, 209 module: LocalModuleId,
209 sink: &mut DiagnosticSink, 210 sink: &mut DiagnosticSink,
210 ) { 211 ) {
@@ -220,7 +221,7 @@ impl CrateDefMap {
220 221
221 pub(crate) fn resolve_path( 222 pub(crate) fn resolve_path(
222 &self, 223 &self,
223 db: &impl DefDatabase, 224 db: &dyn DefDatabase,
224 original_module: LocalModuleId, 225 original_module: LocalModuleId,
225 path: &ModPath, 226 path: &ModPath,
226 shadow: BuiltinShadowMode, 227 shadow: BuiltinShadowMode,
@@ -273,15 +274,15 @@ impl CrateDefMap {
273 274
274impl ModuleData { 275impl ModuleData {
275 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. 276 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
276 pub fn definition_source(&self, db: &impl DefDatabase) -> InFile<ModuleSource> { 277 pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
277 self.origin.definition_source(db) 278 self.origin.definition_source(db)
278 } 279 }
279 280
280 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`. 281 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
281 /// `None` for the crate root or block. 282 /// `None` for the crate root or block.
282 pub fn declaration_source(&self, db: &impl DefDatabase) -> Option<InFile<ast::Module>> { 283 pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
283 let decl = self.origin.declaration()?; 284 let decl = self.origin.declaration()?;
284 let value = decl.to_node(db); 285 let value = decl.to_node(db.upcast());
285 Some(InFile { file_id: decl.file_id, value }) 286 Some(InFile { file_id: decl.file_id, value })
286 } 287 }
287} 288}
@@ -311,7 +312,7 @@ mod diagnostics {
311 impl DefDiagnostic { 312 impl DefDiagnostic {
312 pub(super) fn add_to( 313 pub(super) fn add_to(
313 &self, 314 &self,
314 db: &impl DefDatabase, 315 db: &dyn DefDatabase,
315 target_module: LocalModuleId, 316 target_module: LocalModuleId,
316 sink: &mut DiagnosticSink, 317 sink: &mut DiagnosticSink,
317 ) { 318 ) {
@@ -320,7 +321,7 @@ mod diagnostics {
320 if *module != target_module { 321 if *module != target_module {
321 return; 322 return;
322 } 323 }
323 let decl = declaration.to_node(db); 324 let decl = declaration.to_node(db.upcast());
324 sink.push(UnresolvedModule { 325 sink.push(UnresolvedModule {
325 file: declaration.file_id, 326 file: declaration.file_id,
326 decl: AstPtr::new(&decl), 327 decl: AstPtr::new(&decl),
diff --git a/crates/ra_hir_def/src/nameres/collector.rs b/crates/ra_hir_def/src/nameres/collector.rs
index db9838cb5..7a042e69f 100644
--- a/crates/ra_hir_def/src/nameres/collector.rs
+++ b/crates/ra_hir_def/src/nameres/collector.rs
@@ -30,7 +30,7 @@ use crate::{
30 TraitLoc, TypeAliasLoc, UnionLoc, 30 TraitLoc, TypeAliasLoc, UnionLoc,
31}; 31};
32 32
33pub(super) fn collect_defs(db: &impl DefDatabase, mut def_map: CrateDefMap) -> CrateDefMap { 33pub(super) fn collect_defs(db: &dyn DefDatabase, mut def_map: CrateDefMap) -> CrateDefMap {
34 let crate_graph = db.crate_graph(); 34 let crate_graph = db.crate_graph();
35 35
36 // populate external prelude 36 // populate external prelude
@@ -112,8 +112,8 @@ struct DeriveDirective {
112} 112}
113 113
114/// Walks the tree of module recursively 114/// Walks the tree of module recursively
115struct DefCollector<'a, DB> { 115struct DefCollector<'a> {
116 db: &'a DB, 116 db: &'a dyn DefDatabase,
117 def_map: CrateDefMap, 117 def_map: CrateDefMap,
118 glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>, 118 glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>,
119 unresolved_imports: Vec<ImportDirective>, 119 unresolved_imports: Vec<ImportDirective>,
@@ -124,10 +124,7 @@ struct DefCollector<'a, DB> {
124 cfg_options: &'a CfgOptions, 124 cfg_options: &'a CfgOptions,
125} 125}
126 126
127impl<DB> DefCollector<'_, DB> 127impl DefCollector<'_> {
128where
129 DB: DefDatabase,
130{
131 fn collect(&mut self) { 128 fn collect(&mut self) {
132 let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id; 129 let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
133 let raw_items = self.db.raw_items(file_id.into()); 130 let raw_items = self.db.raw_items(file_id.into());
@@ -605,8 +602,8 @@ where
605} 602}
606 603
607/// Walks a single module, populating defs, imports and macros 604/// Walks a single module, populating defs, imports and macros
608struct ModCollector<'a, D> { 605struct ModCollector<'a, 'b> {
609 def_collector: D, 606 def_collector: &'a mut DefCollector<'b>,
610 macro_depth: usize, 607 macro_depth: usize,
611 module_id: LocalModuleId, 608 module_id: LocalModuleId,
612 file_id: HirFileId, 609 file_id: HirFileId,
@@ -614,10 +611,7 @@ struct ModCollector<'a, D> {
614 mod_dir: ModDir, 611 mod_dir: ModDir,
615} 612}
616 613
617impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>> 614impl ModCollector<'_, '_> {
618where
619 DB: DefDatabase,
620{
621 fn collect(&mut self, items: &[raw::RawItem]) { 615 fn collect(&mut self, items: &[raw::RawItem]) {
622 // Note: don't assert that inserted value is fresh: it's simply not true 616 // Note: don't assert that inserted value is fresh: it's simply not true
623 // for macros. 617 // for macros.
@@ -950,7 +944,7 @@ mod tests {
950 944
951 use super::*; 945 use super::*;
952 946
953 fn do_collect_defs(db: &impl DefDatabase, def_map: CrateDefMap) -> CrateDefMap { 947 fn do_collect_defs(db: &dyn DefDatabase, def_map: CrateDefMap) -> CrateDefMap {
954 let mut collector = DefCollector { 948 let mut collector = DefCollector {
955 db, 949 db,
956 def_map, 950 def_map,
diff --git a/crates/ra_hir_def/src/nameres/mod_resolution.rs b/crates/ra_hir_def/src/nameres/mod_resolution.rs
index 14fb8ba3a..386c5cade 100644
--- a/crates/ra_hir_def/src/nameres/mod_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/mod_resolution.rs
@@ -40,12 +40,12 @@ impl ModDir {
40 40
41 pub(super) fn resolve_declaration( 41 pub(super) fn resolve_declaration(
42 &self, 42 &self,
43 db: &impl DefDatabase, 43 db: &dyn DefDatabase,
44 file_id: HirFileId, 44 file_id: HirFileId,
45 name: &Name, 45 name: &Name,
46 attr_path: Option<&SmolStr>, 46 attr_path: Option<&SmolStr>,
47 ) -> Result<(FileId, ModDir), RelativePathBuf> { 47 ) -> Result<(FileId, ModDir), RelativePathBuf> {
48 let file_id = file_id.original_file(db); 48 let file_id = file_id.original_file(db.upcast());
49 49
50 let mut candidate_files = Vec::new(); 50 let mut candidate_files = Vec::new();
51 match attr_to_path(attr_path) { 51 match attr_to_path(attr_path) {
diff --git a/crates/ra_hir_def/src/nameres/path_resolution.rs b/crates/ra_hir_def/src/nameres/path_resolution.rs
index c058e70aa..35a0a0c98 100644
--- a/crates/ra_hir_def/src/nameres/path_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/path_resolution.rs
@@ -70,7 +70,7 @@ impl CrateDefMap {
70 70
71 pub(crate) fn resolve_visibility( 71 pub(crate) fn resolve_visibility(
72 &self, 72 &self,
73 db: &impl DefDatabase, 73 db: &dyn DefDatabase,
74 original_module: LocalModuleId, 74 original_module: LocalModuleId,
75 visibility: &RawVisibility, 75 visibility: &RawVisibility,
76 ) -> Option<Visibility> { 76 ) -> Option<Visibility> {
@@ -98,7 +98,7 @@ impl CrateDefMap {
98 // the result. 98 // the result.
99 pub(super) fn resolve_path_fp_with_macro( 99 pub(super) fn resolve_path_fp_with_macro(
100 &self, 100 &self,
101 db: &impl DefDatabase, 101 db: &dyn DefDatabase,
102 mode: ResolveMode, 102 mode: ResolveMode,
103 original_module: LocalModuleId, 103 original_module: LocalModuleId,
104 path: &ModPath, 104 path: &ModPath,
@@ -262,7 +262,7 @@ impl CrateDefMap {
262 262
263 fn resolve_name_in_module( 263 fn resolve_name_in_module(
264 &self, 264 &self,
265 db: &impl DefDatabase, 265 db: &dyn DefDatabase,
266 module: LocalModuleId, 266 module: LocalModuleId,
267 name: &Name, 267 name: &Name,
268 shadow: BuiltinShadowMode, 268 shadow: BuiltinShadowMode,
@@ -304,7 +304,7 @@ impl CrateDefMap {
304 from_crate_root.or(from_extern_prelude) 304 from_crate_root.or(from_extern_prelude)
305 } 305 }
306 306
307 fn resolve_in_prelude(&self, db: &impl DefDatabase, name: &Name) -> PerNs { 307 fn resolve_in_prelude(&self, db: &dyn DefDatabase, name: &Name) -> PerNs {
308 if let Some(prelude) = self.prelude { 308 if let Some(prelude) = self.prelude {
309 let keep; 309 let keep;
310 let def_map = if prelude.krate == self.krate { 310 let def_map = if prelude.krate == self.krate {
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir_def/src/nameres/raw.rs
index ea3c00da8..0e4931f58 100644
--- a/crates/ra_hir_def/src/nameres/raw.rs
+++ b/crates/ra_hir_def/src/nameres/raw.rs
@@ -9,7 +9,6 @@ use std::{ops::Index, sync::Arc};
9 9
10use hir_expand::{ 10use hir_expand::{
11 ast_id_map::AstIdMap, 11 ast_id_map::AstIdMap,
12 db::AstDatabase,
13 hygiene::Hygiene, 12 hygiene::Hygiene,
14 name::{AsName, Name}, 13 name::{AsName, Name},
15}; 14};
@@ -45,16 +44,13 @@ pub struct RawItems {
45} 44}
46 45
47impl RawItems { 46impl RawItems {
48 pub(crate) fn raw_items_query( 47 pub(crate) fn raw_items_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<RawItems> {
49 db: &(impl DefDatabase + AstDatabase),
50 file_id: HirFileId,
51 ) -> Arc<RawItems> {
52 let _p = profile("raw_items_query"); 48 let _p = profile("raw_items_query");
53 let mut collector = RawItemsCollector { 49 let mut collector = RawItemsCollector {
54 raw_items: RawItems::default(), 50 raw_items: RawItems::default(),
55 source_ast_id_map: db.ast_id_map(file_id), 51 source_ast_id_map: db.ast_id_map(file_id),
56 file_id, 52 file_id,
57 hygiene: Hygiene::new(db, file_id), 53 hygiene: Hygiene::new(db.upcast(), file_id),
58 }; 54 };
59 if let Some(node) = db.parse_or_expand(file_id) { 55 if let Some(node) = db.parse_or_expand(file_id) {
60 if let Some(source_file) = ast::SourceFile::cast(node.clone()) { 56 if let Some(source_file) = ast::SourceFile::cast(node.clone()) {
diff --git a/crates/ra_hir_def/src/resolver.rs b/crates/ra_hir_def/src/resolver.rs
index 123fae72a..717506358 100644
--- a/crates/ra_hir_def/src/resolver.rs
+++ b/crates/ra_hir_def/src/resolver.rs
@@ -96,7 +96,7 @@ pub enum ValueNs {
96 96
97impl Resolver { 97impl Resolver {
98 /// Resolve known trait from std, like `std::futures::Future` 98 /// Resolve known trait from std, like `std::futures::Future`
99 pub fn resolve_known_trait(&self, db: &impl DefDatabase, path: &ModPath) -> Option<TraitId> { 99 pub fn resolve_known_trait(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<TraitId> {
100 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; 100 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
101 match res { 101 match res {
102 ModuleDefId::TraitId(it) => Some(it), 102 ModuleDefId::TraitId(it) => Some(it),
@@ -105,7 +105,7 @@ impl Resolver {
105 } 105 }
106 106
107 /// Resolve known struct from std, like `std::boxed::Box` 107 /// Resolve known struct from std, like `std::boxed::Box`
108 pub fn resolve_known_struct(&self, db: &impl DefDatabase, path: &ModPath) -> Option<StructId> { 108 pub fn resolve_known_struct(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<StructId> {
109 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; 109 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
110 match res { 110 match res {
111 ModuleDefId::AdtId(AdtId::StructId(it)) => Some(it), 111 ModuleDefId::AdtId(AdtId::StructId(it)) => Some(it),
@@ -114,7 +114,7 @@ impl Resolver {
114 } 114 }
115 115
116 /// Resolve known enum from std, like `std::result::Result` 116 /// Resolve known enum from std, like `std::result::Result`
117 pub fn resolve_known_enum(&self, db: &impl DefDatabase, path: &ModPath) -> Option<EnumId> { 117 pub fn resolve_known_enum(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<EnumId> {
118 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; 118 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
119 match res { 119 match res {
120 ModuleDefId::AdtId(AdtId::EnumId(it)) => Some(it), 120 ModuleDefId::AdtId(AdtId::EnumId(it)) => Some(it),
@@ -124,7 +124,7 @@ impl Resolver {
124 124
125 fn resolve_module_path( 125 fn resolve_module_path(
126 &self, 126 &self,
127 db: &impl DefDatabase, 127 db: &dyn DefDatabase,
128 path: &ModPath, 128 path: &ModPath,
129 shadow: BuiltinShadowMode, 129 shadow: BuiltinShadowMode,
130 ) -> PerNs { 130 ) -> PerNs {
@@ -139,13 +139,13 @@ impl Resolver {
139 module_res 139 module_res
140 } 140 }
141 141
142 pub fn resolve_module_path_in_items(&self, db: &impl DefDatabase, path: &ModPath) -> PerNs { 142 pub fn resolve_module_path_in_items(&self, db: &dyn DefDatabase, path: &ModPath) -> PerNs {
143 self.resolve_module_path(db, path, BuiltinShadowMode::Module) 143 self.resolve_module_path(db, path, BuiltinShadowMode::Module)
144 } 144 }
145 145
146 pub fn resolve_path_in_type_ns( 146 pub fn resolve_path_in_type_ns(
147 &self, 147 &self,
148 db: &impl DefDatabase, 148 db: &dyn DefDatabase,
149 path: &ModPath, 149 path: &ModPath,
150 ) -> Option<(TypeNs, Option<usize>)> { 150 ) -> Option<(TypeNs, Option<usize>)> {
151 let first_name = path.segments.first()?; 151 let first_name = path.segments.first()?;
@@ -222,7 +222,7 @@ impl Resolver {
222 222
223 pub fn resolve_path_in_type_ns_fully( 223 pub fn resolve_path_in_type_ns_fully(
224 &self, 224 &self,
225 db: &impl DefDatabase, 225 db: &dyn DefDatabase,
226 path: &ModPath, 226 path: &ModPath,
227 ) -> Option<TypeNs> { 227 ) -> Option<TypeNs> {
228 let (res, unresolved) = self.resolve_path_in_type_ns(db, path)?; 228 let (res, unresolved) = self.resolve_path_in_type_ns(db, path)?;
@@ -234,7 +234,7 @@ impl Resolver {
234 234
235 pub fn resolve_visibility( 235 pub fn resolve_visibility(
236 &self, 236 &self,
237 db: &impl DefDatabase, 237 db: &dyn DefDatabase,
238 visibility: &RawVisibility, 238 visibility: &RawVisibility,
239 ) -> Option<Visibility> { 239 ) -> Option<Visibility> {
240 match visibility { 240 match visibility {
@@ -251,7 +251,7 @@ impl Resolver {
251 251
252 pub fn resolve_path_in_value_ns( 252 pub fn resolve_path_in_value_ns(
253 &self, 253 &self,
254 db: &impl DefDatabase, 254 db: &dyn DefDatabase,
255 path: &ModPath, 255 path: &ModPath,
256 ) -> Option<ResolveValueResult> { 256 ) -> Option<ResolveValueResult> {
257 let n_segments = path.segments.len(); 257 let n_segments = path.segments.len();
@@ -367,7 +367,7 @@ impl Resolver {
367 367
368 pub fn resolve_path_in_value_ns_fully( 368 pub fn resolve_path_in_value_ns_fully(
369 &self, 369 &self,
370 db: &impl DefDatabase, 370 db: &dyn DefDatabase,
371 path: &ModPath, 371 path: &ModPath,
372 ) -> Option<ValueNs> { 372 ) -> Option<ValueNs> {
373 match self.resolve_path_in_value_ns(db, path)? { 373 match self.resolve_path_in_value_ns(db, path)? {
@@ -378,7 +378,7 @@ impl Resolver {
378 378
379 pub fn resolve_path_as_macro( 379 pub fn resolve_path_as_macro(
380 &self, 380 &self,
381 db: &impl DefDatabase, 381 db: &dyn DefDatabase,
382 path: &ModPath, 382 path: &ModPath,
383 ) -> Option<MacroDefId> { 383 ) -> Option<MacroDefId> {
384 // Search item scope legacy macro first 384 // Search item scope legacy macro first
@@ -390,13 +390,13 @@ impl Resolver {
390 item_map.resolve_path(db, module, &path, BuiltinShadowMode::Other).0.take_macros() 390 item_map.resolve_path(db, module, &path, BuiltinShadowMode::Other).0.take_macros()
391 } 391 }
392 392
393 pub fn process_all_names(&self, db: &impl DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) { 393 pub fn process_all_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
394 for scope in self.scopes.iter().rev() { 394 for scope in self.scopes.iter().rev() {
395 scope.process_names(db, f); 395 scope.process_names(db, f);
396 } 396 }
397 } 397 }
398 398
399 pub fn traits_in_scope(&self, db: &impl DefDatabase) -> FxHashSet<TraitId> { 399 pub fn traits_in_scope(&self, db: &dyn DefDatabase) -> FxHashSet<TraitId> {
400 let mut traits = FxHashSet::default(); 400 let mut traits = FxHashSet::default();
401 for scope in &self.scopes { 401 for scope in &self.scopes {
402 if let Scope::ModuleScope(m) = scope { 402 if let Scope::ModuleScope(m) = scope {
@@ -474,7 +474,7 @@ pub enum ScopeDef {
474} 474}
475 475
476impl Scope { 476impl Scope {
477 fn process_names(&self, db: &impl DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) { 477 fn process_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
478 match self { 478 match self {
479 Scope::ModuleScope(m) => { 479 Scope::ModuleScope(m) => {
480 // FIXME: should we provide `self` here? 480 // FIXME: should we provide `self` here?
@@ -534,13 +534,13 @@ impl Scope {
534} 534}
535 535
536// needs arbitrary_self_types to be a method... or maybe move to the def? 536// needs arbitrary_self_types to be a method... or maybe move to the def?
537pub fn resolver_for_expr(db: &impl DefDatabase, owner: DefWithBodyId, expr_id: ExprId) -> Resolver { 537pub fn resolver_for_expr(db: &dyn DefDatabase, owner: DefWithBodyId, expr_id: ExprId) -> Resolver {
538 let scopes = db.expr_scopes(owner); 538 let scopes = db.expr_scopes(owner);
539 resolver_for_scope(db, owner, scopes.scope_for(expr_id)) 539 resolver_for_scope(db, owner, scopes.scope_for(expr_id))
540} 540}
541 541
542pub fn resolver_for_scope( 542pub fn resolver_for_scope(
543 db: &impl DefDatabase, 543 db: &dyn DefDatabase,
544 owner: DefWithBodyId, 544 owner: DefWithBodyId,
545 scope_id: Option<ScopeId>, 545 scope_id: Option<ScopeId>,
546) -> Resolver { 546) -> Resolver {
@@ -560,7 +560,7 @@ impl Resolver {
560 self 560 self
561 } 561 }
562 562
563 fn push_generic_params_scope(self, db: &impl DefDatabase, def: GenericDefId) -> Resolver { 563 fn push_generic_params_scope(self, db: &dyn DefDatabase, def: GenericDefId) -> Resolver {
564 let params = db.generic_params(def); 564 let params = db.generic_params(def);
565 self.push_scope(Scope::GenericParams { def, params }) 565 self.push_scope(Scope::GenericParams { def, params })
566 } 566 }
@@ -593,24 +593,24 @@ impl Resolver {
593 593
594pub trait HasResolver: Copy { 594pub trait HasResolver: Copy {
595 /// Builds a resolver for type references inside this def. 595 /// Builds a resolver for type references inside this def.
596 fn resolver(self, db: &impl DefDatabase) -> Resolver; 596 fn resolver(self, db: &dyn DefDatabase) -> Resolver;
597} 597}
598 598
599impl HasResolver for ModuleId { 599impl HasResolver for ModuleId {
600 fn resolver(self, db: &impl DefDatabase) -> Resolver { 600 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
601 let def_map = db.crate_def_map(self.krate); 601 let def_map = db.crate_def_map(self.krate);
602 Resolver::default().push_module_scope(def_map, self.local_id) 602 Resolver::default().push_module_scope(def_map, self.local_id)
603 } 603 }
604} 604}
605 605
606impl HasResolver for TraitId { 606impl HasResolver for TraitId {
607 fn resolver(self, db: &impl DefDatabase) -> Resolver { 607 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
608 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into()) 608 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
609 } 609 }
610} 610}
611 611
612impl<T: Into<AdtId> + Copy> HasResolver for T { 612impl<T: Into<AdtId> + Copy> HasResolver for T {
613 fn resolver(self, db: &impl DefDatabase) -> Resolver { 613 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
614 let def = self.into(); 614 let def = self.into();
615 def.module(db) 615 def.module(db)
616 .resolver(db) 616 .resolver(db)
@@ -620,31 +620,31 @@ impl<T: Into<AdtId> + Copy> HasResolver for T {
620} 620}
621 621
622impl HasResolver for FunctionId { 622impl HasResolver for FunctionId {
623 fn resolver(self, db: &impl DefDatabase) -> Resolver { 623 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
624 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into()) 624 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
625 } 625 }
626} 626}
627 627
628impl HasResolver for ConstId { 628impl HasResolver for ConstId {
629 fn resolver(self, db: &impl DefDatabase) -> Resolver { 629 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
630 self.lookup(db).container.resolver(db) 630 self.lookup(db).container.resolver(db)
631 } 631 }
632} 632}
633 633
634impl HasResolver for StaticId { 634impl HasResolver for StaticId {
635 fn resolver(self, db: &impl DefDatabase) -> Resolver { 635 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
636 self.lookup(db).container.resolver(db) 636 self.lookup(db).container.resolver(db)
637 } 637 }
638} 638}
639 639
640impl HasResolver for TypeAliasId { 640impl HasResolver for TypeAliasId {
641 fn resolver(self, db: &impl DefDatabase) -> Resolver { 641 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
642 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into()) 642 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
643 } 643 }
644} 644}
645 645
646impl HasResolver for ImplId { 646impl HasResolver for ImplId {
647 fn resolver(self, db: &impl DefDatabase) -> Resolver { 647 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
648 self.lookup(db) 648 self.lookup(db)
649 .container 649 .container
650 .resolver(db) 650 .resolver(db)
@@ -654,7 +654,7 @@ impl HasResolver for ImplId {
654} 654}
655 655
656impl HasResolver for DefWithBodyId { 656impl HasResolver for DefWithBodyId {
657 fn resolver(self, db: &impl DefDatabase) -> Resolver { 657 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
658 match self { 658 match self {
659 DefWithBodyId::ConstId(c) => c.resolver(db), 659 DefWithBodyId::ConstId(c) => c.resolver(db),
660 DefWithBodyId::FunctionId(f) => f.resolver(db), 660 DefWithBodyId::FunctionId(f) => f.resolver(db),
@@ -664,7 +664,7 @@ impl HasResolver for DefWithBodyId {
664} 664}
665 665
666impl HasResolver for ContainerId { 666impl HasResolver for ContainerId {
667 fn resolver(self, db: &impl DefDatabase) -> Resolver { 667 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
668 match self { 668 match self {
669 ContainerId::ModuleId(it) => it.resolver(db), 669 ContainerId::ModuleId(it) => it.resolver(db),
670 ContainerId::DefWithBodyId(it) => it.module(db).resolver(db), 670 ContainerId::DefWithBodyId(it) => it.module(db).resolver(db),
@@ -673,7 +673,7 @@ impl HasResolver for ContainerId {
673} 673}
674 674
675impl HasResolver for AssocContainerId { 675impl HasResolver for AssocContainerId {
676 fn resolver(self, db: &impl DefDatabase) -> Resolver { 676 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
677 match self { 677 match self {
678 AssocContainerId::ContainerId(it) => it.resolver(db), 678 AssocContainerId::ContainerId(it) => it.resolver(db),
679 AssocContainerId::TraitId(it) => it.resolver(db), 679 AssocContainerId::TraitId(it) => it.resolver(db),
@@ -683,7 +683,7 @@ impl HasResolver for AssocContainerId {
683} 683}
684 684
685impl HasResolver for GenericDefId { 685impl HasResolver for GenericDefId {
686 fn resolver(self, db: &impl DefDatabase) -> Resolver { 686 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
687 match self { 687 match self {
688 GenericDefId::FunctionId(inner) => inner.resolver(db), 688 GenericDefId::FunctionId(inner) => inner.resolver(db),
689 GenericDefId::AdtId(adt) => adt.resolver(db), 689 GenericDefId::AdtId(adt) => adt.resolver(db),
@@ -697,7 +697,7 @@ impl HasResolver for GenericDefId {
697} 697}
698 698
699impl HasResolver for VariantId { 699impl HasResolver for VariantId {
700 fn resolver(self, db: &impl DefDatabase) -> Resolver { 700 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
701 match self { 701 match self {
702 VariantId::EnumVariantId(it) => it.parent.resolver(db), 702 VariantId::EnumVariantId(it) => it.parent.resolver(db),
703 VariantId::StructId(it) => it.resolver(db), 703 VariantId::StructId(it) => it.resolver(db),
diff --git a/crates/ra_hir_def/src/src.rs b/crates/ra_hir_def/src/src.rs
index 499375b80..46e90da70 100644
--- a/crates/ra_hir_def/src/src.rs
+++ b/crates/ra_hir_def/src/src.rs
@@ -8,14 +8,14 @@ use crate::{db::DefDatabase, AssocItemLoc, ItemLoc};
8 8
9pub trait HasSource { 9pub trait HasSource {
10 type Value; 10 type Value;
11 fn source(&self, db: &impl DefDatabase) -> InFile<Self::Value>; 11 fn source(&self, db: &dyn DefDatabase) -> InFile<Self::Value>;
12} 12}
13 13
14impl<N: AstNode> HasSource for AssocItemLoc<N> { 14impl<N: AstNode> HasSource for AssocItemLoc<N> {
15 type Value = N; 15 type Value = N;
16 16
17 fn source(&self, db: &impl DefDatabase) -> InFile<N> { 17 fn source(&self, db: &dyn DefDatabase) -> InFile<N> {
18 let node = self.ast_id.to_node(db); 18 let node = self.ast_id.to_node(db.upcast());
19 InFile::new(self.ast_id.file_id, node) 19 InFile::new(self.ast_id.file_id, node)
20 } 20 }
21} 21}
@@ -23,8 +23,8 @@ impl<N: AstNode> HasSource for AssocItemLoc<N> {
23impl<N: AstNode> HasSource for ItemLoc<N> { 23impl<N: AstNode> HasSource for ItemLoc<N> {
24 type Value = N; 24 type Value = N;
25 25
26 fn source(&self, db: &impl DefDatabase) -> InFile<N> { 26 fn source(&self, db: &dyn DefDatabase) -> InFile<N> {
27 let node = self.ast_id.to_node(db); 27 let node = self.ast_id.to_node(db.upcast());
28 InFile::new(self.ast_id.file_id, node) 28 InFile::new(self.ast_id.file_id, node)
29 } 29 }
30} 30}
@@ -32,5 +32,5 @@ impl<N: AstNode> HasSource for ItemLoc<N> {
32pub trait HasChildSource { 32pub trait HasChildSource {
33 type ChildId; 33 type ChildId;
34 type Value; 34 type Value;
35 fn child_source(&self, db: &impl DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>>; 35 fn child_source(&self, db: &dyn DefDatabase) -> InFile<ArenaMap<Self::ChildId, Self::Value>>;
36} 36}
diff --git a/crates/ra_hir_def/src/test_db.rs b/crates/ra_hir_def/src/test_db.rs
index 0756916a8..eb83dee79 100644
--- a/crates/ra_hir_def/src/test_db.rs
+++ b/crates/ra_hir_def/src/test_db.rs
@@ -5,8 +5,12 @@ use std::{
5 sync::{Arc, Mutex}, 5 sync::{Arc, Mutex},
6}; 6};
7 7
8use hir_expand::db::AstDatabase;
9use ra_db::{
10 salsa, CrateId, ExternSourceId, FileId, FileLoader, FileLoaderDelegate, RelativePath, Upcast,
11};
12
8use crate::db::DefDatabase; 13use crate::db::DefDatabase;
9use ra_db::{salsa, CrateId, ExternSourceId, FileId, FileLoader, FileLoaderDelegate, RelativePath};
10 14
11#[salsa::database( 15#[salsa::database(
12 ra_db::SourceDatabaseExtStorage, 16 ra_db::SourceDatabaseExtStorage,
@@ -21,6 +25,18 @@ pub struct TestDB {
21 events: Mutex<Option<Vec<salsa::Event<TestDB>>>>, 25 events: Mutex<Option<Vec<salsa::Event<TestDB>>>>,
22} 26}
23 27
28impl Upcast<dyn AstDatabase> for TestDB {
29 fn upcast(&self) -> &(dyn AstDatabase + 'static) {
30 &*self
31 }
32}
33
34impl Upcast<dyn DefDatabase> for TestDB {
35 fn upcast(&self) -> &(dyn DefDatabase + 'static) {
36 &*self
37 }
38}
39
24impl salsa::Database for TestDB { 40impl salsa::Database for TestDB {
25 fn salsa_runtime(&self) -> &salsa::Runtime<Self> { 41 fn salsa_runtime(&self) -> &salsa::Runtime<Self> {
26 &self.runtime 42 &self.runtime
diff --git a/crates/ra_hir_def/src/visibility.rs b/crates/ra_hir_def/src/visibility.rs
index e0c59e905..62513873e 100644
--- a/crates/ra_hir_def/src/visibility.rs
+++ b/crates/ra_hir_def/src/visibility.rs
@@ -33,22 +33,22 @@ impl RawVisibility {
33 } 33 }
34 34
35 pub(crate) fn from_ast_with_default( 35 pub(crate) fn from_ast_with_default(
36 db: &impl DefDatabase, 36 db: &dyn DefDatabase,
37 default: RawVisibility, 37 default: RawVisibility,
38 node: InFile<Option<ast::Visibility>>, 38 node: InFile<Option<ast::Visibility>>,
39 ) -> RawVisibility { 39 ) -> RawVisibility {
40 Self::from_ast_with_hygiene_and_default( 40 Self::from_ast_with_hygiene_and_default(
41 node.value, 41 node.value,
42 default, 42 default,
43 &Hygiene::new(db, node.file_id), 43 &Hygiene::new(db.upcast(), node.file_id),
44 ) 44 )
45 } 45 }
46 46
47 pub(crate) fn from_ast( 47 pub(crate) fn from_ast(
48 db: &impl DefDatabase, 48 db: &dyn DefDatabase,
49 node: InFile<Option<ast::Visibility>>, 49 node: InFile<Option<ast::Visibility>>,
50 ) -> RawVisibility { 50 ) -> RawVisibility {
51 Self::from_ast_with_hygiene(node.value, &Hygiene::new(db, node.file_id)) 51 Self::from_ast_with_hygiene(node.value, &Hygiene::new(db.upcast(), node.file_id))
52 } 52 }
53 53
54 pub(crate) fn from_ast_with_hygiene( 54 pub(crate) fn from_ast_with_hygiene(
@@ -90,7 +90,7 @@ impl RawVisibility {
90 90
91 pub fn resolve( 91 pub fn resolve(
92 &self, 92 &self,
93 db: &impl DefDatabase, 93 db: &dyn DefDatabase,
94 resolver: &crate::resolver::Resolver, 94 resolver: &crate::resolver::Resolver,
95 ) -> Visibility { 95 ) -> Visibility {
96 // we fall back to public visibility (i.e. fail open) if the path can't be resolved 96 // we fall back to public visibility (i.e. fail open) if the path can't be resolved
@@ -108,7 +108,7 @@ pub enum Visibility {
108} 108}
109 109
110impl Visibility { 110impl Visibility {
111 pub fn is_visible_from(self, db: &impl DefDatabase, from_module: ModuleId) -> bool { 111 pub fn is_visible_from(self, db: &dyn DefDatabase, from_module: ModuleId) -> bool {
112 let to_module = match self { 112 let to_module = match self {
113 Visibility::Module(m) => m, 113 Visibility::Module(m) => m,
114 Visibility::Public => return true, 114 Visibility::Public => return true,
diff --git a/crates/ra_hir_expand/src/db.rs b/crates/ra_hir_expand/src/db.rs
index 29dde3d80..c3e1c68b7 100644
--- a/crates/ra_hir_expand/src/db.rs
+++ b/crates/ra_hir_expand/src/db.rs
@@ -77,7 +77,7 @@ pub trait AstDatabase: SourceDatabase {
77/// token. The `token_to_map` mapped down into the expansion, with the mapped 77/// token. The `token_to_map` mapped down into the expansion, with the mapped
78/// token returned. 78/// token returned.
79pub fn expand_hypothetical( 79pub fn expand_hypothetical(
80 db: &impl AstDatabase, 80 db: &dyn AstDatabase,
81 actual_macro_call: MacroCallId, 81 actual_macro_call: MacroCallId,
82 hypothetical_args: &ra_syntax::ast::TokenTree, 82 hypothetical_args: &ra_syntax::ast::TokenTree,
83 token_to_map: ra_syntax::SyntaxToken, 83 token_to_map: ra_syntax::SyntaxToken,
diff --git a/crates/ra_hir_expand/src/eager.rs b/crates/ra_hir_expand/src/eager.rs
index 2e6dd3dd8..4cbce4df5 100644
--- a/crates/ra_hir_expand/src/eager.rs
+++ b/crates/ra_hir_expand/src/eager.rs
@@ -30,7 +30,7 @@ use ra_syntax::{algo::replace_descendants, SyntaxElement, SyntaxNode};
30use std::{collections::HashMap, sync::Arc}; 30use std::{collections::HashMap, sync::Arc};
31 31
32pub fn expand_eager_macro( 32pub fn expand_eager_macro(
33 db: &impl AstDatabase, 33 db: &dyn AstDatabase,
34 macro_call: InFile<ast::MacroCall>, 34 macro_call: InFile<ast::MacroCall>,
35 def: MacroDefId, 35 def: MacroDefId,
36 resolver: &dyn Fn(ast::Path) -> Option<MacroDefId>, 36 resolver: &dyn Fn(ast::Path) -> Option<MacroDefId>,
@@ -78,7 +78,7 @@ fn to_subtree(node: &SyntaxNode) -> Option<tt::Subtree> {
78} 78}
79 79
80fn lazy_expand( 80fn lazy_expand(
81 db: &impl AstDatabase, 81 db: &dyn AstDatabase,
82 def: &MacroDefId, 82 def: &MacroDefId,
83 macro_call: InFile<ast::MacroCall>, 83 macro_call: InFile<ast::MacroCall>,
84) -> Option<InFile<SyntaxNode>> { 84) -> Option<InFile<SyntaxNode>> {
@@ -91,7 +91,7 @@ fn lazy_expand(
91} 91}
92 92
93fn eager_macro_recur( 93fn eager_macro_recur(
94 db: &impl AstDatabase, 94 db: &dyn AstDatabase,
95 curr: InFile<SyntaxNode>, 95 curr: InFile<SyntaxNode>,
96 macro_resolver: &dyn Fn(ast::Path) -> Option<MacroDefId>, 96 macro_resolver: &dyn Fn(ast::Path) -> Option<MacroDefId>,
97) -> Option<SyntaxNode> { 97) -> Option<SyntaxNode> {
diff --git a/crates/ra_hir_expand/src/hygiene.rs b/crates/ra_hir_expand/src/hygiene.rs
index cb554ae4b..dfbac494f 100644
--- a/crates/ra_hir_expand/src/hygiene.rs
+++ b/crates/ra_hir_expand/src/hygiene.rs
@@ -19,7 +19,7 @@ pub struct Hygiene {
19} 19}
20 20
21impl Hygiene { 21impl Hygiene {
22 pub fn new(db: &impl AstDatabase, file_id: HirFileId) -> Hygiene { 22 pub fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Hygiene {
23 let def_crate = match file_id.0 { 23 let def_crate = match file_id.0 {
24 HirFileIdRepr::FileId(_) => None, 24 HirFileIdRepr::FileId(_) => None,
25 HirFileIdRepr::MacroFile(macro_file) => match macro_file.macro_call_id { 25 HirFileIdRepr::MacroFile(macro_file) => match macro_file.macro_call_id {
diff --git a/crates/ra_hir_expand/src/lib.rs b/crates/ra_hir_expand/src/lib.rs
index 7b72eb7a0..6b59ea4c9 100644
--- a/crates/ra_hir_expand/src/lib.rs
+++ b/crates/ra_hir_expand/src/lib.rs
@@ -366,7 +366,7 @@ impl<T> InFile<T> {
366 pub fn as_ref(&self) -> InFile<&T> { 366 pub fn as_ref(&self) -> InFile<&T> {
367 self.with_value(&self.value) 367 self.with_value(&self.value)
368 } 368 }
369 pub fn file_syntax(&self, db: &impl db::AstDatabase) -> SyntaxNode { 369 pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
370 db.parse_or_expand(self.file_id).expect("source created from invalid file") 370 db.parse_or_expand(self.file_id).expect("source created from invalid file")
371 } 371 }
372} 372}
@@ -387,7 +387,7 @@ impl<T> InFile<Option<T>> {
387impl InFile<SyntaxNode> { 387impl InFile<SyntaxNode> {
388 pub fn ancestors_with_macros( 388 pub fn ancestors_with_macros(
389 self, 389 self,
390 db: &impl crate::db::AstDatabase, 390 db: &dyn db::AstDatabase,
391 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ { 391 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
392 std::iter::successors(Some(self), move |node| match node.value.parent() { 392 std::iter::successors(Some(self), move |node| match node.value.parent() {
393 Some(parent) => Some(node.with_value(parent)), 393 Some(parent) => Some(node.with_value(parent)),
@@ -402,7 +402,7 @@ impl InFile<SyntaxNode> {
402impl InFile<SyntaxToken> { 402impl InFile<SyntaxToken> {
403 pub fn ancestors_with_macros( 403 pub fn ancestors_with_macros(
404 self, 404 self,
405 db: &impl crate::db::AstDatabase, 405 db: &dyn db::AstDatabase,
406 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ { 406 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
407 self.map(|it| it.parent()).ancestors_with_macros(db) 407 self.map(|it| it.parent()).ancestors_with_macros(db)
408 } 408 }
diff --git a/crates/ra_hir_ty/src/autoderef.rs b/crates/ra_hir_ty/src/autoderef.rs
index f32d5786a..53e81e85d 100644
--- a/crates/ra_hir_ty/src/autoderef.rs
+++ b/crates/ra_hir_ty/src/autoderef.rs
@@ -20,7 +20,7 @@ use crate::{
20const AUTODEREF_RECURSION_LIMIT: usize = 10; 20const AUTODEREF_RECURSION_LIMIT: usize = 10;
21 21
22pub fn autoderef<'a>( 22pub fn autoderef<'a>(
23 db: &'a impl HirDatabase, 23 db: &'a dyn HirDatabase,
24 krate: Option<CrateId>, 24 krate: Option<CrateId>,
25 ty: InEnvironment<Canonical<Ty>>, 25 ty: InEnvironment<Canonical<Ty>>,
26) -> impl Iterator<Item = Canonical<Ty>> + 'a { 26) -> impl Iterator<Item = Canonical<Ty>> + 'a {
@@ -32,7 +32,7 @@ pub fn autoderef<'a>(
32} 32}
33 33
34pub(crate) fn deref( 34pub(crate) fn deref(
35 db: &impl HirDatabase, 35 db: &dyn HirDatabase,
36 krate: CrateId, 36 krate: CrateId,
37 ty: InEnvironment<&Canonical<Ty>>, 37 ty: InEnvironment<&Canonical<Ty>>,
38) -> Option<Canonical<Ty>> { 38) -> Option<Canonical<Ty>> {
@@ -44,7 +44,7 @@ pub(crate) fn deref(
44} 44}
45 45
46fn deref_by_trait( 46fn deref_by_trait(
47 db: &impl HirDatabase, 47 db: &dyn HirDatabase,
48 krate: CrateId, 48 krate: CrateId,
49 ty: InEnvironment<&Canonical<Ty>>, 49 ty: InEnvironment<&Canonical<Ty>>,
50) -> Option<Canonical<Ty>> { 50) -> Option<Canonical<Ty>> {
@@ -54,7 +54,7 @@ fn deref_by_trait(
54 }; 54 };
55 let target = db.trait_data(deref_trait).associated_type_by_name(&name![Target])?; 55 let target = db.trait_data(deref_trait).associated_type_by_name(&name![Target])?;
56 56
57 let generic_params = generics(db, target.into()); 57 let generic_params = generics(db.upcast(), target.into());
58 if generic_params.len() != 1 { 58 if generic_params.len() != 1 {
59 // the Target type + Deref trait should only have one generic parameter, 59 // the Target type + Deref trait should only have one generic parameter,
60 // namely Deref's Self type 60 // namely Deref's Self type
diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs
index 74b309005..11fc2ac3d 100644
--- a/crates/ra_hir_ty/src/db.rs
+++ b/crates/ra_hir_ty/src/db.rs
@@ -7,7 +7,7 @@ use hir_def::{
7 VariantId, 7 VariantId,
8}; 8};
9use ra_arena::map::ArenaMap; 9use ra_arena::map::ArenaMap;
10use ra_db::{impl_intern_key, salsa, CrateId}; 10use ra_db::{impl_intern_key, salsa, CrateId, Upcast};
11use ra_prof::profile; 11use ra_prof::profile;
12 12
13use crate::{ 13use crate::{
@@ -20,7 +20,7 @@ use hir_expand::name::Name;
20 20
21#[salsa::query_group(HirDatabaseStorage)] 21#[salsa::query_group(HirDatabaseStorage)]
22#[salsa::requires(salsa::Database)] 22#[salsa::requires(salsa::Database)]
23pub trait HirDatabase: DefDatabase { 23pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
24 #[salsa::invoke(infer_wait)] 24 #[salsa::invoke(infer_wait)]
25 fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>; 25 fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>;
26 26
diff --git a/crates/ra_hir_ty/src/display.rs b/crates/ra_hir_ty/src/display.rs
index 14e089cf4..a6ef44a31 100644
--- a/crates/ra_hir_ty/src/display.rs
+++ b/crates/ra_hir_ty/src/display.rs
@@ -9,8 +9,8 @@ use crate::{
9use hir_def::{generics::TypeParamProvenance, AdtId, AssocContainerId, Lookup}; 9use hir_def::{generics::TypeParamProvenance, AdtId, AssocContainerId, Lookup};
10use hir_expand::name::Name; 10use hir_expand::name::Name;
11 11
12pub struct HirFormatter<'a, 'b, DB> { 12pub struct HirFormatter<'a, 'b> {
13 pub db: &'a DB, 13 pub db: &'a dyn HirDatabase,
14 fmt: &'a mut fmt::Formatter<'b>, 14 fmt: &'a mut fmt::Formatter<'b>,
15 buf: String, 15 buf: String,
16 curr_size: usize, 16 curr_size: usize,
@@ -19,20 +19,20 @@ pub struct HirFormatter<'a, 'b, DB> {
19} 19}
20 20
21pub trait HirDisplay { 21pub trait HirDisplay {
22 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; 22 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result;
23 23
24 fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> 24 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
25 where 25 where
26 Self: Sized, 26 Self: Sized,
27 { 27 {
28 HirDisplayWrapper(db, self, None, false) 28 HirDisplayWrapper(db, self, None, false)
29 } 29 }
30 30
31 fn display_truncated<'a, DB>( 31 fn display_truncated<'a>(
32 &'a self, 32 &'a self,
33 db: &'a DB, 33 db: &'a dyn HirDatabase,
34 max_size: Option<usize>, 34 max_size: Option<usize>,
35 ) -> HirDisplayWrapper<'a, DB, Self> 35 ) -> HirDisplayWrapper<'a, Self>
36 where 36 where
37 Self: Sized, 37 Self: Sized,
38 { 38 {
@@ -40,10 +40,7 @@ pub trait HirDisplay {
40 } 40 }
41} 41}
42 42
43impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> 43impl<'a, 'b> HirFormatter<'a, 'b> {
44where
45 DB: HirDatabase,
46{
47 pub fn write_joined<T: HirDisplay>( 44 pub fn write_joined<T: HirDisplay>(
48 &mut self, 45 &mut self,
49 iter: impl IntoIterator<Item = T>, 46 iter: impl IntoIterator<Item = T>,
@@ -84,11 +81,10 @@ where
84 } 81 }
85} 82}
86 83
87pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>, bool); 84pub struct HirDisplayWrapper<'a, T>(&'a dyn HirDatabase, &'a T, Option<usize>, bool);
88 85
89impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> 86impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T>
90where 87where
91 DB: HirDatabase,
92 T: HirDisplay, 88 T: HirDisplay,
93{ 89{
94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -106,13 +102,13 @@ where
106const TYPE_HINT_TRUNCATION: &str = "…"; 102const TYPE_HINT_TRUNCATION: &str = "…";
107 103
108impl HirDisplay for &Ty { 104impl HirDisplay for &Ty {
109 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 105 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
110 HirDisplay::hir_fmt(*self, f) 106 HirDisplay::hir_fmt(*self, f)
111 } 107 }
112} 108}
113 109
114impl HirDisplay for ApplicationTy { 110impl HirDisplay for ApplicationTy {
115 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 111 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
116 if f.should_truncate() { 112 if f.should_truncate() {
117 return write!(f, "{}", TYPE_HINT_TRUNCATION); 113 return write!(f, "{}", TYPE_HINT_TRUNCATION);
118 } 114 }
@@ -178,7 +174,7 @@ impl HirDisplay for ApplicationTy {
178 } 174 }
179 } 175 }
180 if self.parameters.len() > 0 { 176 if self.parameters.len() > 0 {
181 let generics = generics(f.db, def.into()); 177 let generics = generics(f.db.upcast(), def.into());
182 let (parent_params, self_param, type_params, _impl_trait_params) = 178 let (parent_params, self_param, type_params, _impl_trait_params) =
183 generics.provenance_split(); 179 generics.provenance_split();
184 let total_len = parent_params + self_param + type_params; 180 let total_len = parent_params + self_param + type_params;
@@ -238,7 +234,7 @@ impl HirDisplay for ApplicationTy {
238 } 234 }
239 } 235 }
240 TypeCtor::AssociatedType(type_alias) => { 236 TypeCtor::AssociatedType(type_alias) => {
241 let trait_ = match type_alias.lookup(f.db).container { 237 let trait_ = match type_alias.lookup(f.db.upcast()).container {
242 AssocContainerId::TraitId(it) => it, 238 AssocContainerId::TraitId(it) => it,
243 _ => panic!("not an associated type"), 239 _ => panic!("not an associated type"),
244 }; 240 };
@@ -272,7 +268,7 @@ impl HirDisplay for ApplicationTy {
272} 268}
273 269
274impl HirDisplay for ProjectionTy { 270impl HirDisplay for ProjectionTy {
275 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 271 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
276 if f.should_truncate() { 272 if f.should_truncate() {
277 return write!(f, "{}", TYPE_HINT_TRUNCATION); 273 return write!(f, "{}", TYPE_HINT_TRUNCATION);
278 } 274 }
@@ -290,7 +286,7 @@ impl HirDisplay for ProjectionTy {
290} 286}
291 287
292impl HirDisplay for Ty { 288impl HirDisplay for Ty {
293 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 289 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
294 if f.should_truncate() { 290 if f.should_truncate() {
295 return write!(f, "{}", TYPE_HINT_TRUNCATION); 291 return write!(f, "{}", TYPE_HINT_TRUNCATION);
296 } 292 }
@@ -299,7 +295,7 @@ impl HirDisplay for Ty {
299 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, 295 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
300 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, 296 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
301 Ty::Placeholder(id) => { 297 Ty::Placeholder(id) => {
302 let generics = generics(f.db, id.parent); 298 let generics = generics(f.db.upcast(), id.parent);
303 let param_data = &generics.params.types[id.local_id]; 299 let param_data = &generics.params.types[id.local_id];
304 match param_data.provenance { 300 match param_data.provenance {
305 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => { 301 TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
@@ -334,7 +330,7 @@ impl HirDisplay for Ty {
334 330
335fn write_bounds_like_dyn_trait( 331fn write_bounds_like_dyn_trait(
336 predicates: &[GenericPredicate], 332 predicates: &[GenericPredicate],
337 f: &mut HirFormatter<impl HirDatabase>, 333 f: &mut HirFormatter,
338) -> fmt::Result { 334) -> fmt::Result {
339 // Note: This code is written to produce nice results (i.e. 335 // Note: This code is written to produce nice results (i.e.
340 // corresponding to surface Rust) for types that can occur in 336 // corresponding to surface Rust) for types that can occur in
@@ -398,7 +394,7 @@ fn write_bounds_like_dyn_trait(
398} 394}
399 395
400impl TraitRef { 396impl TraitRef {
401 fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { 397 fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> fmt::Result {
402 if f.should_truncate() { 398 if f.should_truncate() {
403 return write!(f, "{}", TYPE_HINT_TRUNCATION); 399 return write!(f, "{}", TYPE_HINT_TRUNCATION);
404 } 400 }
@@ -420,19 +416,19 @@ impl TraitRef {
420} 416}
421 417
422impl HirDisplay for TraitRef { 418impl HirDisplay for TraitRef {
423 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 419 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
424 self.hir_fmt_ext(f, false) 420 self.hir_fmt_ext(f, false)
425 } 421 }
426} 422}
427 423
428impl HirDisplay for &GenericPredicate { 424impl HirDisplay for &GenericPredicate {
429 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 425 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
430 HirDisplay::hir_fmt(*self, f) 426 HirDisplay::hir_fmt(*self, f)
431 } 427 }
432} 428}
433 429
434impl HirDisplay for GenericPredicate { 430impl HirDisplay for GenericPredicate {
435 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 431 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
436 if f.should_truncate() { 432 if f.should_truncate() {
437 return write!(f, "{}", TYPE_HINT_TRUNCATION); 433 return write!(f, "{}", TYPE_HINT_TRUNCATION);
438 } 434 }
@@ -456,7 +452,7 @@ impl HirDisplay for GenericPredicate {
456} 452}
457 453
458impl HirDisplay for Obligation { 454impl HirDisplay for Obligation {
459 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { 455 fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result {
460 match self { 456 match self {
461 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), 457 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)),
462 Obligation::Projection(proj) => write!( 458 Obligation::Projection(proj) => write!(
diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs
index d8cdf5266..b7b476b4c 100644
--- a/crates/ra_hir_ty/src/expr.rs
+++ b/crates/ra_hir_ty/src/expr.rs
@@ -46,7 +46,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
46 ExprValidator { func, infer, sink } 46 ExprValidator { func, infer, sink }
47 } 47 }
48 48
49 pub fn validate_body(&mut self, db: &impl HirDatabase) { 49 pub fn validate_body(&mut self, db: &dyn HirDatabase) {
50 let body = db.body(self.func.into()); 50 let body = db.body(self.func.into());
51 51
52 for e in body.exprs.iter() { 52 for e in body.exprs.iter() {
@@ -67,7 +67,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
67 _path: &Option<Path>, 67 _path: &Option<Path>,
68 fields: &[RecordLitField], 68 fields: &[RecordLitField],
69 spread: Option<ExprId>, 69 spread: Option<ExprId>,
70 db: &impl HirDatabase, 70 db: &dyn HirDatabase,
71 ) { 71 ) {
72 if spread.is_some() { 72 if spread.is_some() {
73 return; 73 return;
@@ -80,7 +80,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
80 return; 80 return;
81 } 81 }
82 82
83 let variant_data = variant_data(db, variant_def); 83 let variant_data = variant_data(db.upcast(), variant_def);
84 84
85 let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); 85 let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
86 let missed_fields: Vec<Name> = variant_data 86 let missed_fields: Vec<Name> = variant_data
@@ -102,7 +102,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
102 102
103 if let Ok(source_ptr) = source_map.expr_syntax(id) { 103 if let Ok(source_ptr) = source_map.expr_syntax(id) {
104 if let Some(expr) = source_ptr.value.left() { 104 if let Some(expr) = source_ptr.value.left() {
105 let root = source_ptr.file_syntax(db); 105 let root = source_ptr.file_syntax(db.upcast());
106 if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) { 106 if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) {
107 if let Some(field_list) = record_lit.record_field_list() { 107 if let Some(field_list) = record_lit.record_field_list() {
108 self.sink.push(MissingFields { 108 self.sink.push(MissingFields {
@@ -116,12 +116,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
116 } 116 }
117 } 117 }
118 118
119 fn validate_results_in_tail_expr( 119 fn validate_results_in_tail_expr(&mut self, body_id: ExprId, id: ExprId, db: &dyn HirDatabase) {
120 &mut self,
121 body_id: ExprId,
122 id: ExprId,
123 db: &impl HirDatabase,
124 ) {
125 // the mismatch will be on the whole block currently 120 // the mismatch will be on the whole block currently
126 let mismatch = match self.infer.type_mismatch_for_expr(body_id) { 121 let mismatch = match self.infer.type_mismatch_for_expr(body_id) {
127 Some(m) => m, 122 Some(m) => m,
@@ -130,8 +125,8 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
130 125
131 let std_result_path = path![std::result::Result]; 126 let std_result_path = path![std::result::Result];
132 127
133 let resolver = self.func.resolver(db); 128 let resolver = self.func.resolver(db.upcast());
134 let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { 129 let std_result_enum = match resolver.resolve_known_enum(db.upcast(), &std_result_path) {
135 Some(it) => it, 130 Some(it) => it,
136 _ => return, 131 _ => return,
137 }; 132 };
diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs
index 947833412..246b0e9be 100644
--- a/crates/ra_hir_ty/src/infer.rs
+++ b/crates/ra_hir_ty/src/infer.rs
@@ -63,9 +63,9 @@ mod pat;
63mod coerce; 63mod coerce;
64 64
65/// The entry point of type inference. 65/// The entry point of type inference.
66pub(crate) fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> { 66pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
67 let _p = profile("infer_query"); 67 let _p = profile("infer_query");
68 let resolver = def.resolver(db); 68 let resolver = def.resolver(db.upcast());
69 let mut ctx = InferenceContext::new(db, def, resolver); 69 let mut ctx = InferenceContext::new(db, def, resolver);
70 70
71 match def { 71 match def {
@@ -164,7 +164,7 @@ impl InferenceResult {
164 } 164 }
165 pub fn add_diagnostics( 165 pub fn add_diagnostics(
166 &self, 166 &self,
167 db: &impl HirDatabase, 167 db: &dyn HirDatabase,
168 owner: FunctionId, 168 owner: FunctionId,
169 sink: &mut DiagnosticSink, 169 sink: &mut DiagnosticSink,
170 ) { 170 ) {
@@ -190,8 +190,8 @@ impl Index<PatId> for InferenceResult {
190 190
191/// The inference context contains all information needed during type inference. 191/// The inference context contains all information needed during type inference.
192#[derive(Clone, Debug)] 192#[derive(Clone, Debug)]
193struct InferenceContext<'a, D: HirDatabase> { 193struct InferenceContext<'a> {
194 db: &'a D, 194 db: &'a dyn HirDatabase,
195 owner: DefWithBodyId, 195 owner: DefWithBodyId,
196 body: Arc<Body>, 196 body: Arc<Body>,
197 resolver: Resolver, 197 resolver: Resolver,
@@ -208,8 +208,8 @@ struct InferenceContext<'a, D: HirDatabase> {
208 return_ty: Ty, 208 return_ty: Ty,
209} 209}
210 210
211impl<'a, D: HirDatabase> InferenceContext<'a, D> { 211impl<'a> InferenceContext<'a> {
212 fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self { 212 fn new(db: &'a dyn HirDatabase, owner: DefWithBodyId, resolver: Resolver) -> Self {
213 InferenceContext { 213 InferenceContext {
214 result: InferenceResult::default(), 214 result: InferenceResult::default(),
215 table: unify::InferenceTable::new(), 215 table: unify::InferenceTable::new(),
@@ -425,7 +425,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
425 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 425 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
426 // FIXME: this should resolve assoc items as well, see this example: 426 // FIXME: this should resolve assoc items as well, see this example:
427 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 427 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
428 return match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) { 428 return match resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path()) {
429 Some(TypeNs::AdtId(AdtId::StructId(strukt))) => { 429 Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
430 let substs = Ty::substs_from_path(&ctx, path, strukt.into()); 430 let substs = Ty::substs_from_path(&ctx, path, strukt.into());
431 let ty = self.db.ty(strukt.into()); 431 let ty = self.db.ty(strukt.into());
@@ -439,7 +439,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
439 (ty, Some(var.into())) 439 (ty, Some(var.into()))
440 } 440 }
441 Some(TypeNs::SelfType(impl_id)) => { 441 Some(TypeNs::SelfType(impl_id)) => {
442 let generics = crate::utils::generics(self.db, impl_id.into()); 442 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
443 let substs = Substs::type_params_for_generics(&generics); 443 let substs = Substs::type_params_for_generics(&generics);
444 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 444 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
445 let variant = ty_variant(&ty); 445 let variant = ty_variant(&ty);
@@ -500,13 +500,13 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
500 500
501 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> { 501 fn resolve_into_iter_item(&self) -> Option<TypeAliasId> {
502 let path = path![std::iter::IntoIterator]; 502 let path = path![std::iter::IntoIterator];
503 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; 503 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
504 self.db.trait_data(trait_).associated_type_by_name(&name![Item]) 504 self.db.trait_data(trait_).associated_type_by_name(&name![Item])
505 } 505 }
506 506
507 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> { 507 fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> {
508 let path = path![std::ops::Try]; 508 let path = path![std::ops::Try];
509 let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; 509 let trait_ = self.resolver.resolve_known_trait(self.db.upcast(), &path)?;
510 self.db.trait_data(trait_).associated_type_by_name(&name![Ok]) 510 self.db.trait_data(trait_).associated_type_by_name(&name![Ok])
511 } 511 }
512 512
@@ -532,37 +532,37 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
532 532
533 fn resolve_range_full(&self) -> Option<AdtId> { 533 fn resolve_range_full(&self) -> Option<AdtId> {
534 let path = path![std::ops::RangeFull]; 534 let path = path![std::ops::RangeFull];
535 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 535 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
536 Some(struct_.into()) 536 Some(struct_.into())
537 } 537 }
538 538
539 fn resolve_range(&self) -> Option<AdtId> { 539 fn resolve_range(&self) -> Option<AdtId> {
540 let path = path![std::ops::Range]; 540 let path = path![std::ops::Range];
541 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 541 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
542 Some(struct_.into()) 542 Some(struct_.into())
543 } 543 }
544 544
545 fn resolve_range_inclusive(&self) -> Option<AdtId> { 545 fn resolve_range_inclusive(&self) -> Option<AdtId> {
546 let path = path![std::ops::RangeInclusive]; 546 let path = path![std::ops::RangeInclusive];
547 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 547 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
548 Some(struct_.into()) 548 Some(struct_.into())
549 } 549 }
550 550
551 fn resolve_range_from(&self) -> Option<AdtId> { 551 fn resolve_range_from(&self) -> Option<AdtId> {
552 let path = path![std::ops::RangeFrom]; 552 let path = path![std::ops::RangeFrom];
553 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 553 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
554 Some(struct_.into()) 554 Some(struct_.into())
555 } 555 }
556 556
557 fn resolve_range_to(&self) -> Option<AdtId> { 557 fn resolve_range_to(&self) -> Option<AdtId> {
558 let path = path![std::ops::RangeTo]; 558 let path = path![std::ops::RangeTo];
559 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 559 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
560 Some(struct_.into()) 560 Some(struct_.into())
561 } 561 }
562 562
563 fn resolve_range_to_inclusive(&self) -> Option<AdtId> { 563 fn resolve_range_to_inclusive(&self) -> Option<AdtId> {
564 let path = path![std::ops::RangeToInclusive]; 564 let path = path![std::ops::RangeToInclusive];
565 let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; 565 let struct_ = self.resolver.resolve_known_struct(self.db.upcast(), &path)?;
566 Some(struct_.into()) 566 Some(struct_.into())
567 } 567 }
568 568
@@ -676,13 +676,13 @@ mod diagnostics {
676 impl InferenceDiagnostic { 676 impl InferenceDiagnostic {
677 pub(super) fn add_to( 677 pub(super) fn add_to(
678 &self, 678 &self,
679 db: &impl HirDatabase, 679 db: &dyn HirDatabase,
680 owner: FunctionId, 680 owner: FunctionId,
681 sink: &mut DiagnosticSink, 681 sink: &mut DiagnosticSink,
682 ) { 682 ) {
683 match self { 683 match self {
684 InferenceDiagnostic::NoSuchField { expr, field } => { 684 InferenceDiagnostic::NoSuchField { expr, field } => {
685 let file = owner.lookup(db).source(db).file_id; 685 let file = owner.lookup(db.upcast()).source(db.upcast()).file_id;
686 let (_, source_map) = db.body_with_source_map(owner.into()); 686 let (_, source_map) = db.body_with_source_map(owner.into());
687 let field = source_map.field_syntax(*expr, *field); 687 let field = source_map.field_syntax(*expr, *field);
688 sink.push(NoSuchField { file, field }) 688 sink.push(NoSuchField { file, field })
diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs
index 95ac3c713..959b1e212 100644
--- a/crates/ra_hir_ty/src/infer/coerce.rs
+++ b/crates/ra_hir_ty/src/infer/coerce.rs
@@ -7,13 +7,11 @@
7use hir_def::{lang_item::LangItemTarget, type_ref::Mutability}; 7use hir_def::{lang_item::LangItemTarget, type_ref::Mutability};
8use test_utils::tested_by; 8use test_utils::tested_by;
9 9
10use crate::{ 10use crate::{autoderef, traits::Solution, Obligation, Substs, TraitRef, Ty, TypeCtor};
11 autoderef, db::HirDatabase, traits::Solution, Obligation, Substs, TraitRef, Ty, TypeCtor,
12};
13 11
14use super::{unify::TypeVarValue, InEnvironment, InferTy, InferenceContext}; 12use super::{unify::TypeVarValue, InEnvironment, InferTy, InferenceContext};
15 13
16impl<'a, D: HirDatabase> InferenceContext<'a, D> { 14impl<'a> InferenceContext<'a> {
17 /// Unify two types, but may coerce the first one to the second one 15 /// Unify two types, but may coerce the first one to the second one
18 /// using "implicit coercion rules" if needed. 16 /// using "implicit coercion rules" if needed.
19 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { 17 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
@@ -126,7 +124,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
126 _ => return None, 124 _ => return None,
127 }; 125 };
128 126
129 let generic_params = crate::utils::generics(self.db, coerce_unsized_trait.into()); 127 let generic_params = crate::utils::generics(self.db.upcast(), coerce_unsized_trait.into());
130 if generic_params.len() != 2 { 128 if generic_params.len() != 2 {
131 // The CoerceUnsized trait should have two generic params: Self and T. 129 // The CoerceUnsized trait should have two generic params: Self and T.
132 return None; 130 return None;
diff --git a/crates/ra_hir_ty/src/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs
index e89cc7298..1fdb235a0 100644
--- a/crates/ra_hir_ty/src/infer/expr.rs
+++ b/crates/ra_hir_ty/src/infer/expr.rs
@@ -14,9 +14,7 @@ use hir_expand::name::Name;
14use ra_syntax::ast::RangeOp; 14use ra_syntax::ast::RangeOp;
15 15
16use crate::{ 16use crate::{
17 autoderef, 17 autoderef, method_resolution, op,
18 db::HirDatabase,
19 method_resolution, op,
20 traits::InEnvironment, 18 traits::InEnvironment,
21 utils::{generics, variant_data, Generics}, 19 utils::{generics, variant_data, Generics},
22 ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef, 20 ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef,
@@ -25,7 +23,7 @@ use crate::{
25 23
26use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; 24use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
27 25
28impl<'a, D: HirDatabase> InferenceContext<'a, D> { 26impl<'a> InferenceContext<'a> {
29 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { 27 pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
30 let ty = self.infer_expr_inner(tgt_expr, expected); 28 let ty = self.infer_expr_inner(tgt_expr, expected);
31 let could_unify = self.unify(&ty, &expected.ty); 29 let could_unify = self.unify(&ty, &expected.ty);
@@ -184,7 +182,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
184 } 182 }
185 Expr::Path(p) => { 183 Expr::Path(p) => {
186 // FIXME this could be more efficient... 184 // FIXME this could be more efficient...
187 let resolver = resolver_for_expr(self.db, self.owner, tgt_expr); 185 let resolver = resolver_for_expr(self.db.upcast(), self.owner, tgt_expr);
188 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) 186 self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown)
189 } 187 }
190 Expr::Continue => Ty::simple(TypeCtor::Never), 188 Expr::Continue => Ty::simple(TypeCtor::Never),
@@ -214,7 +212,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
214 212
215 let substs = ty.substs().unwrap_or_else(Substs::empty); 213 let substs = ty.substs().unwrap_or_else(Substs::empty);
216 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default(); 214 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
217 let variant_data = def_id.map(|it| variant_data(self.db, it)); 215 let variant_data = def_id.map(|it| variant_data(self.db.upcast(), it));
218 for (field_idx, field) in fields.iter().enumerate() { 216 for (field_idx, field) in fields.iter().enumerate() {
219 let field_def = 217 let field_def =
220 variant_data.as_ref().and_then(|it| match it.field(&field.name) { 218 variant_data.as_ref().and_then(|it| match it.field(&field.name) {
@@ -579,7 +577,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
579 let receiver_ty = self.infer_expr(receiver, &Expectation::none()); 577 let receiver_ty = self.infer_expr(receiver, &Expectation::none());
580 let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); 578 let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone());
581 579
582 let traits_in_scope = self.resolver.traits_in_scope(self.db); 580 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
583 581
584 let resolved = self.resolver.krate().and_then(|krate| { 582 let resolved = self.resolver.krate().and_then(|krate| {
585 method_resolution::lookup_method( 583 method_resolution::lookup_method(
@@ -595,7 +593,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
595 Some((ty, func)) => { 593 Some((ty, func)) => {
596 let ty = canonicalized_receiver.decanonicalize_ty(ty); 594 let ty = canonicalized_receiver.decanonicalize_ty(ty);
597 self.write_method_resolution(tgt_expr, func); 595 self.write_method_resolution(tgt_expr, func);
598 (ty, self.db.value_ty(func.into()), Some(generics(self.db, func.into()))) 596 (ty, self.db.value_ty(func.into()), Some(generics(self.db.upcast(), func.into())))
599 } 597 }
600 None => (receiver_ty, Binders::new(0, Ty::Unknown), None), 598 None => (receiver_ty, Binders::new(0, Ty::Unknown), None),
601 }; 599 };
@@ -703,10 +701,13 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
703 // add obligation for trait implementation, if this is a trait method 701 // add obligation for trait implementation, if this is a trait method
704 match def { 702 match def {
705 CallableDef::FunctionId(f) => { 703 CallableDef::FunctionId(f) => {
706 if let AssocContainerId::TraitId(trait_) = f.lookup(self.db).container { 704 if let AssocContainerId::TraitId(trait_) =
705 f.lookup(self.db.upcast()).container
706 {
707 // construct a TraitDef 707 // construct a TraitDef
708 let substs = 708 let substs = a_ty
709 a_ty.parameters.prefix(generics(self.db, trait_.into()).len()); 709 .parameters
710 .prefix(generics(self.db.upcast(), trait_.into()).len());
710 self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); 711 self.obligations.push(Obligation::Trait(TraitRef { trait_, substs }));
711 } 712 }
712 } 713 }
diff --git a/crates/ra_hir_ty/src/infer/pat.rs b/crates/ra_hir_ty/src/infer/pat.rs
index 7a84e47f8..baed6225b 100644
--- a/crates/ra_hir_ty/src/infer/pat.rs
+++ b/crates/ra_hir_ty/src/infer/pat.rs
@@ -12,9 +12,9 @@ use hir_expand::name::Name;
12use test_utils::tested_by; 12use test_utils::tested_by;
13 13
14use super::{BindingMode, InferenceContext}; 14use super::{BindingMode, InferenceContext};
15use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor}; 15use crate::{utils::variant_data, Substs, Ty, TypeCtor};
16 16
17impl<'a, D: HirDatabase> InferenceContext<'a, D> { 17impl<'a> InferenceContext<'a> {
18 fn infer_tuple_struct_pat( 18 fn infer_tuple_struct_pat(
19 &mut self, 19 &mut self,
20 path: Option<&Path>, 20 path: Option<&Path>,
@@ -23,7 +23,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
23 default_bm: BindingMode, 23 default_bm: BindingMode,
24 ) -> Ty { 24 ) -> Ty {
25 let (ty, def) = self.resolve_variant(path); 25 let (ty, def) = self.resolve_variant(path);
26 let var_data = def.map(|it| variant_data(self.db, it)); 26 let var_data = def.map(|it| variant_data(self.db.upcast(), it));
27 self.unify(&ty, expected); 27 self.unify(&ty, expected);
28 28
29 let substs = ty.substs().unwrap_or_else(Substs::empty); 29 let substs = ty.substs().unwrap_or_else(Substs::empty);
@@ -51,7 +51,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
51 id: PatId, 51 id: PatId,
52 ) -> Ty { 52 ) -> Ty {
53 let (ty, def) = self.resolve_variant(path); 53 let (ty, def) = self.resolve_variant(path);
54 let var_data = def.map(|it| variant_data(self.db, it)); 54 let var_data = def.map(|it| variant_data(self.db.upcast(), it));
55 if let Some(variant) = def { 55 if let Some(variant) = def {
56 self.write_variant_resolution(id.into(), variant); 56 self.write_variant_resolution(id.into(), variant);
57 } 57 }
diff --git a/crates/ra_hir_ty/src/infer/path.rs b/crates/ra_hir_ty/src/infer/path.rs
index c733b9e1d..318652c61 100644
--- a/crates/ra_hir_ty/src/infer/path.rs
+++ b/crates/ra_hir_ty/src/infer/path.rs
@@ -9,11 +9,11 @@ use hir_def::{
9}; 9};
10use hir_expand::name::Name; 10use hir_expand::name::Name;
11 11
12use crate::{db::HirDatabase, method_resolution, Substs, Ty, ValueTyDefId}; 12use crate::{method_resolution, Substs, Ty, ValueTyDefId};
13 13
14use super::{ExprOrPatId, InferenceContext, TraitRef}; 14use super::{ExprOrPatId, InferenceContext, TraitRef};
15 15
16impl<'a, D: HirDatabase> InferenceContext<'a, D> { 16impl<'a> InferenceContext<'a> {
17 pub(super) fn infer_path( 17 pub(super) fn infer_path(
18 &mut self, 18 &mut self,
19 resolver: &Resolver, 19 resolver: &Resolver,
@@ -47,7 +47,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
47 id, 47 id,
48 )? 48 )?
49 } else { 49 } else {
50 let value_or_partial = resolver.resolve_path_in_value_ns(self.db, path.mod_path())?; 50 let value_or_partial =
51 resolver.resolve_path_in_value_ns(self.db.upcast(), path.mod_path())?;
51 52
52 match value_or_partial { 53 match value_or_partial {
53 ResolveValueResult::ValueNs(it) => (it, None), 54 ResolveValueResult::ValueNs(it) => (it, None),
@@ -192,7 +193,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
192 193
193 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); 194 let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
194 let krate = self.resolver.krate()?; 195 let krate = self.resolver.krate()?;
195 let traits_in_scope = self.resolver.traits_in_scope(self.db); 196 let traits_in_scope = self.resolver.traits_in_scope(self.db.upcast());
196 197
197 method_resolution::iterate_method_candidates( 198 method_resolution::iterate_method_candidates(
198 &canonical_ty.value, 199 &canonical_ty.value,
@@ -205,9 +206,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
205 move |_ty, item| { 206 move |_ty, item| {
206 let (def, container) = match item { 207 let (def, container) = match item {
207 AssocItemId::FunctionId(f) => { 208 AssocItemId::FunctionId(f) => {
208 (ValueNs::FunctionId(f), f.lookup(self.db).container) 209 (ValueNs::FunctionId(f), f.lookup(self.db.upcast()).container)
210 }
211 AssocItemId::ConstId(c) => {
212 (ValueNs::ConstId(c), c.lookup(self.db.upcast()).container)
209 } 213 }
210 AssocItemId::ConstId(c) => (ValueNs::ConstId(c), c.lookup(self.db).container),
211 AssocItemId::TypeAliasId(_) => unreachable!(), 214 AssocItemId::TypeAliasId(_) => unreachable!(),
212 }; 215 };
213 let substs = match container { 216 let substs = match container {
diff --git a/crates/ra_hir_ty/src/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs
index 82b85d570..0bf8fbd63 100644
--- a/crates/ra_hir_ty/src/infer/unify.rs
+++ b/crates/ra_hir_ty/src/infer/unify.rs
@@ -7,10 +7,10 @@ use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
7use test_utils::tested_by; 7use test_utils::tested_by;
8 8
9use super::{InferenceContext, Obligation}; 9use super::{InferenceContext, Obligation};
10use crate::{db::HirDatabase, Canonical, InEnvironment, InferTy, Substs, Ty, TypeCtor, TypeWalk}; 10use crate::{Canonical, InEnvironment, InferTy, Substs, Ty, TypeCtor, TypeWalk};
11 11
12impl<'a, D: HirDatabase> InferenceContext<'a, D> { 12impl<'a> InferenceContext<'a> {
13 pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> 13 pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b>
14 where 14 where
15 'a: 'b, 15 'a: 'b,
16 { 16 {
@@ -18,11 +18,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
18 } 18 }
19} 19}
20 20
21pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> 21pub(super) struct Canonicalizer<'a, 'b>
22where 22where
23 'a: 'b, 23 'a: 'b,
24{ 24{
25 ctx: &'b mut InferenceContext<'a, D>, 25 ctx: &'b mut InferenceContext<'a>,
26 free_vars: Vec<InferTy>, 26 free_vars: Vec<InferTy>,
27 /// A stack of type variables that is used to detect recursive types (which 27 /// A stack of type variables that is used to detect recursive types (which
28 /// are an error, but we need to protect against them to avoid stack 28 /// are an error, but we need to protect against them to avoid stack
@@ -35,7 +35,7 @@ pub(super) struct Canonicalized<T> {
35 free_vars: Vec<InferTy>, 35 free_vars: Vec<InferTy>,
36} 36}
37 37
38impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> 38impl<'a, 'b> Canonicalizer<'a, 'b>
39where 39where
40 'a: 'b, 40 'a: 'b,
41{ 41{
@@ -123,11 +123,7 @@ impl<T> Canonicalized<T> {
123 ty 123 ty
124 } 124 }
125 125
126 pub fn apply_solution( 126 pub fn apply_solution(&self, ctx: &mut InferenceContext<'_>, solution: Canonical<Vec<Ty>>) {
127 &self,
128 ctx: &mut InferenceContext<'_, impl HirDatabase>,
129 solution: Canonical<Vec<Ty>>,
130 ) {
131 // the solution may contain new variables, which we need to convert to new inference vars 127 // the solution may contain new variables, which we need to convert to new inference vars
132 let new_vars = Substs((0..solution.num_vars).map(|_| ctx.table.new_type_var()).collect()); 128 let new_vars = Substs((0..solution.num_vars).map(|_| ctx.table.new_type_var()).collect());
133 for (i, ty) in solution.value.into_iter().enumerate() { 129 for (i, ty) in solution.value.into_iter().enumerate() {
diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs
index 4127f1a8d..6c5469ecd 100644
--- a/crates/ra_hir_ty/src/lib.rs
+++ b/crates/ra_hir_ty/src/lib.rs
@@ -152,7 +152,7 @@ pub struct TypeCtorId(salsa::InternId);
152impl_intern_key!(TypeCtorId); 152impl_intern_key!(TypeCtorId);
153 153
154impl TypeCtor { 154impl TypeCtor {
155 pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { 155 pub fn num_ty_params(self, db: &dyn HirDatabase) -> usize {
156 match self { 156 match self {
157 TypeCtor::Bool 157 TypeCtor::Bool
158 | TypeCtor::Char 158 | TypeCtor::Char
@@ -167,15 +167,15 @@ impl TypeCtor {
167 | TypeCtor::Closure { .. } // 1 param representing the signature of the closure 167 | TypeCtor::Closure { .. } // 1 param representing the signature of the closure
168 => 1, 168 => 1,
169 TypeCtor::Adt(adt) => { 169 TypeCtor::Adt(adt) => {
170 let generic_params = generics(db, adt.into()); 170 let generic_params = generics(db.upcast(), adt.into());
171 generic_params.len() 171 generic_params.len()
172 } 172 }
173 TypeCtor::FnDef(callable) => { 173 TypeCtor::FnDef(callable) => {
174 let generic_params = generics(db, callable.into()); 174 let generic_params = generics(db.upcast(), callable.into());
175 generic_params.len() 175 generic_params.len()
176 } 176 }
177 TypeCtor::AssociatedType(type_alias) => { 177 TypeCtor::AssociatedType(type_alias) => {
178 let generic_params = generics(db, type_alias.into()); 178 let generic_params = generics(db.upcast(), type_alias.into());
179 generic_params.len() 179 generic_params.len()
180 } 180 }
181 TypeCtor::FnPtr { num_args } => num_args as usize + 1, 181 TypeCtor::FnPtr { num_args } => num_args as usize + 1,
@@ -183,7 +183,7 @@ impl TypeCtor {
183 } 183 }
184 } 184 }
185 185
186 pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> { 186 pub fn krate(self, db: &dyn HirDatabase) -> Option<CrateId> {
187 match self { 187 match self {
188 TypeCtor::Bool 188 TypeCtor::Bool
189 | TypeCtor::Char 189 | TypeCtor::Char
@@ -199,9 +199,11 @@ impl TypeCtor {
199 | TypeCtor::Tuple { .. } => None, 199 | TypeCtor::Tuple { .. } => None,
200 // Closure's krate is irrelevant for coherence I would think? 200 // Closure's krate is irrelevant for coherence I would think?
201 TypeCtor::Closure { .. } => None, 201 TypeCtor::Closure { .. } => None,
202 TypeCtor::Adt(adt) => Some(adt.module(db).krate), 202 TypeCtor::Adt(adt) => Some(adt.module(db.upcast()).krate),
203 TypeCtor::FnDef(callable) => Some(callable.krate(db)), 203 TypeCtor::FnDef(callable) => Some(callable.krate(db)),
204 TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate), 204 TypeCtor::AssociatedType(type_alias) => {
205 Some(type_alias.lookup(db.upcast()).module(db.upcast()).krate)
206 }
205 } 207 }
206 } 208 }
207 209
@@ -246,12 +248,12 @@ pub struct ProjectionTy {
246} 248}
247 249
248impl ProjectionTy { 250impl ProjectionTy {
249 pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { 251 pub fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
250 TraitRef { trait_: self.trait_(db), substs: self.parameters.clone() } 252 TraitRef { trait_: self.trait_(db), substs: self.parameters.clone() }
251 } 253 }
252 254
253 fn trait_(&self, db: &impl HirDatabase) -> TraitId { 255 fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
254 match self.associated_ty.lookup(db).container { 256 match self.associated_ty.lookup(db.upcast()).container {
255 AssocContainerId::TraitId(it) => it, 257 AssocContainerId::TraitId(it) => it,
256 _ => panic!("projection ty without parent trait"), 258 _ => panic!("projection ty without parent trait"),
257 } 259 }
@@ -372,8 +374,8 @@ impl Substs {
372 } 374 }
373 375
374 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 376 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
375 pub fn type_params(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> Substs { 377 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs {
376 let params = generics(db, def.into()); 378 let params = generics(db.upcast(), def.into());
377 Substs::type_params_for_generics(&params) 379 Substs::type_params_for_generics(&params)
378 } 380 }
379 381
@@ -382,9 +384,9 @@ impl Substs {
382 Substs(generic_params.iter().enumerate().map(|(idx, _)| Ty::Bound(idx as u32)).collect()) 384 Substs(generic_params.iter().enumerate().map(|(idx, _)| Ty::Bound(idx as u32)).collect())
383 } 385 }
384 386
385 pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder { 387 pub fn build_for_def(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder {
386 let def = def.into(); 388 let def = def.into();
387 let params = generics(db, def); 389 let params = generics(db.upcast(), def);
388 let param_count = params.len(); 390 let param_count = params.len();
389 Substs::builder(param_count) 391 Substs::builder(param_count)
390 } 392 }
@@ -393,7 +395,7 @@ impl Substs {
393 Substs::builder(generic_params.len()) 395 Substs::builder(generic_params.len())
394 } 396 }
395 397
396 pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { 398 pub fn build_for_type_ctor(db: &dyn HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder {
397 Substs::builder(type_ctor.num_ty_params(db)) 399 Substs::builder(type_ctor.num_ty_params(db))
398 } 400 }
399 401
@@ -538,7 +540,7 @@ impl GenericPredicate {
538 } 540 }
539 } 541 }
540 542
541 pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { 543 pub fn trait_ref(&self, db: &dyn HirDatabase) -> Option<TraitRef> {
542 match self { 544 match self {
543 GenericPredicate::Implemented(tr) => Some(tr.clone()), 545 GenericPredicate::Implemented(tr) => Some(tr.clone()),
544 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), 546 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
@@ -693,7 +695,7 @@ impl Ty {
693 } 695 }
694 } 696 }
695 697
696 fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> { 698 fn callable_sig(&self, db: &dyn HirDatabase) -> Option<FnSig> {
697 match self { 699 match self {
698 Ty::Apply(a_ty) => match a_ty.ctor { 700 Ty::Apply(a_ty) => match a_ty.ctor {
699 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), 701 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)),
diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs
index b96dc126c..d7f250783 100644
--- a/crates/ra_hir_ty/src/lower.rs
+++ b/crates/ra_hir_ty/src/lower.rs
@@ -34,8 +34,8 @@ use crate::{
34}; 34};
35 35
36#[derive(Debug)] 36#[derive(Debug)]
37pub struct TyLoweringContext<'a, DB: HirDatabase> { 37pub struct TyLoweringContext<'a> {
38 pub db: &'a DB, 38 pub db: &'a dyn HirDatabase,
39 pub resolver: &'a Resolver, 39 pub resolver: &'a Resolver,
40 /// Note: Conceptually, it's thinkable that we could be in a location where 40 /// Note: Conceptually, it's thinkable that we could be in a location where
41 /// some type params should be represented as placeholders, and others 41 /// some type params should be represented as placeholders, and others
@@ -46,8 +46,8 @@ pub struct TyLoweringContext<'a, DB: HirDatabase> {
46 pub impl_trait_counter: std::cell::Cell<u16>, 46 pub impl_trait_counter: std::cell::Cell<u16>,
47} 47}
48 48
49impl<'a, DB: HirDatabase> TyLoweringContext<'a, DB> { 49impl<'a> TyLoweringContext<'a> {
50 pub fn new(db: &'a DB, resolver: &'a Resolver) -> Self { 50 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
51 let impl_trait_counter = std::cell::Cell::new(0); 51 let impl_trait_counter = std::cell::Cell::new(0);
52 let impl_trait_mode = ImplTraitLoweringMode::Disallowed; 52 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
53 let type_param_mode = TypeParamLoweringMode::Placeholder; 53 let type_param_mode = TypeParamLoweringMode::Placeholder;
@@ -90,13 +90,10 @@ pub enum TypeParamLoweringMode {
90} 90}
91 91
92impl Ty { 92impl Ty {
93 pub fn from_hir(ctx: &TyLoweringContext<'_, impl HirDatabase>, type_ref: &TypeRef) -> Self { 93 pub fn from_hir(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Self {
94 Ty::from_hir_ext(ctx, type_ref).0 94 Ty::from_hir_ext(ctx, type_ref).0
95 } 95 }
96 pub fn from_hir_ext( 96 pub fn from_hir_ext(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> (Self, Option<TypeNs>) {
97 ctx: &TyLoweringContext<'_, impl HirDatabase>,
98 type_ref: &TypeRef,
99 ) -> (Self, Option<TypeNs>) {
100 let mut res = None; 97 let mut res = None;
101 let ty = match type_ref { 98 let ty = match type_ref {
102 TypeRef::Never => Ty::simple(TypeCtor::Never), 99 TypeRef::Never => Ty::simple(TypeCtor::Never),
@@ -157,7 +154,7 @@ impl Ty {
157 let idx = ctx.impl_trait_counter.get(); 154 let idx = ctx.impl_trait_counter.get();
158 ctx.impl_trait_counter.set(idx + 1); 155 ctx.impl_trait_counter.set(idx + 1);
159 if let Some(def) = ctx.resolver.generic_def() { 156 if let Some(def) = ctx.resolver.generic_def() {
160 let generics = generics(ctx.db, def); 157 let generics = generics(ctx.db.upcast(), def);
161 let param = generics 158 let param = generics
162 .iter() 159 .iter()
163 .filter(|(_, data)| { 160 .filter(|(_, data)| {
@@ -175,7 +172,7 @@ impl Ty {
175 ctx.impl_trait_counter.set(idx + 1); 172 ctx.impl_trait_counter.set(idx + 1);
176 let (parent_params, self_params, list_params, _impl_trait_params) = 173 let (parent_params, self_params, list_params, _impl_trait_params) =
177 if let Some(def) = ctx.resolver.generic_def() { 174 if let Some(def) = ctx.resolver.generic_def() {
178 let generics = generics(ctx.db, def); 175 let generics = generics(ctx.db.upcast(), def);
179 generics.provenance_split() 176 generics.provenance_split()
180 } else { 177 } else {
181 (0, 0, 0, 0) 178 (0, 0, 0, 0)
@@ -201,10 +198,7 @@ impl Ty {
201 /// This is only for `generic_predicates_for_param`, where we can't just 198 /// This is only for `generic_predicates_for_param`, where we can't just
202 /// lower the self types of the predicates since that could lead to cycles. 199 /// lower the self types of the predicates since that could lead to cycles.
203 /// So we just check here if the `type_ref` resolves to a generic param, and which. 200 /// So we just check here if the `type_ref` resolves to a generic param, and which.
204 fn from_hir_only_param( 201 fn from_hir_only_param(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Option<TypeParamId> {
205 ctx: &TyLoweringContext<'_, impl HirDatabase>,
206 type_ref: &TypeRef,
207 ) -> Option<TypeParamId> {
208 let path = match type_ref { 202 let path = match type_ref {
209 TypeRef::Path(path) => path, 203 TypeRef::Path(path) => path,
210 _ => return None, 204 _ => return None,
@@ -215,10 +209,11 @@ impl Ty {
215 if path.segments().len() > 1 { 209 if path.segments().len() > 1 {
216 return None; 210 return None;
217 } 211 }
218 let resolution = match ctx.resolver.resolve_path_in_type_ns(ctx.db, path.mod_path()) { 212 let resolution =
219 Some((it, None)) => it, 213 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) {
220 _ => return None, 214 Some((it, None)) => it,
221 }; 215 _ => return None,
216 };
222 if let TypeNs::GenericParam(param_id) = resolution { 217 if let TypeNs::GenericParam(param_id) = resolution {
223 Some(param_id) 218 Some(param_id)
224 } else { 219 } else {
@@ -227,7 +222,7 @@ impl Ty {
227 } 222 }
228 223
229 pub(crate) fn from_type_relative_path( 224 pub(crate) fn from_type_relative_path(
230 ctx: &TyLoweringContext<'_, impl HirDatabase>, 225 ctx: &TyLoweringContext<'_>,
231 ty: Ty, 226 ty: Ty,
232 // We need the original resolution to lower `Self::AssocTy` correctly 227 // We need the original resolution to lower `Self::AssocTy` correctly
233 res: Option<TypeNs>, 228 res: Option<TypeNs>,
@@ -246,7 +241,7 @@ impl Ty {
246 } 241 }
247 242
248 pub(crate) fn from_partly_resolved_hir_path( 243 pub(crate) fn from_partly_resolved_hir_path(
249 ctx: &TyLoweringContext<'_, impl HirDatabase>, 244 ctx: &TyLoweringContext<'_>,
250 resolution: TypeNs, 245 resolution: TypeNs,
251 resolved_segment: PathSegment<'_>, 246 resolved_segment: PathSegment<'_>,
252 remaining_segments: PathSegments<'_>, 247 remaining_segments: PathSegments<'_>,
@@ -260,7 +255,7 @@ impl Ty {
260 let ty = if remaining_segments.len() == 1 { 255 let ty = if remaining_segments.len() == 1 {
261 let segment = remaining_segments.first().unwrap(); 256 let segment = remaining_segments.first().unwrap();
262 let associated_ty = associated_type_by_name_including_super_traits( 257 let associated_ty = associated_type_by_name_including_super_traits(
263 ctx.db, 258 ctx.db.upcast(),
264 trait_ref.trait_, 259 trait_ref.trait_,
265 &segment.name, 260 &segment.name,
266 ); 261 );
@@ -286,8 +281,10 @@ impl Ty {
286 return (ty, None); 281 return (ty, None);
287 } 282 }
288 TypeNs::GenericParam(param_id) => { 283 TypeNs::GenericParam(param_id) => {
289 let generics = 284 let generics = generics(
290 generics(ctx.db, ctx.resolver.generic_def().expect("generics in scope")); 285 ctx.db.upcast(),
286 ctx.resolver.generic_def().expect("generics in scope"),
287 );
291 match ctx.type_param_mode { 288 match ctx.type_param_mode {
292 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id), 289 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id),
293 TypeParamLoweringMode::Variable => { 290 TypeParamLoweringMode::Variable => {
@@ -297,7 +294,7 @@ impl Ty {
297 } 294 }
298 } 295 }
299 TypeNs::SelfType(impl_id) => { 296 TypeNs::SelfType(impl_id) => {
300 let generics = generics(ctx.db, impl_id.into()); 297 let generics = generics(ctx.db.upcast(), impl_id.into());
301 let substs = match ctx.type_param_mode { 298 let substs = match ctx.type_param_mode {
302 TypeParamLoweringMode::Placeholder => { 299 TypeParamLoweringMode::Placeholder => {
303 Substs::type_params_for_generics(&generics) 300 Substs::type_params_for_generics(&generics)
@@ -307,7 +304,7 @@ impl Ty {
307 ctx.db.impl_self_ty(impl_id).subst(&substs) 304 ctx.db.impl_self_ty(impl_id).subst(&substs)
308 } 305 }
309 TypeNs::AdtSelfType(adt) => { 306 TypeNs::AdtSelfType(adt) => {
310 let generics = generics(ctx.db, adt.into()); 307 let generics = generics(ctx.db.upcast(), adt.into());
311 let substs = match ctx.type_param_mode { 308 let substs = match ctx.type_param_mode {
312 TypeParamLoweringMode::Placeholder => { 309 TypeParamLoweringMode::Placeholder => {
313 Substs::type_params_for_generics(&generics) 310 Substs::type_params_for_generics(&generics)
@@ -327,17 +324,14 @@ impl Ty {
327 Ty::from_type_relative_path(ctx, ty, Some(resolution), remaining_segments) 324 Ty::from_type_relative_path(ctx, ty, Some(resolution), remaining_segments)
328 } 325 }
329 326
330 pub(crate) fn from_hir_path( 327 pub(crate) fn from_hir_path(ctx: &TyLoweringContext<'_>, path: &Path) -> (Ty, Option<TypeNs>) {
331 ctx: &TyLoweringContext<'_, impl HirDatabase>,
332 path: &Path,
333 ) -> (Ty, Option<TypeNs>) {
334 // Resolve the path (in type namespace) 328 // Resolve the path (in type namespace)
335 if let Some(type_ref) = path.type_anchor() { 329 if let Some(type_ref) = path.type_anchor() {
336 let (ty, res) = Ty::from_hir_ext(ctx, &type_ref); 330 let (ty, res) = Ty::from_hir_ext(ctx, &type_ref);
337 return Ty::from_type_relative_path(ctx, ty, res, path.segments()); 331 return Ty::from_type_relative_path(ctx, ty, res, path.segments());
338 } 332 }
339 let (resolution, remaining_index) = 333 let (resolution, remaining_index) =
340 match ctx.resolver.resolve_path_in_type_ns(ctx.db, path.mod_path()) { 334 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) {
341 Some(it) => it, 335 Some(it) => it,
342 None => return (Ty::Unknown, None), 336 None => return (Ty::Unknown, None),
343 }; 337 };
@@ -352,7 +346,7 @@ impl Ty {
352 } 346 }
353 347
354 fn select_associated_type( 348 fn select_associated_type(
355 ctx: &TyLoweringContext<'_, impl HirDatabase>, 349 ctx: &TyLoweringContext<'_>,
356 self_ty: Ty, 350 self_ty: Ty,
357 res: Option<TypeNs>, 351 res: Option<TypeNs>,
358 segment: PathSegment<'_>, 352 segment: PathSegment<'_>,
@@ -374,7 +368,7 @@ impl Ty {
374 } 368 }
375 _ => return Ty::Unknown, 369 _ => return Ty::Unknown,
376 }; 370 };
377 let traits = traits_from_env.into_iter().flat_map(|t| all_super_traits(ctx.db, t)); 371 let traits = traits_from_env.into_iter().flat_map(|t| all_super_traits(ctx.db.upcast(), t));
378 for t in traits { 372 for t in traits {
379 if let Some(associated_ty) = ctx.db.trait_data(t).associated_type_by_name(&segment.name) 373 if let Some(associated_ty) = ctx.db.trait_data(t).associated_type_by_name(&segment.name)
380 { 374 {
@@ -388,7 +382,7 @@ impl Ty {
388 } 382 }
389 383
390 fn from_hir_path_inner( 384 fn from_hir_path_inner(
391 ctx: &TyLoweringContext<'_, impl HirDatabase>, 385 ctx: &TyLoweringContext<'_>,
392 segment: PathSegment<'_>, 386 segment: PathSegment<'_>,
393 typable: TyDefId, 387 typable: TyDefId,
394 ) -> Ty { 388 ) -> Ty {
@@ -404,7 +398,7 @@ impl Ty {
404 /// Collect generic arguments from a path into a `Substs`. See also 398 /// Collect generic arguments from a path into a `Substs`. See also
405 /// `create_substs_for_ast_path` and `def_to_ty` in rustc. 399 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
406 pub(super) fn substs_from_path( 400 pub(super) fn substs_from_path(
407 ctx: &TyLoweringContext<'_, impl HirDatabase>, 401 ctx: &TyLoweringContext<'_>,
408 path: &Path, 402 path: &Path,
409 // Note that we don't call `db.value_type(resolved)` here, 403 // Note that we don't call `db.value_type(resolved)` here,
410 // `ValueTyDefId` is just a convenient way to pass generics and 404 // `ValueTyDefId` is just a convenient way to pass generics and
@@ -437,13 +431,13 @@ impl Ty {
437} 431}
438 432
439pub(super) fn substs_from_path_segment( 433pub(super) fn substs_from_path_segment(
440 ctx: &TyLoweringContext<'_, impl HirDatabase>, 434 ctx: &TyLoweringContext<'_>,
441 segment: PathSegment<'_>, 435 segment: PathSegment<'_>,
442 def_generic: Option<GenericDefId>, 436 def_generic: Option<GenericDefId>,
443 _add_self_param: bool, 437 _add_self_param: bool,
444) -> Substs { 438) -> Substs {
445 let mut substs = Vec::new(); 439 let mut substs = Vec::new();
446 let def_generics = def_generic.map(|def| generics(ctx.db, def)); 440 let def_generics = def_generic.map(|def| generics(ctx.db.upcast(), def));
447 441
448 let (parent_params, self_params, type_params, impl_trait_params) = 442 let (parent_params, self_params, type_params, impl_trait_params) =
449 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split()); 443 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
@@ -489,20 +483,21 @@ pub(super) fn substs_from_path_segment(
489 483
490impl TraitRef { 484impl TraitRef {
491 fn from_path( 485 fn from_path(
492 ctx: &TyLoweringContext<'_, impl HirDatabase>, 486 ctx: &TyLoweringContext<'_>,
493 path: &Path, 487 path: &Path,
494 explicit_self_ty: Option<Ty>, 488 explicit_self_ty: Option<Ty>,
495 ) -> Option<Self> { 489 ) -> Option<Self> {
496 let resolved = match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db, path.mod_path())? { 490 let resolved =
497 TypeNs::TraitId(tr) => tr, 491 match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db.upcast(), path.mod_path())? {
498 _ => return None, 492 TypeNs::TraitId(tr) => tr,
499 }; 493 _ => return None,
494 };
500 let segment = path.segments().last().expect("path should have at least one segment"); 495 let segment = path.segments().last().expect("path should have at least one segment");
501 Some(TraitRef::from_resolved_path(ctx, resolved, segment, explicit_self_ty)) 496 Some(TraitRef::from_resolved_path(ctx, resolved, segment, explicit_self_ty))
502 } 497 }
503 498
504 pub(crate) fn from_resolved_path( 499 pub(crate) fn from_resolved_path(
505 ctx: &TyLoweringContext<'_, impl HirDatabase>, 500 ctx: &TyLoweringContext<'_>,
506 resolved: TraitId, 501 resolved: TraitId,
507 segment: PathSegment<'_>, 502 segment: PathSegment<'_>,
508 explicit_self_ty: Option<Ty>, 503 explicit_self_ty: Option<Ty>,
@@ -515,7 +510,7 @@ impl TraitRef {
515 } 510 }
516 511
517 fn from_hir( 512 fn from_hir(
518 ctx: &TyLoweringContext<'_, impl HirDatabase>, 513 ctx: &TyLoweringContext<'_>,
519 type_ref: &TypeRef, 514 type_ref: &TypeRef,
520 explicit_self_ty: Option<Ty>, 515 explicit_self_ty: Option<Ty>,
521 ) -> Option<Self> { 516 ) -> Option<Self> {
@@ -527,7 +522,7 @@ impl TraitRef {
527 } 522 }
528 523
529 fn substs_from_path( 524 fn substs_from_path(
530 ctx: &TyLoweringContext<'_, impl HirDatabase>, 525 ctx: &TyLoweringContext<'_>,
531 segment: PathSegment<'_>, 526 segment: PathSegment<'_>,
532 resolved: TraitId, 527 resolved: TraitId,
533 ) -> Substs { 528 ) -> Substs {
@@ -537,7 +532,7 @@ impl TraitRef {
537 } 532 }
538 533
539 pub(crate) fn from_type_bound( 534 pub(crate) fn from_type_bound(
540 ctx: &TyLoweringContext<'_, impl HirDatabase>, 535 ctx: &TyLoweringContext<'_>,
541 bound: &TypeBound, 536 bound: &TypeBound,
542 self_ty: Ty, 537 self_ty: Ty,
543 ) -> Option<TraitRef> { 538 ) -> Option<TraitRef> {
@@ -550,14 +545,14 @@ impl TraitRef {
550 545
551impl GenericPredicate { 546impl GenericPredicate {
552 pub(crate) fn from_where_predicate<'a>( 547 pub(crate) fn from_where_predicate<'a>(
553 ctx: &'a TyLoweringContext<'a, impl HirDatabase>, 548 ctx: &'a TyLoweringContext<'a>,
554 where_predicate: &'a WherePredicate, 549 where_predicate: &'a WherePredicate,
555 ) -> impl Iterator<Item = GenericPredicate> + 'a { 550 ) -> impl Iterator<Item = GenericPredicate> + 'a {
556 let self_ty = match &where_predicate.target { 551 let self_ty = match &where_predicate.target {
557 WherePredicateTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref), 552 WherePredicateTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref),
558 WherePredicateTarget::TypeParam(param_id) => { 553 WherePredicateTarget::TypeParam(param_id) => {
559 let generic_def = ctx.resolver.generic_def().expect("generics in scope"); 554 let generic_def = ctx.resolver.generic_def().expect("generics in scope");
560 let generics = generics(ctx.db, generic_def); 555 let generics = generics(ctx.db.upcast(), generic_def);
561 let param_id = hir_def::TypeParamId { parent: generic_def, local_id: *param_id }; 556 let param_id = hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
562 match ctx.type_param_mode { 557 match ctx.type_param_mode {
563 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id), 558 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id),
@@ -572,7 +567,7 @@ impl GenericPredicate {
572 } 567 }
573 568
574 pub(crate) fn from_type_bound<'a>( 569 pub(crate) fn from_type_bound<'a>(
575 ctx: &'a TyLoweringContext<'a, impl HirDatabase>, 570 ctx: &'a TyLoweringContext<'a>,
576 bound: &'a TypeBound, 571 bound: &'a TypeBound,
577 self_ty: Ty, 572 self_ty: Ty,
578 ) -> impl Iterator<Item = GenericPredicate> + 'a { 573 ) -> impl Iterator<Item = GenericPredicate> + 'a {
@@ -587,7 +582,7 @@ impl GenericPredicate {
587} 582}
588 583
589fn assoc_type_bindings_from_type_bound<'a>( 584fn assoc_type_bindings_from_type_bound<'a>(
590 ctx: &'a TyLoweringContext<'a, impl HirDatabase>, 585 ctx: &'a TyLoweringContext<'a>,
591 bound: &'a TypeBound, 586 bound: &'a TypeBound,
592 trait_ref: TraitRef, 587 trait_ref: TraitRef,
593) -> impl Iterator<Item = GenericPredicate> + 'a { 588) -> impl Iterator<Item = GenericPredicate> + 'a {
@@ -600,8 +595,11 @@ fn assoc_type_bindings_from_type_bound<'a>(
600 .flat_map(|segment| segment.args_and_bindings.into_iter()) 595 .flat_map(|segment| segment.args_and_bindings.into_iter())
601 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) 596 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
602 .map(move |(name, type_ref)| { 597 .map(move |(name, type_ref)| {
603 let associated_ty = 598 let associated_ty = associated_type_by_name_including_super_traits(
604 associated_type_by_name_including_super_traits(ctx.db, trait_ref.trait_, &name); 599 ctx.db.upcast(),
600 trait_ref.trait_,
601 &name,
602 );
605 let associated_ty = match associated_ty { 603 let associated_ty = match associated_ty {
606 None => return GenericPredicate::Error, 604 None => return GenericPredicate::Error,
607 Some(t) => t, 605 Some(t) => t,
@@ -615,7 +613,7 @@ fn assoc_type_bindings_from_type_bound<'a>(
615} 613}
616 614
617/// Build the signature of a callable item (function, struct or enum variant). 615/// Build the signature of a callable item (function, struct or enum variant).
618pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig { 616pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDef) -> PolyFnSig {
619 match def { 617 match def {
620 CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), 618 CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),
621 CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), 619 CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s),
@@ -625,16 +623,16 @@ pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig {
625 623
626/// Build the type of all specific fields of a struct or enum variant. 624/// Build the type of all specific fields of a struct or enum variant.
627pub(crate) fn field_types_query( 625pub(crate) fn field_types_query(
628 db: &impl HirDatabase, 626 db: &dyn HirDatabase,
629 variant_id: VariantId, 627 variant_id: VariantId,
630) -> Arc<ArenaMap<LocalStructFieldId, Binders<Ty>>> { 628) -> Arc<ArenaMap<LocalStructFieldId, Binders<Ty>>> {
631 let var_data = variant_data(db, variant_id); 629 let var_data = variant_data(db.upcast(), variant_id);
632 let (resolver, def): (_, GenericDefId) = match variant_id { 630 let (resolver, def): (_, GenericDefId) = match variant_id {
633 VariantId::StructId(it) => (it.resolver(db), it.into()), 631 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
634 VariantId::UnionId(it) => (it.resolver(db), it.into()), 632 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
635 VariantId::EnumVariantId(it) => (it.parent.resolver(db), it.parent.into()), 633 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
636 }; 634 };
637 let generics = generics(db, def); 635 let generics = generics(db.upcast(), def);
638 let mut res = ArenaMap::default(); 636 let mut res = ArenaMap::default();
639 let ctx = 637 let ctx =
640 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 638 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
@@ -653,13 +651,13 @@ pub(crate) fn field_types_query(
653/// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but 651/// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
654/// these are fine: `T: Foo<U::Item>, U: Foo<()>`. 652/// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
655pub(crate) fn generic_predicates_for_param_query( 653pub(crate) fn generic_predicates_for_param_query(
656 db: &impl HirDatabase, 654 db: &dyn HirDatabase,
657 param_id: TypeParamId, 655 param_id: TypeParamId,
658) -> Arc<[Binders<GenericPredicate>]> { 656) -> Arc<[Binders<GenericPredicate>]> {
659 let resolver = param_id.parent.resolver(db); 657 let resolver = param_id.parent.resolver(db.upcast());
660 let ctx = 658 let ctx =
661 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 659 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
662 let generics = generics(db, param_id.parent); 660 let generics = generics(db.upcast(), param_id.parent);
663 resolver 661 resolver
664 .where_predicates_in_scope() 662 .where_predicates_in_scope()
665 // we have to filter out all other predicates *first*, before attempting to lower them 663 // we have to filter out all other predicates *first*, before attempting to lower them
@@ -677,7 +675,7 @@ pub(crate) fn generic_predicates_for_param_query(
677} 675}
678 676
679pub(crate) fn generic_predicates_for_param_recover( 677pub(crate) fn generic_predicates_for_param_recover(
680 _db: &impl HirDatabase, 678 _db: &dyn HirDatabase,
681 _cycle: &[String], 679 _cycle: &[String],
682 _param_id: &TypeParamId, 680 _param_id: &TypeParamId,
683) -> Arc<[Binders<GenericPredicate>]> { 681) -> Arc<[Binders<GenericPredicate>]> {
@@ -685,7 +683,7 @@ pub(crate) fn generic_predicates_for_param_recover(
685} 683}
686 684
687impl TraitEnvironment { 685impl TraitEnvironment {
688 pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { 686 pub fn lower(db: &dyn HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
689 let ctx = TyLoweringContext::new(db, &resolver) 687 let ctx = TyLoweringContext::new(db, &resolver)
690 .with_type_param_mode(TypeParamLoweringMode::Placeholder); 688 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
691 let mut predicates = resolver 689 let mut predicates = resolver
@@ -696,13 +694,13 @@ impl TraitEnvironment {
696 if let Some(def) = resolver.generic_def() { 694 if let Some(def) = resolver.generic_def() {
697 let container: Option<AssocContainerId> = match def { 695 let container: Option<AssocContainerId> = match def {
698 // FIXME: is there a function for this? 696 // FIXME: is there a function for this?
699 GenericDefId::FunctionId(f) => Some(f.lookup(db).container), 697 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
700 GenericDefId::AdtId(_) => None, 698 GenericDefId::AdtId(_) => None,
701 GenericDefId::TraitId(_) => None, 699 GenericDefId::TraitId(_) => None,
702 GenericDefId::TypeAliasId(t) => Some(t.lookup(db).container), 700 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
703 GenericDefId::ImplId(_) => None, 701 GenericDefId::ImplId(_) => None,
704 GenericDefId::EnumVariantId(_) => None, 702 GenericDefId::EnumVariantId(_) => None,
705 GenericDefId::ConstId(c) => Some(c.lookup(db).container), 703 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
706 }; 704 };
707 if let Some(AssocContainerId::TraitId(trait_id)) = container { 705 if let Some(AssocContainerId::TraitId(trait_id)) = container {
708 // add `Self: Trait<T1, T2, ...>` to the environment in trait 706 // add `Self: Trait<T1, T2, ...>` to the environment in trait
@@ -723,13 +721,13 @@ impl TraitEnvironment {
723 721
724/// Resolve the where clause(s) of an item with generics. 722/// Resolve the where clause(s) of an item with generics.
725pub(crate) fn generic_predicates_query( 723pub(crate) fn generic_predicates_query(
726 db: &impl HirDatabase, 724 db: &dyn HirDatabase,
727 def: GenericDefId, 725 def: GenericDefId,
728) -> Arc<[Binders<GenericPredicate>]> { 726) -> Arc<[Binders<GenericPredicate>]> {
729 let resolver = def.resolver(db); 727 let resolver = def.resolver(db.upcast());
730 let ctx = 728 let ctx =
731 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 729 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
732 let generics = generics(db, def); 730 let generics = generics(db.upcast(), def);
733 resolver 731 resolver
734 .where_predicates_in_scope() 732 .where_predicates_in_scope()
735 .flat_map(|pred| { 733 .flat_map(|pred| {
@@ -740,10 +738,10 @@ pub(crate) fn generic_predicates_query(
740} 738}
741 739
742/// Resolve the default type params from generics 740/// Resolve the default type params from generics
743pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs { 741pub(crate) fn generic_defaults_query(db: &dyn HirDatabase, def: GenericDefId) -> Substs {
744 let resolver = def.resolver(db); 742 let resolver = def.resolver(db.upcast());
745 let ctx = TyLoweringContext::new(db, &resolver); 743 let ctx = TyLoweringContext::new(db, &resolver);
746 let generic_params = generics(db, def); 744 let generic_params = generics(db.upcast(), def);
747 745
748 let defaults = generic_params 746 let defaults = generic_params
749 .iter() 747 .iter()
@@ -753,33 +751,33 @@ pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -
753 Substs(defaults) 751 Substs(defaults)
754} 752}
755 753
756fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> PolyFnSig { 754fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
757 let data = db.function_data(def); 755 let data = db.function_data(def);
758 let resolver = def.resolver(db); 756 let resolver = def.resolver(db.upcast());
759 let ctx_params = TyLoweringContext::new(db, &resolver) 757 let ctx_params = TyLoweringContext::new(db, &resolver)
760 .with_impl_trait_mode(ImplTraitLoweringMode::Variable) 758 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
761 .with_type_param_mode(TypeParamLoweringMode::Variable); 759 .with_type_param_mode(TypeParamLoweringMode::Variable);
762 let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>(); 760 let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>();
763 let ctx_ret = ctx_params.with_impl_trait_mode(ImplTraitLoweringMode::Opaque); 761 let ctx_ret = ctx_params.with_impl_trait_mode(ImplTraitLoweringMode::Opaque);
764 let ret = Ty::from_hir(&ctx_ret, &data.ret_type); 762 let ret = Ty::from_hir(&ctx_ret, &data.ret_type);
765 let generics = generics(db, def.into()); 763 let generics = generics(db.upcast(), def.into());
766 let num_binders = generics.len(); 764 let num_binders = generics.len();
767 Binders::new(num_binders, FnSig::from_params_and_return(params, ret)) 765 Binders::new(num_binders, FnSig::from_params_and_return(params, ret))
768} 766}
769 767
770/// Build the declared type of a function. This should not need to look at the 768/// Build the declared type of a function. This should not need to look at the
771/// function body. 769/// function body.
772fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Binders<Ty> { 770fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
773 let generics = generics(db, def.into()); 771 let generics = generics(db.upcast(), def.into());
774 let substs = Substs::bound_vars(&generics); 772 let substs = Substs::bound_vars(&generics);
775 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs)) 773 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
776} 774}
777 775
778/// Build the declared type of a const. 776/// Build the declared type of a const.
779fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Binders<Ty> { 777fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
780 let data = db.const_data(def); 778 let data = db.const_data(def);
781 let generics = generics(db, def.into()); 779 let generics = generics(db.upcast(), def.into());
782 let resolver = def.resolver(db); 780 let resolver = def.resolver(db.upcast());
783 let ctx = 781 let ctx =
784 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 782 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
785 783
@@ -787,9 +785,9 @@ fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Binders<Ty> {
787} 785}
788 786
789/// Build the declared type of a static. 787/// Build the declared type of a static.
790fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Binders<Ty> { 788fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
791 let data = db.static_data(def); 789 let data = db.static_data(def);
792 let resolver = def.resolver(db); 790 let resolver = def.resolver(db.upcast());
793 let ctx = TyLoweringContext::new(db, &resolver); 791 let ctx = TyLoweringContext::new(db, &resolver);
794 792
795 Binders::new(0, Ty::from_hir(&ctx, &data.type_ref)) 793 Binders::new(0, Ty::from_hir(&ctx, &data.type_ref))
@@ -806,10 +804,10 @@ fn type_for_builtin(def: BuiltinType) -> Ty {
806 }) 804 })
807} 805}
808 806
809fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> PolyFnSig { 807fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
810 let struct_data = db.struct_data(def); 808 let struct_data = db.struct_data(def);
811 let fields = struct_data.variant_data.fields(); 809 let fields = struct_data.variant_data.fields();
812 let resolver = def.resolver(db); 810 let resolver = def.resolver(db.upcast());
813 let ctx = 811 let ctx =
814 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 812 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
815 let params = 813 let params =
@@ -819,21 +817,21 @@ fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> PolyFn
819} 817}
820 818
821/// Build the type of a tuple struct constructor. 819/// Build the type of a tuple struct constructor.
822fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Binders<Ty> { 820fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
823 let struct_data = db.struct_data(def); 821 let struct_data = db.struct_data(def);
824 if let StructKind::Unit = struct_data.variant_data.kind() { 822 if let StructKind::Unit = struct_data.variant_data.kind() {
825 return type_for_adt(db, def.into()); 823 return type_for_adt(db, def.into());
826 } 824 }
827 let generics = generics(db, def.into()); 825 let generics = generics(db.upcast(), def.into());
828 let substs = Substs::bound_vars(&generics); 826 let substs = Substs::bound_vars(&generics);
829 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs)) 827 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
830} 828}
831 829
832fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> PolyFnSig { 830fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
833 let enum_data = db.enum_data(def.parent); 831 let enum_data = db.enum_data(def.parent);
834 let var_data = &enum_data.variants[def.local_id]; 832 let var_data = &enum_data.variants[def.local_id];
835 let fields = var_data.variant_data.fields(); 833 let fields = var_data.variant_data.fields();
836 let resolver = def.parent.resolver(db); 834 let resolver = def.parent.resolver(db.upcast());
837 let ctx = 835 let ctx =
838 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 836 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
839 let params = 837 let params =
@@ -843,26 +841,26 @@ fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId
843} 841}
844 842
845/// Build the type of a tuple enum variant constructor. 843/// Build the type of a tuple enum variant constructor.
846fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Binders<Ty> { 844fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
847 let enum_data = db.enum_data(def.parent); 845 let enum_data = db.enum_data(def.parent);
848 let var_data = &enum_data.variants[def.local_id].variant_data; 846 let var_data = &enum_data.variants[def.local_id].variant_data;
849 if let StructKind::Unit = var_data.kind() { 847 if let StructKind::Unit = var_data.kind() {
850 return type_for_adt(db, def.parent.into()); 848 return type_for_adt(db, def.parent.into());
851 } 849 }
852 let generics = generics(db, def.parent.into()); 850 let generics = generics(db.upcast(), def.parent.into());
853 let substs = Substs::bound_vars(&generics); 851 let substs = Substs::bound_vars(&generics);
854 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs)) 852 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
855} 853}
856 854
857fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Binders<Ty> { 855fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
858 let generics = generics(db, adt.into()); 856 let generics = generics(db.upcast(), adt.into());
859 let substs = Substs::bound_vars(&generics); 857 let substs = Substs::bound_vars(&generics);
860 Binders::new(substs.len(), Ty::apply(TypeCtor::Adt(adt), substs)) 858 Binders::new(substs.len(), Ty::apply(TypeCtor::Adt(adt), substs))
861} 859}
862 860
863fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Binders<Ty> { 861fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
864 let generics = generics(db, t.into()); 862 let generics = generics(db.upcast(), t.into());
865 let resolver = t.resolver(db); 863 let resolver = t.resolver(db.upcast());
866 let ctx = 864 let ctx =
867 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 865 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
868 let type_ref = &db.type_alias_data(t).type_ref; 866 let type_ref = &db.type_alias_data(t).type_ref;
@@ -880,7 +878,8 @@ pub enum CallableDef {
880impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId); 878impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId);
881 879
882impl CallableDef { 880impl CallableDef {
883 pub fn krate(self, db: &impl HirDatabase) -> CrateId { 881 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
882 let db = db.upcast();
884 match self { 883 match self {
885 CallableDef::FunctionId(f) => f.lookup(db).module(db), 884 CallableDef::FunctionId(f) => f.lookup(db).module(db),
886 CallableDef::StructId(s) => s.lookup(db).container.module(db), 885 CallableDef::StructId(s) => s.lookup(db).container.module(db),
@@ -922,7 +921,7 @@ impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId
922/// `struct Foo(usize)`, we have two types: The type of the struct itself, and 921/// `struct Foo(usize)`, we have two types: The type of the struct itself, and
923/// the constructor function `(usize) -> Foo` which lives in the values 922/// the constructor function `(usize) -> Foo` which lives in the values
924/// namespace. 923/// namespace.
925pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Binders<Ty> { 924pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
926 match def { 925 match def {
927 TyDefId::BuiltinType(it) => Binders::new(0, type_for_builtin(it)), 926 TyDefId::BuiltinType(it) => Binders::new(0, type_for_builtin(it)),
928 TyDefId::AdtId(it) => type_for_adt(db, it), 927 TyDefId::AdtId(it) => type_for_adt(db, it),
@@ -930,16 +929,16 @@ pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Binders<Ty> {
930 } 929 }
931} 930}
932 931
933pub(crate) fn ty_recover(db: &impl HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> { 932pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
934 let num_binders = match *def { 933 let num_binders = match *def {
935 TyDefId::BuiltinType(_) => 0, 934 TyDefId::BuiltinType(_) => 0,
936 TyDefId::AdtId(it) => generics(db, it.into()).len(), 935 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
937 TyDefId::TypeAliasId(it) => generics(db, it.into()).len(), 936 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
938 }; 937 };
939 Binders::new(num_binders, Ty::Unknown) 938 Binders::new(num_binders, Ty::Unknown)
940} 939}
941 940
942pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Binders<Ty> { 941pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
943 match def { 942 match def {
944 ValueTyDefId::FunctionId(it) => type_for_fn(db, it), 943 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
945 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), 944 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
@@ -949,30 +948,27 @@ pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Binder
949 } 948 }
950} 949}
951 950
952pub(crate) fn impl_self_ty_query(db: &impl HirDatabase, impl_id: ImplId) -> Binders<Ty> { 951pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
953 let impl_data = db.impl_data(impl_id); 952 let impl_data = db.impl_data(impl_id);
954 let resolver = impl_id.resolver(db); 953 let resolver = impl_id.resolver(db.upcast());
955 let generics = generics(db, impl_id.into()); 954 let generics = generics(db.upcast(), impl_id.into());
956 let ctx = 955 let ctx =
957 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 956 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
958 Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type)) 957 Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type))
959} 958}
960 959
961pub(crate) fn impl_self_ty_recover( 960pub(crate) fn impl_self_ty_recover(
962 db: &impl HirDatabase, 961 db: &dyn HirDatabase,
963 _cycle: &[String], 962 _cycle: &[String],
964 impl_id: &ImplId, 963 impl_id: &ImplId,
965) -> Binders<Ty> { 964) -> Binders<Ty> {
966 let generics = generics(db, (*impl_id).into()); 965 let generics = generics(db.upcast(), (*impl_id).into());
967 Binders::new(generics.len(), Ty::Unknown) 966 Binders::new(generics.len(), Ty::Unknown)
968} 967}
969 968
970pub(crate) fn impl_trait_query( 969pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
971 db: &impl HirDatabase,
972 impl_id: ImplId,
973) -> Option<Binders<TraitRef>> {
974 let impl_data = db.impl_data(impl_id); 970 let impl_data = db.impl_data(impl_id);
975 let resolver = impl_id.resolver(db); 971 let resolver = impl_id.resolver(db.upcast());
976 let ctx = 972 let ctx =
977 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); 973 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
978 let self_ty = db.impl_self_ty(impl_id); 974 let self_ty = db.impl_self_ty(impl_id);
diff --git a/crates/ra_hir_ty/src/method_resolution.rs b/crates/ra_hir_ty/src/method_resolution.rs
index 7f5e1469e..69c059ac8 100644
--- a/crates/ra_hir_ty/src/method_resolution.rs
+++ b/crates/ra_hir_ty/src/method_resolution.rs
@@ -48,10 +48,7 @@ pub struct CrateImplDefs {
48} 48}
49 49
50impl CrateImplDefs { 50impl CrateImplDefs {
51 pub(crate) fn impls_in_crate_query( 51 pub(crate) fn impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<CrateImplDefs> {
52 db: &impl HirDatabase,
53 krate: CrateId,
54 ) -> Arc<CrateImplDefs> {
55 let _p = profile("impls_in_crate_query"); 52 let _p = profile("impls_in_crate_query");
56 let mut res = 53 let mut res =
57 CrateImplDefs { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; 54 CrateImplDefs { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() };
@@ -92,7 +89,7 @@ impl CrateImplDefs {
92impl Ty { 89impl Ty {
93 pub fn def_crates( 90 pub fn def_crates(
94 &self, 91 &self,
95 db: &impl HirDatabase, 92 db: &dyn HirDatabase,
96 cur_crate: CrateId, 93 cur_crate: CrateId,
97 ) -> Option<ArrayVec<[CrateId; 2]>> { 94 ) -> Option<ArrayVec<[CrateId; 2]>> {
98 // Types like slice can have inherent impls in several crates, (core and alloc). 95 // Types like slice can have inherent impls in several crates, (core and alloc).
@@ -110,7 +107,7 @@ impl Ty {
110 let lang_item_targets = match self { 107 let lang_item_targets = match self {
111 Ty::Apply(a_ty) => match a_ty.ctor { 108 Ty::Apply(a_ty) => match a_ty.ctor {
112 TypeCtor::Adt(def_id) => { 109 TypeCtor::Adt(def_id) => {
113 return Some(std::iter::once(def_id.module(db).krate).collect()) 110 return Some(std::iter::once(def_id.module(db.upcast()).krate).collect())
114 } 111 }
115 TypeCtor::Bool => lang_item_crate!("bool"), 112 TypeCtor::Bool => lang_item_crate!("bool"),
116 TypeCtor::Char => lang_item_crate!("char"), 113 TypeCtor::Char => lang_item_crate!("char"),
@@ -134,7 +131,7 @@ impl Ty {
134 LangItemTarget::ImplDefId(it) => Some(it), 131 LangItemTarget::ImplDefId(it) => Some(it),
135 _ => None, 132 _ => None,
136 }) 133 })
137 .map(|it| it.lookup(db).container.module(db).krate) 134 .map(|it| it.lookup(db.upcast()).container.module(db.upcast()).krate)
138 .collect(); 135 .collect();
139 Some(res) 136 Some(res)
140 } 137 }
@@ -143,7 +140,7 @@ impl Ty {
143/// receiver type (but without autoref applied yet). 140/// receiver type (but without autoref applied yet).
144pub(crate) fn lookup_method( 141pub(crate) fn lookup_method(
145 ty: &Canonical<Ty>, 142 ty: &Canonical<Ty>,
146 db: &impl HirDatabase, 143 db: &dyn HirDatabase,
147 env: Arc<TraitEnvironment>, 144 env: Arc<TraitEnvironment>,
148 krate: CrateId, 145 krate: CrateId,
149 traits_in_scope: &FxHashSet<TraitId>, 146 traits_in_scope: &FxHashSet<TraitId>,
@@ -181,7 +178,7 @@ pub enum LookupMode {
181// FIXME add a context type here? 178// FIXME add a context type here?
182pub fn iterate_method_candidates<T>( 179pub fn iterate_method_candidates<T>(
183 ty: &Canonical<Ty>, 180 ty: &Canonical<Ty>,
184 db: &impl HirDatabase, 181 db: &dyn HirDatabase,
185 env: Arc<TraitEnvironment>, 182 env: Arc<TraitEnvironment>,
186 krate: CrateId, 183 krate: CrateId,
187 traits_in_scope: &FxHashSet<TraitId>, 184 traits_in_scope: &FxHashSet<TraitId>,
@@ -247,7 +244,7 @@ pub fn iterate_method_candidates<T>(
247 244
248fn iterate_method_candidates_with_autoref<T>( 245fn iterate_method_candidates_with_autoref<T>(
249 deref_chain: &[Canonical<Ty>], 246 deref_chain: &[Canonical<Ty>],
250 db: &impl HirDatabase, 247 db: &dyn HirDatabase,
251 env: Arc<TraitEnvironment>, 248 env: Arc<TraitEnvironment>,
252 krate: CrateId, 249 krate: CrateId,
253 traits_in_scope: &FxHashSet<TraitId>, 250 traits_in_scope: &FxHashSet<TraitId>,
@@ -304,7 +301,7 @@ fn iterate_method_candidates_with_autoref<T>(
304fn iterate_method_candidates_by_receiver<T>( 301fn iterate_method_candidates_by_receiver<T>(
305 receiver_ty: &Canonical<Ty>, 302 receiver_ty: &Canonical<Ty>,
306 rest_of_deref_chain: &[Canonical<Ty>], 303 rest_of_deref_chain: &[Canonical<Ty>],
307 db: &impl HirDatabase, 304 db: &dyn HirDatabase,
308 env: Arc<TraitEnvironment>, 305 env: Arc<TraitEnvironment>,
309 krate: CrateId, 306 krate: CrateId,
310 traits_in_scope: &FxHashSet<TraitId>, 307 traits_in_scope: &FxHashSet<TraitId>,
@@ -340,7 +337,7 @@ fn iterate_method_candidates_by_receiver<T>(
340 337
341fn iterate_method_candidates_for_self_ty<T>( 338fn iterate_method_candidates_for_self_ty<T>(
342 self_ty: &Canonical<Ty>, 339 self_ty: &Canonical<Ty>,
343 db: &impl HirDatabase, 340 db: &dyn HirDatabase,
344 env: Arc<TraitEnvironment>, 341 env: Arc<TraitEnvironment>,
345 krate: CrateId, 342 krate: CrateId,
346 traits_in_scope: &FxHashSet<TraitId>, 343 traits_in_scope: &FxHashSet<TraitId>,
@@ -367,7 +364,7 @@ fn iterate_method_candidates_for_self_ty<T>(
367 364
368fn iterate_trait_method_candidates<T>( 365fn iterate_trait_method_candidates<T>(
369 self_ty: &Canonical<Ty>, 366 self_ty: &Canonical<Ty>,
370 db: &impl HirDatabase, 367 db: &dyn HirDatabase,
371 env: Arc<TraitEnvironment>, 368 env: Arc<TraitEnvironment>,
372 krate: CrateId, 369 krate: CrateId,
373 traits_in_scope: &FxHashSet<TraitId>, 370 traits_in_scope: &FxHashSet<TraitId>,
@@ -381,7 +378,7 @@ fn iterate_trait_method_candidates<T>(
381 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope 378 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
382 env.trait_predicates_for_self_ty(&self_ty.value) 379 env.trait_predicates_for_self_ty(&self_ty.value)
383 .map(|tr| tr.trait_) 380 .map(|tr| tr.trait_)
384 .flat_map(|t| all_super_traits(db, t)) 381 .flat_map(|t| all_super_traits(db.upcast(), t))
385 .collect() 382 .collect()
386 } else { 383 } else {
387 Vec::new() 384 Vec::new()
@@ -416,7 +413,7 @@ fn iterate_trait_method_candidates<T>(
416 413
417fn iterate_inherent_methods<T>( 414fn iterate_inherent_methods<T>(
418 self_ty: &Canonical<Ty>, 415 self_ty: &Canonical<Ty>,
419 db: &impl HirDatabase, 416 db: &dyn HirDatabase,
420 name: Option<&Name>, 417 name: Option<&Name>,
421 receiver_ty: Option<&Canonical<Ty>>, 418 receiver_ty: Option<&Canonical<Ty>>,
422 krate: CrateId, 419 krate: CrateId,
@@ -449,7 +446,7 @@ fn iterate_inherent_methods<T>(
449 446
450/// Returns the self type for the index trait call. 447/// Returns the self type for the index trait call.
451pub fn resolve_indexing_op( 448pub fn resolve_indexing_op(
452 db: &impl HirDatabase, 449 db: &dyn HirDatabase,
453 ty: &Canonical<Ty>, 450 ty: &Canonical<Ty>,
454 env: Arc<TraitEnvironment>, 451 env: Arc<TraitEnvironment>,
455 krate: CrateId, 452 krate: CrateId,
@@ -467,7 +464,7 @@ pub fn resolve_indexing_op(
467} 464}
468 465
469fn is_valid_candidate( 466fn is_valid_candidate(
470 db: &impl HirDatabase, 467 db: &dyn HirDatabase,
471 name: Option<&Name>, 468 name: Option<&Name>,
472 receiver_ty: Option<&Canonical<Ty>>, 469 receiver_ty: Option<&Canonical<Ty>>,
473 item: AssocItemId, 470 item: AssocItemId,
@@ -504,7 +501,7 @@ fn is_valid_candidate(
504} 501}
505 502
506pub(crate) fn inherent_impl_substs( 503pub(crate) fn inherent_impl_substs(
507 db: &impl HirDatabase, 504 db: &dyn HirDatabase,
508 impl_id: ImplId, 505 impl_id: ImplId,
509 self_ty: &Canonical<Ty>, 506 self_ty: &Canonical<Ty>,
510) -> Option<Substs> { 507) -> Option<Substs> {
@@ -544,11 +541,11 @@ fn fallback_bound_vars(s: Substs, num_vars_to_keep: usize) -> Substs {
544} 541}
545 542
546fn transform_receiver_ty( 543fn transform_receiver_ty(
547 db: &impl HirDatabase, 544 db: &dyn HirDatabase,
548 function_id: FunctionId, 545 function_id: FunctionId,
549 self_ty: &Canonical<Ty>, 546 self_ty: &Canonical<Ty>,
550) -> Option<Ty> { 547) -> Option<Ty> {
551 let substs = match function_id.lookup(db).container { 548 let substs = match function_id.lookup(db.upcast()).container {
552 AssocContainerId::TraitId(_) => Substs::build_for_def(db, function_id) 549 AssocContainerId::TraitId(_) => Substs::build_for_def(db, function_id)
553 .push(self_ty.value.clone()) 550 .push(self_ty.value.clone())
554 .fill_with_unknown() 551 .fill_with_unknown()
@@ -562,7 +559,7 @@ fn transform_receiver_ty(
562 559
563pub fn implements_trait( 560pub fn implements_trait(
564 ty: &Canonical<Ty>, 561 ty: &Canonical<Ty>,
565 db: &impl HirDatabase, 562 db: &dyn HirDatabase,
566 env: Arc<TraitEnvironment>, 563 env: Arc<TraitEnvironment>,
567 krate: CrateId, 564 krate: CrateId,
568 trait_: TraitId, 565 trait_: TraitId,
@@ -581,7 +578,7 @@ pub fn implements_trait(
581/// This creates Substs for a trait with the given Self type and type variables 578/// This creates Substs for a trait with the given Self type and type variables
582/// for all other parameters, to query Chalk with it. 579/// for all other parameters, to query Chalk with it.
583fn generic_implements_goal( 580fn generic_implements_goal(
584 db: &impl HirDatabase, 581 db: &dyn HirDatabase,
585 env: Arc<TraitEnvironment>, 582 env: Arc<TraitEnvironment>,
586 trait_: TraitId, 583 trait_: TraitId,
587 self_ty: Canonical<Ty>, 584 self_ty: Canonical<Ty>,
@@ -598,7 +595,7 @@ fn generic_implements_goal(
598} 595}
599 596
600fn autoderef_method_receiver( 597fn autoderef_method_receiver(
601 db: &impl HirDatabase, 598 db: &dyn HirDatabase,
602 krate: CrateId, 599 krate: CrateId,
603 ty: InEnvironment<Canonical<Ty>>, 600 ty: InEnvironment<Canonical<Ty>>,
604) -> Vec<Canonical<Ty>> { 601) -> Vec<Canonical<Ty>> {
diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs
index 0be2fea4b..5bbeabf51 100644
--- a/crates/ra_hir_ty/src/test_db.rs
+++ b/crates/ra_hir_ty/src/test_db.rs
@@ -6,8 +6,10 @@ use std::{
6}; 6};
7 7
8use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId}; 8use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId};
9use hir_expand::diagnostics::DiagnosticSink; 9use hir_expand::{db::AstDatabase, diagnostics::DiagnosticSink};
10use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; 10use ra_db::{
11 salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase, Upcast,
12};
11 13
12use crate::{db::HirDatabase, expr::ExprValidator}; 14use crate::{db::HirDatabase, expr::ExprValidator};
13 15
@@ -25,6 +27,18 @@ pub struct TestDB {
25 runtime: salsa::Runtime<TestDB>, 27 runtime: salsa::Runtime<TestDB>,
26} 28}
27 29
30impl Upcast<dyn AstDatabase> for TestDB {
31 fn upcast(&self) -> &(dyn AstDatabase + 'static) {
32 &*self
33 }
34}
35
36impl Upcast<dyn DefDatabase> for TestDB {
37 fn upcast(&self) -> &(dyn DefDatabase + 'static) {
38 &*self
39 }
40}
41
28impl salsa::Database for TestDB { 42impl salsa::Database for TestDB {
29 fn salsa_runtime(&self) -> &salsa::Runtime<TestDB> { 43 fn salsa_runtime(&self) -> &salsa::Runtime<TestDB> {
30 &self.runtime 44 &self.runtime
diff --git a/crates/ra_hir_ty/src/traits.rs b/crates/ra_hir_ty/src/traits.rs
index 6e1c8e42a..a1ca33c98 100644
--- a/crates/ra_hir_ty/src/traits.rs
+++ b/crates/ra_hir_ty/src/traits.rs
@@ -24,8 +24,8 @@ const CHALK_SOLVER_MAX_SIZE: usize = 10;
24const CHALK_SOLVER_FUEL: i32 = 100; 24const CHALK_SOLVER_FUEL: i32 = 100;
25 25
26#[derive(Debug, Copy, Clone)] 26#[derive(Debug, Copy, Clone)]
27struct ChalkContext<'a, DB> { 27struct ChalkContext<'a> {
28 db: &'a DB, 28 db: &'a dyn HirDatabase,
29 krate: CrateId, 29 krate: CrateId,
30} 30}
31 31
@@ -37,7 +37,7 @@ fn create_chalk_solver() -> chalk_solve::Solver<Interner> {
37 37
38/// Collects impls for the given trait in the whole dependency tree of `krate`. 38/// Collects impls for the given trait in the whole dependency tree of `krate`.
39pub(crate) fn impls_for_trait_query( 39pub(crate) fn impls_for_trait_query(
40 db: &impl HirDatabase, 40 db: &dyn HirDatabase,
41 krate: CrateId, 41 krate: CrateId,
42 trait_: TraitId, 42 trait_: TraitId,
43) -> Arc<[ImplId]> { 43) -> Arc<[ImplId]> {
@@ -136,7 +136,7 @@ impl TypeWalk for ProjectionPredicate {
136 136
137/// Solve a trait goal using Chalk. 137/// Solve a trait goal using Chalk.
138pub(crate) fn trait_solve_query( 138pub(crate) fn trait_solve_query(
139 db: &impl HirDatabase, 139 db: &dyn HirDatabase,
140 krate: CrateId, 140 krate: CrateId,
141 goal: Canonical<InEnvironment<Obligation>>, 141 goal: Canonical<InEnvironment<Obligation>>,
142) -> Option<Solution> { 142) -> Option<Solution> {
@@ -163,7 +163,7 @@ pub(crate) fn trait_solve_query(
163} 163}
164 164
165fn solve( 165fn solve(
166 db: &impl HirDatabase, 166 db: &dyn HirDatabase,
167 krate: CrateId, 167 krate: CrateId,
168 goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<Interner>>>, 168 goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<Interner>>>,
169) -> Option<chalk_solve::Solution<Interner>> { 169) -> Option<chalk_solve::Solution<Interner>> {
@@ -188,7 +188,7 @@ fn solve(
188} 188}
189 189
190fn solution_from_chalk( 190fn solution_from_chalk(
191 db: &impl HirDatabase, 191 db: &dyn HirDatabase,
192 solution: chalk_solve::Solution<Interner>, 192 solution: chalk_solve::Solution<Interner>,
193) -> Solution { 193) -> Solution {
194 let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<Interner>>| { 194 let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<Interner>>| {
diff --git a/crates/ra_hir_ty/src/traits/builtin.rs b/crates/ra_hir_ty/src/traits/builtin.rs
index 03f9b4e27..73e3c5c78 100644
--- a/crates/ra_hir_ty/src/traits/builtin.rs
+++ b/crates/ra_hir_ty/src/traits/builtin.rs
@@ -26,7 +26,7 @@ pub(super) struct BuiltinImplAssocTyValueData {
26} 26}
27 27
28pub(super) fn get_builtin_impls( 28pub(super) fn get_builtin_impls(
29 db: &impl HirDatabase, 29 db: &dyn HirDatabase,
30 krate: CrateId, 30 krate: CrateId,
31 ty: &Ty, 31 ty: &Ty,
32 // The first argument for the trait, if present 32 // The first argument for the trait, if present
@@ -59,7 +59,7 @@ pub(super) fn get_builtin_impls(
59} 59}
60 60
61fn get_builtin_unsize_impls( 61fn get_builtin_unsize_impls(
62 db: &impl HirDatabase, 62 db: &dyn HirDatabase,
63 krate: CrateId, 63 krate: CrateId,
64 ty: &Ty, 64 ty: &Ty,
65 // The first argument for the trait, if present 65 // The first argument for the trait, if present
@@ -79,7 +79,7 @@ fn get_builtin_unsize_impls(
79 // FIXME what about more complicated dyn tys with marker traits? 79 // FIXME what about more complicated dyn tys with marker traits?
80 if let Some(trait_ref) = ty.dyn_trait_ref() { 80 if let Some(trait_ref) = ty.dyn_trait_ref() {
81 if trait_ref.trait_ != target_trait.trait_ { 81 if trait_ref.trait_ != target_trait.trait_ {
82 let super_traits = all_super_traits(db, trait_ref.trait_); 82 let super_traits = all_super_traits(db.upcast(), trait_ref.trait_);
83 if super_traits.contains(&target_trait.trait_) { 83 if super_traits.contains(&target_trait.trait_) {
84 callback(Impl::UnsizeToSuperTraitObject(UnsizeToSuperTraitObjectData { 84 callback(Impl::UnsizeToSuperTraitObject(UnsizeToSuperTraitObjectData {
85 trait_: trait_ref.trait_, 85 trait_: trait_ref.trait_,
@@ -94,7 +94,7 @@ fn get_builtin_unsize_impls(
94 } 94 }
95} 95}
96 96
97pub(super) fn impl_datum(db: &impl HirDatabase, krate: CrateId, impl_: Impl) -> BuiltinImplData { 97pub(super) fn impl_datum(db: &dyn HirDatabase, krate: CrateId, impl_: Impl) -> BuiltinImplData {
98 match impl_ { 98 match impl_ {
99 Impl::ImplDef(_) => unreachable!(), 99 Impl::ImplDef(_) => unreachable!(),
100 Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data), 100 Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data),
@@ -107,7 +107,7 @@ pub(super) fn impl_datum(db: &impl HirDatabase, krate: CrateId, impl_: Impl) ->
107} 107}
108 108
109pub(super) fn associated_ty_value( 109pub(super) fn associated_ty_value(
110 db: &impl HirDatabase, 110 db: &dyn HirDatabase,
111 krate: CrateId, 111 krate: CrateId,
112 data: AssocTyValue, 112 data: AssocTyValue,
113) -> BuiltinImplAssocTyValueData { 113) -> BuiltinImplAssocTyValueData {
@@ -122,7 +122,7 @@ pub(super) fn associated_ty_value(
122// Closure Fn trait impls 122// Closure Fn trait impls
123 123
124fn check_closure_fn_trait_impl_prerequisites( 124fn check_closure_fn_trait_impl_prerequisites(
125 db: &impl HirDatabase, 125 db: &dyn HirDatabase,
126 krate: CrateId, 126 krate: CrateId,
127 data: super::ClosureFnTraitImplData, 127 data: super::ClosureFnTraitImplData,
128) -> bool { 128) -> bool {
@@ -143,7 +143,7 @@ fn check_closure_fn_trait_impl_prerequisites(
143} 143}
144 144
145fn closure_fn_trait_impl_datum( 145fn closure_fn_trait_impl_datum(
146 db: &impl HirDatabase, 146 db: &dyn HirDatabase,
147 krate: CrateId, 147 krate: CrateId,
148 data: super::ClosureFnTraitImplData, 148 data: super::ClosureFnTraitImplData,
149) -> BuiltinImplData { 149) -> BuiltinImplData {
@@ -189,7 +189,7 @@ fn closure_fn_trait_impl_datum(
189} 189}
190 190
191fn closure_fn_trait_output_assoc_ty_value( 191fn closure_fn_trait_output_assoc_ty_value(
192 db: &impl HirDatabase, 192 db: &dyn HirDatabase,
193 krate: CrateId, 193 krate: CrateId,
194 data: super::ClosureFnTraitImplData, 194 data: super::ClosureFnTraitImplData,
195) -> BuiltinImplAssocTyValueData { 195) -> BuiltinImplAssocTyValueData {
@@ -223,17 +223,17 @@ fn closure_fn_trait_output_assoc_ty_value(
223 223
224// Array unsizing 224// Array unsizing
225 225
226fn check_unsize_impl_prerequisites(db: &impl HirDatabase, krate: CrateId) -> bool { 226fn check_unsize_impl_prerequisites(db: &dyn HirDatabase, krate: CrateId) -> bool {
227 // the Unsize trait needs to exist and have two type parameters (Self and T) 227 // the Unsize trait needs to exist and have two type parameters (Self and T)
228 let unsize_trait = match get_unsize_trait(db, krate) { 228 let unsize_trait = match get_unsize_trait(db, krate) {
229 Some(t) => t, 229 Some(t) => t,
230 None => return false, 230 None => return false,
231 }; 231 };
232 let generic_params = generics(db, unsize_trait.into()); 232 let generic_params = generics(db.upcast(), unsize_trait.into());
233 generic_params.len() == 2 233 generic_params.len() == 2
234} 234}
235 235
236fn array_unsize_impl_datum(db: &impl HirDatabase, krate: CrateId) -> BuiltinImplData { 236fn array_unsize_impl_datum(db: &dyn HirDatabase, krate: CrateId) -> BuiltinImplData {
237 // impl<T> Unsize<[T]> for [T; _] 237 // impl<T> Unsize<[T]> for [T; _]
238 // (this can be a single impl because we don't distinguish array sizes currently) 238 // (this can be a single impl because we don't distinguish array sizes currently)
239 239
@@ -260,7 +260,7 @@ fn array_unsize_impl_datum(db: &impl HirDatabase, krate: CrateId) -> BuiltinImpl
260// Trait object unsizing 260// Trait object unsizing
261 261
262fn trait_object_unsize_impl_datum( 262fn trait_object_unsize_impl_datum(
263 db: &impl HirDatabase, 263 db: &dyn HirDatabase,
264 krate: CrateId, 264 krate: CrateId,
265 trait_: TraitId, 265 trait_: TraitId,
266) -> BuiltinImplData { 266) -> BuiltinImplData {
@@ -295,7 +295,7 @@ fn trait_object_unsize_impl_datum(
295} 295}
296 296
297fn super_trait_object_unsize_impl_datum( 297fn super_trait_object_unsize_impl_datum(
298 db: &impl HirDatabase, 298 db: &dyn HirDatabase,
299 krate: CrateId, 299 krate: CrateId,
300 data: UnsizeToSuperTraitObjectData, 300 data: UnsizeToSuperTraitObjectData,
301) -> BuiltinImplData { 301) -> BuiltinImplData {
@@ -313,7 +313,7 @@ fn super_trait_object_unsize_impl_datum(
313 let self_bounds = vec![GenericPredicate::Implemented(self_trait_ref.clone())]; 313 let self_bounds = vec![GenericPredicate::Implemented(self_trait_ref.clone())];
314 314
315 // we need to go from our trait to the super trait, substituting type parameters 315 // we need to go from our trait to the super trait, substituting type parameters
316 let path = crate::utils::find_super_trait_path(db, data.trait_, data.super_trait); 316 let path = crate::utils::find_super_trait_path(db.upcast(), data.trait_, data.super_trait);
317 317
318 let mut current_trait_ref = self_trait_ref; 318 let mut current_trait_ref = self_trait_ref;
319 for t in path.into_iter().skip(1) { 319 for t in path.into_iter().skip(1) {
@@ -344,11 +344,7 @@ fn super_trait_object_unsize_impl_datum(
344 BuiltinImplData { num_vars, trait_ref, where_clauses: Vec::new(), assoc_ty_values: Vec::new() } 344 BuiltinImplData { num_vars, trait_ref, where_clauses: Vec::new(), assoc_ty_values: Vec::new() }
345} 345}
346 346
347fn get_fn_trait( 347fn get_fn_trait(db: &dyn HirDatabase, krate: CrateId, fn_trait: super::FnTrait) -> Option<TraitId> {
348 db: &impl HirDatabase,
349 krate: CrateId,
350 fn_trait: super::FnTrait,
351) -> Option<TraitId> {
352 let target = db.lang_item(krate, fn_trait.lang_item_name().into())?; 348 let target = db.lang_item(krate, fn_trait.lang_item_name().into())?;
353 match target { 349 match target {
354 LangItemTarget::TraitId(t) => Some(t), 350 LangItemTarget::TraitId(t) => Some(t),
@@ -356,7 +352,7 @@ fn get_fn_trait(
356 } 352 }
357} 353}
358 354
359fn get_unsize_trait(db: &impl HirDatabase, krate: CrateId) -> Option<TraitId> { 355fn get_unsize_trait(db: &dyn HirDatabase, krate: CrateId) -> Option<TraitId> {
360 let target = db.lang_item(krate, "unsize".into())?; 356 let target = db.lang_item(krate, "unsize".into())?;
361 match target { 357 match target {
362 LangItemTarget::TraitId(t) => Some(t), 358 LangItemTarget::TraitId(t) => Some(t),
diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs
index 62509bc29..943d5f125 100644
--- a/crates/ra_hir_ty/src/traits/chalk.rs
+++ b/crates/ra_hir_ty/src/traits/chalk.rs
@@ -127,11 +127,11 @@ pub type AssociatedTyValue = chalk_rust_ir::AssociatedTyValue<Interner>;
127 127
128pub(super) trait ToChalk { 128pub(super) trait ToChalk {
129 type Chalk; 129 type Chalk;
130 fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; 130 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk;
131 fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; 131 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self;
132} 132}
133 133
134pub(super) fn from_chalk<T, ChalkT>(db: &impl HirDatabase, chalk: ChalkT) -> T 134pub(super) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T
135where 135where
136 T: ToChalk<Chalk = ChalkT>, 136 T: ToChalk<Chalk = ChalkT>,
137{ 137{
@@ -140,7 +140,7 @@ where
140 140
141impl ToChalk for Ty { 141impl ToChalk for Ty {
142 type Chalk = chalk_ir::Ty<Interner>; 142 type Chalk = chalk_ir::Ty<Interner>;
143 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty<Interner> { 143 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> {
144 match self { 144 match self {
145 Ty::Apply(apply_ty) => { 145 Ty::Apply(apply_ty) => {
146 let name = apply_ty.ctor.to_chalk(db); 146 let name = apply_ty.ctor.to_chalk(db);
@@ -179,7 +179,7 @@ impl ToChalk for Ty {
179 } 179 }
180 } 180 }
181 } 181 }
182 fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self { 182 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
183 match chalk.data().clone() { 183 match chalk.data().clone() {
184 chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name { 184 chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name {
185 TypeName::Error => Ty::Unknown, 185 TypeName::Error => Ty::Unknown,
@@ -217,11 +217,11 @@ impl ToChalk for Ty {
217impl ToChalk for Substs { 217impl ToChalk for Substs {
218 type Chalk = chalk_ir::Substitution<Interner>; 218 type Chalk = chalk_ir::Substitution<Interner>;
219 219
220 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Substitution<Interner> { 220 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> {
221 chalk_ir::Substitution::from(self.iter().map(|ty| ty.clone().to_chalk(db))) 221 chalk_ir::Substitution::from(self.iter().map(|ty| ty.clone().to_chalk(db)))
222 } 222 }
223 223
224 fn from_chalk(db: &impl HirDatabase, parameters: chalk_ir::Substitution<Interner>) -> Substs { 224 fn from_chalk(db: &dyn HirDatabase, parameters: chalk_ir::Substitution<Interner>) -> Substs {
225 let tys = parameters 225 let tys = parameters
226 .into_iter() 226 .into_iter()
227 .map(|p| match p.ty() { 227 .map(|p| match p.ty() {
@@ -236,13 +236,13 @@ impl ToChalk for Substs {
236impl ToChalk for TraitRef { 236impl ToChalk for TraitRef {
237 type Chalk = chalk_ir::TraitRef<Interner>; 237 type Chalk = chalk_ir::TraitRef<Interner>;
238 238
239 fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef<Interner> { 239 fn to_chalk(self: TraitRef, db: &dyn HirDatabase) -> chalk_ir::TraitRef<Interner> {
240 let trait_id = self.trait_.to_chalk(db); 240 let trait_id = self.trait_.to_chalk(db);
241 let substitution = self.substs.to_chalk(db); 241 let substitution = self.substs.to_chalk(db);
242 chalk_ir::TraitRef { trait_id, substitution } 242 chalk_ir::TraitRef { trait_id, substitution }
243 } 243 }
244 244
245 fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef<Interner>) -> Self { 245 fn from_chalk(db: &dyn HirDatabase, trait_ref: chalk_ir::TraitRef<Interner>) -> Self {
246 let trait_ = from_chalk(db, trait_ref.trait_id); 246 let trait_ = from_chalk(db, trait_ref.trait_id);
247 let substs = from_chalk(db, trait_ref.substitution); 247 let substs = from_chalk(db, trait_ref.substitution);
248 TraitRef { trait_, substs } 248 TraitRef { trait_, substs }
@@ -252,11 +252,11 @@ impl ToChalk for TraitRef {
252impl ToChalk for hir_def::TraitId { 252impl ToChalk for hir_def::TraitId {
253 type Chalk = TraitId; 253 type Chalk = TraitId;
254 254
255 fn to_chalk(self, _db: &impl HirDatabase) -> TraitId { 255 fn to_chalk(self, _db: &dyn HirDatabase) -> TraitId {
256 chalk_ir::TraitId(self.as_intern_id()) 256 chalk_ir::TraitId(self.as_intern_id())
257 } 257 }
258 258
259 fn from_chalk(_db: &impl HirDatabase, trait_id: TraitId) -> hir_def::TraitId { 259 fn from_chalk(_db: &dyn HirDatabase, trait_id: TraitId) -> hir_def::TraitId {
260 InternKey::from_intern_id(trait_id.0) 260 InternKey::from_intern_id(trait_id.0)
261 } 261 }
262} 262}
@@ -264,7 +264,7 @@ impl ToChalk for hir_def::TraitId {
264impl ToChalk for TypeCtor { 264impl ToChalk for TypeCtor {
265 type Chalk = TypeName<Interner>; 265 type Chalk = TypeName<Interner>;
266 266
267 fn to_chalk(self, db: &impl HirDatabase) -> TypeName<Interner> { 267 fn to_chalk(self, db: &dyn HirDatabase) -> TypeName<Interner> {
268 match self { 268 match self {
269 TypeCtor::AssociatedType(type_alias) => { 269 TypeCtor::AssociatedType(type_alias) => {
270 let type_id = type_alias.to_chalk(db); 270 let type_id = type_alias.to_chalk(db);
@@ -278,7 +278,7 @@ impl ToChalk for TypeCtor {
278 } 278 }
279 } 279 }
280 280
281 fn from_chalk(db: &impl HirDatabase, type_name: TypeName<Interner>) -> TypeCtor { 281 fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
282 match type_name { 282 match type_name {
283 TypeName::Struct(struct_id) => db.lookup_intern_type_ctor(struct_id.into()), 283 TypeName::Struct(struct_id) => db.lookup_intern_type_ctor(struct_id.into()),
284 TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)), 284 TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
@@ -293,11 +293,11 @@ impl ToChalk for TypeCtor {
293impl ToChalk for Impl { 293impl ToChalk for Impl {
294 type Chalk = ImplId; 294 type Chalk = ImplId;
295 295
296 fn to_chalk(self, db: &impl HirDatabase) -> ImplId { 296 fn to_chalk(self, db: &dyn HirDatabase) -> ImplId {
297 db.intern_chalk_impl(self).into() 297 db.intern_chalk_impl(self).into()
298 } 298 }
299 299
300 fn from_chalk(db: &impl HirDatabase, impl_id: ImplId) -> Impl { 300 fn from_chalk(db: &dyn HirDatabase, impl_id: ImplId) -> Impl {
301 db.lookup_intern_chalk_impl(impl_id.into()) 301 db.lookup_intern_chalk_impl(impl_id.into())
302 } 302 }
303} 303}
@@ -305,11 +305,11 @@ impl ToChalk for Impl {
305impl ToChalk for TypeAliasId { 305impl ToChalk for TypeAliasId {
306 type Chalk = AssocTypeId; 306 type Chalk = AssocTypeId;
307 307
308 fn to_chalk(self, _db: &impl HirDatabase) -> AssocTypeId { 308 fn to_chalk(self, _db: &dyn HirDatabase) -> AssocTypeId {
309 chalk_ir::AssocTypeId(self.as_intern_id()) 309 chalk_ir::AssocTypeId(self.as_intern_id())
310 } 310 }
311 311
312 fn from_chalk(_db: &impl HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId { 312 fn from_chalk(_db: &dyn HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId {
313 InternKey::from_intern_id(type_alias_id.0) 313 InternKey::from_intern_id(type_alias_id.0)
314 } 314 }
315} 315}
@@ -317,11 +317,11 @@ impl ToChalk for TypeAliasId {
317impl ToChalk for AssocTyValue { 317impl ToChalk for AssocTyValue {
318 type Chalk = AssociatedTyValueId; 318 type Chalk = AssociatedTyValueId;
319 319
320 fn to_chalk(self, db: &impl HirDatabase) -> AssociatedTyValueId { 320 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValueId {
321 db.intern_assoc_ty_value(self).into() 321 db.intern_assoc_ty_value(self).into()
322 } 322 }
323 323
324 fn from_chalk(db: &impl HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue { 324 fn from_chalk(db: &dyn HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue {
325 db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) 325 db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
326 } 326 }
327} 327}
@@ -329,7 +329,7 @@ impl ToChalk for AssocTyValue {
329impl ToChalk for GenericPredicate { 329impl ToChalk for GenericPredicate {
330 type Chalk = chalk_ir::QuantifiedWhereClause<Interner>; 330 type Chalk = chalk_ir::QuantifiedWhereClause<Interner>;
331 331
332 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause<Interner> { 332 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::QuantifiedWhereClause<Interner> {
333 match self { 333 match self {
334 GenericPredicate::Implemented(trait_ref) => { 334 GenericPredicate::Implemented(trait_ref) => {
335 make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0) 335 make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0)
@@ -346,7 +346,7 @@ impl ToChalk for GenericPredicate {
346 } 346 }
347 347
348 fn from_chalk( 348 fn from_chalk(
349 db: &impl HirDatabase, 349 db: &dyn HirDatabase,
350 where_clause: chalk_ir::QuantifiedWhereClause<Interner>, 350 where_clause: chalk_ir::QuantifiedWhereClause<Interner>,
351 ) -> GenericPredicate { 351 ) -> GenericPredicate {
352 match where_clause.value { 352 match where_clause.value {
@@ -365,7 +365,7 @@ impl ToChalk for GenericPredicate {
365impl ToChalk for ProjectionTy { 365impl ToChalk for ProjectionTy {
366 type Chalk = chalk_ir::AliasTy<Interner>; 366 type Chalk = chalk_ir::AliasTy<Interner>;
367 367
368 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::AliasTy<Interner> { 368 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::AliasTy<Interner> {
369 chalk_ir::AliasTy { 369 chalk_ir::AliasTy {
370 associated_ty_id: self.associated_ty.to_chalk(db), 370 associated_ty_id: self.associated_ty.to_chalk(db),
371 substitution: self.parameters.to_chalk(db), 371 substitution: self.parameters.to_chalk(db),
@@ -373,7 +373,7 @@ impl ToChalk for ProjectionTy {
373 } 373 }
374 374
375 fn from_chalk( 375 fn from_chalk(
376 db: &impl HirDatabase, 376 db: &dyn HirDatabase,
377 projection_ty: chalk_ir::AliasTy<Interner>, 377 projection_ty: chalk_ir::AliasTy<Interner>,
378 ) -> ProjectionTy { 378 ) -> ProjectionTy {
379 ProjectionTy { 379 ProjectionTy {
@@ -386,11 +386,11 @@ impl ToChalk for ProjectionTy {
386impl ToChalk for super::ProjectionPredicate { 386impl ToChalk for super::ProjectionPredicate {
387 type Chalk = chalk_ir::Normalize<Interner>; 387 type Chalk = chalk_ir::Normalize<Interner>;
388 388
389 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize<Interner> { 389 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Normalize<Interner> {
390 chalk_ir::Normalize { alias: self.projection_ty.to_chalk(db), ty: self.ty.to_chalk(db) } 390 chalk_ir::Normalize { alias: self.projection_ty.to_chalk(db), ty: self.ty.to_chalk(db) }
391 } 391 }
392 392
393 fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize<Interner>) -> Self { 393 fn from_chalk(_db: &dyn HirDatabase, _normalize: chalk_ir::Normalize<Interner>) -> Self {
394 unimplemented!() 394 unimplemented!()
395 } 395 }
396} 396}
@@ -398,14 +398,14 @@ impl ToChalk for super::ProjectionPredicate {
398impl ToChalk for Obligation { 398impl ToChalk for Obligation {
399 type Chalk = chalk_ir::DomainGoal<Interner>; 399 type Chalk = chalk_ir::DomainGoal<Interner>;
400 400
401 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal<Interner> { 401 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::DomainGoal<Interner> {
402 match self { 402 match self {
403 Obligation::Trait(tr) => tr.to_chalk(db).cast(), 403 Obligation::Trait(tr) => tr.to_chalk(db).cast(),
404 Obligation::Projection(pr) => pr.to_chalk(db).cast(), 404 Obligation::Projection(pr) => pr.to_chalk(db).cast(),
405 } 405 }
406 } 406 }
407 407
408 fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal<Interner>) -> Self { 408 fn from_chalk(_db: &dyn HirDatabase, _goal: chalk_ir::DomainGoal<Interner>) -> Self {
409 unimplemented!() 409 unimplemented!()
410 } 410 }
411} 411}
@@ -416,13 +416,13 @@ where
416{ 416{
417 type Chalk = chalk_ir::Canonical<T::Chalk>; 417 type Chalk = chalk_ir::Canonical<T::Chalk>;
418 418
419 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical<T::Chalk> { 419 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
420 let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); 420 let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT);
421 let value = self.value.to_chalk(db); 421 let value = self.value.to_chalk(db);
422 chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] } 422 chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }
423 } 423 }
424 424
425 fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> { 425 fn from_chalk(db: &dyn HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {
426 Canonical { num_vars: canonical.binders.len(), value: from_chalk(db, canonical.value) } 426 Canonical { num_vars: canonical.binders.len(), value: from_chalk(db, canonical.value) }
427 } 427 }
428} 428}
@@ -430,7 +430,7 @@ where
430impl ToChalk for Arc<super::TraitEnvironment> { 430impl ToChalk for Arc<super::TraitEnvironment> {
431 type Chalk = chalk_ir::Environment<Interner>; 431 type Chalk = chalk_ir::Environment<Interner>;
432 432
433 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment<Interner> { 433 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Environment<Interner> {
434 let mut clauses = Vec::new(); 434 let mut clauses = Vec::new();
435 for pred in &self.predicates { 435 for pred in &self.predicates {
436 if pred.is_error() { 436 if pred.is_error() {
@@ -445,7 +445,7 @@ impl ToChalk for Arc<super::TraitEnvironment> {
445 } 445 }
446 446
447 fn from_chalk( 447 fn from_chalk(
448 _db: &impl HirDatabase, 448 _db: &dyn HirDatabase,
449 _env: chalk_ir::Environment<Interner>, 449 _env: chalk_ir::Environment<Interner>,
450 ) -> Arc<super::TraitEnvironment> { 450 ) -> Arc<super::TraitEnvironment> {
451 unimplemented!() 451 unimplemented!()
@@ -458,7 +458,7 @@ where
458{ 458{
459 type Chalk = chalk_ir::InEnvironment<T::Chalk>; 459 type Chalk = chalk_ir::InEnvironment<T::Chalk>;
460 460
461 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> { 461 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
462 chalk_ir::InEnvironment { 462 chalk_ir::InEnvironment {
463 environment: self.environment.to_chalk(db), 463 environment: self.environment.to_chalk(db),
464 goal: self.value.to_chalk(db), 464 goal: self.value.to_chalk(db),
@@ -466,7 +466,7 @@ where
466 } 466 }
467 467
468 fn from_chalk( 468 fn from_chalk(
469 db: &impl HirDatabase, 469 db: &dyn HirDatabase,
470 in_env: chalk_ir::InEnvironment<T::Chalk>, 470 in_env: chalk_ir::InEnvironment<T::Chalk>,
471 ) -> super::InEnvironment<T> { 471 ) -> super::InEnvironment<T> {
472 super::InEnvironment { 472 super::InEnvironment {
@@ -479,7 +479,7 @@ where
479impl ToChalk for builtin::BuiltinImplData { 479impl ToChalk for builtin::BuiltinImplData {
480 type Chalk = ImplDatum; 480 type Chalk = ImplDatum;
481 481
482 fn to_chalk(self, db: &impl HirDatabase) -> ImplDatum { 482 fn to_chalk(self, db: &dyn HirDatabase) -> ImplDatum {
483 let impl_type = chalk_rust_ir::ImplType::External; 483 let impl_type = chalk_rust_ir::ImplType::External;
484 let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect(); 484 let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect();
485 485
@@ -495,7 +495,7 @@ impl ToChalk for builtin::BuiltinImplData {
495 } 495 }
496 } 496 }
497 497
498 fn from_chalk(_db: &impl HirDatabase, _data: ImplDatum) -> Self { 498 fn from_chalk(_db: &dyn HirDatabase, _data: ImplDatum) -> Self {
499 unimplemented!() 499 unimplemented!()
500 } 500 }
501} 501}
@@ -503,7 +503,7 @@ impl ToChalk for builtin::BuiltinImplData {
503impl ToChalk for builtin::BuiltinImplAssocTyValueData { 503impl ToChalk for builtin::BuiltinImplAssocTyValueData {
504 type Chalk = AssociatedTyValue; 504 type Chalk = AssociatedTyValue;
505 505
506 fn to_chalk(self, db: &impl HirDatabase) -> AssociatedTyValue { 506 fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValue {
507 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: self.value.to_chalk(db) }; 507 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: self.value.to_chalk(db) };
508 508
509 chalk_rust_ir::AssociatedTyValue { 509 chalk_rust_ir::AssociatedTyValue {
@@ -514,7 +514,7 @@ impl ToChalk for builtin::BuiltinImplAssocTyValueData {
514 } 514 }
515 515
516 fn from_chalk( 516 fn from_chalk(
517 _db: &impl HirDatabase, 517 _db: &dyn HirDatabase,
518 _data: AssociatedTyValue, 518 _data: AssociatedTyValue,
519 ) -> builtin::BuiltinImplAssocTyValueData { 519 ) -> builtin::BuiltinImplAssocTyValueData {
520 unimplemented!() 520 unimplemented!()
@@ -529,7 +529,7 @@ fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T> {
529} 529}
530 530
531fn convert_where_clauses( 531fn convert_where_clauses(
532 db: &impl HirDatabase, 532 db: &dyn HirDatabase,
533 def: GenericDefId, 533 def: GenericDefId,
534 substs: &Substs, 534 substs: &Substs,
535) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> { 535) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
@@ -545,10 +545,7 @@ fn convert_where_clauses(
545 result 545 result
546} 546}
547 547
548impl<'a, DB> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a, DB> 548impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
549where
550 DB: HirDatabase,
551{
552 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> { 549 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
553 self.db.associated_ty_data(id) 550 self.db.associated_ty_data(id)
554 } 551 }
@@ -618,16 +615,16 @@ where
618} 615}
619 616
620pub(crate) fn associated_ty_data_query( 617pub(crate) fn associated_ty_data_query(
621 db: &impl HirDatabase, 618 db: &dyn HirDatabase,
622 id: AssocTypeId, 619 id: AssocTypeId,
623) -> Arc<AssociatedTyDatum> { 620) -> Arc<AssociatedTyDatum> {
624 debug!("associated_ty_data {:?}", id); 621 debug!("associated_ty_data {:?}", id);
625 let type_alias: TypeAliasId = from_chalk(db, id); 622 let type_alias: TypeAliasId = from_chalk(db, id);
626 let trait_ = match type_alias.lookup(db).container { 623 let trait_ = match type_alias.lookup(db.upcast()).container {
627 AssocContainerId::TraitId(t) => t, 624 AssocContainerId::TraitId(t) => t,
628 _ => panic!("associated type not in trait"), 625 _ => panic!("associated type not in trait"),
629 }; 626 };
630 let generic_params = generics(db, type_alias.into()); 627 let generic_params = generics(db.upcast(), type_alias.into());
631 let bound_data = chalk_rust_ir::AssociatedTyDatumBound { 628 let bound_data = chalk_rust_ir::AssociatedTyDatumBound {
632 // FIXME add bounds and where clauses 629 // FIXME add bounds and where clauses
633 bounds: vec![], 630 bounds: vec![],
@@ -643,7 +640,7 @@ pub(crate) fn associated_ty_data_query(
643} 640}
644 641
645pub(crate) fn trait_datum_query( 642pub(crate) fn trait_datum_query(
646 db: &impl HirDatabase, 643 db: &dyn HirDatabase,
647 krate: CrateId, 644 krate: CrateId,
648 trait_id: TraitId, 645 trait_id: TraitId,
649) -> Arc<TraitDatum> { 646) -> Arc<TraitDatum> {
@@ -651,11 +648,11 @@ pub(crate) fn trait_datum_query(
651 let trait_: hir_def::TraitId = from_chalk(db, trait_id); 648 let trait_: hir_def::TraitId = from_chalk(db, trait_id);
652 let trait_data = db.trait_data(trait_); 649 let trait_data = db.trait_data(trait_);
653 debug!("trait {:?} = {:?}", trait_id, trait_data.name); 650 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
654 let generic_params = generics(db, trait_.into()); 651 let generic_params = generics(db.upcast(), trait_.into());
655 let bound_vars = Substs::bound_vars(&generic_params); 652 let bound_vars = Substs::bound_vars(&generic_params);
656 let flags = chalk_rust_ir::TraitFlags { 653 let flags = chalk_rust_ir::TraitFlags {
657 auto: trait_data.auto, 654 auto: trait_data.auto,
658 upstream: trait_.lookup(db).container.module(db).krate != krate, 655 upstream: trait_.lookup(db.upcast()).container.module(db.upcast()).krate != krate,
659 non_enumerable: true, 656 non_enumerable: true,
660 coinductive: false, // only relevant for Chalk testing 657 coinductive: false, // only relevant for Chalk testing
661 // FIXME set these flags correctly 658 // FIXME set these flags correctly
@@ -676,7 +673,7 @@ pub(crate) fn trait_datum_query(
676} 673}
677 674
678pub(crate) fn struct_datum_query( 675pub(crate) fn struct_datum_query(
679 db: &impl HirDatabase, 676 db: &dyn HirDatabase,
680 krate: CrateId, 677 krate: CrateId,
681 struct_id: StructId, 678 struct_id: StructId,
682) -> Arc<StructDatum> { 679) -> Arc<StructDatum> {
@@ -688,7 +685,7 @@ pub(crate) fn struct_datum_query(
688 let where_clauses = type_ctor 685 let where_clauses = type_ctor
689 .as_generic_def() 686 .as_generic_def()
690 .map(|generic_def| { 687 .map(|generic_def| {
691 let generic_params = generics(db, generic_def); 688 let generic_params = generics(db.upcast(), generic_def);
692 let bound_vars = Substs::bound_vars(&generic_params); 689 let bound_vars = Substs::bound_vars(&generic_params);
693 convert_where_clauses(db, generic_def, &bound_vars) 690 convert_where_clauses(db, generic_def, &bound_vars)
694 }) 691 })
@@ -708,7 +705,7 @@ pub(crate) fn struct_datum_query(
708} 705}
709 706
710pub(crate) fn impl_datum_query( 707pub(crate) fn impl_datum_query(
711 db: &impl HirDatabase, 708 db: &dyn HirDatabase,
712 krate: CrateId, 709 krate: CrateId,
713 impl_id: ImplId, 710 impl_id: ImplId,
714) -> Arc<ImplDatum> { 711) -> Arc<ImplDatum> {
@@ -722,7 +719,7 @@ pub(crate) fn impl_datum_query(
722} 719}
723 720
724fn impl_def_datum( 721fn impl_def_datum(
725 db: &impl HirDatabase, 722 db: &dyn HirDatabase,
726 krate: CrateId, 723 krate: CrateId,
727 chalk_id: ImplId, 724 chalk_id: ImplId,
728 impl_id: hir_def::ImplId, 725 impl_id: hir_def::ImplId,
@@ -734,10 +731,10 @@ fn impl_def_datum(
734 .value; 731 .value;
735 let impl_data = db.impl_data(impl_id); 732 let impl_data = db.impl_data(impl_id);
736 733
737 let generic_params = generics(db, impl_id.into()); 734 let generic_params = generics(db.upcast(), impl_id.into());
738 let bound_vars = Substs::bound_vars(&generic_params); 735 let bound_vars = Substs::bound_vars(&generic_params);
739 let trait_ = trait_ref.trait_; 736 let trait_ = trait_ref.trait_;
740 let impl_type = if impl_id.lookup(db).container.module(db).krate == krate { 737 let impl_type = if impl_id.lookup(db.upcast()).container.module(db.upcast()).krate == krate {
741 chalk_rust_ir::ImplType::Local 738 chalk_rust_ir::ImplType::Local
742 } else { 739 } else {
743 chalk_rust_ir::ImplType::External 740 chalk_rust_ir::ImplType::External
@@ -786,7 +783,7 @@ fn impl_def_datum(
786} 783}
787 784
788pub(crate) fn associated_ty_value_query( 785pub(crate) fn associated_ty_value_query(
789 db: &impl HirDatabase, 786 db: &dyn HirDatabase,
790 krate: CrateId, 787 krate: CrateId,
791 id: AssociatedTyValueId, 788 id: AssociatedTyValueId,
792) -> Arc<AssociatedTyValue> { 789) -> Arc<AssociatedTyValue> {
@@ -800,12 +797,12 @@ pub(crate) fn associated_ty_value_query(
800} 797}
801 798
802fn type_alias_associated_ty_value( 799fn type_alias_associated_ty_value(
803 db: &impl HirDatabase, 800 db: &dyn HirDatabase,
804 _krate: CrateId, 801 _krate: CrateId,
805 type_alias: TypeAliasId, 802 type_alias: TypeAliasId,
806) -> Arc<AssociatedTyValue> { 803) -> Arc<AssociatedTyValue> {
807 let type_alias_data = db.type_alias_data(type_alias); 804 let type_alias_data = db.type_alias_data(type_alias);
808 let impl_id = match type_alias.lookup(db).container { 805 let impl_id = match type_alias.lookup(db.upcast()).container {
809 AssocContainerId::ImplId(it) => it, 806 AssocContainerId::ImplId(it) => it,
810 _ => panic!("assoc ty value should be in impl"), 807 _ => panic!("assoc ty value should be in impl"),
811 }; 808 };
diff --git a/crates/ra_hir_ty/src/utils.rs b/crates/ra_hir_ty/src/utils.rs
index 463fd65b4..b40d4eb73 100644
--- a/crates/ra_hir_ty/src/utils.rs
+++ b/crates/ra_hir_ty/src/utils.rs
@@ -14,7 +14,7 @@ use hir_def::{
14}; 14};
15use hir_expand::name::{name, Name}; 15use hir_expand::name::{name, Name};
16 16
17fn direct_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> { 17fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> {
18 let resolver = trait_.resolver(db); 18 let resolver = trait_.resolver(db);
19 // returning the iterator directly doesn't easily work because of 19 // returning the iterator directly doesn't easily work because of
20 // lifetime problems, but since there usually shouldn't be more than a 20 // lifetime problems, but since there usually shouldn't be more than a
@@ -43,7 +43,7 @@ fn direct_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> {
43 43
44/// Returns an iterator over the whole super trait hierarchy (including the 44/// Returns an iterator over the whole super trait hierarchy (including the
45/// trait itself). 45/// trait itself).
46pub(super) fn all_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> { 46pub(super) fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> {
47 // we need to take care a bit here to avoid infinite loops in case of cycles 47 // we need to take care a bit here to avoid infinite loops in case of cycles
48 // (i.e. if we have `trait A: B; trait B: A;`) 48 // (i.e. if we have `trait A: B; trait B: A;`)
49 let mut result = vec![trait_]; 49 let mut result = vec![trait_];
@@ -65,7 +65,7 @@ pub(super) fn all_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<Tr
65/// Finds a path from a trait to one of its super traits. Returns an empty 65/// Finds a path from a trait to one of its super traits. Returns an empty
66/// vector if there is no path. 66/// vector if there is no path.
67pub(super) fn find_super_trait_path( 67pub(super) fn find_super_trait_path(
68 db: &impl DefDatabase, 68 db: &dyn DefDatabase,
69 trait_: TraitId, 69 trait_: TraitId,
70 super_trait: TraitId, 70 super_trait: TraitId,
71) -> Vec<TraitId> { 71) -> Vec<TraitId> {
@@ -73,7 +73,7 @@ pub(super) fn find_super_trait_path(
73 result.push(trait_); 73 result.push(trait_);
74 return if go(db, super_trait, &mut result) { result } else { Vec::new() }; 74 return if go(db, super_trait, &mut result) { result } else { Vec::new() };
75 75
76 fn go(db: &impl DefDatabase, super_trait: TraitId, path: &mut Vec<TraitId>) -> bool { 76 fn go(db: &dyn DefDatabase, super_trait: TraitId, path: &mut Vec<TraitId>) -> bool {
77 let trait_ = *path.last().unwrap(); 77 let trait_ = *path.last().unwrap();
78 if trait_ == super_trait { 78 if trait_ == super_trait {
79 return true; 79 return true;
@@ -95,7 +95,7 @@ pub(super) fn find_super_trait_path(
95} 95}
96 96
97pub(super) fn associated_type_by_name_including_super_traits( 97pub(super) fn associated_type_by_name_including_super_traits(
98 db: &impl DefDatabase, 98 db: &dyn DefDatabase,
99 trait_: TraitId, 99 trait_: TraitId,
100 name: &Name, 100 name: &Name,
101) -> Option<TypeAliasId> { 101) -> Option<TypeAliasId> {
@@ -104,7 +104,7 @@ pub(super) fn associated_type_by_name_including_super_traits(
104 .find_map(|t| db.trait_data(t).associated_type_by_name(name)) 104 .find_map(|t| db.trait_data(t).associated_type_by_name(name))
105} 105}
106 106
107pub(super) fn variant_data(db: &impl DefDatabase, var: VariantId) -> Arc<VariantData> { 107pub(super) fn variant_data(db: &dyn DefDatabase, var: VariantId) -> Arc<VariantData> {
108 match var { 108 match var {
109 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(), 109 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
110 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(), 110 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
@@ -123,7 +123,7 @@ pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
123 Arc::get_mut(a).unwrap() 123 Arc::get_mut(a).unwrap()
124} 124}
125 125
126pub(crate) fn generics(db: &impl DefDatabase, def: GenericDefId) -> Generics { 126pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
127 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def))); 127 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
128 Generics { def, params: db.generic_params(def), parent_generics } 128 Generics { def, params: db.generic_params(def), parent_generics }
129} 129}
@@ -222,7 +222,7 @@ impl Generics {
222 } 222 }
223} 223}
224 224
225fn parent_generic_def(db: &impl DefDatabase, def: GenericDefId) -> Option<GenericDefId> { 225fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
226 let container = match def { 226 let container = match def {
227 GenericDefId::FunctionId(it) => it.lookup(db).container, 227 GenericDefId::FunctionId(it) => it.lookup(db).container,
228 GenericDefId::TypeAliasId(it) => it.lookup(db).container, 228 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
diff --git a/crates/ra_ide_db/src/lib.rs b/crates/ra_ide_db/src/lib.rs
index fc1b19def..4faeefa8d 100644
--- a/crates/ra_ide_db/src/lib.rs
+++ b/crates/ra_ide_db/src/lib.rs
@@ -14,10 +14,11 @@ mod wasm_shims;
14 14
15use std::sync::Arc; 15use std::sync::Arc;
16 16
17use hir::db::{AstDatabase, DefDatabase};
17use ra_db::{ 18use ra_db::{
18 salsa::{self, Database, Durability}, 19 salsa::{self, Database, Durability},
19 Canceled, CheckCanceled, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, 20 Canceled, CheckCanceled, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath,
20 SourceDatabase, SourceRootId, 21 SourceDatabase, SourceRootId, Upcast,
21}; 22};
22use rustc_hash::FxHashMap; 23use rustc_hash::FxHashMap;
23 24
@@ -41,6 +42,18 @@ pub struct RootDatabase {
41 pub last_gc_check: crate::wasm_shims::Instant, 42 pub last_gc_check: crate::wasm_shims::Instant,
42} 43}
43 44
45impl Upcast<dyn AstDatabase> for RootDatabase {
46 fn upcast(&self) -> &(dyn AstDatabase + 'static) {
47 &*self
48 }
49}
50
51impl Upcast<dyn DefDatabase> for RootDatabase {
52 fn upcast(&self) -> &(dyn DefDatabase + 'static) {
53 &*self
54 }
55}
56
44impl FileLoader for RootDatabase { 57impl FileLoader for RootDatabase {
45 fn file_text(&self, file_id: FileId) -> Arc<String> { 58 fn file_text(&self, file_id: FileId) -> Arc<String> {
46 FileLoaderDelegate(self).file_text(file_id) 59 FileLoaderDelegate(self).file_text(file_id)