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