]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_scope.rs
Handle attribute macros in `descend_into_macros`
[rust.git] / crates / hir_def / src / item_scope.rs
1 //! Describes items defined or visible (ie, imported) in a certain scope.
2 //! This is shared between modules and blocks.
3
4 use std::collections::hash_map::Entry;
5
6 use base_db::CrateId;
7 use hir_expand::{name::Name, AstId, MacroCallId, MacroDefKind};
8 use once_cell::sync::Lazy;
9 use rustc_hash::{FxHashMap, FxHashSet};
10 use stdx::format_to;
11 use syntax::ast;
12
13 use crate::{
14     db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ConstId, ImplId,
15     LocalModuleId, MacroDefId, ModuleDefId, ModuleId, TraitId,
16 };
17
18 #[derive(Copy, Clone)]
19 pub(crate) enum ImportType {
20     Glob,
21     Named,
22 }
23
24 #[derive(Debug, Default)]
25 pub struct PerNsGlobImports {
26     types: FxHashSet<(LocalModuleId, Name)>,
27     values: FxHashSet<(LocalModuleId, Name)>,
28     macros: FxHashSet<(LocalModuleId, Name)>,
29 }
30
31 #[derive(Debug, Default, PartialEq, Eq)]
32 pub struct ItemScope {
33     types: FxHashMap<Name, (ModuleDefId, Visibility)>,
34     values: FxHashMap<Name, (ModuleDefId, Visibility)>,
35     macros: FxHashMap<Name, (MacroDefId, Visibility)>,
36     unresolved: FxHashSet<Name>,
37
38     defs: Vec<ModuleDefId>,
39     impls: Vec<ImplId>,
40     unnamed_consts: Vec<ConstId>,
41     /// Traits imported via `use Trait as _;`.
42     unnamed_trait_imports: FxHashMap<TraitId, Visibility>,
43     /// Macros visible in current module in legacy textual scope
44     ///
45     /// For macros invoked by an unqualified identifier like `bar!()`, `legacy_macros` will be searched in first.
46     /// If it yields no result, then it turns to module scoped `macros`.
47     /// It macros with name qualified with a path like `crate::foo::bar!()`, `legacy_macros` will be skipped,
48     /// and only normal scoped `macros` will be searched in.
49     ///
50     /// Note that this automatically inherit macros defined textually before the definition of module itself.
51     ///
52     /// Module scoped macros will be inserted into `items` instead of here.
53     // FIXME: Macro shadowing in one module is not properly handled. Non-item place macros will
54     // be all resolved to the last one defined if shadowing happens.
55     legacy_macros: FxHashMap<Name, MacroDefId>,
56     attr_macros: FxHashMap<AstId<ast::Item>, MacroCallId>,
57 }
58
59 pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
60     BuiltinType::ALL
61         .iter()
62         .map(|(name, ty)| (name.clone(), PerNs::types(ty.clone().into(), Visibility::Public)))
63         .collect()
64 });
65
66 /// Shadow mode for builtin type which can be shadowed by module.
67 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
68 pub(crate) enum BuiltinShadowMode {
69     /// Prefer user-defined modules (or other types) over builtins.
70     Module,
71     /// Prefer builtins over user-defined modules (but not other types).
72     Other,
73 }
74
75 /// Legacy macros can only be accessed through special methods like `get_legacy_macros`.
76 /// Other methods will only resolve values, types and module scoped macros only.
77 impl ItemScope {
78     pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, PerNs)> + 'a {
79         // FIXME: shadowing
80         let keys: FxHashSet<_> = self
81             .types
82             .keys()
83             .chain(self.values.keys())
84             .chain(self.macros.keys())
85             .chain(self.unresolved.iter())
86             .collect();
87
88         keys.into_iter().map(move |name| (name, self.get(name)))
89     }
90
91     pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
92         self.defs.iter().copied()
93     }
94
95     pub fn impls(&self) -> impl Iterator<Item = ImplId> + ExactSizeIterator + '_ {
96         self.impls.iter().copied()
97     }
98
99     pub fn values(
100         &self,
101     ) -> impl Iterator<Item = (ModuleDefId, Visibility)> + ExactSizeIterator + '_ {
102         self.values.values().copied()
103     }
104
105     pub fn visibility_of(&self, def: ModuleDefId) -> Option<Visibility> {
106         self.name_of(ItemInNs::Types(def))
107             .or_else(|| self.name_of(ItemInNs::Values(def)))
108             .map(|(_, v)| v)
109     }
110
111     pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
112         self.unnamed_consts.iter().copied()
113     }
114
115     /// Iterate over all module scoped macros
116     pub(crate) fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
117         self.entries().filter_map(|(name, def)| def.take_macros().map(|macro_| (name, macro_)))
118     }
119
120     /// Iterate over all legacy textual scoped macros visible at the end of the module
121     pub(crate) fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
122         self.legacy_macros.iter().map(|(name, def)| (name, *def))
123     }
124
125     /// Get a name from current module scope, legacy macros are not included
126     pub(crate) fn get(&self, name: &Name) -> PerNs {
127         PerNs {
128             types: self.types.get(name).copied(),
129             values: self.values.get(name).copied(),
130             macros: self.macros.get(name).copied(),
131         }
132     }
133
134     pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility)> {
135         for (name, per_ns) in self.entries() {
136             if let Some(vis) = item.match_with(per_ns) {
137                 return Some((name, vis));
138             }
139         }
140         None
141     }
142
143     pub(crate) fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
144         self.types
145             .values()
146             .filter_map(|(def, _)| match def {
147                 ModuleDefId::TraitId(t) => Some(*t),
148                 _ => None,
149             })
150             .chain(self.unnamed_trait_imports.keys().copied())
151     }
152
153     pub(crate) fn define_def(&mut self, def: ModuleDefId) {
154         self.defs.push(def)
155     }
156
157     pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
158         self.legacy_macros.get(name).copied()
159     }
160
161     pub(crate) fn define_impl(&mut self, imp: ImplId) {
162         self.impls.push(imp)
163     }
164
165     pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
166         self.unnamed_consts.push(konst);
167     }
168
169     pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroDefId) {
170         self.legacy_macros.insert(name, mac);
171     }
172
173     pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
174         self.attr_macros.insert(item, call);
175     }
176
177     pub(crate) fn attr_macro_invocs(
178         &self,
179     ) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
180         self.attr_macros.iter().map(|(k, v)| (*k, *v))
181     }
182
183     pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
184         self.unnamed_trait_imports.get(&tr).copied()
185     }
186
187     pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
188         self.unnamed_trait_imports.insert(tr, vis);
189     }
190
191     pub(crate) fn push_res_with_import(
192         &mut self,
193         glob_imports: &mut PerNsGlobImports,
194         lookup: (LocalModuleId, Name),
195         def: PerNs,
196         def_import_type: ImportType,
197     ) -> bool {
198         let mut changed = false;
199
200         macro_rules! check_changed {
201             (
202                 $changed:ident,
203                 ( $this:ident / $def:ident ) . $field:ident,
204                 $glob_imports:ident [ $lookup:ident ],
205                 $def_import_type:ident
206             ) => {{
207                 let existing = $this.$field.entry($lookup.1.clone());
208                 match (existing, $def.$field) {
209                     (Entry::Vacant(entry), Some(_)) => {
210                         match $def_import_type {
211                             ImportType::Glob => {
212                                 $glob_imports.$field.insert($lookup.clone());
213                             }
214                             ImportType::Named => {
215                                 $glob_imports.$field.remove(&$lookup);
216                             }
217                         }
218
219                         if let Some(fld) = $def.$field {
220                             entry.insert(fld);
221                         }
222                         $changed = true;
223                     }
224                     (Entry::Occupied(mut entry), Some(_))
225                         if $glob_imports.$field.contains(&$lookup)
226                             && matches!($def_import_type, ImportType::Named) =>
227                     {
228                         cov_mark::hit!(import_shadowed);
229                         $glob_imports.$field.remove(&$lookup);
230                         if let Some(fld) = $def.$field {
231                             entry.insert(fld);
232                         }
233                         $changed = true;
234                     }
235                     _ => {}
236                 }
237             }};
238         }
239
240         check_changed!(changed, (self / def).types, glob_imports[lookup], def_import_type);
241         check_changed!(changed, (self / def).values, glob_imports[lookup], def_import_type);
242         check_changed!(changed, (self / def).macros, glob_imports[lookup], def_import_type);
243
244         if def.is_none() {
245             if self.unresolved.insert(lookup.1) {
246                 changed = true;
247             }
248         }
249
250         changed
251     }
252
253     pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Option<Name>, PerNs)> + 'a {
254         self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
255             self.unnamed_trait_imports
256                 .iter()
257                 .map(|(tr, vis)| (None, PerNs::types(ModuleDefId::TraitId(*tr), *vis))),
258         )
259     }
260
261     pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {
262         self.legacy_macros.clone()
263     }
264
265     /// Marks everything that is not a procedural macro as private to `this_module`.
266     pub(crate) fn censor_non_proc_macros(&mut self, this_module: ModuleId) {
267         self.types
268             .values_mut()
269             .chain(self.values.values_mut())
270             .map(|(_, v)| v)
271             .chain(self.unnamed_trait_imports.values_mut())
272             .for_each(|vis| *vis = Visibility::Module(this_module));
273
274         for (mac, vis) in self.macros.values_mut() {
275             if let MacroDefKind::ProcMacro(..) = mac.kind {
276                 // FIXME: Technically this is insufficient since reexports of proc macros are also
277                 // forbidden. Practically nobody does that.
278                 continue;
279             }
280
281             *vis = Visibility::Module(this_module);
282         }
283     }
284
285     pub(crate) fn dump(&self, buf: &mut String) {
286         let mut entries: Vec<_> = self.resolutions().collect();
287         entries.sort_by_key(|(name, _)| name.clone());
288
289         for (name, def) in entries {
290             format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
291
292             if def.types.is_some() {
293                 buf.push_str(" t");
294             }
295             if def.values.is_some() {
296                 buf.push_str(" v");
297             }
298             if def.macros.is_some() {
299                 buf.push_str(" m");
300             }
301             if def.is_none() {
302                 buf.push_str(" _");
303             }
304
305             buf.push('\n');
306         }
307     }
308
309     pub(crate) fn shrink_to_fit(&mut self) {
310         // Exhaustive match to require handling new fields.
311         let Self {
312             types,
313             values,
314             macros,
315             unresolved,
316             defs,
317             impls,
318             unnamed_consts,
319             unnamed_trait_imports,
320             legacy_macros,
321             attr_macros,
322         } = self;
323         types.shrink_to_fit();
324         values.shrink_to_fit();
325         macros.shrink_to_fit();
326         unresolved.shrink_to_fit();
327         defs.shrink_to_fit();
328         impls.shrink_to_fit();
329         unnamed_consts.shrink_to_fit();
330         unnamed_trait_imports.shrink_to_fit();
331         legacy_macros.shrink_to_fit();
332         attr_macros.shrink_to_fit();
333     }
334 }
335
336 impl PerNs {
337     pub(crate) fn from_def(def: ModuleDefId, v: Visibility, has_constructor: bool) -> PerNs {
338         match def {
339             ModuleDefId::ModuleId(_) => PerNs::types(def, v),
340             ModuleDefId::FunctionId(_) => PerNs::values(def, v),
341             ModuleDefId::AdtId(adt) => match adt {
342                 AdtId::UnionId(_) => PerNs::types(def, v),
343                 AdtId::EnumId(_) => PerNs::types(def, v),
344                 AdtId::StructId(_) => {
345                     if has_constructor {
346                         PerNs::both(def, def, v)
347                     } else {
348                         PerNs::types(def, v)
349                     }
350                 }
351             },
352             ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v),
353             ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => PerNs::values(def, v),
354             ModuleDefId::TraitId(_) => PerNs::types(def, v),
355             ModuleDefId::TypeAliasId(_) => PerNs::types(def, v),
356             ModuleDefId::BuiltinType(_) => PerNs::types(def, v),
357         }
358     }
359 }
360
361 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
362 pub enum ItemInNs {
363     Types(ModuleDefId),
364     Values(ModuleDefId),
365     Macros(MacroDefId),
366 }
367
368 impl ItemInNs {
369     fn match_with(self, per_ns: PerNs) -> Option<Visibility> {
370         match self {
371             ItemInNs::Types(def) => {
372                 per_ns.types.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
373             }
374             ItemInNs::Values(def) => {
375                 per_ns.values.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
376             }
377             ItemInNs::Macros(def) => {
378                 per_ns.macros.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
379             }
380         }
381     }
382
383     pub fn as_module_def_id(self) -> Option<ModuleDefId> {
384         match self {
385             ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
386             ItemInNs::Macros(_) => None,
387         }
388     }
389
390     /// Returns the crate defining this item (or `None` if `self` is built-in).
391     pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
392         match self {
393             ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
394             ItemInNs::Macros(id) => Some(id.krate),
395         }
396     }
397 }