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