aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src')
-rw-r--r--crates/ra_hir/src/code_model_api.rs15
-rw-r--r--crates/ra_hir/src/expr/scope.rs2
-rw-r--r--crates/ra_hir/src/ids.rs16
-rw-r--r--crates/ra_hir/src/macros.rs2
-rw-r--r--crates/ra_hir/src/marks.rs1
-rw-r--r--crates/ra_hir/src/mock.rs18
-rw-r--r--crates/ra_hir/src/nameres.rs129
-rw-r--r--crates/ra_hir/src/nameres/lower.rs18
-rw-r--r--crates/ra_hir/src/nameres/tests.rs112
-rw-r--r--crates/ra_hir/src/path.rs2
-rw-r--r--crates/ra_hir/src/resolve.rs24
-rw-r--r--crates/ra_hir/src/ty.rs4
-rw-r--r--crates/ra_hir/src/ty/snapshots/tests__infer_nested_generics_crash.snap12
-rw-r--r--crates/ra_hir/src/ty/tests.rs19
14 files changed, 320 insertions, 54 deletions
diff --git a/crates/ra_hir/src/code_model_api.rs b/crates/ra_hir/src/code_model_api.rs
index 94a08aa63..fb7ad0867 100644
--- a/crates/ra_hir/src/code_model_api.rs
+++ b/crates/ra_hir/src/code_model_api.rs
@@ -1,7 +1,7 @@
1use std::sync::Arc; 1use std::sync::Arc;
2 2
3use relative_path::RelativePathBuf; 3use relative_path::RelativePathBuf;
4use ra_db::{CrateId, FileId, SourceRootId}; 4use ra_db::{CrateId, FileId, SourceRootId, Edition};
5use ra_syntax::{ast::self, TreeArc, SyntaxNode}; 5use ra_syntax::{ast::self, TreeArc, SyntaxNode};
6 6
7use crate::{ 7use crate::{
@@ -38,13 +38,20 @@ impl Crate {
38 pub fn crate_id(&self) -> CrateId { 38 pub fn crate_id(&self) -> CrateId {
39 self.crate_id 39 self.crate_id
40 } 40 }
41
41 pub fn dependencies(&self, db: &impl PersistentHirDatabase) -> Vec<CrateDependency> { 42 pub fn dependencies(&self, db: &impl PersistentHirDatabase) -> Vec<CrateDependency> {
42 self.dependencies_impl(db) 43 self.dependencies_impl(db)
43 } 44 }
45
44 pub fn root_module(&self, db: &impl PersistentHirDatabase) -> Option<Module> { 46 pub fn root_module(&self, db: &impl PersistentHirDatabase) -> Option<Module> {
45 self.root_module_impl(db) 47 self.root_module_impl(db)
46 } 48 }
47 49
50 pub fn edition(&self, db: &impl PersistentHirDatabase) -> Edition {
51 let crate_graph = db.crate_graph();
52 crate_graph.edition(self.crate_id)
53 }
54
48 // TODO: should this be in source_binder? 55 // TODO: should this be in source_binder?
49 pub fn source_root_crates( 56 pub fn source_root_crates(
50 db: &impl PersistentHirDatabase, 57 db: &impl PersistentHirDatabase,
@@ -134,7 +141,7 @@ impl Module {
134 141
135 /// Topmost parent of this module. Every module has a `crate_root`, but some 142 /// Topmost parent of this module. Every module has a `crate_root`, but some
136 /// might be missing `krate`. This can happen if a module's file is not included 143 /// might be missing `krate`. This can happen if a module's file is not included
137 /// in the module tree of any target in Cargo.toml. 144 /// in the module tree of any target in `Cargo.toml`.
138 pub fn crate_root(&self, db: &impl PersistentHirDatabase) -> Module { 145 pub fn crate_root(&self, db: &impl PersistentHirDatabase) -> Module {
139 self.crate_root_impl(db) 146 self.crate_root_impl(db)
140 } 147 }
@@ -351,7 +358,7 @@ impl Enum {
351 db.type_for_def((*self).into()) 358 db.type_for_def((*self).into())
352 } 359 }
353 360
354 // TODO move to a more general type 361 // TODO: move to a more general type
355 /// Builds a resolver for type references inside this struct. 362 /// Builds a resolver for type references inside this struct.
356 pub fn resolver(&self, db: &impl HirDatabase) -> Resolver { 363 pub fn resolver(&self, db: &impl HirDatabase) -> Resolver {
357 // take the outer scope... 364 // take the outer scope...
@@ -495,7 +502,7 @@ impl Function {
495 db.generic_params((*self).into()) 502 db.generic_params((*self).into())
496 } 503 }
497 504
498 // TODO move to a more general type for 'body-having' items 505 // TODO: move to a more general type for 'body-having' items
499 /// Builds a resolver for code inside this item. 506 /// Builds a resolver for code inside this item.
500 pub fn resolver(&self, db: &impl HirDatabase) -> Resolver { 507 pub fn resolver(&self, db: &impl HirDatabase) -> Resolver {
501 // take the outer scope... 508 // take the outer scope...
diff --git a/crates/ra_hir/src/expr/scope.rs b/crates/ra_hir/src/expr/scope.rs
index 44d5c2429..bb8d50db8 100644
--- a/crates/ra_hir/src/expr/scope.rs
+++ b/crates/ra_hir/src/expr/scope.rs
@@ -84,7 +84,7 @@ impl ExprScopes {
84 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) { 84 fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
85 match &body[pat] { 85 match &body[pat] {
86 Pat::Bind { name, .. } => { 86 Pat::Bind { name, .. } => {
87 // bind can have a subpattern, but it's actually not allowed 87 // bind can have a sub pattern, but it's actually not allowed
88 // to bind to things in there 88 // to bind to things in there
89 let entry = ScopeEntry { name: name.clone(), pat }; 89 let entry = ScopeEntry { name: name.clone(), pat };
90 self.scopes[scope].entries.push(entry) 90 self.scopes[scope].entries.push(entry)
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs
index d3fa7d266..8d81d5ebf 100644
--- a/crates/ra_hir/src/ids.rs
+++ b/crates/ra_hir/src/ids.rs
@@ -46,24 +46,24 @@ impl HirInterner {
46/// This module defines a bunch of ids we are using. The most important ones are 46/// This module defines a bunch of ids we are using. The most important ones are
47/// probably `HirFileId` and `DefId`. 47/// probably `HirFileId` and `DefId`.
48 48
49/// Input to the analyzer is a set of files, where each file is indentified by 49/// Input to the analyzer is a set of files, where each file is identified by
50/// `FileId` and contains source code. However, another source of source code in 50/// `FileId` and contains source code. However, another source of source code in
51/// Rust are macros: each macro can be thought of as producing a "temporary 51/// Rust are macros: each macro can be thought of as producing a "temporary
52/// file". To assign an id to such a file, we use the id of the macro call that 52/// file". To assign an id to such a file, we use the id of the macro call that
53/// produced the file. So, a `HirFileId` is either a `FileId` (source code 53/// produced the file. So, a `HirFileId` is either a `FileId` (source code
54/// written by user), or a `MacroCallId` (source code produced by macro). 54/// written by user), or a `MacroCallId` (source code produced by macro).
55/// 55///
56/// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file containin 56/// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
57/// the call plus the offset of the macro call in the file. Note that this is a 57/// containing the call plus the offset of the macro call in the file. Note that
58/// recursive definition! However, the size_of of `HirFileId` is finite 58/// this is a recursive definition! However, the size_of of `HirFileId` is
59/// (because everything bottoms out at the real `FileId`) and small 59/// finite (because everything bottoms out at the real `FileId`) and small
60/// (`MacroCallId` uses the location interner). 60/// (`MacroCallId` uses the location interner).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub struct HirFileId(HirFileIdRepr); 62pub struct HirFileId(HirFileIdRepr);
63 63
64impl HirFileId { 64impl HirFileId {
65 /// For macro-expansion files, returns the file original source file the 65 /// For macro-expansion files, returns the file original source file the
66 /// expansionoriginated from. 66 /// expansion originated from.
67 pub fn original_file(self, db: &impl PersistentHirDatabase) -> FileId { 67 pub fn original_file(self, db: &impl PersistentHirDatabase) -> FileId {
68 match self.0 { 68 match self.0 {
69 HirFileIdRepr::File(file_id) => file_id, 69 HirFileIdRepr::File(file_id) => file_id,
@@ -324,9 +324,9 @@ impl SourceFileItems {
324 324
325 fn init(&mut self, source_file: &SourceFile) { 325 fn init(&mut self, source_file: &SourceFile) {
326 // By walking the tree in bread-first order we make sure that parents 326 // By walking the tree in bread-first order we make sure that parents
327 // get lower ids then children. That is, addding a new child does not 327 // get lower ids then children. That is, adding a new child does not
328 // change parent's id. This means that, say, adding a new function to a 328 // change parent's id. This means that, say, adding a new function to a
329 // trait does not chage ids of top-level items, which helps caching. 329 // trait does not change ids of top-level items, which helps caching.
330 bfs(source_file.syntax(), |it| { 330 bfs(source_file.syntax(), |it| {
331 if let Some(module_item) = ast::ModuleItem::cast(it) { 331 if let Some(module_item) = ast::ModuleItem::cast(it) {
332 self.alloc(module_item.syntax()); 332 self.alloc(module_item.syntax());
diff --git a/crates/ra_hir/src/macros.rs b/crates/ra_hir/src/macros.rs
index dd477e9f9..45128c7df 100644
--- a/crates/ra_hir/src/macros.rs
+++ b/crates/ra_hir/src/macros.rs
@@ -67,7 +67,7 @@ impl MacroDef {
67 } 67 }
68} 68}
69 69
70#[derive(Debug, Clone, PartialEq, Eq, Hash)] 70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct MacroInput { 71pub struct MacroInput {
72 // Should be token trees 72 // Should be token trees
73 pub text: String, 73 pub text: String,
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs
index 50d4e824c..16852a6a1 100644
--- a/crates/ra_hir/src/marks.rs
+++ b/crates/ra_hir/src/marks.rs
@@ -6,4 +6,5 @@ test_utils::marks!(
6 type_var_resolves_to_int_var 6 type_var_resolves_to_int_var
7 glob_enum 7 glob_enum
8 glob_across_crates 8 glob_across_crates
9 std_prelude
9); 10);
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs
index 5ca870867..f1cad77c5 100644
--- a/crates/ra_hir/src/mock.rs
+++ b/crates/ra_hir/src/mock.rs
@@ -3,6 +3,7 @@ use std::{sync::Arc, panic};
3use parking_lot::Mutex; 3use parking_lot::Mutex;
4use ra_db::{ 4use ra_db::{
5 FilePosition, FileId, CrateGraph, SourceRoot, SourceRootId, SourceDatabase, salsa, 5 FilePosition, FileId, CrateGraph, SourceRoot, SourceRootId, SourceDatabase, salsa,
6 Edition,
6}; 7};
7use relative_path::RelativePathBuf; 8use relative_path::RelativePathBuf;
8use test_utils::{parse_fixture, CURSOR_MARKER, extract_offset}; 9use test_utils::{parse_fixture, CURSOR_MARKER, extract_offset};
@@ -58,12 +59,12 @@ impl MockDatabase {
58 pub fn set_crate_graph_from_fixture(&mut self, graph: CrateGraphFixture) { 59 pub fn set_crate_graph_from_fixture(&mut self, graph: CrateGraphFixture) {
59 let mut ids = FxHashMap::default(); 60 let mut ids = FxHashMap::default();
60 let mut crate_graph = CrateGraph::default(); 61 let mut crate_graph = CrateGraph::default();
61 for (crate_name, (crate_root, _)) in graph.0.iter() { 62 for (crate_name, (crate_root, edition, _)) in graph.0.iter() {
62 let crate_root = self.file_id_of(&crate_root); 63 let crate_root = self.file_id_of(&crate_root);
63 let crate_id = crate_graph.add_crate_root(crate_root); 64 let crate_id = crate_graph.add_crate_root(crate_root, *edition);
64 ids.insert(crate_name, crate_id); 65 ids.insert(crate_name, crate_id);
65 } 66 }
66 for (crate_name, (_, deps)) in graph.0.iter() { 67 for (crate_name, (_, _, deps)) in graph.0.iter() {
67 let from = ids[crate_name]; 68 let from = ids[crate_name];
68 for dep in deps { 69 for dep in deps {
69 let to = ids[dep]; 70 let to = ids[dep];
@@ -144,7 +145,7 @@ impl MockDatabase {
144 145
145 if is_crate_root { 146 if is_crate_root {
146 let mut crate_graph = CrateGraph::default(); 147 let mut crate_graph = CrateGraph::default();
147 crate_graph.add_crate_root(file_id); 148 crate_graph.add_crate_root(file_id, Edition::Edition2018);
148 self.set_crate_graph(Arc::new(crate_graph)); 149 self.set_crate_graph(Arc::new(crate_graph));
149 } 150 }
150 file_id 151 file_id
@@ -232,16 +233,19 @@ impl MockDatabase {
232} 233}
233 234
234#[derive(Default)] 235#[derive(Default)]
235pub struct CrateGraphFixture(pub FxHashMap<String, (String, Vec<String>)>); 236pub struct CrateGraphFixture(pub FxHashMap<String, (String, Edition, Vec<String>)>);
236 237
237#[macro_export] 238#[macro_export]
238macro_rules! crate_graph { 239macro_rules! crate_graph {
239 ($($crate_name:literal: ($crate_path:literal, [$($dep:literal),*]),)*) => {{ 240 ($($crate_name:literal: ($crate_path:literal, $($edition:literal,)? [$($dep:literal),*]),)*) => {{
240 let mut res = $crate::mock::CrateGraphFixture::default(); 241 let mut res = $crate::mock::CrateGraphFixture::default();
241 $( 242 $(
243 #[allow(unused_mut, unused_assignments)]
244 let mut edition = ra_db::Edition::Edition2018;
245 $(edition = ra_db::Edition::from_string($edition);)?
242 res.0.insert( 246 res.0.insert(
243 $crate_name.to_string(), 247 $crate_name.to_string(),
244 ($crate_path.to_string(), vec![$($dep.to_string()),*]) 248 ($crate_path.to_string(), edition, vec![$($dep.to_string()),*])
245 ); 249 );
246 )* 250 )*
247 res 251 res
diff --git a/crates/ra_hir/src/nameres.rs b/crates/ra_hir/src/nameres.rs
index 261ebdf97..e35b4b129 100644
--- a/crates/ra_hir/src/nameres.rs
+++ b/crates/ra_hir/src/nameres.rs
@@ -18,9 +18,11 @@ pub(crate) mod lower;
18 18
19use std::{time, sync::Arc}; 19use std::{time, sync::Arc};
20 20
21use rustc_hash::{FxHashMap, FxHashSet};
22
21use ra_arena::map::ArenaMap; 23use ra_arena::map::ArenaMap;
24use ra_db::Edition;
22use test_utils::tested_by; 25use test_utils::tested_by;
23use rustc_hash::{FxHashMap, FxHashSet};
24 26
25use crate::{ 27use crate::{
26 Module, ModuleDef, 28 Module, ModuleDef,
@@ -32,8 +34,13 @@ use crate::{
32 34
33/// `ItemMap` is the result of module name resolution. It contains, for each 35/// `ItemMap` is the result of module name resolution. It contains, for each
34/// module, the set of visible items. 36/// module, the set of visible items.
35#[derive(Default, Debug, PartialEq, Eq)] 37#[derive(Debug, PartialEq, Eq)]
36pub struct ItemMap { 38pub struct ItemMap {
39 edition: Edition,
40 /// The prelude module for this crate. This either comes from an import
41 /// marked with the `prelude_import` attribute, or (in the normal case) from
42 /// a dependency (`std` or `core`).
43 pub(crate) prelude: Option<Module>,
37 pub(crate) extern_prelude: FxHashMap<Name, ModuleDef>, 44 pub(crate) extern_prelude: FxHashMap<Name, ModuleDef>,
38 per_module: ArenaMap<ModuleId, ModuleScope>, 45 per_module: ArenaMap<ModuleId, ModuleScope>,
39} 46}
@@ -176,7 +183,12 @@ where
176 module_tree, 183 module_tree,
177 processed_imports: FxHashSet::default(), 184 processed_imports: FxHashSet::default(),
178 glob_imports: FxHashMap::default(), 185 glob_imports: FxHashMap::default(),
179 result: ItemMap::default(), 186 result: ItemMap {
187 edition: krate.edition(db),
188 prelude: None,
189 extern_prelude: FxHashMap::default(),
190 per_module: ArenaMap::default(),
191 },
180 } 192 }
181 } 193 }
182 194
@@ -211,6 +223,13 @@ where
211 if let Some(module) = dep.krate.root_module(self.db) { 223 if let Some(module) = dep.krate.root_module(self.db) {
212 self.result.extern_prelude.insert(dep.name.clone(), module.into()); 224 self.result.extern_prelude.insert(dep.name.clone(), module.into());
213 } 225 }
226 // look for the prelude
227 if self.result.prelude.is_none() {
228 let item_map = self.db.item_map(dep.krate);
229 if item_map.prelude.is_some() {
230 self.result.prelude = item_map.prelude;
231 }
232 }
214 } 233 }
215 } 234 }
216 235
@@ -266,10 +285,20 @@ where
266 import_id: ImportId, 285 import_id: ImportId,
267 import: &ImportData, 286 import: &ImportData,
268 ) -> ReachedFixedPoint { 287 ) -> ReachedFixedPoint {
269 log::debug!("resolving import: {:?}", import); 288 log::debug!("resolving import: {:?} ({:?})", import, self.result.edition);
270 let original_module = Module { krate: self.krate, module_id }; 289 let original_module = Module { krate: self.krate, module_id };
271 let (def, reached_fixedpoint) = 290
272 self.result.resolve_path_fp(self.db, original_module, &import.path); 291 let (def, reached_fixedpoint) = if import.is_extern_crate {
292 let res = self.result.resolve_name_in_extern_prelude(
293 &import
294 .path
295 .as_ident()
296 .expect("extern crate should have been desugared to one-element path"),
297 );
298 (res, if res.is_none() { ReachedFixedPoint::No } else { ReachedFixedPoint::Yes })
299 } else {
300 self.result.resolve_path_fp(self.db, ResolveMode::Import, original_module, &import.path)
301 };
273 302
274 if reached_fixedpoint != ReachedFixedPoint::Yes { 303 if reached_fixedpoint != ReachedFixedPoint::Yes {
275 return reached_fixedpoint; 304 return reached_fixedpoint;
@@ -279,7 +308,10 @@ where
279 log::debug!("glob import: {:?}", import); 308 log::debug!("glob import: {:?}", import);
280 match def.take_types() { 309 match def.take_types() {
281 Some(ModuleDef::Module(m)) => { 310 Some(ModuleDef::Module(m)) => {
282 if m.krate != self.krate { 311 if import.is_prelude {
312 tested_by!(std_prelude);
313 self.result.prelude = Some(m);
314 } else if m.krate != self.krate {
283 tested_by!(glob_across_crates); 315 tested_by!(glob_across_crates);
284 // glob import from other crate => we can just import everything once 316 // glob import from other crate => we can just import everything once
285 let item_map = self.db.item_map(m.krate); 317 let item_map = self.db.item_map(m.krate);
@@ -404,6 +436,12 @@ where
404} 436}
405 437
406#[derive(Debug, Clone, Copy, PartialEq, Eq)] 438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439enum ResolveMode {
440 Import,
441 Other,
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407enum ReachedFixedPoint { 445enum ReachedFixedPoint {
408 Yes, 446 Yes,
409 No, 447 No,
@@ -431,15 +469,61 @@ impl ItemMap {
431 original_module: Module, 469 original_module: Module,
432 path: &Path, 470 path: &Path,
433 ) -> PerNs<ModuleDef> { 471 ) -> PerNs<ModuleDef> {
434 self.resolve_path_fp(db, original_module, path).0 472 self.resolve_path_fp(db, ResolveMode::Other, original_module, path).0
473 }
474
475 fn resolve_in_prelude(
476 &self,
477 db: &impl PersistentHirDatabase,
478 original_module: Module,
479 name: &Name,
480 ) -> PerNs<ModuleDef> {
481 if let Some(prelude) = self.prelude {
482 let resolution = if prelude.krate == original_module.krate {
483 self[prelude.module_id].items.get(name).cloned()
484 } else {
485 db.item_map(prelude.krate)[prelude.module_id].items.get(name).cloned()
486 };
487 resolution.map(|r| r.def).unwrap_or_else(PerNs::none)
488 } else {
489 PerNs::none()
490 }
435 } 491 }
436 492
437 pub(crate) fn resolve_name_in_module(&self, module: Module, name: &Name) -> PerNs<ModuleDef> { 493 pub(crate) fn resolve_name_in_module(
494 &self,
495 db: &impl PersistentHirDatabase,
496 module: Module,
497 name: &Name,
498 ) -> PerNs<ModuleDef> {
499 // Resolve in:
500 // - current module / scope
501 // - extern prelude
502 // - std prelude
438 let from_scope = self[module.module_id].items.get(name).map_or(PerNs::none(), |it| it.def); 503 let from_scope = self[module.module_id].items.get(name).map_or(PerNs::none(), |it| it.def);
439 let from_extern_prelude = 504 let from_extern_prelude =
440 self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it)); 505 self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it));
506 let from_prelude = self.resolve_in_prelude(db, module, name);
507
508 from_scope.or(from_extern_prelude).or(from_prelude)
509 }
510
511 fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs<ModuleDef> {
512 self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it))
513 }
441 514
442 from_scope.or(from_extern_prelude) 515 fn resolve_name_in_crate_root_or_extern_prelude(
516 &self,
517 db: &impl PersistentHirDatabase,
518 module: Module,
519 name: &Name,
520 ) -> PerNs<ModuleDef> {
521 let crate_root = module.crate_root(db);
522 let from_crate_root =
523 self[crate_root.module_id].items.get(name).map_or(PerNs::none(), |it| it.def);
524 let from_extern_prelude = self.resolve_name_in_extern_prelude(name);
525
526 from_crate_root.or(from_extern_prelude)
443 } 527 }
444 528
445 // Returns Yes if we are sure that additions to `ItemMap` wouldn't change 529 // Returns Yes if we are sure that additions to `ItemMap` wouldn't change
@@ -447,6 +531,7 @@ impl ItemMap {
447 fn resolve_path_fp( 531 fn resolve_path_fp(
448 &self, 532 &self,
449 db: &impl PersistentHirDatabase, 533 db: &impl PersistentHirDatabase,
534 mode: ResolveMode,
450 original_module: Module, 535 original_module: Module,
451 path: &Path, 536 path: &Path,
452 ) -> (PerNs<ModuleDef>, ReachedFixedPoint) { 537 ) -> (PerNs<ModuleDef>, ReachedFixedPoint) {
@@ -454,12 +539,32 @@ impl ItemMap {
454 let mut curr_per_ns: PerNs<ModuleDef> = match path.kind { 539 let mut curr_per_ns: PerNs<ModuleDef> = match path.kind {
455 PathKind::Crate => PerNs::types(original_module.crate_root(db).into()), 540 PathKind::Crate => PerNs::types(original_module.crate_root(db).into()),
456 PathKind::Self_ => PerNs::types(original_module.into()), 541 PathKind::Self_ => PerNs::types(original_module.into()),
542 // plain import or absolute path in 2015: crate-relative with
543 // fallback to extern prelude (with the simplification in
544 // rust-lang/rust#57745)
545 // TODO there must be a nicer way to write this condition
546 PathKind::Plain | PathKind::Abs
547 if self.edition == Edition::Edition2015
548 && (path.kind == PathKind::Abs || mode == ResolveMode::Import) =>
549 {
550 let segment = match segments.next() {
551 Some((_, segment)) => segment,
552 None => return (PerNs::none(), ReachedFixedPoint::Yes),
553 };
554 log::debug!("resolving {:?} in crate root (+ extern prelude)", segment);
555 self.resolve_name_in_crate_root_or_extern_prelude(
556 db,
557 original_module,
558 &segment.name,
559 )
560 }
457 PathKind::Plain => { 561 PathKind::Plain => {
458 let segment = match segments.next() { 562 let segment = match segments.next() {
459 Some((_, segment)) => segment, 563 Some((_, segment)) => segment,
460 None => return (PerNs::none(), ReachedFixedPoint::Yes), 564 None => return (PerNs::none(), ReachedFixedPoint::Yes),
461 }; 565 };
462 self.resolve_name_in_module(original_module, &segment.name) 566 log::debug!("resolving {:?} in module", segment);
567 self.resolve_name_in_module(db, original_module, &segment.name)
463 } 568 }
464 PathKind::Super => { 569 PathKind::Super => {
465 if let Some(p) = original_module.parent(db) { 570 if let Some(p) = original_module.parent(db) {
@@ -490,7 +595,7 @@ impl ItemMap {
490 None => { 595 None => {
491 // we still have path segments left, but the path so far 596 // we still have path segments left, but the path so far
492 // didn't resolve in the types namespace => no resolution 597 // didn't resolve in the types namespace => no resolution
493 // (don't break here because curr_per_ns might contain 598 // (don't break here because `curr_per_ns` might contain
494 // something in the value namespace, and it would be wrong 599 // something in the value namespace, and it would be wrong
495 // to return that) 600 // to return that)
496 return (PerNs::none(), ReachedFixedPoint::No); 601 return (PerNs::none(), ReachedFixedPoint::No);
diff --git a/crates/ra_hir/src/nameres/lower.rs b/crates/ra_hir/src/nameres/lower.rs
index 7e9a3de2b..81d80654c 100644
--- a/crates/ra_hir/src/nameres/lower.rs
+++ b/crates/ra_hir/src/nameres/lower.rs
@@ -2,13 +2,13 @@ use std::sync::Arc;
2 2
3use ra_syntax::{ 3use ra_syntax::{
4 AstNode, SourceFile, TreeArc, AstPtr, 4 AstNode, SourceFile, TreeArc, AstPtr,
5 ast::{self, ModuleItemOwner, NameOwner}, 5 ast::{self, ModuleItemOwner, NameOwner, AttrsOwner},
6}; 6};
7use ra_arena::{Arena, RawId, impl_arena_id, map::ArenaMap}; 7use ra_arena::{Arena, RawId, impl_arena_id, map::ArenaMap};
8use rustc_hash::FxHashMap; 8use rustc_hash::FxHashMap;
9 9
10use crate::{ 10use crate::{
11 SourceItemId, Path, PathKind, ModuleSource, Name, 11 SourceItemId, Path, ModuleSource, Name,
12 HirFileId, MacroCallLoc, AsName, PerNs, Function, 12 HirFileId, MacroCallLoc, AsName, PerNs, Function,
13 ModuleDef, Module, Struct, Enum, Const, Static, Trait, Type, 13 ModuleDef, Module, Struct, Enum, Const, Static, Trait, Type,
14 ids::LocationCtx, PersistentHirDatabase, 14 ids::LocationCtx, PersistentHirDatabase,
@@ -23,6 +23,7 @@ pub(super) struct ImportData {
23 pub(super) path: Path, 23 pub(super) path: Path,
24 pub(super) alias: Option<Name>, 24 pub(super) alias: Option<Name>,
25 pub(super) is_glob: bool, 25 pub(super) is_glob: bool,
26 pub(super) is_prelude: bool,
26 pub(super) is_extern_crate: bool, 27 pub(super) is_extern_crate: bool,
27} 28}
28 29
@@ -179,18 +180,14 @@ impl LoweredModule {
179 self.add_use_item(source_map, it); 180 self.add_use_item(source_map, it);
180 } 181 }
181 ast::ModuleItemKind::ExternCrateItem(it) => { 182 ast::ModuleItemKind::ExternCrateItem(it) => {
182 // Lower `extern crate x` to `use ::x`. This is kind of cheating
183 // and only works if we always interpret absolute paths in the
184 // 2018 style; otherwise `::x` could also refer to a module in
185 // the crate root.
186 if let Some(name_ref) = it.name_ref() { 183 if let Some(name_ref) = it.name_ref() {
187 let mut path = Path::from_name_ref(name_ref); 184 let path = Path::from_name_ref(name_ref);
188 path.kind = PathKind::Abs;
189 let alias = it.alias().and_then(|a| a.name()).map(AsName::as_name); 185 let alias = it.alias().and_then(|a| a.name()).map(AsName::as_name);
190 self.imports.alloc(ImportData { 186 self.imports.alloc(ImportData {
191 path, 187 path,
192 alias, 188 alias,
193 is_glob: false, 189 is_glob: false,
190 is_prelude: false,
194 is_extern_crate: true, 191 is_extern_crate: true,
195 }); 192 });
196 } 193 }
@@ -208,17 +205,20 @@ impl LoweredModule {
208 } 205 }
209 } 206 }
210 ast::ModuleItemKind::Module(_) => { 207 ast::ModuleItemKind::Module(_) => {
211 // modules are handled separately direclty by nameres 208 // modules are handled separately directly by name res
212 } 209 }
213 }; 210 };
214 } 211 }
215 212
216 fn add_use_item(&mut self, source_map: &mut ImportSourceMap, item: &ast::UseItem) { 213 fn add_use_item(&mut self, source_map: &mut ImportSourceMap, item: &ast::UseItem) {
214 let is_prelude =
215 item.attrs().any(|attr| attr.as_atom().map(|s| s == "prelude_import").unwrap_or(false));
217 Path::expand_use_item(item, |path, segment, alias| { 216 Path::expand_use_item(item, |path, segment, alias| {
218 let import = self.imports.alloc(ImportData { 217 let import = self.imports.alloc(ImportData {
219 path, 218 path,
220 alias, 219 alias,
221 is_glob: segment.is_none(), 220 is_glob: segment.is_none(),
221 is_prelude,
222 is_extern_crate: false, 222 is_extern_crate: false,
223 }); 223 });
224 if let Some(segment) = segment { 224 if let Some(segment) = segment {
diff --git a/crates/ra_hir/src/nameres/tests.rs b/crates/ra_hir/src/nameres/tests.rs
index 6dbe759d1..6402c89c0 100644
--- a/crates/ra_hir/src/nameres/tests.rs
+++ b/crates/ra_hir/src/nameres/tests.rs
@@ -266,6 +266,45 @@ fn glob_across_crates() {
266} 266}
267 267
268#[test] 268#[test]
269fn edition_2015_imports() {
270 let mut db = MockDatabase::with_files(
271 "
272 //- /main.rs
273 mod foo;
274 mod bar;
275
276 //- /bar.rs
277 struct Bar;
278
279 //- /foo.rs
280 use bar::Bar;
281 use other_crate::FromLib;
282
283 //- /lib.rs
284 struct FromLib;
285 ",
286 );
287 db.set_crate_graph_from_fixture(crate_graph! {
288 "main": ("/main.rs", "2015", ["other_crate"]),
289 "other_crate": ("/lib.rs", "2018", []),
290 });
291 let foo_id = db.file_id_of("/foo.rs");
292
293 let module = crate::source_binder::module_from_file_id(&db, foo_id).unwrap();
294 let krate = module.krate(&db).unwrap();
295 let item_map = db.item_map(krate);
296
297 check_module_item_map(
298 &item_map,
299 module.module_id,
300 "
301 Bar: t v
302 FromLib: t v
303 ",
304 );
305}
306
307#[test]
269fn module_resolution_works_for_non_standard_filenames() { 308fn module_resolution_works_for_non_standard_filenames() {
270 let mut db = MockDatabase::with_files( 309 let mut db = MockDatabase::with_files(
271 " 310 "
@@ -297,6 +336,43 @@ fn module_resolution_works_for_non_standard_filenames() {
297} 336}
298 337
299#[test] 338#[test]
339fn std_prelude() {
340 covers!(std_prelude);
341 let mut db = MockDatabase::with_files(
342 "
343 //- /main.rs
344 use Foo::*;
345
346 //- /lib.rs
347 mod prelude;
348 #[prelude_import]
349 use prelude::*;
350
351 //- /prelude.rs
352 pub enum Foo { Bar, Baz };
353 ",
354 );
355 db.set_crate_graph_from_fixture(crate_graph! {
356 "main": ("/main.rs", ["test_crate"]),
357 "test_crate": ("/lib.rs", []),
358 });
359 let main_id = db.file_id_of("/main.rs");
360
361 let module = crate::source_binder::module_from_file_id(&db, main_id).unwrap();
362 let krate = module.krate(&db).unwrap();
363 let item_map = db.item_map(krate);
364
365 check_module_item_map(
366 &item_map,
367 module.module_id,
368 "
369 Bar: t v
370 Baz: t v
371 ",
372 );
373}
374
375#[test]
300fn name_res_works_for_broken_modules() { 376fn name_res_works_for_broken_modules() {
301 covers!(name_res_works_for_broken_modules); 377 covers!(name_res_works_for_broken_modules);
302 let (item_map, module_id) = item_map( 378 let (item_map, module_id) = item_map(
@@ -467,6 +543,42 @@ fn extern_crate_rename() {
467} 543}
468 544
469#[test] 545#[test]
546fn extern_crate_rename_2015_edition() {
547 let mut db = MockDatabase::with_files(
548 "
549 //- /main.rs
550 extern crate alloc as alloc_crate;
551
552 mod alloc;
553 mod sync;
554
555 //- /sync.rs
556 use alloc_crate::Arc;
557
558 //- /lib.rs
559 struct Arc;
560 ",
561 );
562 db.set_crate_graph_from_fixture(crate_graph! {
563 "main": ("/main.rs", "2015", ["alloc"]),
564 "alloc": ("/lib.rs", []),
565 });
566 let sync_id = db.file_id_of("/sync.rs");
567
568 let module = crate::source_binder::module_from_file_id(&db, sync_id).unwrap();
569 let krate = module.krate(&db).unwrap();
570 let item_map = db.item_map(krate);
571
572 check_module_item_map(
573 &item_map,
574 module.module_id,
575 "
576 Arc: t v
577 ",
578 );
579}
580
581#[test]
470fn import_across_source_roots() { 582fn import_across_source_roots() {
471 let mut db = MockDatabase::with_files( 583 let mut db = MockDatabase::with_files(
472 " 584 "
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs
index 6a24c8aa7..8ed54607a 100644
--- a/crates/ra_hir/src/path.rs
+++ b/crates/ra_hir/src/path.rs
@@ -97,7 +97,7 @@ impl Path {
97 return Some(q); 97 return Some(q);
98 } 98 }
99 // TODO: this bottom up traversal is not too precise. 99 // TODO: this bottom up traversal is not too precise.
100 // Should we handle do a top-down analysiss, recording results? 100 // Should we handle do a top-down analysis, recording results?
101 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?; 101 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
102 let use_tree = use_tree_list.parent_use_tree(); 102 let use_tree = use_tree_list.parent_use_tree();
103 use_tree.path() 103 use_tree.path()
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs
index 40c860cf4..91a531801 100644
--- a/crates/ra_hir/src/resolve.rs
+++ b/crates/ra_hir/src/resolve.rs
@@ -56,10 +56,10 @@ pub enum Resolution {
56} 56}
57 57
58impl Resolver { 58impl Resolver {
59 pub fn resolve_name(&self, name: &Name) -> PerNs<Resolution> { 59 pub fn resolve_name(&self, db: &impl HirDatabase, name: &Name) -> PerNs<Resolution> {
60 let mut resolution = PerNs::none(); 60 let mut resolution = PerNs::none();
61 for scope in self.scopes.iter().rev() { 61 for scope in self.scopes.iter().rev() {
62 resolution = resolution.or(scope.resolve_name(name)); 62 resolution = resolution.or(scope.resolve_name(db, name));
63 if resolution.is_both() { 63 if resolution.is_both() {
64 return resolution; 64 return resolution;
65 } 65 }
@@ -69,9 +69,9 @@ impl Resolver {
69 69
70 pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> PerNs<Resolution> { 70 pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> PerNs<Resolution> {
71 if let Some(name) = path.as_ident() { 71 if let Some(name) = path.as_ident() {
72 self.resolve_name(name) 72 self.resolve_name(db, name)
73 } else if path.is_self() { 73 } else if path.is_self() {
74 self.resolve_name(&Name::self_param()) 74 self.resolve_name(db, &Name::self_param())
75 } else { 75 } else {
76 let (item_map, module) = match self.module() { 76 let (item_map, module) = match self.module() {
77 Some(m) => m, 77 Some(m) => m,
@@ -82,10 +82,10 @@ impl Resolver {
82 } 82 }
83 } 83 }
84 84
85 pub fn all_names(&self) -> FxHashMap<Name, PerNs<Resolution>> { 85 pub fn all_names(&self, db: &impl HirDatabase) -> FxHashMap<Name, PerNs<Resolution>> {
86 let mut names = FxHashMap::default(); 86 let mut names = FxHashMap::default();
87 for scope in self.scopes.iter().rev() { 87 for scope in self.scopes.iter().rev() {
88 scope.collect_names(&mut |name, res| { 88 scope.collect_names(db, &mut |name, res| {
89 let current: &mut PerNs<Resolution> = names.entry(name).or_default(); 89 let current: &mut PerNs<Resolution> = names.entry(name).or_default();
90 if current.types.is_none() { 90 if current.types.is_none() {
91 current.types = res.types; 91 current.types = res.types;
@@ -143,13 +143,13 @@ impl Resolver {
143} 143}
144 144
145impl Scope { 145impl Scope {
146 fn resolve_name(&self, name: &Name) -> PerNs<Resolution> { 146 fn resolve_name(&self, db: &impl HirDatabase, name: &Name) -> PerNs<Resolution> {
147 match self { 147 match self {
148 Scope::ModuleScope(m) => { 148 Scope::ModuleScope(m) => {
149 if let Some(KnownName::SelfParam) = name.as_known_name() { 149 if let Some(KnownName::SelfParam) = name.as_known_name() {
150 PerNs::types(Resolution::Def(m.module.into())) 150 PerNs::types(Resolution::Def(m.module.into()))
151 } else { 151 } else {
152 m.item_map.resolve_name_in_module(m.module, name).map(Resolution::Def) 152 m.item_map.resolve_name_in_module(db, m.module, name).map(Resolution::Def)
153 } 153 }
154 } 154 }
155 Scope::GenericParams(gp) => match gp.find_by_name(name) { 155 Scope::GenericParams(gp) => match gp.find_by_name(name) {
@@ -174,7 +174,7 @@ impl Scope {
174 } 174 }
175 } 175 }
176 176
177 fn collect_names(&self, f: &mut dyn FnMut(Name, PerNs<Resolution>)) { 177 fn collect_names(&self, db: &impl HirDatabase, f: &mut dyn FnMut(Name, PerNs<Resolution>)) {
178 match self { 178 match self {
179 Scope::ModuleScope(m) => { 179 Scope::ModuleScope(m) => {
180 // TODO: should we provide `self` here? 180 // TODO: should we provide `self` here?
@@ -190,6 +190,12 @@ impl Scope {
190 m.item_map.extern_prelude.iter().for_each(|(name, def)| { 190 m.item_map.extern_prelude.iter().for_each(|(name, def)| {
191 f(name.clone(), PerNs::types(Resolution::Def(*def))); 191 f(name.clone(), PerNs::types(Resolution::Def(*def)));
192 }); 192 });
193 if let Some(prelude) = m.item_map.prelude {
194 let prelude_item_map = db.item_map(prelude.krate);
195 prelude_item_map[prelude.module_id].entries().for_each(|(name, res)| {
196 f(name.clone(), res.def.map(Resolution::Def));
197 });
198 }
193 } 199 }
194 Scope::GenericParams(gp) => { 200 Scope::GenericParams(gp) => {
195 for param in &gp.params { 201 for param in &gp.params {
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index 2dc1de41a..f28a7e731 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -450,7 +450,6 @@ impl Ty {
450 } 450 }
451 451
452 pub fn walk(&self, f: &mut impl FnMut(&Ty)) { 452 pub fn walk(&self, f: &mut impl FnMut(&Ty)) {
453 f(self);
454 match self { 453 match self {
455 Ty::Slice(t) | Ty::Array(t) => t.walk(f), 454 Ty::Slice(t) | Ty::Array(t) => t.walk(f),
456 Ty::RawPtr(t, _) => t.walk(f), 455 Ty::RawPtr(t, _) => t.walk(f),
@@ -490,10 +489,10 @@ impl Ty {
490 | Ty::Infer(_) 489 | Ty::Infer(_)
491 | Ty::Unknown => {} 490 | Ty::Unknown => {}
492 } 491 }
492 f(self);
493 } 493 }
494 494
495 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { 495 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
496 f(self);
497 match self { 496 match self {
498 Ty::Slice(t) | Ty::Array(t) => Arc::make_mut(t).walk_mut(f), 497 Ty::Slice(t) | Ty::Array(t) => Arc::make_mut(t).walk_mut(f),
499 Ty::RawPtr(t, _) => Arc::make_mut(t).walk_mut(f), 498 Ty::RawPtr(t, _) => Arc::make_mut(t).walk_mut(f),
@@ -544,6 +543,7 @@ impl Ty {
544 | Ty::Infer(_) 543 | Ty::Infer(_)
545 | Ty::Unknown => {} 544 | Ty::Unknown => {}
546 } 545 }
546 f(self);
547 } 547 }
548 548
549 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Ty { 549 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Ty {
diff --git a/crates/ra_hir/src/ty/snapshots/tests__infer_nested_generics_crash.snap b/crates/ra_hir/src/ty/snapshots/tests__infer_nested_generics_crash.snap
new file mode 100644
index 000000000..209454a91
--- /dev/null
+++ b/crates/ra_hir/src/ty/snapshots/tests__infer_nested_generics_crash.snap
@@ -0,0 +1,12 @@
1---
2created: "2019-02-11T21:59:04.302375838Z"
3creator: [email protected]
4source: crates/ra_hir/src/ty/tests.rs
5expression: "&result"
6---
7[92; 106) 'query_response': Canonical<QueryResponse<R>>
8[137; 167) '{ ...lue; }': ()
9[143; 164) '&query....value': &QueryResponse<R>
10[144; 158) 'query_response': Canonical<QueryResponse<R>>
11[144; 164) 'query_....value': QueryResponse<R>
12
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs
index e64fd2749..203f1fe4d 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir/src/ty/tests.rs
@@ -719,6 +719,25 @@ fn extra_compiler_flags() {
719 ); 719 );
720} 720}
721 721
722#[test]
723fn infer_nested_generics_crash() {
724 // another crash found typechecking rustc
725 check_inference(
726 "infer_nested_generics_crash",
727 r#"
728struct Canonical<V> {
729 value: V,
730}
731struct QueryResponse<V> {
732 value: V,
733}
734fn test<R>(query_response: Canonical<QueryResponse<R>>) {
735 &query_response.value;
736}
737"#,
738 );
739}
740
722fn infer(content: &str) -> String { 741fn infer(content: &str) -> String {
723 let (db, _, file_id) = MockDatabase::with_single_file(content); 742 let (db, _, file_id) = MockDatabase::with_single_file(content);
724 let source_file = db.parse(file_id); 743 let source_file = db.parse(file_id);