]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/nameres/collector.rs
Merge #10385
[rust.git] / crates / hir_def / src / nameres / collector.rs
1 //! The core of the module-level name resolution algorithm.
2 //!
3 //! `DefCollector::collect` contains the fixed-point iteration loop which
4 //! resolves imports and expands macros.
5
6 use std::iter;
7
8 use base_db::{CrateId, Edition, FileId, ProcMacroId};
9 use cfg::{CfgExpr, CfgOptions};
10 use hir_expand::{
11     ast_id_map::FileAstId,
12     builtin_attr::find_builtin_attr,
13     builtin_derive::find_builtin_derive,
14     builtin_macro::find_builtin_macro,
15     name::{name, AsName, Name},
16     proc_macro::ProcMacroExpander,
17     ExpandTo, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
18 };
19 use hir_expand::{InFile, MacroCallLoc};
20 use itertools::Itertools;
21 use la_arena::Idx;
22 use limit::Limit;
23 use rustc_hash::{FxHashMap, FxHashSet};
24 use syntax::ast;
25
26 use crate::{
27     attr::{Attr, AttrId, AttrInput, Attrs},
28     attr_macro_as_call_id, builtin_attr,
29     db::DefDatabase,
30     derive_macro_as_call_id,
31     intern::Interned,
32     item_scope::{ImportType, PerNsGlobImports},
33     item_tree::{
34         self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, MacroCall, MacroDef,
35         MacroRules, Mod, ModItem, ModKind, TreeId,
36     },
37     macro_call_as_call_id,
38     nameres::{
39         diagnostics::DefDiagnostic,
40         mod_resolution::ModDir,
41         path_resolution::ReachedFixedPoint,
42         proc_macro::{ProcMacroDef, ProcMacroKind},
43         BuiltinShadowMode, DefMap, ModuleData, ModuleOrigin, ResolveMode,
44     },
45     path::{ImportAlias, ModPath, PathKind},
46     per_ns::PerNs,
47     visibility::{RawVisibility, Visibility},
48     AdtId, AstId, AstIdWithPath, ConstLoc, EnumLoc, EnumVariantId, FunctionLoc, ImplLoc, Intern,
49     LocalModuleId, ModuleDefId, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
50     UnresolvedMacro,
51 };
52
53 const GLOB_RECURSION_LIMIT: Limit = Limit::new(100);
54 const EXPANSION_DEPTH_LIMIT: Limit = Limit::new(128);
55 const FIXED_POINT_LIMIT: Limit = Limit::new(8192);
56
57 pub(super) fn collect_defs(
58     db: &dyn DefDatabase,
59     mut def_map: DefMap,
60     block: Option<AstId<ast::BlockExpr>>,
61 ) -> DefMap {
62     let crate_graph = db.crate_graph();
63
64     let mut deps = FxHashMap::default();
65     // populate external prelude and dependency list
66     for dep in &crate_graph[def_map.krate].dependencies {
67         tracing::debug!("crate dep {:?} -> {:?}", dep.name, dep.crate_id);
68         let dep_def_map = db.crate_def_map(dep.crate_id);
69         let dep_root = dep_def_map.module_id(dep_def_map.root);
70
71         deps.insert(dep.as_name(), dep_root.into());
72
73         if dep.is_prelude() && block.is_none() {
74             def_map.extern_prelude.insert(dep.as_name(), dep_root.into());
75         }
76     }
77
78     let cfg_options = &crate_graph[def_map.krate].cfg_options;
79     let proc_macros = &crate_graph[def_map.krate].proc_macro;
80     let proc_macros = proc_macros
81         .iter()
82         .enumerate()
83         .map(|(idx, it)| {
84             // FIXME: a hacky way to create a Name from string.
85             let name = tt::Ident { text: it.name.clone(), id: tt::TokenId::unspecified() };
86             (name.as_name(), ProcMacroExpander::new(def_map.krate, ProcMacroId(idx as u32)))
87         })
88         .collect();
89
90     let mut collector = DefCollector {
91         db,
92         def_map,
93         deps,
94         glob_imports: FxHashMap::default(),
95         unresolved_imports: Vec::new(),
96         resolved_imports: Vec::new(),
97
98         unresolved_macros: Vec::new(),
99         mod_dirs: FxHashMap::default(),
100         cfg_options,
101         proc_macros,
102         exports_proc_macros: false,
103         from_glob_import: Default::default(),
104         skip_attrs: Default::default(),
105         derive_helpers_in_scope: Default::default(),
106         registered_attrs: Default::default(),
107         registered_tools: Default::default(),
108     };
109     match block {
110         Some(block) => {
111             collector.seed_with_inner(block);
112         }
113         None => {
114             collector.seed_with_top_level();
115         }
116     }
117     collector.collect();
118     let mut def_map = collector.finish();
119     def_map.shrink_to_fit();
120     def_map
121 }
122
123 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
124 enum PartialResolvedImport {
125     /// None of any namespaces is resolved
126     Unresolved,
127     /// One of namespaces is resolved
128     Indeterminate(PerNs),
129     /// All namespaces are resolved, OR it is came from other crate
130     Resolved(PerNs),
131 }
132
133 impl PartialResolvedImport {
134     fn namespaces(&self) -> PerNs {
135         match self {
136             PartialResolvedImport::Unresolved => PerNs::none(),
137             PartialResolvedImport::Indeterminate(ns) => *ns,
138             PartialResolvedImport::Resolved(ns) => *ns,
139         }
140     }
141 }
142
143 #[derive(Clone, Debug, Eq, PartialEq)]
144 enum ImportSource {
145     Import { id: ItemTreeId<item_tree::Import>, use_tree: Idx<ast::UseTree> },
146     ExternCrate(ItemTreeId<item_tree::ExternCrate>),
147 }
148
149 #[derive(Clone, Debug, Eq, PartialEq)]
150 struct Import {
151     path: Interned<ModPath>,
152     alias: Option<ImportAlias>,
153     visibility: RawVisibility,
154     kind: ImportKind,
155     is_prelude: bool,
156     is_extern_crate: bool,
157     is_macro_use: bool,
158     source: ImportSource,
159 }
160
161 impl Import {
162     fn from_use(
163         db: &dyn DefDatabase,
164         krate: CrateId,
165         tree: &ItemTree,
166         id: ItemTreeId<item_tree::Import>,
167     ) -> Vec<Self> {
168         let it = &tree[id.value];
169         let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
170         let visibility = &tree[it.visibility];
171         let is_prelude = attrs.by_key("prelude_import").exists();
172
173         let mut res = Vec::new();
174         it.use_tree.expand(|idx, path, kind, alias| {
175             res.push(Self {
176                 path: Interned::new(path), // FIXME this makes little sense
177                 alias,
178                 visibility: visibility.clone(),
179                 kind,
180                 is_prelude,
181                 is_extern_crate: false,
182                 is_macro_use: false,
183                 source: ImportSource::Import { id, use_tree: idx },
184             });
185         });
186         res
187     }
188
189     fn from_extern_crate(
190         db: &dyn DefDatabase,
191         krate: CrateId,
192         tree: &ItemTree,
193         id: ItemTreeId<item_tree::ExternCrate>,
194     ) -> Self {
195         let it = &tree[id.value];
196         let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
197         let visibility = &tree[it.visibility];
198         Self {
199             path: Interned::new(ModPath::from_segments(
200                 PathKind::Plain,
201                 iter::once(it.name.clone()),
202             )),
203             alias: it.alias.clone(),
204             visibility: visibility.clone(),
205             kind: ImportKind::Plain,
206             is_prelude: false,
207             is_extern_crate: true,
208             is_macro_use: attrs.by_key("macro_use").exists(),
209             source: ImportSource::ExternCrate(id),
210         }
211     }
212 }
213
214 #[derive(Clone, Debug, Eq, PartialEq)]
215 struct ImportDirective {
216     module_id: LocalModuleId,
217     import: Import,
218     status: PartialResolvedImport,
219 }
220
221 #[derive(Clone, Debug, Eq, PartialEq)]
222 struct MacroDirective {
223     module_id: LocalModuleId,
224     depth: usize,
225     kind: MacroDirectiveKind,
226 }
227
228 #[derive(Clone, Debug, Eq, PartialEq)]
229 enum MacroDirectiveKind {
230     FnLike { ast_id: AstIdWithPath<ast::MacroCall>, expand_to: ExpandTo },
231     Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId },
232     Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem },
233 }
234
235 struct DefData<'a> {
236     id: ModuleDefId,
237     name: &'a Name,
238     visibility: &'a RawVisibility,
239     has_constructor: bool,
240 }
241
242 /// Walks the tree of module recursively
243 struct DefCollector<'a> {
244     db: &'a dyn DefDatabase,
245     def_map: DefMap,
246     deps: FxHashMap<Name, ModuleDefId>,
247     glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>,
248     unresolved_imports: Vec<ImportDirective>,
249     resolved_imports: Vec<ImportDirective>,
250     unresolved_macros: Vec<MacroDirective>,
251     mod_dirs: FxHashMap<LocalModuleId, ModDir>,
252     cfg_options: &'a CfgOptions,
253     /// List of procedural macros defined by this crate. This is read from the dynamic library
254     /// built by the build system, and is the list of proc. macros we can actually expand. It is
255     /// empty when proc. macro support is disabled (in which case we still do name resolution for
256     /// them).
257     proc_macros: Vec<(Name, ProcMacroExpander)>,
258     exports_proc_macros: bool,
259     from_glob_import: PerNsGlobImports,
260     /// If we fail to resolve an attribute on a `ModItem`, we fall back to ignoring the attribute.
261     /// This map is used to skip all attributes up to and including the one that failed to resolve,
262     /// in order to not expand them twice.
263     ///
264     /// This also stores the attributes to skip when we resolve derive helpers and non-macro
265     /// non-builtin attributes in general.
266     skip_attrs: FxHashMap<InFile<ModItem>, AttrId>,
267     /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
268     /// attributes.
269     derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<Name>>,
270     /// Custom attributes registered with `#![register_attr]`.
271     registered_attrs: Vec<String>,
272     /// Custom tool modules registered with `#![register_tool]`.
273     registered_tools: Vec<String>,
274 }
275
276 impl DefCollector<'_> {
277     fn seed_with_top_level(&mut self) {
278         let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
279         let item_tree = self.db.file_item_tree(file_id.into());
280         let module_id = self.def_map.root;
281
282         let attrs = item_tree.top_level_attrs(self.db, self.def_map.krate);
283         if attrs.cfg().map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false)) {
284             self.inject_prelude(&attrs);
285
286             // Process other crate-level attributes.
287             for attr in &*attrs {
288                 let attr_name = match attr.path.as_ident() {
289                     Some(name) => name,
290                     None => continue,
291                 };
292
293                 let registered_name = if *attr_name == hir_expand::name![register_attr]
294                     || *attr_name == hir_expand::name![register_tool]
295                 {
296                     match attr.input.as_deref() {
297                         Some(AttrInput::TokenTree(subtree, _)) => match &*subtree.token_trees {
298                             [tt::TokenTree::Leaf(tt::Leaf::Ident(name))] => name.as_name(),
299                             _ => continue,
300                         },
301                         _ => continue,
302                     }
303                 } else {
304                     continue;
305                 };
306
307                 if *attr_name == hir_expand::name![register_attr] {
308                     self.registered_attrs.push(registered_name.to_string());
309                     cov_mark::hit!(register_attr);
310                 } else {
311                     self.registered_tools.push(registered_name.to_string());
312                     cov_mark::hit!(register_tool);
313                 }
314             }
315
316             ModCollector {
317                 def_collector: &mut *self,
318                 macro_depth: 0,
319                 module_id,
320                 tree_id: TreeId::new(file_id.into(), None),
321                 item_tree: &item_tree,
322                 mod_dir: ModDir::root(),
323             }
324             .collect(item_tree.top_level_items());
325         }
326     }
327
328     fn seed_with_inner(&mut self, block: AstId<ast::BlockExpr>) {
329         let item_tree = self.db.file_item_tree(block.file_id);
330         let module_id = self.def_map.root;
331         if item_tree
332             .top_level_attrs(self.db, self.def_map.krate)
333             .cfg()
334             .map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false))
335         {
336             ModCollector {
337                 def_collector: &mut *self,
338                 macro_depth: 0,
339                 module_id,
340                 // FIXME: populate block once we have per-block ItemTrees
341                 tree_id: TreeId::new(block.file_id, None),
342                 item_tree: &item_tree,
343                 mod_dir: ModDir::root(),
344             }
345             .collect(item_tree.inner_items_of_block(block.value));
346         }
347     }
348
349     fn collect(&mut self) {
350         // main name resolution fixed-point loop.
351         let mut i = 0;
352         'outer: loop {
353             loop {
354                 self.db.unwind_if_cancelled();
355                 loop {
356                     if self.resolve_imports() == ReachedFixedPoint::Yes {
357                         break;
358                     }
359                 }
360                 if self.resolve_macros() == ReachedFixedPoint::Yes {
361                     break;
362                 }
363
364                 i += 1;
365                 if FIXED_POINT_LIMIT.check(i).is_err() {
366                     tracing::error!("name resolution is stuck");
367                     break 'outer;
368                 }
369             }
370
371             if self.reseed_with_unresolved_attribute() == ReachedFixedPoint::Yes {
372                 break;
373             }
374         }
375
376         // Resolve all indeterminate resolved imports again
377         // As some of the macros will expand newly import shadowing partial resolved imports
378         // FIXME: We maybe could skip this, if we handle the indeterminate imports in `resolve_imports`
379         // correctly
380         let partial_resolved = self.resolved_imports.iter().filter_map(|directive| {
381             if let PartialResolvedImport::Indeterminate(_) = directive.status {
382                 let mut directive = directive.clone();
383                 directive.status = PartialResolvedImport::Unresolved;
384                 Some(directive)
385             } else {
386                 None
387             }
388         });
389         self.unresolved_imports.extend(partial_resolved);
390         self.resolve_imports();
391
392         let unresolved_imports = std::mem::take(&mut self.unresolved_imports);
393         // show unresolved imports in completion, etc
394         for directive in &unresolved_imports {
395             self.record_resolved_import(directive)
396         }
397         self.unresolved_imports = unresolved_imports;
398
399         // FIXME: This condition should instead check if this is a `proc-macro` type crate.
400         if self.exports_proc_macros {
401             // A crate exporting procedural macros is not allowed to export anything else.
402             //
403             // Additionally, while the proc macro entry points must be `pub`, they are not publicly
404             // exported in type/value namespace. This function reduces the visibility of all items
405             // in the crate root that aren't proc macros.
406             let root = self.def_map.root;
407             let module_id = self.def_map.module_id(root);
408             let root = &mut self.def_map.modules[root];
409             root.scope.censor_non_proc_macros(module_id);
410         }
411     }
412
413     /// When the fixed-point loop reaches a stable state, we might still have some unresolved
414     /// attributes (or unexpanded attribute proc macros) left over. This takes one of them, and
415     /// feeds the item it's applied to back into name resolution.
416     ///
417     /// This effectively ignores the fact that the macro is there and just treats the items as
418     /// normal code.
419     ///
420     /// This improves UX when proc macros are turned off or don't work, and replicates the behavior
421     /// before we supported proc. attribute macros.
422     fn reseed_with_unresolved_attribute(&mut self) -> ReachedFixedPoint {
423         cov_mark::hit!(unresolved_attribute_fallback);
424
425         let mut unresolved_macros = std::mem::take(&mut self.unresolved_macros);
426         let pos = unresolved_macros.iter().position(|directive| {
427             if let MacroDirectiveKind::Attr { ast_id, mod_item, attr } = &directive.kind {
428                 self.skip_attrs.insert(ast_id.ast_id.with_value(*mod_item), attr.id);
429
430                 let file_id = ast_id.ast_id.file_id;
431                 let item_tree = self.db.file_item_tree(file_id);
432                 let mod_dir = self.mod_dirs[&directive.module_id].clone();
433                 ModCollector {
434                     def_collector: &mut *self,
435                     macro_depth: directive.depth,
436                     module_id: directive.module_id,
437                     tree_id: TreeId::new(file_id, None),
438                     item_tree: &item_tree,
439                     mod_dir,
440                 }
441                 .collect(&[*mod_item]);
442                 true
443             } else {
444                 false
445             }
446         });
447
448         if let Some(pos) = pos {
449             unresolved_macros.remove(pos);
450         }
451
452         // The collection above might add new unresolved macros (eg. derives), so merge the lists.
453         self.unresolved_macros.extend(unresolved_macros);
454
455         if pos.is_some() {
456             // Continue name resolution with the new data.
457             ReachedFixedPoint::No
458         } else {
459             ReachedFixedPoint::Yes
460         }
461     }
462
463     fn inject_prelude(&mut self, crate_attrs: &Attrs) {
464         // See compiler/rustc_builtin_macros/src/standard_library_imports.rs
465
466         if crate_attrs.by_key("no_core").exists() {
467             // libcore does not get a prelude.
468             return;
469         }
470
471         let krate = if crate_attrs.by_key("no_std").exists() {
472             name![core]
473         } else {
474             let std = name![std];
475             if self.def_map.extern_prelude().any(|(name, _)| *name == std) {
476                 std
477             } else {
478                 // If `std` does not exist for some reason, fall back to core. This mostly helps
479                 // keep r-a's own tests minimal.
480                 name![core]
481             }
482         };
483
484         let edition = match self.def_map.edition {
485             Edition::Edition2015 => name![rust_2015],
486             Edition::Edition2018 => name![rust_2018],
487             Edition::Edition2021 => name![rust_2021],
488         };
489
490         let path_kind = if self.def_map.edition == Edition::Edition2015 {
491             PathKind::Plain
492         } else {
493             PathKind::Abs
494         };
495         let path = ModPath::from_segments(
496             path_kind.clone(),
497             [krate.clone(), name![prelude], edition].iter().cloned(),
498         );
499         // Fall back to the older `std::prelude::v1` for compatibility with Rust <1.52.0
500         // FIXME remove this fallback
501         let fallback_path =
502             ModPath::from_segments(path_kind, [krate, name![prelude], name![v1]].iter().cloned());
503
504         for path in &[path, fallback_path] {
505             let (per_ns, _) = self.def_map.resolve_path(
506                 self.db,
507                 self.def_map.root,
508                 path,
509                 BuiltinShadowMode::Other,
510             );
511
512             match &per_ns.types {
513                 Some((ModuleDefId::ModuleId(m), _)) => {
514                     self.def_map.prelude = Some(*m);
515                     return;
516                 }
517                 _ => {
518                     tracing::debug!(
519                         "could not resolve prelude path `{}` to module (resolved to {:?})",
520                         path,
521                         per_ns.types
522                     );
523                 }
524             }
525         }
526     }
527
528     /// Adds a definition of procedural macro `name` to the root module.
529     ///
530     /// # Notes on procedural macro resolution
531     ///
532     /// Procedural macro functionality is provided by the build system: It has to build the proc
533     /// macro and pass the resulting dynamic library to rust-analyzer.
534     ///
535     /// When procedural macro support is enabled, the list of proc macros exported by a crate is
536     /// known before we resolve names in the crate. This list is stored in `self.proc_macros` and is
537     /// derived from the dynamic library.
538     ///
539     /// However, we *also* would like to be able to at least *resolve* macros on our own, without
540     /// help by the build system. So, when the macro isn't found in `self.proc_macros`, we instead
541     /// use a dummy expander that always errors. This comes with the drawback of macros potentially
542     /// going out of sync with what the build system sees (since we resolve using VFS state, but
543     /// Cargo builds only on-disk files). We could and probably should add diagnostics for that.
544     fn export_proc_macro(&mut self, def: ProcMacroDef, ast_id: AstId<ast::Fn>) {
545         let kind = def.kind.to_basedb_kind();
546         self.exports_proc_macros = true;
547         let macro_def = match self.proc_macros.iter().find(|(n, _)| n == &def.name) {
548             Some((_, expander)) => MacroDefId {
549                 krate: self.def_map.krate,
550                 kind: MacroDefKind::ProcMacro(*expander, kind, ast_id),
551                 local_inner: false,
552             },
553             None => MacroDefId {
554                 krate: self.def_map.krate,
555                 kind: MacroDefKind::ProcMacro(
556                     ProcMacroExpander::dummy(self.def_map.krate),
557                     kind,
558                     ast_id,
559                 ),
560                 local_inner: false,
561             },
562         };
563
564         self.define_proc_macro(def.name.clone(), macro_def);
565         self.def_map.exported_proc_macros.insert(macro_def, def);
566     }
567
568     /// Define a macro with `macro_rules`.
569     ///
570     /// It will define the macro in legacy textual scope, and if it has `#[macro_export]`,
571     /// then it is also defined in the root module scope.
572     /// You can `use` or invoke it by `crate::macro_name` anywhere, before or after the definition.
573     ///
574     /// It is surprising that the macro will never be in the current module scope.
575     /// These code fails with "unresolved import/macro",
576     /// ```rust,compile_fail
577     /// mod m { macro_rules! foo { () => {} } }
578     /// use m::foo as bar;
579     /// ```
580     ///
581     /// ```rust,compile_fail
582     /// macro_rules! foo { () => {} }
583     /// self::foo!();
584     /// crate::foo!();
585     /// ```
586     ///
587     /// Well, this code compiles, because the plain path `foo` in `use` is searched
588     /// in the legacy textual scope only.
589     /// ```rust
590     /// macro_rules! foo { () => {} }
591     /// use foo as bar;
592     /// ```
593     fn define_macro_rules(
594         &mut self,
595         module_id: LocalModuleId,
596         name: Name,
597         macro_: MacroDefId,
598         export: bool,
599     ) {
600         // Textual scoping
601         self.define_legacy_macro(module_id, name.clone(), macro_);
602
603         // Module scoping
604         // In Rust, `#[macro_export]` macros are unconditionally visible at the
605         // crate root, even if the parent modules is **not** visible.
606         if export {
607             self.update(
608                 self.def_map.root,
609                 &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
610                 Visibility::Public,
611                 ImportType::Named,
612             );
613         }
614     }
615
616     /// Define a legacy textual scoped macro in module
617     ///
618     /// We use a map `legacy_macros` to store all legacy textual scoped macros visible per module.
619     /// It will clone all macros from parent legacy scope, whose definition is prior to
620     /// the definition of current module.
621     /// And also, `macro_use` on a module will import all legacy macros visible inside to
622     /// current legacy scope, with possible shadowing.
623     fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, mac: MacroDefId) {
624         // Always shadowing
625         self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
626     }
627
628     /// Define a macro 2.0 macro
629     ///
630     /// The scoped of macro 2.0 macro is equal to normal function
631     fn define_macro_def(
632         &mut self,
633         module_id: LocalModuleId,
634         name: Name,
635         macro_: MacroDefId,
636         vis: &RawVisibility,
637     ) {
638         let vis =
639             self.def_map.resolve_visibility(self.db, module_id, vis).unwrap_or(Visibility::Public);
640         self.update(module_id, &[(Some(name), PerNs::macros(macro_, vis))], vis, ImportType::Named);
641     }
642
643     /// Define a proc macro
644     ///
645     /// A proc macro is similar to normal macro scope, but it would not visible in legacy textual scoped.
646     /// And unconditionally exported.
647     fn define_proc_macro(&mut self, name: Name, macro_: MacroDefId) {
648         self.update(
649             self.def_map.root,
650             &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
651             Visibility::Public,
652             ImportType::Named,
653         );
654     }
655
656     /// Import macros from `#[macro_use] extern crate`.
657     fn import_macros_from_extern_crate(
658         &mut self,
659         current_module_id: LocalModuleId,
660         extern_crate: &item_tree::ExternCrate,
661     ) {
662         tracing::debug!(
663             "importing macros from extern crate: {:?} ({:?})",
664             extern_crate,
665             self.def_map.edition,
666         );
667
668         let res = self.resolve_extern_crate(&extern_crate.name);
669
670         if let Some(ModuleDefId::ModuleId(m)) = res.take_types() {
671             if m == self.def_map.module_id(current_module_id) {
672                 cov_mark::hit!(ignore_macro_use_extern_crate_self);
673                 return;
674             }
675
676             cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use);
677             self.import_all_macros_exported(current_module_id, m.krate);
678         }
679     }
680
681     /// Import all exported macros from another crate
682     ///
683     /// Exported macros are just all macros in the root module scope.
684     /// Note that it contains not only all `#[macro_export]` macros, but also all aliases
685     /// created by `use` in the root module, ignoring the visibility of `use`.
686     fn import_all_macros_exported(&mut self, current_module_id: LocalModuleId, krate: CrateId) {
687         let def_map = self.db.crate_def_map(krate);
688         for (name, def) in def_map[def_map.root].scope.macros() {
689             // `macro_use` only bring things into legacy scope.
690             self.define_legacy_macro(current_module_id, name.clone(), def);
691         }
692     }
693
694     /// Tries to resolve every currently unresolved import.
695     fn resolve_imports(&mut self) -> ReachedFixedPoint {
696         let mut res = ReachedFixedPoint::Yes;
697         let imports = std::mem::take(&mut self.unresolved_imports);
698         let imports = imports
699             .into_iter()
700             .filter_map(|mut directive| {
701                 directive.status = self.resolve_import(directive.module_id, &directive.import);
702                 match directive.status {
703                     PartialResolvedImport::Indeterminate(_) => {
704                         self.record_resolved_import(&directive);
705                         // FIXME: For avoid performance regression,
706                         // we consider an imported resolved if it is indeterminate (i.e not all namespace resolved)
707                         self.resolved_imports.push(directive);
708                         res = ReachedFixedPoint::No;
709                         None
710                     }
711                     PartialResolvedImport::Resolved(_) => {
712                         self.record_resolved_import(&directive);
713                         self.resolved_imports.push(directive);
714                         res = ReachedFixedPoint::No;
715                         None
716                     }
717                     PartialResolvedImport::Unresolved => Some(directive),
718                 }
719             })
720             .collect();
721         self.unresolved_imports = imports;
722         res
723     }
724
725     fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
726         tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
727         if import.is_extern_crate {
728             let name = import
729                 .path
730                 .as_ident()
731                 .expect("extern crate should have been desugared to one-element path");
732
733             let res = self.resolve_extern_crate(name);
734
735             if res.is_none() {
736                 PartialResolvedImport::Unresolved
737             } else {
738                 PartialResolvedImport::Resolved(res)
739             }
740         } else {
741             let res = self.def_map.resolve_path_fp_with_macro(
742                 self.db,
743                 ResolveMode::Import,
744                 module_id,
745                 &import.path,
746                 BuiltinShadowMode::Module,
747             );
748
749             let def = res.resolved_def;
750             if res.reached_fixedpoint == ReachedFixedPoint::No || def.is_none() {
751                 return PartialResolvedImport::Unresolved;
752             }
753
754             if let Some(krate) = res.krate {
755                 if krate != self.def_map.krate {
756                     return PartialResolvedImport::Resolved(
757                         def.filter_visibility(|v| matches!(v, Visibility::Public)),
758                     );
759                 }
760             }
761
762             // Check whether all namespace is resolved
763             if def.take_types().is_some()
764                 && def.take_values().is_some()
765                 && def.take_macros().is_some()
766             {
767                 PartialResolvedImport::Resolved(def)
768             } else {
769                 PartialResolvedImport::Indeterminate(def)
770             }
771         }
772     }
773
774     fn resolve_extern_crate(&self, name: &Name) -> PerNs {
775         let arc;
776         let root = match self.def_map.block {
777             Some(_) => {
778                 arc = self.def_map.crate_root(self.db).def_map(self.db);
779                 &*arc
780             }
781             None => &self.def_map,
782         };
783
784         if name == &name!(self) {
785             cov_mark::hit!(extern_crate_self_as);
786             PerNs::types(root.module_id(root.root()).into(), Visibility::Public)
787         } else {
788             self.deps.get(name).map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public))
789         }
790     }
791
792     fn record_resolved_import(&mut self, directive: &ImportDirective) {
793         let module_id = directive.module_id;
794         let import = &directive.import;
795         let mut def = directive.status.namespaces();
796         let vis = self
797             .def_map
798             .resolve_visibility(self.db, module_id, &directive.import.visibility)
799             .unwrap_or(Visibility::Public);
800
801         match import.kind {
802             ImportKind::Plain | ImportKind::TypeOnly => {
803                 let name = match &import.alias {
804                     Some(ImportAlias::Alias(name)) => Some(name.clone()),
805                     Some(ImportAlias::Underscore) => None,
806                     None => match import.path.segments().last() {
807                         Some(last_segment) => Some(last_segment.clone()),
808                         None => {
809                             cov_mark::hit!(bogus_paths);
810                             return;
811                         }
812                     },
813                 };
814
815                 if import.kind == ImportKind::TypeOnly {
816                     def.values = None;
817                     def.macros = None;
818                 }
819
820                 tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
821
822                 // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
823                 if import.is_extern_crate && module_id == self.def_map.root {
824                     if let (Some(def), Some(name)) = (def.take_types(), name.as_ref()) {
825                         self.def_map.extern_prelude.insert(name.clone(), def);
826                     }
827                 }
828
829                 self.update(module_id, &[(name, def)], vis, ImportType::Named);
830             }
831             ImportKind::Glob => {
832                 tracing::debug!("glob import: {:?}", import);
833                 match def.take_types() {
834                     Some(ModuleDefId::ModuleId(m)) => {
835                         if import.is_prelude {
836                             // Note: This dodgily overrides the injected prelude. The rustc
837                             // implementation seems to work the same though.
838                             cov_mark::hit!(std_prelude);
839                             self.def_map.prelude = Some(m);
840                         } else if m.krate != self.def_map.krate {
841                             cov_mark::hit!(glob_across_crates);
842                             // glob import from other crate => we can just import everything once
843                             let item_map = m.def_map(self.db);
844                             let scope = &item_map[m.local_id].scope;
845
846                             // Module scoped macros is included
847                             let items = scope
848                                 .resolutions()
849                                 // only keep visible names...
850                                 .map(|(n, res)| {
851                                     (n, res.filter_visibility(|v| v.is_visible_from_other_crate()))
852                                 })
853                                 .filter(|(_, res)| !res.is_none())
854                                 .collect::<Vec<_>>();
855
856                             self.update(module_id, &items, vis, ImportType::Glob);
857                         } else {
858                             // glob import from same crate => we do an initial
859                             // import, and then need to propagate any further
860                             // additions
861                             let def_map;
862                             let scope = if m.block == self.def_map.block_id() {
863                                 &self.def_map[m.local_id].scope
864                             } else {
865                                 def_map = m.def_map(self.db);
866                                 &def_map[m.local_id].scope
867                             };
868
869                             // Module scoped macros is included
870                             let items = scope
871                                 .resolutions()
872                                 // only keep visible names...
873                                 .map(|(n, res)| {
874                                     (
875                                         n,
876                                         res.filter_visibility(|v| {
877                                             v.is_visible_from_def_map(
878                                                 self.db,
879                                                 &self.def_map,
880                                                 module_id,
881                                             )
882                                         }),
883                                     )
884                                 })
885                                 .filter(|(_, res)| !res.is_none())
886                                 .collect::<Vec<_>>();
887
888                             self.update(module_id, &items, vis, ImportType::Glob);
889                             // record the glob import in case we add further items
890                             let glob = self.glob_imports.entry(m.local_id).or_default();
891                             if !glob.iter().any(|(mid, _)| *mid == module_id) {
892                                 glob.push((module_id, vis));
893                             }
894                         }
895                     }
896                     Some(ModuleDefId::AdtId(AdtId::EnumId(e))) => {
897                         cov_mark::hit!(glob_enum);
898                         // glob import from enum => just import all the variants
899
900                         // XXX: urgh, so this works by accident! Here, we look at
901                         // the enum data, and, in theory, this might require us to
902                         // look back at the crate_def_map, creating a cycle. For
903                         // example, `enum E { crate::some_macro!(); }`. Luckily, the
904                         // only kind of macro that is allowed inside enum is a
905                         // `cfg_macro`, and we don't need to run name resolution for
906                         // it, but this is sheer luck!
907                         let enum_data = self.db.enum_data(e);
908                         let resolutions = enum_data
909                             .variants
910                             .iter()
911                             .map(|(local_id, variant_data)| {
912                                 let name = variant_data.name.clone();
913                                 let variant = EnumVariantId { parent: e, local_id };
914                                 let res = PerNs::both(variant.into(), variant.into(), vis);
915                                 (Some(name), res)
916                             })
917                             .collect::<Vec<_>>();
918                         self.update(module_id, &resolutions, vis, ImportType::Glob);
919                     }
920                     Some(d) => {
921                         tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
922                     }
923                     None => {
924                         tracing::debug!("glob import {:?} didn't resolve as type", import);
925                     }
926                 }
927             }
928         }
929     }
930
931     fn update(
932         &mut self,
933         module_id: LocalModuleId,
934         resolutions: &[(Option<Name>, PerNs)],
935         vis: Visibility,
936         import_type: ImportType,
937     ) {
938         self.db.unwind_if_cancelled();
939         self.update_recursive(module_id, resolutions, vis, import_type, 0)
940     }
941
942     fn update_recursive(
943         &mut self,
944         module_id: LocalModuleId,
945         resolutions: &[(Option<Name>, PerNs)],
946         // All resolutions are imported with this visibility; the visibilities in
947         // the `PerNs` values are ignored and overwritten
948         vis: Visibility,
949         import_type: ImportType,
950         depth: usize,
951     ) {
952         if GLOB_RECURSION_LIMIT.check(depth).is_err() {
953             // prevent stack overflows (but this shouldn't be possible)
954             panic!("infinite recursion in glob imports!");
955         }
956         let mut changed = false;
957
958         for (name, res) in resolutions {
959             match name {
960                 Some(name) => {
961                     let scope = &mut self.def_map.modules[module_id].scope;
962                     changed |= scope.push_res_with_import(
963                         &mut self.from_glob_import,
964                         (module_id, name.clone()),
965                         res.with_visibility(vis),
966                         import_type,
967                     );
968                 }
969                 None => {
970                     let tr = match res.take_types() {
971                         Some(ModuleDefId::TraitId(tr)) => tr,
972                         Some(other) => {
973                             tracing::debug!("non-trait `_` import of {:?}", other);
974                             continue;
975                         }
976                         None => continue,
977                     };
978                     let old_vis = self.def_map.modules[module_id].scope.unnamed_trait_vis(tr);
979                     let should_update = match old_vis {
980                         None => true,
981                         Some(old_vis) => {
982                             let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
983                                 panic!("`Tr as _` imports with unrelated visibilities {:?} and {:?} (trait {:?})", old_vis, vis, tr);
984                             });
985
986                             if max_vis == old_vis {
987                                 false
988                             } else {
989                                 cov_mark::hit!(upgrade_underscore_visibility);
990                                 true
991                             }
992                         }
993                     };
994
995                     if should_update {
996                         changed = true;
997                         self.def_map.modules[module_id].scope.push_unnamed_trait(tr, vis);
998                     }
999                 }
1000             }
1001         }
1002
1003         if !changed {
1004             return;
1005         }
1006         let glob_imports = self
1007             .glob_imports
1008             .get(&module_id)
1009             .into_iter()
1010             .flat_map(|v| v.iter())
1011             .filter(|(glob_importing_module, _)| {
1012                 // we know all resolutions have the same visibility (`vis`), so we
1013                 // just need to check that once
1014                 vis.is_visible_from_def_map(self.db, &self.def_map, *glob_importing_module)
1015             })
1016             .cloned()
1017             .collect::<Vec<_>>();
1018
1019         for (glob_importing_module, glob_import_vis) in glob_imports {
1020             self.update_recursive(
1021                 glob_importing_module,
1022                 resolutions,
1023                 glob_import_vis,
1024                 ImportType::Glob,
1025                 depth + 1,
1026             );
1027         }
1028     }
1029
1030     fn resolve_macros(&mut self) -> ReachedFixedPoint {
1031         let mut macros = std::mem::take(&mut self.unresolved_macros);
1032         let mut resolved = Vec::new();
1033         let mut res = ReachedFixedPoint::Yes;
1034         macros.retain(|directive| {
1035             let resolver = |path| {
1036                 let resolved_res = self.def_map.resolve_path_fp_with_macro(
1037                     self.db,
1038                     ResolveMode::Other,
1039                     directive.module_id,
1040                     &path,
1041                     BuiltinShadowMode::Module,
1042                 );
1043                 resolved_res.resolved_def.take_macros()
1044             };
1045
1046             match &directive.kind {
1047                 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1048                     match macro_call_as_call_id(
1049                         ast_id,
1050                         *expand_to,
1051                         self.db,
1052                         self.def_map.krate,
1053                         &resolver,
1054                         &mut |_err| (),
1055                     ) {
1056                         Ok(Ok(call_id)) => {
1057                             resolved.push((directive.module_id, call_id, directive.depth));
1058                             res = ReachedFixedPoint::No;
1059                             return false;
1060                         }
1061                         Err(UnresolvedMacro { .. }) | Ok(Err(_)) => {}
1062                     }
1063                 }
1064                 MacroDirectiveKind::Derive { ast_id, derive_attr } => {
1065                     match derive_macro_as_call_id(
1066                         ast_id,
1067                         *derive_attr,
1068                         self.db,
1069                         self.def_map.krate,
1070                         &resolver,
1071                     ) {
1072                         Ok(call_id) => {
1073                             self.def_map.modules[directive.module_id].scope.add_derive_macro_invoc(
1074                                 ast_id.ast_id,
1075                                 call_id,
1076                                 *derive_attr,
1077                             );
1078
1079                             resolved.push((directive.module_id, call_id, directive.depth));
1080                             res = ReachedFixedPoint::No;
1081                             return false;
1082                         }
1083                         Err(UnresolvedMacro { .. }) => (),
1084                     }
1085                 }
1086                 MacroDirectiveKind::Attr { ast_id, mod_item, attr } => {
1087                     if let Some(ident) = ast_id.path.as_ident() {
1088                         if let Some(helpers) = self.derive_helpers_in_scope.get(&ast_id.ast_id) {
1089                             if helpers.contains(ident) {
1090                                 cov_mark::hit!(resolved_derive_helper);
1091
1092                                 // Resolved to derive helper. Collect the item's attributes again,
1093                                 // starting after the derive helper.
1094                                 let file_id = ast_id.ast_id.file_id;
1095                                 let item_tree = self.db.file_item_tree(file_id);
1096                                 let mod_dir = self.mod_dirs[&directive.module_id].clone();
1097                                 self.skip_attrs.insert(InFile::new(file_id, *mod_item), attr.id);
1098                                 ModCollector {
1099                                     def_collector: &mut *self,
1100                                     macro_depth: directive.depth,
1101                                     module_id: directive.module_id,
1102                                     tree_id: TreeId::new(file_id, None),
1103                                     item_tree: &item_tree,
1104                                     mod_dir,
1105                                 }
1106                                 .collect(&[*mod_item]);
1107
1108                                 // Remove the original directive since we resolved it.
1109                                 res = ReachedFixedPoint::No;
1110                                 return false;
1111                             }
1112                         }
1113                     }
1114
1115                     if !self.db.enable_proc_attr_macros() {
1116                         return true;
1117                     }
1118
1119                     // Not resolved to a derive helper, so try to resolve as a macro.
1120                     match attr_macro_as_call_id(
1121                         ast_id,
1122                         attr,
1123                         self.db,
1124                         self.def_map.krate,
1125                         &resolver,
1126                     ) {
1127                         Ok(call_id) => {
1128                             let loc: MacroCallLoc = self.db.lookup_intern_macro(call_id);
1129                             if let MacroDefKind::ProcMacro(exp, ..) = &loc.def.kind {
1130                                 if exp.is_dummy() {
1131                                     // Proc macros that cannot be expanded are treated as not
1132                                     // resolved, in order to fall back later.
1133                                     self.def_map.diagnostics.push(
1134                                         DefDiagnostic::unresolved_proc_macro(
1135                                             directive.module_id,
1136                                             loc.kind,
1137                                         ),
1138                                     );
1139
1140                                     let file_id = ast_id.ast_id.file_id;
1141                                     let item_tree = self.db.file_item_tree(file_id);
1142                                     let mod_dir = self.mod_dirs[&directive.module_id].clone();
1143                                     self.skip_attrs
1144                                         .insert(InFile::new(file_id, *mod_item), attr.id);
1145                                     ModCollector {
1146                                         def_collector: &mut *self,
1147                                         macro_depth: directive.depth,
1148                                         module_id: directive.module_id,
1149                                         tree_id: TreeId::new(file_id, None),
1150                                         item_tree: &item_tree,
1151                                         mod_dir,
1152                                     }
1153                                     .collect(&[*mod_item]);
1154
1155                                     // Remove the macro directive.
1156                                     return false;
1157                                 }
1158                             }
1159
1160                             self.def_map.modules[directive.module_id]
1161                                 .scope
1162                                 .add_attr_macro_invoc(ast_id.ast_id, call_id);
1163
1164                             resolved.push((directive.module_id, call_id, directive.depth));
1165                             res = ReachedFixedPoint::No;
1166                             return false;
1167                         }
1168                         Err(UnresolvedMacro { .. }) => (),
1169                     }
1170                 }
1171             }
1172
1173             true
1174         });
1175         // Attribute resolution can add unresolved macro invocations, so concatenate the lists.
1176         self.unresolved_macros.extend(macros);
1177
1178         for (module_id, macro_call_id, depth) in resolved {
1179             self.collect_macro_expansion(module_id, macro_call_id, depth);
1180         }
1181
1182         res
1183     }
1184
1185     fn collect_macro_expansion(
1186         &mut self,
1187         module_id: LocalModuleId,
1188         macro_call_id: MacroCallId,
1189         depth: usize,
1190     ) {
1191         if EXPANSION_DEPTH_LIMIT.check(depth).is_err() {
1192             cov_mark::hit!(macro_expansion_overflow);
1193             tracing::warn!("macro expansion is too deep");
1194             return;
1195         }
1196         let file_id = macro_call_id.as_file();
1197
1198         // First, fetch the raw expansion result for purposes of error reporting. This goes through
1199         // `macro_expand_error` to avoid depending on the full expansion result (to improve
1200         // incrementality).
1201         let loc: MacroCallLoc = self.db.lookup_intern_macro(macro_call_id);
1202         let err = self.db.macro_expand_error(macro_call_id);
1203         if let Some(err) = err {
1204             let diag = match err {
1205                 hir_expand::ExpandError::UnresolvedProcMacro => {
1206                     // Missing proc macros are non-fatal, so they are handled specially.
1207                     DefDiagnostic::unresolved_proc_macro(module_id, loc.kind.clone())
1208                 }
1209                 _ => DefDiagnostic::macro_error(module_id, loc.kind.clone(), err.to_string()),
1210             };
1211
1212             self.def_map.diagnostics.push(diag);
1213         }
1214
1215         // If we've just resolved a derive, record its helper attributes.
1216         if let MacroCallKind::Derive { ast_id, .. } = &loc.kind {
1217             if loc.def.krate != self.def_map.krate {
1218                 let def_map = self.db.crate_def_map(loc.def.krate);
1219                 if let Some(def) = def_map.exported_proc_macros.get(&loc.def) {
1220                     if let ProcMacroKind::CustomDerive { helpers } = &def.kind {
1221                         self.derive_helpers_in_scope
1222                             .entry(*ast_id)
1223                             .or_default()
1224                             .extend(helpers.iter().cloned());
1225                     }
1226                 }
1227             }
1228         }
1229
1230         // Then, fetch and process the item tree. This will reuse the expansion result from above.
1231         let item_tree = self.db.file_item_tree(file_id);
1232         let mod_dir = self.mod_dirs[&module_id].clone();
1233         ModCollector {
1234             def_collector: &mut *self,
1235             macro_depth: depth,
1236             tree_id: TreeId::new(file_id, None),
1237             module_id,
1238             item_tree: &item_tree,
1239             mod_dir,
1240         }
1241         .collect(item_tree.top_level_items());
1242     }
1243
1244     fn finish(mut self) -> DefMap {
1245         // Emit diagnostics for all remaining unexpanded macros.
1246
1247         for directive in &self.unresolved_macros {
1248             match &directive.kind {
1249                 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1250                     match macro_call_as_call_id(
1251                         ast_id,
1252                         *expand_to,
1253                         self.db,
1254                         self.def_map.krate,
1255                         |path| {
1256                             let resolved_res = self.def_map.resolve_path_fp_with_macro(
1257                                 self.db,
1258                                 ResolveMode::Other,
1259                                 directive.module_id,
1260                                 &path,
1261                                 BuiltinShadowMode::Module,
1262                             );
1263                             resolved_res.resolved_def.take_macros()
1264                         },
1265                         &mut |_| (),
1266                     ) {
1267                         Ok(_) => (),
1268                         Err(UnresolvedMacro { path }) => {
1269                             self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
1270                                 directive.module_id,
1271                                 ast_id.ast_id,
1272                                 path,
1273                             ));
1274                         }
1275                     }
1276                 }
1277                 MacroDirectiveKind::Derive { .. } | MacroDirectiveKind::Attr { .. } => {
1278                     // FIXME: we might want to diagnose this too
1279                 }
1280             }
1281         }
1282
1283         // Emit diagnostics for all remaining unresolved imports.
1284
1285         // We'd like to avoid emitting a diagnostics avalanche when some `extern crate` doesn't
1286         // resolve. We first emit diagnostics for unresolved extern crates and collect the missing
1287         // crate names. Then we emit diagnostics for unresolved imports, but only if the import
1288         // doesn't start with an unresolved crate's name. Due to renaming and reexports, this is a
1289         // heuristic, but it works in practice.
1290         let mut diagnosed_extern_crates = FxHashSet::default();
1291         for directive in &self.unresolved_imports {
1292             if let ImportSource::ExternCrate(krate) = directive.import.source {
1293                 let item_tree = krate.item_tree(self.db);
1294                 let extern_crate = &item_tree[krate.value];
1295
1296                 diagnosed_extern_crates.insert(extern_crate.name.clone());
1297
1298                 self.def_map.diagnostics.push(DefDiagnostic::unresolved_extern_crate(
1299                     directive.module_id,
1300                     InFile::new(krate.file_id(), extern_crate.ast_id),
1301                 ));
1302             }
1303         }
1304
1305         for directive in &self.unresolved_imports {
1306             if let ImportSource::Import { id: import, use_tree } = &directive.import.source {
1307                 if let (Some(krate), PathKind::Plain | PathKind::Abs) =
1308                     (directive.import.path.segments().first(), &directive.import.path.kind)
1309                 {
1310                     if diagnosed_extern_crates.contains(krate) {
1311                         continue;
1312                     }
1313                 }
1314
1315                 self.def_map.diagnostics.push(DefDiagnostic::unresolved_import(
1316                     directive.module_id,
1317                     *import,
1318                     *use_tree,
1319                 ));
1320             }
1321         }
1322
1323         self.def_map
1324     }
1325 }
1326
1327 /// Walks a single module, populating defs, imports and macros
1328 struct ModCollector<'a, 'b> {
1329     def_collector: &'a mut DefCollector<'b>,
1330     macro_depth: usize,
1331     module_id: LocalModuleId,
1332     tree_id: TreeId,
1333     item_tree: &'a ItemTree,
1334     mod_dir: ModDir,
1335 }
1336
1337 impl ModCollector<'_, '_> {
1338     fn collect(&mut self, items: &[ModItem]) {
1339         let krate = self.def_collector.def_map.krate;
1340
1341         // Note: don't assert that inserted value is fresh: it's simply not true
1342         // for macros.
1343         self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone());
1344
1345         // Prelude module is always considered to be `#[macro_use]`.
1346         if let Some(prelude_module) = self.def_collector.def_map.prelude {
1347             if prelude_module.krate != krate {
1348                 cov_mark::hit!(prelude_is_macro_use);
1349                 self.def_collector.import_all_macros_exported(self.module_id, prelude_module.krate);
1350             }
1351         }
1352
1353         // This should be processed eagerly instead of deferred to resolving.
1354         // `#[macro_use] extern crate` is hoisted to imports macros before collecting
1355         // any other items.
1356         for item in items {
1357             let attrs = self.item_tree.attrs(self.def_collector.db, krate, (*item).into());
1358             if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) {
1359                 if let ModItem::ExternCrate(id) = item {
1360                     let import = self.item_tree[*id].clone();
1361                     let attrs = self.item_tree.attrs(
1362                         self.def_collector.db,
1363                         krate,
1364                         ModItem::from(*id).into(),
1365                     );
1366                     if attrs.by_key("macro_use").exists() {
1367                         self.def_collector.import_macros_from_extern_crate(self.module_id, &import);
1368                     }
1369                 }
1370             }
1371         }
1372
1373         for &item in items {
1374             let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
1375             if let Some(cfg) = attrs.cfg() {
1376                 if !self.is_cfg_enabled(&cfg) {
1377                     self.emit_unconfigured_diagnostic(item, &cfg);
1378                     continue;
1379                 }
1380             }
1381
1382             if let Err(()) = self.resolve_attributes(&attrs, item) {
1383                 // Do not process the item. It has at least one non-builtin attribute, so the
1384                 // fixed-point algorithm is required to resolve the rest of them.
1385                 continue;
1386             }
1387
1388             let module = self.def_collector.def_map.module_id(self.module_id);
1389
1390             let mut def = None;
1391             match item {
1392                 ModItem::Mod(m) => self.collect_module(&self.item_tree[m], &attrs),
1393                 ModItem::Import(import_id) => {
1394                     let module_id = self.module_id;
1395                     let imports = Import::from_use(
1396                         self.def_collector.db,
1397                         krate,
1398                         self.item_tree,
1399                         ItemTreeId::new(self.tree_id, import_id),
1400                     );
1401                     self.def_collector.unresolved_imports.extend(imports.into_iter().map(
1402                         |import| ImportDirective {
1403                             module_id,
1404                             import,
1405                             status: PartialResolvedImport::Unresolved,
1406                         },
1407                     ));
1408                 }
1409                 ModItem::ExternCrate(import_id) => {
1410                     self.def_collector.unresolved_imports.push(ImportDirective {
1411                         module_id: self.module_id,
1412                         import: Import::from_extern_crate(
1413                             self.def_collector.db,
1414                             krate,
1415                             self.item_tree,
1416                             ItemTreeId::new(self.tree_id, import_id),
1417                         ),
1418                         status: PartialResolvedImport::Unresolved,
1419                     })
1420                 }
1421                 ModItem::ExternBlock(block) => self.collect(&self.item_tree[block].children),
1422                 ModItem::MacroCall(mac) => self.collect_macro_call(&self.item_tree[mac]),
1423                 ModItem::MacroRules(id) => self.collect_macro_rules(id),
1424                 ModItem::MacroDef(id) => self.collect_macro_def(id),
1425                 ModItem::Impl(imp) => {
1426                     let module = self.def_collector.def_map.module_id(self.module_id);
1427                     let impl_id =
1428                         ImplLoc { container: module, id: ItemTreeId::new(self.tree_id, imp) }
1429                             .intern(self.def_collector.db);
1430                     self.def_collector.def_map.modules[self.module_id].scope.define_impl(impl_id)
1431                 }
1432                 ModItem::Function(id) => {
1433                     let func = &self.item_tree[id];
1434
1435                     let ast_id = InFile::new(self.file_id(), func.ast_id);
1436                     self.collect_proc_macro_def(&func.name, ast_id, &attrs);
1437
1438                     def = Some(DefData {
1439                         id: FunctionLoc {
1440                             container: module.into(),
1441                             id: ItemTreeId::new(self.tree_id, id),
1442                         }
1443                         .intern(self.def_collector.db)
1444                         .into(),
1445                         name: &func.name,
1446                         visibility: &self.item_tree[func.visibility],
1447                         has_constructor: false,
1448                     });
1449                 }
1450                 ModItem::Struct(id) => {
1451                     let it = &self.item_tree[id];
1452
1453                     def = Some(DefData {
1454                         id: StructLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1455                             .intern(self.def_collector.db)
1456                             .into(),
1457                         name: &it.name,
1458                         visibility: &self.item_tree[it.visibility],
1459                         has_constructor: !matches!(it.fields, Fields::Record(_)),
1460                     });
1461                 }
1462                 ModItem::Union(id) => {
1463                     let it = &self.item_tree[id];
1464
1465                     def = Some(DefData {
1466                         id: UnionLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1467                             .intern(self.def_collector.db)
1468                             .into(),
1469                         name: &it.name,
1470                         visibility: &self.item_tree[it.visibility],
1471                         has_constructor: false,
1472                     });
1473                 }
1474                 ModItem::Enum(id) => {
1475                     let it = &self.item_tree[id];
1476
1477                     def = Some(DefData {
1478                         id: EnumLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1479                             .intern(self.def_collector.db)
1480                             .into(),
1481                         name: &it.name,
1482                         visibility: &self.item_tree[it.visibility],
1483                         has_constructor: false,
1484                     });
1485                 }
1486                 ModItem::Const(id) => {
1487                     let it = &self.item_tree[id];
1488                     let const_id = ConstLoc {
1489                         container: module.into(),
1490                         id: ItemTreeId::new(self.tree_id, id),
1491                     }
1492                     .intern(self.def_collector.db);
1493
1494                     match &it.name {
1495                         Some(name) => {
1496                             def = Some(DefData {
1497                                 id: const_id.into(),
1498                                 name,
1499                                 visibility: &self.item_tree[it.visibility],
1500                                 has_constructor: false,
1501                             });
1502                         }
1503                         None => {
1504                             // const _: T = ...;
1505                             self.def_collector.def_map.modules[self.module_id]
1506                                 .scope
1507                                 .define_unnamed_const(const_id);
1508                         }
1509                     }
1510                 }
1511                 ModItem::Static(id) => {
1512                     let it = &self.item_tree[id];
1513
1514                     def = Some(DefData {
1515                         id: StaticLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1516                             .intern(self.def_collector.db)
1517                             .into(),
1518                         name: &it.name,
1519                         visibility: &self.item_tree[it.visibility],
1520                         has_constructor: false,
1521                     });
1522                 }
1523                 ModItem::Trait(id) => {
1524                     let it = &self.item_tree[id];
1525
1526                     def = Some(DefData {
1527                         id: TraitLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1528                             .intern(self.def_collector.db)
1529                             .into(),
1530                         name: &it.name,
1531                         visibility: &self.item_tree[it.visibility],
1532                         has_constructor: false,
1533                     });
1534                 }
1535                 ModItem::TypeAlias(id) => {
1536                     let it = &self.item_tree[id];
1537
1538                     def = Some(DefData {
1539                         id: TypeAliasLoc {
1540                             container: module.into(),
1541                             id: ItemTreeId::new(self.tree_id, id),
1542                         }
1543                         .intern(self.def_collector.db)
1544                         .into(),
1545                         name: &it.name,
1546                         visibility: &self.item_tree[it.visibility],
1547                         has_constructor: false,
1548                     });
1549                 }
1550             }
1551
1552             if let Some(DefData { id, name, visibility, has_constructor }) = def {
1553                 self.def_collector.def_map.modules[self.module_id].scope.declare(id);
1554                 let vis = self
1555                     .def_collector
1556                     .def_map
1557                     .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1558                     .unwrap_or(Visibility::Public);
1559                 self.def_collector.update(
1560                     self.module_id,
1561                     &[(Some(name.clone()), PerNs::from_def(id, vis, has_constructor))],
1562                     vis,
1563                     ImportType::Named,
1564                 )
1565             }
1566         }
1567     }
1568
1569     fn collect_module(&mut self, module: &Mod, attrs: &Attrs) {
1570         let path_attr = attrs.by_key("path").string_value();
1571         let is_macro_use = attrs.by_key("macro_use").exists();
1572         match &module.kind {
1573             // inline module, just recurse
1574             ModKind::Inline { items } => {
1575                 let module_id = self.push_child_module(
1576                     module.name.clone(),
1577                     AstId::new(self.file_id(), module.ast_id),
1578                     None,
1579                     &self.item_tree[module.visibility],
1580                 );
1581
1582                 if let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
1583                 {
1584                     ModCollector {
1585                         def_collector: &mut *self.def_collector,
1586                         macro_depth: self.macro_depth,
1587                         module_id,
1588                         tree_id: self.tree_id,
1589                         item_tree: self.item_tree,
1590                         mod_dir,
1591                     }
1592                     .collect(&*items);
1593                     if is_macro_use {
1594                         self.import_all_legacy_macros(module_id);
1595                     }
1596                 }
1597             }
1598             // out of line module, resolve, parse and recurse
1599             ModKind::Outline {} => {
1600                 let ast_id = AstId::new(self.tree_id.file_id(), module.ast_id);
1601                 let db = self.def_collector.db;
1602                 match self.mod_dir.resolve_declaration(db, self.file_id(), &module.name, path_attr)
1603                 {
1604                     Ok((file_id, is_mod_rs, mod_dir)) => {
1605                         let item_tree = db.file_item_tree(file_id.into());
1606                         let is_enabled = item_tree
1607                             .top_level_attrs(db, self.def_collector.def_map.krate)
1608                             .cfg()
1609                             .map_or(true, |cfg| {
1610                                 self.def_collector.cfg_options.check(&cfg) != Some(false)
1611                             });
1612                         if is_enabled {
1613                             let module_id = self.push_child_module(
1614                                 module.name.clone(),
1615                                 ast_id,
1616                                 Some((file_id, is_mod_rs)),
1617                                 &self.item_tree[module.visibility],
1618                             );
1619                             ModCollector {
1620                                 def_collector: &mut *self.def_collector,
1621                                 macro_depth: self.macro_depth,
1622                                 module_id,
1623                                 tree_id: TreeId::new(file_id.into(), None),
1624                                 item_tree: &item_tree,
1625                                 mod_dir,
1626                             }
1627                             .collect(item_tree.top_level_items());
1628                             if is_macro_use
1629                                 || item_tree
1630                                     .top_level_attrs(db, self.def_collector.def_map.krate)
1631                                     .by_key("macro_use")
1632                                     .exists()
1633                             {
1634                                 self.import_all_legacy_macros(module_id);
1635                             }
1636                         }
1637                     }
1638                     Err(candidate) => {
1639                         self.def_collector.def_map.diagnostics.push(
1640                             DefDiagnostic::unresolved_module(self.module_id, ast_id, candidate),
1641                         );
1642                     }
1643                 };
1644             }
1645         }
1646     }
1647
1648     fn push_child_module(
1649         &mut self,
1650         name: Name,
1651         declaration: AstId<ast::Module>,
1652         definition: Option<(FileId, bool)>,
1653         visibility: &crate::visibility::RawVisibility,
1654     ) -> LocalModuleId {
1655         let vis = self
1656             .def_collector
1657             .def_map
1658             .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1659             .unwrap_or(Visibility::Public);
1660         let modules = &mut self.def_collector.def_map.modules;
1661         let origin = match definition {
1662             None => ModuleOrigin::Inline { definition: declaration },
1663             Some((definition, is_mod_rs)) => {
1664                 ModuleOrigin::File { declaration, definition, is_mod_rs }
1665             }
1666         };
1667         let res = modules.alloc(ModuleData::new(origin, vis));
1668         modules[res].parent = Some(self.module_id);
1669         for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() {
1670             modules[res].scope.define_legacy_macro(name, mac)
1671         }
1672         modules[self.module_id].children.insert(name.clone(), res);
1673         let module = self.def_collector.def_map.module_id(res);
1674         let def: ModuleDefId = module.into();
1675         self.def_collector.def_map.modules[self.module_id].scope.declare(def);
1676         self.def_collector.update(
1677             self.module_id,
1678             &[(Some(name), PerNs::from_def(def, vis, false))],
1679             vis,
1680             ImportType::Named,
1681         );
1682         res
1683     }
1684
1685     /// Resolves attributes on an item.
1686     ///
1687     /// Returns `Err` when some attributes could not be resolved to builtins and have been
1688     /// registered as unresolved.
1689     ///
1690     /// If `ignore_up_to` is `Some`, attributes precending and including that attribute will be
1691     /// assumed to be resolved already.
1692     fn resolve_attributes(&mut self, attrs: &Attrs, mod_item: ModItem) -> Result<(), ()> {
1693         let mut ignore_up_to =
1694             self.def_collector.skip_attrs.get(&InFile::new(self.file_id(), mod_item)).copied();
1695         let iter = attrs
1696             .iter()
1697             .dedup_by(|a, b| {
1698                 // FIXME: this should not be required, all attributes on an item should have a
1699                 // unique ID!
1700                 // Still, this occurs because `#[cfg_attr]` can "expand" to multiple attributes:
1701                 //     #[cfg_attr(not(off), unresolved, unresolved)]
1702                 //     struct S;
1703                 // We should come up with a different way to ID attributes.
1704                 a.id == b.id
1705             })
1706             .skip_while(|attr| match ignore_up_to {
1707                 Some(id) if attr.id == id => {
1708                     ignore_up_to = None;
1709                     true
1710                 }
1711                 Some(_) => true,
1712                 None => false,
1713             });
1714
1715         for attr in iter {
1716             if attr.path.as_ident() == Some(&hir_expand::name![derive]) {
1717                 self.collect_derive(attr, mod_item);
1718             } else if self.is_builtin_or_registered_attr(&attr.path) {
1719                 continue;
1720             } else {
1721                 tracing::debug!("non-builtin attribute {}", attr.path);
1722
1723                 let ast_id = AstIdWithPath::new(
1724                     self.file_id(),
1725                     mod_item.ast_id(self.item_tree),
1726                     attr.path.as_ref().clone(),
1727                 );
1728                 self.def_collector.unresolved_macros.push(MacroDirective {
1729                     module_id: self.module_id,
1730                     depth: self.macro_depth + 1,
1731                     kind: MacroDirectiveKind::Attr { ast_id, attr: attr.clone(), mod_item },
1732                 });
1733
1734                 return Err(());
1735             }
1736         }
1737
1738         Ok(())
1739     }
1740
1741     fn is_builtin_or_registered_attr(&self, path: &ModPath) -> bool {
1742         if path.kind == PathKind::Plain {
1743             if let Some(tool_module) = path.segments().first() {
1744                 let tool_module = tool_module.to_string();
1745                 let is_tool = builtin_attr::TOOL_MODULES
1746                     .iter()
1747                     .copied()
1748                     .chain(self.def_collector.registered_tools.iter().map(AsRef::as_ref))
1749                     .any(|m| tool_module == *m);
1750                 if is_tool {
1751                     return true;
1752                 }
1753             }
1754
1755             if let Some(name) = path.as_ident() {
1756                 let name = name.to_string();
1757                 let is_inert = builtin_attr::INERT_ATTRIBUTES
1758                     .iter()
1759                     .chain(builtin_attr::EXTRA_ATTRIBUTES)
1760                     .copied()
1761                     .chain(self.def_collector.registered_attrs.iter().map(AsRef::as_ref))
1762                     .any(|attr| name == *attr);
1763                 return is_inert;
1764             }
1765         }
1766
1767         false
1768     }
1769
1770     fn collect_derive(&mut self, attr: &Attr, mod_item: ModItem) {
1771         let ast_id: FileAstId<ast::Item> = match mod_item {
1772             ModItem::Struct(it) => self.item_tree[it].ast_id.upcast(),
1773             ModItem::Union(it) => self.item_tree[it].ast_id.upcast(),
1774             ModItem::Enum(it) => self.item_tree[it].ast_id.upcast(),
1775             _ => {
1776                 // Cannot use derive on this item.
1777                 // FIXME: diagnose
1778                 return;
1779             }
1780         };
1781
1782         match attr.parse_derive() {
1783             Some(derive_macros) => {
1784                 for path in derive_macros {
1785                     let ast_id = AstIdWithPath::new(self.file_id(), ast_id, path);
1786                     self.def_collector.unresolved_macros.push(MacroDirective {
1787                         module_id: self.module_id,
1788                         depth: self.macro_depth + 1,
1789                         kind: MacroDirectiveKind::Derive { ast_id, derive_attr: attr.id },
1790                     });
1791                 }
1792             }
1793             None => {
1794                 // FIXME: diagnose
1795                 tracing::debug!("malformed derive: {:?}", attr);
1796             }
1797         }
1798     }
1799
1800     /// If `attrs` registers a procedural macro, collects its definition.
1801     fn collect_proc_macro_def(&mut self, func_name: &Name, ast_id: AstId<ast::Fn>, attrs: &Attrs) {
1802         // FIXME: this should only be done in the root module of `proc-macro` crates, not everywhere
1803         if let Some(proc_macro) = attrs.parse_proc_macro_decl(func_name) {
1804             self.def_collector.export_proc_macro(proc_macro, ast_id);
1805         }
1806     }
1807
1808     fn collect_macro_rules(&mut self, id: FileItemTreeId<MacroRules>) {
1809         let krate = self.def_collector.def_map.krate;
1810         let mac = &self.item_tree[id];
1811         let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1812         let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1813
1814         let export_attr = attrs.by_key("macro_export");
1815
1816         let is_export = export_attr.exists();
1817         let is_local_inner = if is_export {
1818             export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it {
1819                 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
1820                     ident.text.contains("local_inner_macros")
1821                 }
1822                 _ => false,
1823             })
1824         } else {
1825             false
1826         };
1827
1828         // Case 1: builtin macros
1829         if attrs.by_key("rustc_builtin_macro").exists() {
1830             // `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name.
1831             let name;
1832             let name = match attrs.by_key("rustc_builtin_macro").string_value() {
1833                 Some(it) => {
1834                     // FIXME: a hacky way to create a Name from string.
1835                     name = tt::Ident { text: it.clone(), id: tt::TokenId::unspecified() }.as_name();
1836                     &name
1837                 }
1838                 None => {
1839                     match attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| {
1840                         match tt.token_trees.first() {
1841                             Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
1842                             _ => None,
1843                         }
1844                     }) {
1845                         Some(ident) => {
1846                             name = ident.as_name();
1847                             &name
1848                         }
1849                         None => &mac.name,
1850                     }
1851                 }
1852             };
1853             let krate = self.def_collector.def_map.krate;
1854             match find_builtin_macro(name, krate, ast_id) {
1855                 Some(macro_id) => {
1856                     self.def_collector.define_macro_rules(
1857                         self.module_id,
1858                         mac.name.clone(),
1859                         macro_id,
1860                         is_export,
1861                     );
1862                     return;
1863                 }
1864                 None => {
1865                     self.def_collector
1866                         .def_map
1867                         .diagnostics
1868                         .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1869                 }
1870             }
1871         }
1872
1873         // Case 2: normal `macro_rules!` macro
1874         let macro_id = MacroDefId {
1875             krate: self.def_collector.def_map.krate,
1876             kind: MacroDefKind::Declarative(ast_id),
1877             local_inner: is_local_inner,
1878         };
1879         self.def_collector.define_macro_rules(
1880             self.module_id,
1881             mac.name.clone(),
1882             macro_id,
1883             is_export,
1884         );
1885     }
1886
1887     fn collect_macro_def(&mut self, id: FileItemTreeId<MacroDef>) {
1888         let krate = self.def_collector.def_map.krate;
1889         let mac = &self.item_tree[id];
1890         let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1891
1892         // Case 1: bulitin macros
1893         let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1894         if attrs.by_key("rustc_builtin_macro").exists() {
1895             let macro_id = find_builtin_macro(&mac.name, krate, ast_id)
1896                 .or_else(|| find_builtin_derive(&mac.name, krate, ast_id))
1897                 .or_else(|| find_builtin_attr(&mac.name, krate, ast_id));
1898
1899             match macro_id {
1900                 Some(macro_id) => {
1901                     self.def_collector.define_macro_def(
1902                         self.module_id,
1903                         mac.name.clone(),
1904                         macro_id,
1905                         &self.item_tree[mac.visibility],
1906                     );
1907                     return;
1908                 }
1909                 None => {
1910                     self.def_collector
1911                         .def_map
1912                         .diagnostics
1913                         .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1914                 }
1915             }
1916         }
1917
1918         // Case 2: normal `macro`
1919         let macro_id = MacroDefId {
1920             krate: self.def_collector.def_map.krate,
1921             kind: MacroDefKind::Declarative(ast_id),
1922             local_inner: false,
1923         };
1924
1925         self.def_collector.define_macro_def(
1926             self.module_id,
1927             mac.name.clone(),
1928             macro_id,
1929             &self.item_tree[mac.visibility],
1930         );
1931     }
1932
1933     fn collect_macro_call(&mut self, mac: &MacroCall) {
1934         let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, (*mac.path).clone());
1935
1936         // Case 1: try to resolve in legacy scope and expand macro_rules
1937         let mut error = None;
1938         match macro_call_as_call_id(
1939             &ast_id,
1940             mac.expand_to,
1941             self.def_collector.db,
1942             self.def_collector.def_map.krate,
1943             |path| {
1944                 path.as_ident().and_then(|name| {
1945                     self.def_collector.def_map.with_ancestor_maps(
1946                         self.def_collector.db,
1947                         self.module_id,
1948                         &mut |map, module| map[module].scope.get_legacy_macro(name),
1949                     )
1950                 })
1951             },
1952             &mut |err| {
1953                 error.get_or_insert(err);
1954             },
1955         ) {
1956             Ok(Ok(macro_call_id)) => {
1957                 // Legacy macros need to be expanded immediately, so that any macros they produce
1958                 // are in scope.
1959                 self.def_collector.collect_macro_expansion(
1960                     self.module_id,
1961                     macro_call_id,
1962                     self.macro_depth + 1,
1963                 );
1964
1965                 if let Some(err) = error {
1966                     self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1967                         self.module_id,
1968                         MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
1969                         err.to_string(),
1970                     ));
1971                 }
1972
1973                 return;
1974             }
1975             Ok(Err(_)) => {
1976                 // Built-in macro failed eager expansion.
1977
1978                 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1979                     self.module_id,
1980                     MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
1981                     error.unwrap().to_string(),
1982                 ));
1983                 return;
1984             }
1985             Err(UnresolvedMacro { .. }) => (),
1986         }
1987
1988         // Case 2: resolve in module scope, expand during name resolution.
1989         self.def_collector.unresolved_macros.push(MacroDirective {
1990             module_id: self.module_id,
1991             depth: self.macro_depth + 1,
1992             kind: MacroDirectiveKind::FnLike { ast_id, expand_to: mac.expand_to },
1993         });
1994     }
1995
1996     fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
1997         let macros = self.def_collector.def_map[module_id].scope.collect_legacy_macros();
1998         for (name, macro_) in macros {
1999             self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
2000         }
2001     }
2002
2003     fn is_cfg_enabled(&self, cfg: &CfgExpr) -> bool {
2004         self.def_collector.cfg_options.check(cfg) != Some(false)
2005     }
2006
2007     fn emit_unconfigured_diagnostic(&mut self, item: ModItem, cfg: &CfgExpr) {
2008         let ast_id = item.ast_id(self.item_tree);
2009
2010         let ast_id = InFile::new(self.file_id(), ast_id);
2011         self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code(
2012             self.module_id,
2013             ast_id,
2014             cfg.clone(),
2015             self.def_collector.cfg_options.clone(),
2016         ));
2017     }
2018
2019     fn file_id(&self) -> HirFileId {
2020         self.tree_id.file_id()
2021     }
2022 }
2023
2024 #[cfg(test)]
2025 mod tests {
2026     use crate::{db::DefDatabase, test_db::TestDB};
2027     use base_db::{fixture::WithFixture, SourceDatabase};
2028
2029     use super::*;
2030
2031     fn do_collect_defs(db: &dyn DefDatabase, def_map: DefMap) -> DefMap {
2032         let mut collector = DefCollector {
2033             db,
2034             def_map,
2035             deps: FxHashMap::default(),
2036             glob_imports: FxHashMap::default(),
2037             unresolved_imports: Vec::new(),
2038             resolved_imports: Vec::new(),
2039             unresolved_macros: Vec::new(),
2040             mod_dirs: FxHashMap::default(),
2041             cfg_options: &CfgOptions::default(),
2042             proc_macros: Default::default(),
2043             exports_proc_macros: false,
2044             from_glob_import: Default::default(),
2045             skip_attrs: Default::default(),
2046             derive_helpers_in_scope: Default::default(),
2047             registered_attrs: Default::default(),
2048             registered_tools: Default::default(),
2049         };
2050         collector.seed_with_top_level();
2051         collector.collect();
2052         collector.def_map
2053     }
2054
2055     fn do_resolve(not_ra_fixture: &str) -> DefMap {
2056         let (db, file_id) = TestDB::with_single_file(not_ra_fixture);
2057         let krate = db.test_crate();
2058
2059         let edition = db.crate_graph()[krate].edition;
2060         let module_origin = ModuleOrigin::CrateRoot { definition: file_id };
2061         let def_map = DefMap::empty(krate, edition, module_origin);
2062         do_collect_defs(&db, def_map)
2063     }
2064
2065     #[test]
2066     fn test_macro_expand_will_stop_1() {
2067         do_resolve(
2068             r#"
2069 macro_rules! foo {
2070     ($($ty:ty)*) => { foo!($($ty)*); }
2071 }
2072 foo!(KABOOM);
2073 "#,
2074         );
2075         do_resolve(
2076             r#"
2077 macro_rules! foo {
2078     ($($ty:ty)*) => { foo!(() $($ty)*); }
2079 }
2080 foo!(KABOOM);
2081 "#,
2082         );
2083     }
2084
2085     #[ignore]
2086     #[test]
2087     fn test_macro_expand_will_stop_2() {
2088         // FIXME: this test does succeed, but takes quite a while: 90 seconds in
2089         // the release mode. That's why the argument is not an ra_fixture --
2090         // otherwise injection highlighting gets stuck.
2091         //
2092         // We need to find a way to fail this faster.
2093         do_resolve(
2094             r#"
2095 macro_rules! foo {
2096     ($($ty:ty)*) => { foo!($($ty)* $($ty)*); }
2097 }
2098 foo!(KABOOM);
2099 "#,
2100         );
2101     }
2102 }