]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_scope.rs
Merge #7777
[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 use test_utils::mark;
13
14 use crate::{
15     db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ImplId,
16     LocalModuleId, MacroDefId, ModuleDefId, ModuleId, TraitId,
17 };
18
19 #[derive(Copy, Clone)]
20 pub(crate) enum ImportType {
21     Glob,
22     Named,
23 }
24
25 #[derive(Debug, Default)]
26 pub struct PerNsGlobImports {
27     types: FxHashSet<(LocalModuleId, Name)>,
28     values: FxHashSet<(LocalModuleId, Name)>,
29     macros: FxHashSet<(LocalModuleId, Name)>,
30 }
31
32 #[derive(Debug, Default, PartialEq, Eq)]
33 pub struct ItemScope {
34     types: FxHashMap<Name, (ModuleDefId, Visibility)>,
35     values: FxHashMap<Name, (ModuleDefId, Visibility)>,
36     macros: FxHashMap<Name, (MacroDefId, Visibility)>,
37     unresolved: FxHashSet<Name>,
38
39     defs: Vec<ModuleDefId>,
40     impls: Vec<ImplId>,
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     /// Iterate over all module scoped macros
111     pub(crate) fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
112         self.entries().filter_map(|(name, def)| def.take_macros().map(|macro_| (name, macro_)))
113     }
114
115     /// Iterate over all legacy textual scoped macros visible at the end of the module
116     pub(crate) fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
117         self.legacy_macros.iter().map(|(name, def)| (name, *def))
118     }
119
120     /// Get a name from current module scope, legacy macros are not included
121     pub(crate) fn get(&self, name: &Name) -> PerNs {
122         PerNs {
123             types: self.types.get(name).copied(),
124             values: self.values.get(name).copied(),
125             macros: self.macros.get(name).copied(),
126         }
127     }
128
129     pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility)> {
130         for (name, per_ns) in self.entries() {
131             if let Some(vis) = item.match_with(per_ns) {
132                 return Some((name, vis));
133             }
134         }
135         None
136     }
137
138     pub(crate) fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
139         self.types
140             .values()
141             .filter_map(|(def, _)| match def {
142                 ModuleDefId::TraitId(t) => Some(*t),
143                 _ => None,
144             })
145             .chain(self.unnamed_trait_imports.keys().copied())
146     }
147
148     pub(crate) fn define_def(&mut self, def: ModuleDefId) {
149         self.defs.push(def)
150     }
151
152     pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
153         self.legacy_macros.get(name).copied()
154     }
155
156     pub(crate) fn define_impl(&mut self, imp: ImplId) {
157         self.impls.push(imp)
158     }
159
160     pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroDefId) {
161         self.legacy_macros.insert(name, mac);
162     }
163
164     pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
165         self.unnamed_trait_imports.get(&tr).copied()
166     }
167
168     pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
169         self.unnamed_trait_imports.insert(tr, vis);
170     }
171
172     pub(crate) fn push_res(&mut self, name: Name, def: PerNs) -> bool {
173         let mut changed = false;
174
175         if let Some(types) = def.types {
176             self.types.entry(name.clone()).or_insert_with(|| {
177                 changed = true;
178                 types
179             });
180         }
181         if let Some(values) = def.values {
182             self.values.entry(name.clone()).or_insert_with(|| {
183                 changed = true;
184                 values
185             });
186         }
187         if let Some(macros) = def.macros {
188             self.macros.entry(name.clone()).or_insert_with(|| {
189                 changed = true;
190                 macros
191             });
192         }
193
194         if def.is_none() {
195             if self.unresolved.insert(name) {
196                 changed = true;
197             }
198         }
199
200         changed
201     }
202
203     pub(crate) fn push_res_with_import(
204         &mut self,
205         glob_imports: &mut PerNsGlobImports,
206         lookup: (LocalModuleId, Name),
207         def: PerNs,
208         def_import_type: ImportType,
209     ) -> bool {
210         let mut changed = false;
211
212         macro_rules! check_changed {
213             (
214                 $changed:ident,
215                 ( $this:ident / $def:ident ) . $field:ident,
216                 $glob_imports:ident [ $lookup:ident ],
217                 $def_import_type:ident
218             ) => {{
219                 let existing = $this.$field.entry($lookup.1.clone());
220                 match (existing, $def.$field) {
221                     (Entry::Vacant(entry), Some(_)) => {
222                         match $def_import_type {
223                             ImportType::Glob => {
224                                 $glob_imports.$field.insert($lookup.clone());
225                             }
226                             ImportType::Named => {
227                                 $glob_imports.$field.remove(&$lookup);
228                             }
229                         }
230
231                         if let Some(fld) = $def.$field {
232                             entry.insert(fld);
233                         }
234                         $changed = true;
235                     }
236                     (Entry::Occupied(mut entry), Some(_))
237                         if $glob_imports.$field.contains(&$lookup)
238                             && matches!($def_import_type, ImportType::Named) =>
239                     {
240                         mark::hit!(import_shadowed);
241                         $glob_imports.$field.remove(&$lookup);
242                         if let Some(fld) = $def.$field {
243                             entry.insert(fld);
244                         }
245                         $changed = true;
246                     }
247                     _ => {}
248                 }
249             }};
250         }
251
252         check_changed!(changed, (self / def).types, glob_imports[lookup], def_import_type);
253         check_changed!(changed, (self / def).values, glob_imports[lookup], def_import_type);
254         check_changed!(changed, (self / def).macros, glob_imports[lookup], def_import_type);
255
256         if def.is_none() {
257             if self.unresolved.insert(lookup.1) {
258                 changed = true;
259             }
260         }
261
262         changed
263     }
264
265     pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Option<Name>, PerNs)> + 'a {
266         self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
267             self.unnamed_trait_imports
268                 .iter()
269                 .map(|(tr, vis)| (None, PerNs::types(ModuleDefId::TraitId(*tr), *vis))),
270         )
271     }
272
273     pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {
274         self.legacy_macros.clone()
275     }
276
277     /// Marks everything that is not a procedural macro as private to `this_module`.
278     pub(crate) fn censor_non_proc_macros(&mut self, this_module: ModuleId) {
279         self.types
280             .values_mut()
281             .chain(self.values.values_mut())
282             .map(|(_, v)| v)
283             .chain(self.unnamed_trait_imports.values_mut())
284             .for_each(|vis| *vis = Visibility::Module(this_module));
285
286         for (mac, vis) in self.macros.values_mut() {
287             if let MacroDefKind::ProcMacro(_) = mac.kind {
288                 // FIXME: Technically this is insufficient since reexports of proc macros are also
289                 // forbidden. Practically nobody does that.
290                 continue;
291             }
292
293             *vis = Visibility::Module(this_module);
294         }
295     }
296
297     pub(crate) fn dump(&self, buf: &mut String) {
298         let mut entries: Vec<_> = self.resolutions().collect();
299         entries.sort_by_key(|(name, _)| name.clone());
300
301         for (name, def) in entries {
302             format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
303
304             if def.types.is_some() {
305                 buf.push_str(" t");
306             }
307             if def.values.is_some() {
308                 buf.push_str(" v");
309             }
310             if def.macros.is_some() {
311                 buf.push_str(" m");
312             }
313             if def.is_none() {
314                 buf.push_str(" _");
315             }
316
317             buf.push('\n');
318         }
319     }
320 }
321
322 impl PerNs {
323     pub(crate) fn from_def(def: ModuleDefId, v: Visibility, has_constructor: bool) -> PerNs {
324         match def {
325             ModuleDefId::ModuleId(_) => PerNs::types(def, v),
326             ModuleDefId::FunctionId(_) => PerNs::values(def, v),
327             ModuleDefId::AdtId(adt) => match adt {
328                 AdtId::UnionId(_) => PerNs::types(def, v),
329                 AdtId::EnumId(_) => PerNs::types(def, v),
330                 AdtId::StructId(_) => {
331                     if has_constructor {
332                         PerNs::both(def, def, v)
333                     } else {
334                         PerNs::types(def, v)
335                     }
336                 }
337             },
338             ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v),
339             ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => PerNs::values(def, v),
340             ModuleDefId::TraitId(_) => PerNs::types(def, v),
341             ModuleDefId::TypeAliasId(_) => PerNs::types(def, v),
342             ModuleDefId::BuiltinType(_) => PerNs::types(def, v),
343         }
344     }
345 }
346
347 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
348 pub enum ItemInNs {
349     Types(ModuleDefId),
350     Values(ModuleDefId),
351     Macros(MacroDefId),
352 }
353
354 impl ItemInNs {
355     fn match_with(self, per_ns: PerNs) -> Option<Visibility> {
356         match self {
357             ItemInNs::Types(def) => {
358                 per_ns.types.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
359             }
360             ItemInNs::Values(def) => {
361                 per_ns.values.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
362             }
363             ItemInNs::Macros(def) => {
364                 per_ns.macros.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
365             }
366         }
367     }
368
369     pub fn as_module_def_id(self) -> Option<ModuleDefId> {
370         match self {
371             ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
372             ItemInNs::Macros(_) => None,
373         }
374     }
375
376     /// Returns the crate defining this item (or `None` if `self` is built-in).
377     pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
378         match self {
379             ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
380             ItemInNs::Macros(id) => Some(id.krate),
381         }
382     }
383 }