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