1use std::sync::LazyLock;
5
6use base_db::Crate;
7use hir_expand::{AstId, MacroCallId, attrs::AttrId, db::ExpandDatabase, name::Name};
8use indexmap::map::Entry;
9use itertools::Itertools;
10use la_arena::Idx;
11use rustc_hash::{FxHashMap, FxHashSet};
12use smallvec::{SmallVec, smallvec};
13use span::Edition;
14use stdx::format_to;
15use syntax::ast;
16use thin_vec::ThinVec;
17
18use crate::{
19 AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
20 LocalModuleId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
21 db::DefDatabase,
22 per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem},
23 visibility::Visibility,
24};
25
26#[derive(Debug, Default)]
27pub struct PerNsGlobImports {
28 types: FxHashSet<(LocalModuleId, Name)>,
29 values: FxHashSet<(LocalModuleId, Name)>,
30 macros: FxHashSet<(LocalModuleId, Name)>,
31}
32
33#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
34pub enum ImportOrExternCrate {
35 Glob(GlobId),
36 Import(ImportId),
37 ExternCrate(ExternCrateId),
38}
39
40impl From<ImportOrGlob> for ImportOrExternCrate {
41 fn from(value: ImportOrGlob) -> Self {
42 match value {
43 ImportOrGlob::Glob(it) => ImportOrExternCrate::Glob(it),
44 ImportOrGlob::Import(it) => ImportOrExternCrate::Import(it),
45 }
46 }
47}
48
49impl ImportOrExternCrate {
50 pub fn import_or_glob(self) -> Option<ImportOrGlob> {
51 match self {
52 ImportOrExternCrate::Import(it) => Some(ImportOrGlob::Import(it)),
53 ImportOrExternCrate::Glob(it) => Some(ImportOrGlob::Glob(it)),
54 _ => None,
55 }
56 }
57
58 pub fn import(self) -> Option<ImportId> {
59 match self {
60 ImportOrExternCrate::Import(it) => Some(it),
61 _ => None,
62 }
63 }
64
65 pub fn glob(self) -> Option<GlobId> {
66 match self {
67 ImportOrExternCrate::Glob(id) => Some(id),
68 _ => None,
69 }
70 }
71
72 pub fn use_(self) -> Option<UseId> {
73 match self {
74 ImportOrExternCrate::Glob(id) => Some(id.use_),
75 ImportOrExternCrate::Import(id) => Some(id.use_),
76 _ => None,
77 }
78 }
79}
80
81#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
82pub enum ImportOrGlob {
83 Glob(GlobId),
84 Import(ImportId),
85}
86
87impl ImportOrGlob {
88 pub fn into_import(self) -> Option<ImportId> {
89 match self {
90 ImportOrGlob::Import(it) => Some(it),
91 _ => None,
92 }
93 }
94}
95
96#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
97pub enum ImportOrDef {
98 Import(ImportId),
99 Glob(GlobId),
100 ExternCrate(ExternCrateId),
101 Def(ModuleDefId),
102}
103
104impl From<ImportOrExternCrate> for ImportOrDef {
105 fn from(value: ImportOrExternCrate) -> Self {
106 match value {
107 ImportOrExternCrate::Import(it) => ImportOrDef::Import(it),
108 ImportOrExternCrate::Glob(it) => ImportOrDef::Glob(it),
109 ImportOrExternCrate::ExternCrate(it) => ImportOrDef::ExternCrate(it),
110 }
111 }
112}
113
114impl From<ImportOrGlob> for ImportOrDef {
115 fn from(value: ImportOrGlob) -> Self {
116 match value {
117 ImportOrGlob::Import(it) => ImportOrDef::Import(it),
118 ImportOrGlob::Glob(it) => ImportOrDef::Glob(it),
119 }
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
124pub struct ImportId {
125 pub use_: UseId,
126 pub idx: Idx<ast::UseTree>,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
130pub struct GlobId {
131 pub use_: UseId,
132 pub idx: Idx<ast::UseTree>,
133}
134
135impl PerNsGlobImports {
136 pub(crate) fn contains_type(&self, module_id: LocalModuleId, name: Name) -> bool {
137 self.types.contains(&(module_id, name))
138 }
139 pub(crate) fn contains_value(&self, module_id: LocalModuleId, name: Name) -> bool {
140 self.values.contains(&(module_id, name))
141 }
142 pub(crate) fn contains_macro(&self, module_id: LocalModuleId, name: Name) -> bool {
143 self.macros.contains(&(module_id, name))
144 }
145}
146
147#[derive(Debug, Default, PartialEq, Eq)]
148pub struct ItemScope {
149 types: FxIndexMap<Name, TypesItem>,
153 values: FxIndexMap<Name, ValuesItem>,
154 macros: FxIndexMap<Name, MacrosItem>,
155 unresolved: FxHashSet<Name>,
156
157 declarations: ThinVec<ModuleDefId>,
160
161 impls: ThinVec<ImplId>,
162 extern_blocks: ThinVec<ExternBlockId>,
163 unnamed_consts: ThinVec<ConstId>,
164 unnamed_trait_imports: ThinVec<(TraitId, Item<()>)>,
166
167 use_imports_types: FxHashMap<ImportOrExternCrate, ImportOrDef>,
169 use_imports_values: FxHashMap<ImportOrGlob, ImportOrDef>,
170 use_imports_macros: FxHashMap<ImportOrExternCrate, ImportOrDef>,
171
172 use_decls: ThinVec<UseId>,
173 extern_crate_decls: ThinVec<ExternCrateId>,
174 legacy_macros: FxHashMap<Name, SmallVec<[MacroId; 2]>>,
187 attr_macros: FxHashMap<AstId<ast::Item>, MacroCallId>,
189 macro_invocations: FxHashMap<AstId<ast::MacroCall>, MacroCallId>,
191 derive_macros: FxHashMap<AstId<ast::Adt>, SmallVec<[DeriveMacroInvocation; 1]>>,
194}
195
196#[derive(Debug, PartialEq, Eq)]
197struct DeriveMacroInvocation {
198 attr_id: AttrId,
199 attr_call_id: MacroCallId,
201 derive_call_ids: SmallVec<[Option<MacroCallId>; 4]>,
202}
203
204pub(crate) static BUILTIN_SCOPE: LazyLock<FxIndexMap<Name, PerNs>> = LazyLock::new(|| {
205 BuiltinType::all_builtin_types()
206 .iter()
207 .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public, None)))
208 .collect()
209});
210
211#[derive(Debug, Copy, Clone, PartialEq, Eq)]
213pub(crate) enum BuiltinShadowMode {
214 Module,
216 Other,
218}
219
220impl ItemScope {
223 pub fn entries(&self) -> impl Iterator<Item = (&Name, PerNs)> + '_ {
224 self.types
226 .keys()
227 .chain(self.values.keys())
228 .chain(self.macros.keys())
229 .chain(self.unresolved.iter())
230 .sorted()
231 .dedup()
232 .map(move |name| (name, self.get(name)))
233 }
234
235 pub fn values(&self) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportOrGlob>)> + '_ {
236 self.values.iter().map(|(n, &i)| (n, i))
237 }
238
239 pub fn types(
240 &self,
241 ) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportOrExternCrate>)> + '_ {
242 self.types.iter().map(|(n, &i)| (n, i))
243 }
244
245 pub fn macros(&self) -> impl Iterator<Item = (&Name, Item<MacroId, ImportOrExternCrate>)> + '_ {
246 self.macros.iter().map(|(n, &i)| (n, i))
247 }
248
249 pub fn imports(&self) -> impl Iterator<Item = ImportId> + '_ {
250 self.use_imports_types
251 .keys()
252 .copied()
253 .chain(self.use_imports_macros.keys().copied())
254 .filter_map(ImportOrExternCrate::import_or_glob)
255 .chain(self.use_imports_values.keys().copied())
256 .filter_map(ImportOrGlob::into_import)
257 .sorted()
258 .dedup()
259 }
260
261 pub fn fully_resolve_import(&self, db: &dyn DefDatabase, mut import: ImportId) -> PerNs {
262 let mut res = PerNs::none();
263
264 let mut def_map;
265 let mut scope = self;
266 while let Some(&m) = scope.use_imports_macros.get(&ImportOrExternCrate::Import(import)) {
267 match m {
268 ImportOrDef::Import(i) => {
269 let module_id = i.use_.lookup(db).container;
270 def_map = module_id.def_map(db);
271 scope = &def_map[module_id.local_id].scope;
272 import = i;
273 }
274 ImportOrDef::Def(ModuleDefId::MacroId(def)) => {
275 res.macros = Some(Item { def, vis: Visibility::Public, import: None });
276 break;
277 }
278 _ => break,
279 }
280 }
281 let mut scope = self;
282 while let Some(&m) = scope.use_imports_types.get(&ImportOrExternCrate::Import(import)) {
283 match m {
284 ImportOrDef::Import(i) => {
285 let module_id = i.use_.lookup(db).container;
286 def_map = module_id.def_map(db);
287 scope = &def_map[module_id.local_id].scope;
288 import = i;
289 }
290 ImportOrDef::Def(def) => {
291 res.types = Some(Item { def, vis: Visibility::Public, import: None });
292 break;
293 }
294 _ => break,
295 }
296 }
297 let mut scope = self;
298 while let Some(&m) = scope.use_imports_values.get(&ImportOrGlob::Import(import)) {
299 match m {
300 ImportOrDef::Import(i) => {
301 let module_id = i.use_.lookup(db).container;
302 def_map = module_id.def_map(db);
303 scope = &def_map[module_id.local_id].scope;
304 import = i;
305 }
306 ImportOrDef::Def(def) => {
307 res.values = Some(Item { def, vis: Visibility::Public, import: None });
308 break;
309 }
310 _ => break,
311 }
312 }
313 res
314 }
315
316 pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
317 self.declarations.iter().copied()
318 }
319
320 pub fn extern_crate_decls(&self) -> impl ExactSizeIterator<Item = ExternCrateId> + '_ {
321 self.extern_crate_decls.iter().copied()
322 }
323
324 pub fn extern_blocks(&self) -> impl Iterator<Item = ExternBlockId> + '_ {
325 self.extern_blocks.iter().copied()
326 }
327
328 pub fn use_decls(&self) -> impl ExactSizeIterator<Item = UseId> + '_ {
329 self.use_decls.iter().copied()
330 }
331
332 pub fn impls(&self) -> impl ExactSizeIterator<Item = ImplId> + '_ {
333 self.impls.iter().copied()
334 }
335
336 pub fn all_macro_calls(&self) -> impl Iterator<Item = MacroCallId> + '_ {
337 self.macro_invocations.values().copied().chain(self.attr_macros.values().copied()).chain(
338 self.derive_macros.values().flat_map(|it| {
339 it.iter().flat_map(|it| it.derive_call_ids.iter().copied().flatten())
340 }),
341 )
342 }
343
344 pub(crate) fn modules_in_scope(&self) -> impl Iterator<Item = (ModuleId, Visibility)> + '_ {
345 self.types.values().filter_map(|ns| match ns.def {
346 ModuleDefId::ModuleId(module) => Some((module, ns.vis)),
347 _ => None,
348 })
349 }
350
351 pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
352 self.unnamed_consts.iter().copied()
353 }
354
355 pub fn legacy_macros(&self) -> impl Iterator<Item = (&Name, &[MacroId])> + '_ {
357 self.legacy_macros.iter().map(|(name, def)| (name, &**def))
358 }
359
360 pub fn get(&self, name: &Name) -> PerNs {
362 PerNs {
363 types: self.types.get(name).copied(),
364 values: self.values.get(name).copied(),
365 macros: self.macros.get(name).copied(),
366 }
367 }
368
369 pub(crate) fn type_(&self, name: &Name) -> Option<(ModuleDefId, Visibility)> {
370 self.types.get(name).map(|item| (item.def, item.vis))
371 }
372
373 pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility, bool)> {
375 match item {
376 ItemInNs::Macros(def) => self.macros.iter().find_map(|(name, other_def)| {
377 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
378 }),
379 ItemInNs::Types(def) => self.types.iter().find_map(|(name, other_def)| {
380 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
381 }),
382 ItemInNs::Values(def) => self.values.iter().find_map(|(name, other_def)| {
383 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
384 }),
385 }
386 }
387
388 pub(crate) fn names_of<T>(
390 &self,
391 item: ItemInNs,
392 mut cb: impl FnMut(&Name, Visibility, bool) -> Option<T>,
393 ) -> Option<T> {
394 match item {
395 ItemInNs::Macros(def) => self
396 .macros
397 .iter()
398 .filter_map(|(name, other_def)| {
399 (other_def.def == def).then_some((
400 name,
401 other_def.vis,
402 other_def.import.is_none(),
403 ))
404 })
405 .find_map(|(a, b, c)| cb(a, b, c)),
406 ItemInNs::Types(def) => self
407 .types
408 .iter()
409 .filter_map(|(name, other_def)| {
410 (other_def.def == def).then_some((
411 name,
412 other_def.vis,
413 other_def.import.is_none(),
414 ))
415 })
416 .find_map(|(a, b, c)| cb(a, b, c)),
417 ItemInNs::Values(def) => self
418 .values
419 .iter()
420 .filter_map(|(name, other_def)| {
421 (other_def.def == def).then_some((
422 name,
423 other_def.vis,
424 other_def.import.is_none(),
425 ))
426 })
427 .find_map(|(a, b, c)| cb(a, b, c)),
428 }
429 }
430
431 pub(crate) fn traits(&self) -> impl Iterator<Item = TraitId> + '_ {
432 self.types
433 .values()
434 .filter_map(|def| match def.def {
435 ModuleDefId::TraitId(t) => Some(t),
436 _ => None,
437 })
438 .chain(self.unnamed_trait_imports.iter().map(|&(t, _)| t))
439 }
440
441 pub(crate) fn resolutions(&self) -> impl Iterator<Item = (Option<Name>, PerNs)> + '_ {
442 self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
443 self.unnamed_trait_imports.iter().map(|(tr, trait_)| {
444 (
445 None,
446 PerNs::types(
447 ModuleDefId::TraitId(*tr),
448 trait_.vis,
449 trait_.import.map(ImportOrExternCrate::Import),
450 ),
451 )
452 }),
453 )
454 }
455
456 pub fn macro_invoc(&self, call: AstId<ast::MacroCall>) -> Option<MacroCallId> {
457 self.macro_invocations.get(&call).copied()
458 }
459
460 pub fn iter_macro_invoc(&self) -> impl Iterator<Item = (&AstId<ast::MacroCall>, &MacroCallId)> {
461 self.macro_invocations.iter()
462 }
463}
464
465impl ItemScope {
466 pub(crate) fn declare(&mut self, def: ModuleDefId) {
467 self.declarations.push(def)
468 }
469
470 pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<&[MacroId]> {
471 self.legacy_macros.get(name).map(|it| &**it)
472 }
473
474 pub(crate) fn define_impl(&mut self, imp: ImplId) {
475 self.impls.push(imp);
476 }
477
478 pub(crate) fn define_extern_block(&mut self, extern_block: ExternBlockId) {
479 self.extern_blocks.push(extern_block);
480 }
481
482 pub(crate) fn define_extern_crate_decl(&mut self, extern_crate: ExternCrateId) {
483 self.extern_crate_decls.push(extern_crate);
484 }
485
486 pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
487 self.unnamed_consts.push(konst);
488 }
489
490 pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroId) {
491 self.legacy_macros.entry(name).or_default().push(mac);
492 }
493
494 pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
495 self.attr_macros.insert(item, call);
496 }
497
498 pub(crate) fn add_macro_invoc(&mut self, call: AstId<ast::MacroCall>, call_id: MacroCallId) {
499 self.macro_invocations.insert(call, call_id);
500 }
501
502 pub fn attr_macro_invocs(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
503 self.attr_macros.iter().map(|(k, v)| (*k, *v))
504 }
505
506 pub(crate) fn set_derive_macro_invoc(
507 &mut self,
508 adt: AstId<ast::Adt>,
509 call: MacroCallId,
510 id: AttrId,
511 idx: usize,
512 ) {
513 if let Some(derives) = self.derive_macros.get_mut(&adt)
514 && let Some(DeriveMacroInvocation { derive_call_ids, .. }) =
515 derives.iter_mut().find(|&&mut DeriveMacroInvocation { attr_id, .. }| id == attr_id)
516 {
517 derive_call_ids[idx] = Some(call);
518 }
519 }
520
521 pub(crate) fn init_derive_attribute(
525 &mut self,
526 adt: AstId<ast::Adt>,
527 attr_id: AttrId,
528 attr_call_id: MacroCallId,
529 len: usize,
530 ) {
531 self.derive_macros.entry(adt).or_default().push(DeriveMacroInvocation {
532 attr_id,
533 attr_call_id,
534 derive_call_ids: smallvec![None; len],
535 });
536 }
537
538 pub fn derive_macro_invocs(
539 &self,
540 ) -> impl Iterator<
541 Item = (
542 AstId<ast::Adt>,
543 impl Iterator<Item = (AttrId, MacroCallId, &[Option<MacroCallId>])>,
544 ),
545 > + '_ {
546 self.derive_macros.iter().map(|(k, v)| {
547 (
548 *k,
549 v.iter().map(|DeriveMacroInvocation { attr_id, attr_call_id, derive_call_ids }| {
550 (*attr_id, *attr_call_id, &**derive_call_ids)
551 }),
552 )
553 })
554 }
555
556 pub fn derive_macro_invoc(
557 &self,
558 ast_id: AstId<ast::Adt>,
559 attr_id: AttrId,
560 ) -> Option<MacroCallId> {
561 Some(self.derive_macros.get(&ast_id)?.iter().find(|it| it.attr_id == attr_id)?.attr_call_id)
562 }
563
564 pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
566 self.unnamed_trait_imports.iter().find(|&&(t, _)| t == tr).map(|(_, trait_)| trait_.vis)
567 }
568
569 pub(crate) fn push_unnamed_trait(
570 &mut self,
571 tr: TraitId,
572 vis: Visibility,
573 import: Option<ImportId>,
574 ) {
575 self.unnamed_trait_imports.push((tr, Item { def: (), vis, import }));
576 }
577
578 pub(crate) fn push_res_with_import(
579 &mut self,
580 glob_imports: &mut PerNsGlobImports,
581 lookup: (LocalModuleId, Name),
582 def: PerNs,
583 import: Option<ImportOrExternCrate>,
584 ) -> bool {
585 let mut changed = false;
586
587 if let Some(mut fld) = def.types {
590 let existing = self.types.entry(lookup.1.clone());
591 match existing {
592 Entry::Vacant(entry) => {
593 match import {
594 Some(ImportOrExternCrate::Glob(_)) => {
595 glob_imports.types.insert(lookup.clone());
596 }
597 _ => _ = glob_imports.types.remove(&lookup),
598 }
599 let prev = std::mem::replace(&mut fld.import, import);
600 if let Some(import) = import {
601 self.use_imports_types
602 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
603 }
604 entry.insert(fld);
605 changed = true;
606 }
607 Entry::Occupied(mut entry) => {
608 match import {
609 Some(ImportOrExternCrate::Glob(..)) => {
610 }
616 _ => {
617 if glob_imports.types.remove(&lookup) {
618 let prev = std::mem::replace(&mut fld.import, import);
619 if let Some(import) = import {
620 self.use_imports_types.insert(
621 import,
622 prev.map_or(ImportOrDef::Def(fld.def), Into::into),
623 );
624 }
625 cov_mark::hit!(import_shadowed);
626 entry.insert(fld);
627 changed = true;
628 }
629 }
630 }
631 }
632 }
633 }
634
635 if let Some(mut fld) = def.values {
636 let existing = self.values.entry(lookup.1.clone());
637 match existing {
638 Entry::Vacant(entry) => {
639 match import {
640 Some(ImportOrExternCrate::Glob(_)) => {
641 glob_imports.values.insert(lookup.clone());
642 }
643 _ => _ = glob_imports.values.remove(&lookup),
644 }
645 let import = import.and_then(ImportOrExternCrate::import_or_glob);
646 let prev = std::mem::replace(&mut fld.import, import);
647 if let Some(import) = import {
648 self.use_imports_values
649 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
650 }
651 entry.insert(fld);
652 changed = true;
653 }
654 Entry::Occupied(mut entry)
655 if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
656 {
657 if glob_imports.values.remove(&lookup) {
658 cov_mark::hit!(import_shadowed);
659
660 let import = import.and_then(ImportOrExternCrate::import_or_glob);
661 let prev = std::mem::replace(&mut fld.import, import);
662 if let Some(import) = import {
663 self.use_imports_values
664 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
665 }
666 entry.insert(fld);
667 changed = true;
668 }
669 }
670 _ => {}
671 }
672 }
673
674 if let Some(mut fld) = def.macros {
675 let existing = self.macros.entry(lookup.1.clone());
676 match existing {
677 Entry::Vacant(entry) => {
678 match import {
679 Some(ImportOrExternCrate::Glob(_)) => {
680 glob_imports.macros.insert(lookup.clone());
681 }
682 _ => _ = glob_imports.macros.remove(&lookup),
683 }
684 let prev = std::mem::replace(&mut fld.import, import);
685 if let Some(import) = import {
686 self.use_imports_macros.insert(
687 import,
688 prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
689 );
690 }
691 entry.insert(fld);
692 changed = true;
693 }
694 Entry::Occupied(mut entry)
695 if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
696 {
697 if glob_imports.macros.remove(&lookup) {
698 cov_mark::hit!(import_shadowed);
699 let prev = std::mem::replace(&mut fld.import, import);
700 if let Some(import) = import {
701 self.use_imports_macros.insert(
702 import,
703 prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
704 );
705 }
706 entry.insert(fld);
707 changed = true;
708 }
709 }
710 _ => {}
711 }
712 }
713
714 if def.is_none() && self.unresolved.insert(lookup.1) {
715 changed = true;
716 }
717
718 changed
719 }
720
721 pub(crate) fn censor_non_proc_macros(&mut self, krate: Crate) {
723 self.types
724 .values_mut()
725 .map(|def| &mut def.vis)
726 .chain(self.values.values_mut().map(|def| &mut def.vis))
727 .chain(self.unnamed_trait_imports.iter_mut().map(|(_, def)| &mut def.vis))
728 .for_each(|vis| *vis = Visibility::PubCrate(krate));
729
730 for mac in self.macros.values_mut() {
731 if matches!(mac.def, MacroId::ProcMacroId(_) if mac.import.is_none()) {
732 continue;
733 }
734 mac.vis = Visibility::PubCrate(krate)
735 }
736 }
737
738 pub(crate) fn dump(&self, db: &dyn ExpandDatabase, buf: &mut String) {
739 let mut entries: Vec<_> = self.resolutions().collect();
740 entries.sort_by_key(|(name, _)| name.clone());
741
742 for (name, def) in entries {
743 format_to!(
744 buf,
745 "{}:",
746 name.map_or("_".to_owned(), |name| name.display(db, Edition::LATEST).to_string())
747 );
748
749 if let Some(Item { import, .. }) = def.types {
750 buf.push_str(" t");
751 match import {
752 Some(ImportOrExternCrate::Import(_)) => buf.push('i'),
753 Some(ImportOrExternCrate::Glob(_)) => buf.push('g'),
754 Some(ImportOrExternCrate::ExternCrate(_)) => buf.push('e'),
755 None => (),
756 }
757 }
758 if let Some(Item { import, .. }) = def.values {
759 buf.push_str(" v");
760 match import {
761 Some(ImportOrGlob::Import(_)) => buf.push('i'),
762 Some(ImportOrGlob::Glob(_)) => buf.push('g'),
763 None => (),
764 }
765 }
766 if let Some(Item { import, .. }) = def.macros {
767 buf.push_str(" m");
768 match import {
769 Some(ImportOrExternCrate::Import(_)) => buf.push('i'),
770 Some(ImportOrExternCrate::Glob(_)) => buf.push('g'),
771 Some(ImportOrExternCrate::ExternCrate(_)) => buf.push('e'),
772 None => (),
773 }
774 }
775 if def.is_none() {
776 buf.push_str(" _");
777 }
778
779 buf.push('\n');
780 }
781 }
782
783 pub(crate) fn shrink_to_fit(&mut self) {
784 let Self {
786 types,
787 values,
788 macros,
789 unresolved,
790 declarations,
791 impls,
792 unnamed_consts,
793 unnamed_trait_imports,
794 legacy_macros,
795 attr_macros,
796 derive_macros,
797 extern_crate_decls,
798 use_decls,
799 use_imports_values,
800 use_imports_types,
801 use_imports_macros,
802 macro_invocations,
803 extern_blocks,
804 } = self;
805 extern_blocks.shrink_to_fit();
806 types.shrink_to_fit();
807 values.shrink_to_fit();
808 macros.shrink_to_fit();
809 use_imports_types.shrink_to_fit();
810 use_imports_values.shrink_to_fit();
811 use_imports_macros.shrink_to_fit();
812 unresolved.shrink_to_fit();
813 declarations.shrink_to_fit();
814 impls.shrink_to_fit();
815 unnamed_consts.shrink_to_fit();
816 unnamed_trait_imports.shrink_to_fit();
817 legacy_macros.shrink_to_fit();
818 attr_macros.shrink_to_fit();
819 derive_macros.shrink_to_fit();
820 extern_crate_decls.shrink_to_fit();
821 use_decls.shrink_to_fit();
822 macro_invocations.shrink_to_fit();
823 }
824}
825
826impl ItemScope {
828 pub(crate) fn update_visibility_types(&mut self, name: &Name, vis: Visibility) {
829 let res =
830 self.types.get_mut(name).expect("tried to update visibility of non-existent type");
831 res.vis = vis;
832 }
833
834 pub(crate) fn update_visibility_values(&mut self, name: &Name, vis: Visibility) {
835 let res =
836 self.values.get_mut(name).expect("tried to update visibility of non-existent value");
837 res.vis = vis;
838 }
839
840 pub(crate) fn update_visibility_macros(&mut self, name: &Name, vis: Visibility) {
841 let res =
842 self.macros.get_mut(name).expect("tried to update visibility of non-existent macro");
843 res.vis = vis;
844 }
845}
846
847impl PerNs {
848 pub(crate) fn from_def(
849 def: ModuleDefId,
850 v: Visibility,
851 has_constructor: bool,
852 import: Option<ImportOrExternCrate>,
853 ) -> PerNs {
854 match def {
855 ModuleDefId::ModuleId(_) => PerNs::types(def, v, import),
856 ModuleDefId::FunctionId(_) => {
857 PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
858 }
859 ModuleDefId::AdtId(adt) => match adt {
860 AdtId::UnionId(_) => PerNs::types(def, v, import),
861 AdtId::EnumId(_) => PerNs::types(def, v, import),
862 AdtId::StructId(_) => {
863 if has_constructor {
864 PerNs::both(def, def, v, import)
865 } else {
866 PerNs::types(def, v, import)
867 }
868 }
869 },
870 ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v, import),
871 ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => {
872 PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
873 }
874 ModuleDefId::TraitId(_) => PerNs::types(def, v, import),
875 ModuleDefId::TypeAliasId(_) => PerNs::types(def, v, import),
876 ModuleDefId::BuiltinType(_) => PerNs::types(def, v, import),
877 ModuleDefId::MacroId(mac) => PerNs::macros(mac, v, import),
878 }
879 }
880}
881
882#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
883pub enum ItemInNs {
884 Types(ModuleDefId),
885 Values(ModuleDefId),
886 Macros(MacroId),
887}
888
889impl ItemInNs {
890 pub fn as_module_def_id(self) -> Option<ModuleDefId> {
891 match self {
892 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
893 ItemInNs::Macros(_) => None,
894 }
895 }
896
897 pub fn krate(&self, db: &dyn DefDatabase) -> Option<Crate> {
899 match self {
900 ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db).map(|m| m.krate),
901 ItemInNs::Macros(id) => Some(id.module(db).krate),
902 }
903 }
904
905 pub fn module(&self, db: &dyn DefDatabase) -> Option<ModuleId> {
906 match self {
907 ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db),
908 ItemInNs::Macros(id) => Some(id.module(db)),
909 }
910 }
911}