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