aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/nameres/collector.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/nameres/collector.rs')
-rw-r--r--crates/ra_hir/src/nameres/collector.rs564
1 files changed, 564 insertions, 0 deletions
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs
new file mode 100644
index 000000000..12ed49a0a
--- /dev/null
+++ b/crates/ra_hir/src/nameres/collector.rs
@@ -0,0 +1,564 @@
1use arrayvec::ArrayVec;
2use rustc_hash::FxHashMap;
3use relative_path::RelativePathBuf;
4use test_utils::tested_by;
5use ra_db::FileId;
6
7use crate::{
8 Function, Module, Struct, Enum, Const, Static, Trait, TypeAlias,
9 PersistentHirDatabase, HirFileId, Name, Path, Problem, Crate,
10 KnownName,
11 nameres::{Resolution, PerNs, ModuleDef, ReachedFixedPoint, ResolveMode, raw},
12 ids::{AstItemDef, LocationCtx, MacroCallLoc, SourceItemId, MacroCallId},
13};
14
15use super::{CrateDefMap, CrateModuleId, ModuleData, CrateMacroId};
16
17pub(super) fn collect_defs(
18 db: &impl PersistentHirDatabase,
19 mut def_map: CrateDefMap,
20) -> CrateDefMap {
21 // populate external prelude
22 for dep in def_map.krate.dependencies(db) {
23 log::debug!("crate dep {:?} -> {:?}", dep.name, dep.krate);
24 if let Some(module) = dep.krate.root_module(db) {
25 def_map.extern_prelude.insert(dep.name.clone(), module.into());
26 }
27 // look for the prelude
28 if def_map.prelude.is_none() {
29 let map = db.crate_def_map(dep.krate);
30 if map.prelude.is_some() {
31 def_map.prelude = map.prelude;
32 }
33 }
34 }
35
36 let mut collector = DefCollector {
37 db,
38 def_map,
39 glob_imports: FxHashMap::default(),
40 unresolved_imports: Vec::new(),
41 unexpanded_macros: Vec::new(),
42 global_macro_scope: FxHashMap::default(),
43 };
44 collector.collect();
45 collector.finish()
46}
47
48/// Walks the tree of module recursively
49struct DefCollector<DB> {
50 db: DB,
51 def_map: CrateDefMap,
52 glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>,
53 unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>,
54 unexpanded_macros: Vec<(CrateModuleId, MacroCallId, Path, tt::Subtree)>,
55 global_macro_scope: FxHashMap<Name, CrateMacroId>,
56}
57
58impl<'a, DB> DefCollector<&'a DB>
59where
60 DB: PersistentHirDatabase,
61{
62 fn collect(&mut self) {
63 let crate_graph = self.db.crate_graph();
64 let file_id = crate_graph.crate_root(self.def_map.krate.crate_id());
65 let raw_items = self.db.raw_items(file_id);
66 let module_id = self.def_map.root;
67 self.def_map.modules[module_id].definition = Some(file_id);
68 ModCollector {
69 def_collector: &mut *self,
70 module_id,
71 file_id: file_id.into(),
72 raw_items: &raw_items,
73 }
74 .collect(raw_items.items());
75
76 // main name resolution fixed-point loop.
77 let mut i = 0;
78 loop {
79 match (self.resolve_imports(), self.resolve_macros()) {
80 (ReachedFixedPoint::Yes, ReachedFixedPoint::Yes) => break,
81 _ => i += 1,
82 }
83 if i == 1000 {
84 log::error!("diverging name resolution");
85 break;
86 }
87 }
88
89 let unresolved_imports = std::mem::replace(&mut self.unresolved_imports, Vec::new());
90 // show unresolved imports in completion, etc
91 for (module_id, import, import_data) in unresolved_imports {
92 self.record_resolved_import(module_id, PerNs::none(), import, &import_data)
93 }
94 }
95
96 fn define_macro(&mut self, name: Name, tt: &tt::Subtree, export: bool) {
97 if let Ok(rules) = mbe::MacroRules::parse(tt) {
98 let macro_id = self.def_map.macros.alloc(rules);
99 if export {
100 self.def_map.public_macros.insert(name.clone(), macro_id);
101 }
102 self.global_macro_scope.insert(name, macro_id);
103 }
104 }
105
106 fn resolve_imports(&mut self) -> ReachedFixedPoint {
107 let mut imports = std::mem::replace(&mut self.unresolved_imports, Vec::new());
108 let mut resolved = Vec::new();
109 imports.retain(|(module_id, import, import_data)| {
110 let (def, fp) = self.resolve_import(*module_id, import_data);
111 if fp == ReachedFixedPoint::Yes {
112 resolved.push((*module_id, def, *import, import_data.clone()))
113 }
114 fp == ReachedFixedPoint::No
115 });
116 self.unresolved_imports = imports;
117 // Resolves imports, filling-in module scopes
118 let result =
119 if resolved.is_empty() { ReachedFixedPoint::Yes } else { ReachedFixedPoint::No };
120 for (module_id, def, import, import_data) in resolved {
121 self.record_resolved_import(module_id, def, import, &import_data)
122 }
123 result
124 }
125
126 fn resolve_import(
127 &mut self,
128 module_id: CrateModuleId,
129 import: &raw::ImportData,
130 ) -> (PerNs<ModuleDef>, ReachedFixedPoint) {
131 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
132 if import.is_extern_crate {
133 let res = self.def_map.resolve_name_in_extern_prelude(
134 &import
135 .path
136 .as_ident()
137 .expect("extern crate should have been desugared to one-element path"),
138 );
139 (res, ReachedFixedPoint::Yes)
140 } else {
141 let res =
142 self.def_map.resolve_path_fp(self.db, ResolveMode::Import, module_id, &import.path);
143
144 (res.resolved_def, res.reached_fixedpoint)
145 }
146 }
147
148 fn record_resolved_import(
149 &mut self,
150 module_id: CrateModuleId,
151 def: PerNs<ModuleDef>,
152 import_id: raw::ImportId,
153 import: &raw::ImportData,
154 ) {
155 if import.is_glob {
156 log::debug!("glob import: {:?}", import);
157 match def.take_types() {
158 Some(ModuleDef::Module(m)) => {
159 if import.is_prelude {
160 tested_by!(std_prelude);
161 self.def_map.prelude = Some(m);
162 } else if m.krate != self.def_map.krate {
163 tested_by!(glob_across_crates);
164 // glob import from other crate => we can just import everything once
165 let item_map = self.db.crate_def_map(m.krate);
166 let scope = &item_map[m.module_id].scope;
167 let items = scope
168 .items
169 .iter()
170 .map(|(name, res)| (name.clone(), res.clone()))
171 .collect::<Vec<_>>();
172 self.update(module_id, Some(import_id), &items);
173 } else {
174 // glob import from same crate => we do an initial
175 // import, and then need to propagate any further
176 // additions
177 let scope = &self.def_map[m.module_id].scope;
178 let items = scope
179 .items
180 .iter()
181 .map(|(name, res)| (name.clone(), res.clone()))
182 .collect::<Vec<_>>();
183 self.update(module_id, Some(import_id), &items);
184 // record the glob import in case we add further items
185 self.glob_imports
186 .entry(m.module_id)
187 .or_default()
188 .push((module_id, import_id));
189 }
190 }
191 Some(ModuleDef::Enum(e)) => {
192 tested_by!(glob_enum);
193 // glob import from enum => just import all the variants
194 let variants = e.variants(self.db);
195 let resolutions = variants
196 .into_iter()
197 .filter_map(|variant| {
198 let res = Resolution {
199 def: PerNs::both(variant.into(), variant.into()),
200 import: Some(import_id),
201 };
202 let name = variant.name(self.db)?;
203 Some((name, res))
204 })
205 .collect::<Vec<_>>();
206 self.update(module_id, Some(import_id), &resolutions);
207 }
208 Some(d) => {
209 log::debug!("glob import {:?} from non-module/enum {:?}", import, d);
210 }
211 None => {
212 log::debug!("glob import {:?} didn't resolve as type", import);
213 }
214 }
215 } else {
216 match import.path.segments.last() {
217 Some(last_segment) => {
218 let name = import.alias.clone().unwrap_or_else(|| last_segment.name.clone());
219 log::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
220
221 // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
222 if import.is_extern_crate && module_id == self.def_map.root {
223 if let Some(def) = def.take_types() {
224 self.def_map.extern_prelude.insert(name.clone(), def);
225 }
226 }
227 let resolution = Resolution { def, import: Some(import_id) };
228 self.update(module_id, Some(import_id), &[(name, resolution)]);
229 }
230 None => tested_by!(bogus_paths),
231 }
232 }
233 }
234
235 fn update(
236 &mut self,
237 module_id: CrateModuleId,
238 import: Option<raw::ImportId>,
239 resolutions: &[(Name, Resolution)],
240 ) {
241 self.update_recursive(module_id, import, resolutions, 0)
242 }
243
244 fn update_recursive(
245 &mut self,
246 module_id: CrateModuleId,
247 import: Option<raw::ImportId>,
248 resolutions: &[(Name, Resolution)],
249 depth: usize,
250 ) {
251 if depth > 100 {
252 // prevent stack overflows (but this shouldn't be possible)
253 panic!("infinite recursion in glob imports!");
254 }
255 let module_items = &mut self.def_map.modules[module_id].scope;
256 let mut changed = false;
257 for (name, res) in resolutions {
258 let existing = module_items.items.entry(name.clone()).or_default();
259 if existing.def.types.is_none() && res.def.types.is_some() {
260 existing.def.types = res.def.types;
261 existing.import = import.or(res.import);
262 changed = true;
263 }
264 if existing.def.values.is_none() && res.def.values.is_some() {
265 existing.def.values = res.def.values;
266 existing.import = import.or(res.import);
267 changed = true;
268 }
269 if existing.def.is_none()
270 && res.def.is_none()
271 && existing.import.is_none()
272 && res.import.is_some()
273 {
274 existing.import = res.import;
275 }
276 }
277 if !changed {
278 return;
279 }
280 let glob_imports = self
281 .glob_imports
282 .get(&module_id)
283 .into_iter()
284 .flat_map(|v| v.iter())
285 .cloned()
286 .collect::<Vec<_>>();
287 for (glob_importing_module, glob_import) in glob_imports {
288 // We pass the glob import so that the tracked import in those modules is that glob import
289 self.update_recursive(glob_importing_module, Some(glob_import), resolutions, depth + 1);
290 }
291 }
292
293 // XXX: this is just a pile of hacks now, because `PerNs` does not handle
294 // macro namespace.
295 fn resolve_macros(&mut self) -> ReachedFixedPoint {
296 let mut macros = std::mem::replace(&mut self.unexpanded_macros, Vec::new());
297 let mut resolved = Vec::new();
298 let mut res = ReachedFixedPoint::Yes;
299 macros.retain(|(module_id, call_id, path, tt)| {
300 if path.segments.len() != 2 {
301 return true;
302 }
303 let crate_name = &path.segments[0].name;
304 let krate = match self.def_map.resolve_name_in_extern_prelude(crate_name).take_types() {
305 Some(ModuleDef::Module(m)) => m.krate(self.db),
306 _ => return true,
307 };
308 let krate = match krate {
309 Some(it) => it,
310 _ => return true,
311 };
312 res = ReachedFixedPoint::No;
313 let def_map = self.db.crate_def_map(krate);
314 if let Some(macro_id) = def_map.public_macros.get(&path.segments[1].name).cloned() {
315 resolved.push((*module_id, *call_id, (krate, macro_id), tt.clone()));
316 }
317 false
318 });
319
320 for (module_id, macro_call_id, macro_def_id, arg) in resolved {
321 self.collect_macro_expansion(module_id, macro_call_id, macro_def_id, arg);
322 }
323 res
324 }
325
326 fn collect_macro_expansion(
327 &mut self,
328 module_id: CrateModuleId,
329 macro_call_id: MacroCallId,
330 macro_def_id: (Crate, CrateMacroId),
331 macro_arg: tt::Subtree,
332 ) {
333 let (macro_krate, macro_id) = macro_def_id;
334 let dm;
335 let rules = if macro_krate == self.def_map.krate {
336 &self.def_map[macro_id]
337 } else {
338 dm = self.db.crate_def_map(macro_krate);
339 &dm[macro_id]
340 };
341 if let Ok(expansion) = rules.expand(&macro_arg) {
342 self.def_map.macro_resolutions.insert(macro_call_id, macro_def_id);
343 // XXX: this **does not** go through a database, because we can't
344 // identify macro_call without adding the whole state of name resolution
345 // as a parameter to the query.
346 //
347 // So, we run the queries "manually" and we must ensure that
348 // `db.hir_parse(macro_call_id)` returns the same source_file.
349 let file_id: HirFileId = macro_call_id.into();
350 let source_file = mbe::token_tree_to_ast_item_list(&expansion);
351
352 let raw_items = raw::RawItems::from_source_file(&source_file, file_id);
353 ModCollector { def_collector: &mut *self, file_id, module_id, raw_items: &raw_items }
354 .collect(raw_items.items())
355 }
356 }
357
358 fn finish(self) -> CrateDefMap {
359 self.def_map
360 }
361}
362
363/// Walks a single module, populating defs, imports and macros
364struct ModCollector<'a, D> {
365 def_collector: D,
366 module_id: CrateModuleId,
367 file_id: HirFileId,
368 raw_items: &'a raw::RawItems,
369}
370
371impl<DB> ModCollector<'_, &'_ mut DefCollector<&'_ DB>>
372where
373 DB: PersistentHirDatabase,
374{
375 fn collect(&mut self, items: &[raw::RawItem]) {
376 for item in items {
377 match *item {
378 raw::RawItem::Module(m) => self.collect_module(&self.raw_items[m]),
379 raw::RawItem::Import(import) => self.def_collector.unresolved_imports.push((
380 self.module_id,
381 import,
382 self.raw_items[import].clone(),
383 )),
384 raw::RawItem::Def(def) => self.define_def(&self.raw_items[def]),
385 raw::RawItem::Macro(mac) => self.collect_macro(&self.raw_items[mac]),
386 }
387 }
388 }
389
390 fn collect_module(&mut self, module: &raw::ModuleData) {
391 match module {
392 // inline module, just recurse
393 raw::ModuleData::Definition { name, items, source_item_id } => {
394 let module_id = self.push_child_module(
395 name.clone(),
396 source_item_id.with_file_id(self.file_id),
397 None,
398 );
399 ModCollector {
400 def_collector: &mut *self.def_collector,
401 module_id,
402 file_id: self.file_id,
403 raw_items: self.raw_items,
404 }
405 .collect(&*items);
406 }
407 // out of line module, resovle, parse and recurse
408 raw::ModuleData::Declaration { name, source_item_id } => {
409 let source_item_id = source_item_id.with_file_id(self.file_id);
410 let is_root = self.def_collector.def_map.modules[self.module_id].parent.is_none();
411 let (file_ids, problem) =
412 resolve_submodule(self.def_collector.db, self.file_id, name, is_root);
413
414 if let Some(problem) = problem {
415 self.def_collector.def_map.problems.add(source_item_id, problem)
416 }
417
418 if let Some(&file_id) = file_ids.first() {
419 let module_id =
420 self.push_child_module(name.clone(), source_item_id, Some(file_id));
421 let raw_items = self.def_collector.db.raw_items(file_id);
422 ModCollector {
423 def_collector: &mut *self.def_collector,
424 module_id,
425 file_id: file_id.into(),
426 raw_items: &raw_items,
427 }
428 .collect(raw_items.items())
429 }
430 }
431 }
432 }
433
434 fn push_child_module(
435 &mut self,
436 name: Name,
437 declaration: SourceItemId,
438 definition: Option<FileId>,
439 ) -> CrateModuleId {
440 let modules = &mut self.def_collector.def_map.modules;
441 let res = modules.alloc(ModuleData::default());
442 modules[res].parent = Some(self.module_id);
443 modules[res].declaration = Some(declaration);
444 modules[res].definition = definition;
445 modules[self.module_id].children.insert(name.clone(), res);
446 let resolution = Resolution {
447 def: PerNs::types(
448 Module { krate: self.def_collector.def_map.krate, module_id: res }.into(),
449 ),
450 import: None,
451 };
452 self.def_collector.update(self.module_id, None, &[(name, resolution)]);
453 res
454 }
455
456 fn define_def(&mut self, def: &raw::DefData) {
457 let module = Module { krate: self.def_collector.def_map.krate, module_id: self.module_id };
458 let ctx = LocationCtx::new(self.def_collector.db, module, self.file_id.into());
459 macro_rules! id {
460 () => {
461 AstItemDef::from_source_item_id_unchecked(ctx, def.source_item_id)
462 };
463 }
464 let name = def.name.clone();
465 let def: PerNs<ModuleDef> = match def.kind {
466 raw::DefKind::Function => PerNs::values(Function { id: id!() }.into()),
467 raw::DefKind::Struct => {
468 let s = Struct { id: id!() }.into();
469 PerNs::both(s, s)
470 }
471 raw::DefKind::Enum => PerNs::types(Enum { id: id!() }.into()),
472 raw::DefKind::Const => PerNs::values(Const { id: id!() }.into()),
473 raw::DefKind::Static => PerNs::values(Static { id: id!() }.into()),
474 raw::DefKind::Trait => PerNs::types(Trait { id: id!() }.into()),
475 raw::DefKind::TypeAlias => PerNs::types(TypeAlias { id: id!() }.into()),
476 };
477 let resolution = Resolution { def, import: None };
478 self.def_collector.update(self.module_id, None, &[(name, resolution)])
479 }
480
481 fn collect_macro(&mut self, mac: &raw::MacroData) {
482 // Case 1: macro rules, define a macro in crate-global mutable scope
483 if is_macro_rules(&mac.path) {
484 if let Some(name) = &mac.name {
485 self.def_collector.define_macro(name.clone(), &mac.arg, mac.export)
486 }
487 return;
488 }
489
490 let source_item_id = SourceItemId { file_id: self.file_id, item_id: mac.source_item_id };
491 let macro_call_id = MacroCallLoc {
492 module: Module { krate: self.def_collector.def_map.krate, module_id: self.module_id },
493 source_item_id,
494 }
495 .id(self.def_collector.db);
496
497 // Case 2: try to expand macro_rules from this crate, triggering
498 // recursive item collection.
499 if let Some(&macro_id) =
500 mac.path.as_ident().and_then(|name| self.def_collector.global_macro_scope.get(name))
501 {
502 self.def_collector.collect_macro_expansion(
503 self.module_id,
504 macro_call_id,
505 (self.def_collector.def_map.krate, macro_id),
506 mac.arg.clone(),
507 );
508 return;
509 }
510
511 // Case 3: path to a macro from another crate, expand during name resolution
512 self.def_collector.unexpanded_macros.push((
513 self.module_id,
514 macro_call_id,
515 mac.path.clone(),
516 mac.arg.clone(),
517 ))
518 }
519}
520
521fn is_macro_rules(path: &Path) -> bool {
522 path.as_ident().and_then(Name::as_known_name) == Some(KnownName::MacroRules)
523}
524
525fn resolve_submodule(
526 db: &impl PersistentHirDatabase,
527 file_id: HirFileId,
528 name: &Name,
529 is_root: bool,
530) -> (Vec<FileId>, Option<Problem>) {
531 // FIXME: handle submodules of inline modules properly
532 let file_id = file_id.original_file(db);
533 let source_root_id = db.file_source_root(file_id);
534 let path = db.file_relative_path(file_id);
535 let root = RelativePathBuf::default();
536 let dir_path = path.parent().unwrap_or(&root);
537 let mod_name = path.file_stem().unwrap_or("unknown");
538 let is_dir_owner = is_root || mod_name == "mod";
539
540 let file_mod = dir_path.join(format!("{}.rs", name));
541 let dir_mod = dir_path.join(format!("{}/mod.rs", name));
542 let file_dir_mod = dir_path.join(format!("{}/{}.rs", mod_name, name));
543 let mut candidates = ArrayVec::<[_; 2]>::new();
544 if is_dir_owner {
545 candidates.push(file_mod.clone());
546 candidates.push(dir_mod);
547 } else {
548 candidates.push(file_dir_mod.clone());
549 };
550 let sr = db.source_root(source_root_id);
551 let points_to = candidates
552 .into_iter()
553 .filter_map(|path| sr.files.get(&path))
554 .map(|&it| it)
555 .collect::<Vec<_>>();
556 let problem = if points_to.is_empty() {
557 Some(Problem::UnresolvedModule {
558 candidate: if is_dir_owner { file_mod } else { file_dir_mod },
559 })
560 } else {
561 None
562 };
563 (points_to, problem)
564}