1use std::sync::Arc;
9
10use rustc_ast::visit::{self, AssocCtxt, Visitor, WalkItemKind};
11use rustc_ast::{
12 self as ast, AssocItem, AssocItemKind, Block, ConstItem, DUMMY_NODE_ID, Delegation,
13 DelegationSource, Fn, ForeignItem, ForeignItemKind, Inline, Item, ItemKind, NodeId, StaticItem,
14 StmtKind, TraitAlias, TyAlias,
15};
16use rustc_attr_ir::{Attribute, AttributeKind, MacroUseArgs};
17use rustc_attr_parsing::AttributeParser;
18use rustc_data_structures::fx::FxIndexMap;
19use rustc_data_structures::sync::WriteGuard;
20use rustc_expand::base::{ResolverExpand, SyntaxExtension, SyntaxExtensionKind};
21use rustc_hir::def::{self, *};
22use rustc_hir::def_id::{DefId, LocalDefId};
23use rustc_index::bit_set::DenseBitSet;
24use rustc_metadata::creader::LoadedMacro;
25use rustc_middle::middle::resolve::{ModChild, PartialRes, Reexport};
26use rustc_middle::ty::{TyCtxtFeed, Visibility};
27use rustc_span::def_id::{CRATE_MOD_ID, ModId};
28use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind};
29use rustc_span::{Ident, Span, Symbol, bug, kw, span_bug, sym};
30use thin_vec::ThinVec;
31use tracing::debug;
32
33use crate::Namespace::{MacroNS, TypeNS, ValueNS};
34use crate::def_collector::DefCollector;
35use crate::diagnostics::impls::{OnUnknownData, StructCtor};
36use crate::imports::{ImportData, ImportKind, NameResolution, NameResolutionRef};
37use crate::macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
38use crate::ref_mut::CmCell;
39use crate::{
40 BindingKey, Decl, DeclData, DeclKind, DelayedVisResolutionError, ExternModule,
41 ExternPreludeEntry, Finalize, IdentKey, LocalModule, Module, ModuleKind, ModuleOrUniformRoot,
42 ParentScope, PathResult, Res, ResolutionTable, Resolver, Segment, Used, VisResolutionError,
43 diagnostics,
44};
45
46impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
47 pub(crate) fn plant_decl_into_local_module(
50 &mut self,
51 ident: IdentKey,
52 orig_ident_span: Span,
53 ns: Namespace,
54 decl: Decl<'ra>,
55 ) {
56 if let Err(old_decl) =
57 self.try_plant_decl_into_local_module(ident, orig_ident_span, ns, decl)
58 {
59 self.report_conflict(ident, ns, old_decl, decl);
60 }
61 }
62
63 fn define_local(
65 &mut self,
66 parent: LocalModule<'ra>,
67 orig_ident: Ident,
68 ns: Namespace,
69 res: Res,
70 vis: Visibility,
71 span: Span,
72 expn_id: LocalExpnId,
73 ) {
74 let decl =
75 self.arenas.new_def_decl(res, vis.to_mod_id(), span, expn_id, Some(parent.to_module()));
76 let ident = IdentKey::new(orig_ident);
77 self.plant_decl_into_local_module(ident, orig_ident.span, ns, decl);
78 }
79
80 pub(crate) fn get_nearest_non_block_module(&self, mut def_id: DefId) -> Module<'ra> {
97 loop {
98 match self.get_module(def_id) {
99 Some(module) => return module,
100 None => def_id = self.tcx.parent(def_id),
101 }
102 }
103 }
104
105 pub(crate) fn expect_module(&self, def_id: DefId) -> Module<'ra> {
106 self.get_module(def_id).expect("argument `DefId` is not a module")
107 }
108
109 pub(crate) fn get_module(&self, def_id: DefId) -> Option<Module<'ra>> {
113 match def_id.as_local() {
114 Some(local_def_id) => self.local_module_map.get(&local_def_id).map(|m| m.to_module()),
115 None => {
116 if let module @ Some(..) = self.extern_module_map.borrow().get(&def_id) {
117 return module.map(|m| m.to_module());
118 }
119 let mut lock = self.extern_module_map.borrow_mut();
126 self.get_extern_module_with_lock(def_id, &mut lock).map(ExternModule::to_module)
129 }
130 }
131 }
132
133 fn get_extern_module_with_lock(
134 &self,
135 def_id: DefId,
136 map_lock: &mut WriteGuard<'_, FxIndexMap<DefId, ExternModule<'ra>>>,
137 ) -> Option<ExternModule<'ra>> {
138 if let module @ Some(..) = map_lock.get(&def_id) {
139 return module.copied();
140 }
141 let def_kind = self.cstore().def_kind_untracked(def_id);
143 if def_kind.is_module_like() {
144 let parent = self.tcx.opt_parent(def_id).map(|mut parent_id| {
145 loop {
146 match self.get_extern_module_with_lock(parent_id, map_lock) {
147 Some(module) => break module,
148 None => parent_id = self.tcx.parent(parent_id),
149 }
150 }
151 });
152 let expn_id = self.cstore().expn_that_defined_untracked(self.tcx, def_id);
155 let module = ExternModule::new(
156 parent,
157 ModuleKind::Def(def_kind, def_id, DUMMY_NODE_ID, Some(self.tcx.item_name(def_id))),
158 self.tcx.visibility(def_id),
159 expn_id,
160 self.def_span(def_id),
161 parent.is_some_and(|module| module.no_implicit_prelude),
163 self.arenas,
164 );
165 map_lock.insert(def_id, module);
166 return Some(module);
167 }
168
169 None
170 }
171
172 pub(crate) fn expn_def_scope(&self, expn_id: ExpnId) -> Module<'ra> {
173 match expn_id.expn_data().macro_def_id {
174 Some(def_id) => self.macro_def_scope(def_id),
175 None => expn_id
176 .as_local()
177 .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied())
178 .unwrap_or(self.graph_root)
179 .to_module(),
180 }
181 }
182
183 pub(crate) fn macro_def_scope(&self, def_id: DefId) -> Module<'ra> {
184 if let Some(id) = def_id.as_local() {
185 self.local_macro_def_scopes[&id].to_module()
186 } else {
187 self.get_nearest_non_block_module(def_id)
188 }
189 }
190
191 pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra Arc<SyntaxExtension>> {
193 match res {
194 Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
195 Res::NonMacroAttr(_) => Some(self.non_macro_attr),
196 _ => None,
197 }
198 }
199
200 pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra Arc<SyntaxExtension> {
201 match def_id.as_local() {
203 Some(local_def_id) => self.local_macro_map[&local_def_id],
204 None => self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
205 let loaded_macro = self.cstore().load_macro_untracked(self.tcx, def_id);
206 let ext = match loaded_macro {
207 LoadedMacro::MacroDef { def, ident, attrs, span, edition } => {
208 self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition)
209 }
210 LoadedMacro::ProcMacro(ext) => ext,
211 };
212
213 self.arenas.alloc_macro(ext)
214 }),
215 }
216 }
217
218 pub(crate) fn register_macros_for_all_crates(&mut self) {
221 if !self.all_crate_macros_already_registered {
222 for def_id in self.cstore().all_proc_macro_def_ids(self.tcx) {
223 self.get_macro_by_def_id(def_id);
224 }
225 self.all_crate_macros_already_registered = true;
226 }
227 }
228
229 pub(crate) fn try_resolve_visibility(
230 &mut self,
231 parent_scope: &ParentScope<'ra>,
232 vis: &ast::Visibility,
233 finalize: bool,
234 ) -> Result<Visibility, VisResolutionError> {
235 match vis.kind {
236 ast::VisibilityKind::Public => Ok(Visibility::Public),
237 ast::VisibilityKind::Inherited => {
238 Ok(match parent_scope.module.expect_local().kind {
239 ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _, _) => {
243 self.tcx.visibility(def_id).expect_local()
244 }
245 _ => Visibility::Restricted(
247 parent_scope.module.nearest_parent_mod().expect_local(),
248 ),
249 })
250 }
251 ast::VisibilityKind::Restricted { ref path, id, .. } => {
252 let ident = path.segments.get(0).expect("empty path in visibility").ident;
257 let crate_root = if ident.is_path_segment_keyword() {
258 None
259 } else if ident.span.is_rust_2015() {
260 Some(Segment::from_ident(Ident::new(
261 kw::PathRoot,
262 path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
263 )))
264 } else {
265 return Err(VisResolutionError::Relative2018(
266 ident.span,
267 path.as_ref().clone(),
268 ));
269 };
270 let segments = crate_root
271 .into_iter()
272 .chain(path.segments.iter().map(|seg| seg.into()))
273 .collect::<Vec<_>>();
274 let expected_found_error = |res| {
275 Err(VisResolutionError::ExpectedFound(
276 path.span,
277 Segment::names_to_string(&segments),
278 res,
279 ))
280 };
281 match self.cm_mut().resolve_path(
282 &segments,
283 None,
284 parent_scope,
285 finalize.then(|| Finalize::new(id, path.span)),
286 None,
287 None,
288 ) {
289 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
290 let res = module.res().expect("visibility resolved to unnamed block");
291 if module.is_normal() {
292 match res {
293 Res::Err => {
294 if finalize {
295 self.record_partial_res(id, PartialRes::new(res));
296 }
297 Ok(Visibility::Public)
298 }
299 _ => {
300 let vis =
301 Visibility::Restricted(ModId::new_unchecked(res.def_id()));
302 if self.is_accessible_from(vis, parent_scope.module) {
303 if finalize {
304 self.record_partial_res(id, PartialRes::new(res));
305 }
306 Ok(vis.expect_local())
307 } else {
308 Err(VisResolutionError::AncestorOnly(path.span))
309 }
310 }
311 }
312 } else {
313 expected_found_error(res)
314 }
315 }
316 PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
317 PathResult::NonModule(partial_res) => {
318 expected_found_error(partial_res.expect_full_res())
319 }
320 PathResult::Failed { label, suggestion, help, message, segment, .. } => {
321 Err(VisResolutionError::FailedToResolve {
322 span: segment.span,
323 segment: segment.name,
324 label,
325 suggestion,
326 help,
327 message,
328 })
329 }
330 PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
331 }
332 }
333 }
334 }
335
336 pub(crate) fn build_reduced_graph_external(
337 &self,
338 module: ExternModule<'ra>,
339 ) -> ResolutionTable<'ra> {
340 let mut resolutions = FxIndexMap::default();
341 let def_id = module.def_id();
342 let children = self.tcx.module_children(def_id);
343 for (i, child) in children.iter().enumerate() {
344 self.build_reduced_graph_for_external_crate_res(
345 child,
346 module,
347 i,
348 None,
349 &mut resolutions,
350 )
351 }
352 for (i, child) in
353 self.cstore().ambig_module_children_untracked(self.tcx, def_id).enumerate()
354 {
355 self.build_reduced_graph_for_external_crate_res(
356 &child.main,
357 module,
358 children.len() + i,
359 Some(&child.second),
360 &mut resolutions,
361 )
362 }
363 resolutions
364 }
365
366 fn build_reduced_graph_for_external_crate_res(
368 &self,
369 child: &ModChild,
370 parent: ExternModule<'ra>,
371 child_index: usize,
372 ambig_child: Option<&ModChild>,
373 resolutions: &mut FxIndexMap<BindingKey, NameResolutionRef<'ra>>,
374 ) {
375 let child_span = |this: &Self, reexport_chain: &[Reexport], res: def::Res<_>| {
376 this.def_span(
377 reexport_chain
378 .first()
379 .and_then(|reexport| reexport.id())
380 .unwrap_or_else(|| res.def_id()),
381 )
382 };
383 let ModChild { ident: orig_ident, res, vis, ref reexport_chain } = *child;
384 let ident = IdentKey::new(orig_ident);
385 let span = child_span(self, reexport_chain, res);
386 let res = res.expect_non_local();
387 let expansion = LocalExpnId::ROOT;
388 let ambig = ambig_child.map(|ambig_child| {
389 let ModChild { ident: _, res, vis, ref reexport_chain } = *ambig_child;
390 let span = child_span(self, reexport_chain, res);
391 let res = res.expect_non_local();
392 (self.arenas.new_def_decl(res, vis, span, expansion, Some(parent.to_module())), true)
394 });
395
396 let mut define_extern = |ns| {
398 let orig_ident_span = orig_ident.span;
399 let reexport_chain: &[Reexport] = if !reexport_chain.is_empty() {
400 self.arenas.dropless.alloc_slice(reexport_chain)
401 } else {
402 &[]
403 };
404 let decl = self.arenas.alloc_decl(DeclData {
405 kind: DeclKind::Def(res, reexport_chain),
406 ambiguity: CmCell::new(ambig),
407 initial_vis: vis,
408 ambiguity_vis_max: CmCell::new(None),
409 ambiguity_vis_min: CmCell::new(None),
410 span,
411 expansion,
412 parent_module: Some(parent.to_module()),
413 });
414 let resolution = self.arenas.alloc_name_resolution(NameResolution {
415 non_glob_decl: Some(decl),
416 orig_ident_span,
417 single_imports: Default::default(),
418 ..
419 });
420
421 let key =
422 BindingKey::new_disambiguated(ident, ns, || (child_index + 1).try_into().unwrap());
423 if resolutions.insert(key, resolution).is_some() {
424 ::rustc_span::macros::bug_impl(Some(span),
format_args!("an external binding was already defined"),
Location::caller());span_bug!(span, "an external binding was already defined");
425 }
426 };
427 match res {
428 Res::Def(
429 DefKind::Mod
430 | DefKind::Enum
431 | DefKind::Trait
432 | DefKind::Struct
433 | DefKind::Union
434 | DefKind::Variant
435 | DefKind::TyAlias
436 | DefKind::ForeignTy
437 | DefKind::OpaqueTy
438 | DefKind::TraitAlias
439 | DefKind::AssocTy,
440 _,
441 )
442 | Res::PrimTy(..)
443 | Res::ToolMod => define_extern(TypeNS),
444 Res::Def(
445 DefKind::Fn
446 | DefKind::AssocFn
447 | DefKind::Static { .. }
448 | DefKind::Const
449 | DefKind::AssocConst
450 | DefKind::Ctor(..),
451 _,
452 ) => define_extern(ValueNS),
453 Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => define_extern(MacroNS),
454 Res::Def(
455 DefKind::TyParam
456 | DefKind::ConstParam
457 | DefKind::ExternCrate
458 | DefKind::Use
459 | DefKind::ForeignMod
460 | DefKind::AnonConst
461 | DefKind::Field
462 | DefKind::LifetimeParam
463 | DefKind::GlobalAsm
464 | DefKind::Closure
465 | DefKind::SyntheticCoroutineBody
466 | DefKind::Impl { .. }
467 | DefKind::TestBinderConstraints,
468 _,
469 )
470 | Res::Local(..)
471 | Res::SelfTyParam { .. }
472 | Res::SelfTyAlias { .. }
473 | Res::SelfCtor(..)
474 | Res::OpenMod(..)
475 | Res::Err => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected resolution: {0:?}", res), Location::caller())bug!("unexpected resolution: {:?}", res),
476 }
477 }
478}
479
480impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for DefCollector<'_, 'ra, 'tcx> {
481 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
482 self.r
483 }
484}
485
486impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
487 fn res(&self, def_id: impl Into<DefId>) -> Res {
488 let def_id = def_id.into();
489 Res::Def(self.r.tcx.def_kind(def_id), def_id)
490 }
491
492 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> Visibility {
493 match self.r.try_resolve_visibility(&self.parent_scope, vis, false) {
494 Ok(vis) => vis,
495 Err(error) => {
496 self.r.delayed_vis_resolution_errors.push(DelayedVisResolutionError {
497 vis: vis.clone(),
498 parent_scope: self.parent_scope,
499 error,
500 });
501 Visibility::Public
502 }
503 }
504 }
505
506 fn insert_field_idents(&mut self, def_id: LocalDefId, fields: &[ast::FieldDef]) {
507 if fields.iter().any(|field| field.is_placeholder) {
508 return;
510 }
511 let field_name = |i, field: &ast::FieldDef| {
512 field.ident.unwrap_or_else(|| Ident::from_str_and_span(&::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", i)) })format!("{i}"), field.span))
513 };
514 let field_names: Vec<_> =
515 fields.iter().enumerate().map(|(i, field)| field_name(i, field)).collect();
516 let defaults = fields
517 .iter()
518 .enumerate()
519 .filter_map(|(i, field)| field.default_value().map(|_| field_name(i, field).name))
520 .collect();
521 self.r.field_names.insert(def_id, field_names);
522 self.r.field_defaults.insert(def_id, defaults);
523 }
524
525 fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {
526 let field_vis = fields
527 .iter()
528 .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span)))
529 .collect();
530 self.r.field_visibility_spans.insert(def_id, field_vis);
531 }
532
533 fn block_needs_anonymous_module(&self, block: &Block) -> bool {
534 block
536 .stmts
537 .iter()
538 .any(|statement| #[allow(non_exhaustive_omitted_patterns)] match statement.kind {
StmtKind::Item(_) | StmtKind::MacCall(_) => true,
_ => false,
}matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
539 }
540
541 fn add_import(
543 &mut self,
544 module_path: Vec<Segment>,
545 kind: ImportKind<'ra>,
546 span: Span,
547 item: &ast::Item,
548 root_span: Span,
549 root_id: NodeId,
550 vis: Visibility,
551 ) {
552 let current_module = self.parent_scope.module.expect_local();
553 let import = self.r.arenas.alloc_import(ImportData {
554 kind,
555 parent_scope: self.parent_scope,
556 module_path,
557 imported_module: CmCell::new(None),
558 span,
559 use_span: item.span,
560 use_span_with_attributes: item.span_with_attributes(),
561 has_attributes: !item.attrs.is_empty(),
562 root_span,
563 root_id,
564 vis,
565 vis_span: item.vis.span,
566 on_unknown_attr: OnUnknownData::from_attrs(self.r, &item.attrs),
567 });
568
569 self.r.indeterminate_imports.push((import, None, 0));
570 match import.kind {
571 ImportKind::Single { target, .. } => {
572 if target.name != kw::Underscore {
575 self.r.per_ns_mut(|this, ns| {
576 let key = BindingKey::new(IdentKey::new(target), ns);
577 this.resolution_or_default(current_module.to_module(), key, target.span)
578 .borrow_mut(this)
579 .single_imports
580 .insert(import);
581 });
582 }
583 }
584 ImportKind::Glob { .. } => current_module.globs.borrow_mut(self.r).push(import),
585 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
586 }
587 }
588
589 fn build_reduced_graph_for_use_tree(
593 &mut self,
594 item: &Item,
595 use_tree: &ast::UseTree,
596 id: NodeId,
597 parent_prefix: &[Segment],
598 nested: bool,
599 list_stem: bool,
600 vis: Visibility,
601 root_span: Span,
602 feed: TyCtxtFeed<'tcx, LocalDefId>,
603 ) {
604 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_resolve/src/build_reduced_graph.rs:604",
"rustc_resolve::build_reduced_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_resolve/src/build_reduced_graph.rs"),
::tracing_core::__macro_support::Option::Some(604u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::build_reduced_graph"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_reduced_graph_for_use_tree(parent_prefix={0:?}, use_tree={1:?}, nested={2})",
parent_prefix, use_tree, nested) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
605 "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
606 parent_prefix, use_tree, nested
607 );
608
609 if nested && !list_stem {
612 self.r.feed_visibility(feed, vis);
613 }
614
615 let mut prefix_iter = parent_prefix
616 .iter()
617 .cloned()
618 .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
619 .peekable();
620
621 let crate_root = match prefix_iter.peek() {
626 Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => {
627 Some(seg.ident.span.ctxt())
628 }
629 None if let ast::UseTreeKind::Glob(span) = use_tree.kind
630 && span.is_rust_2015() =>
631 {
632 Some(span.ctxt())
633 }
634 _ => None,
635 }
636 .map(|ctxt| {
637 Segment::from_ident(Ident::new(
638 kw::PathRoot,
639 use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
640 ))
641 });
642
643 let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
644 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_resolve/src/build_reduced_graph.rs:644",
"rustc_resolve::build_reduced_graph",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_resolve/src/build_reduced_graph.rs"),
::tracing_core::__macro_support::Option::Some(644u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::build_reduced_graph"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_reduced_graph_for_use_tree: prefix={0:?}",
prefix) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
645
646 match use_tree.kind {
647 ast::UseTreeKind::Simple(rename) => {
648 let mut module_path = prefix;
649 let source = module_path.pop().unwrap();
650
651 let ident = if source.ident.name == kw::SelfLower
654 && rename.is_none()
655 && let Some(parent) = module_path.last()
656 {
657 Ident::new(parent.ident.name, source.ident.span)
658 } else {
659 use_tree.ident()
660 };
661
662 match source.ident.name {
663 kw::DollarCrate => {
664 if !module_path.is_empty() {
665 self.r.dcx().span_err(
666 source.ident.span,
667 "`$crate` in paths can only be used in start position",
668 );
669 return;
670 }
671 }
672 kw::Crate => {
673 if !module_path.is_empty() {
674 self.r.dcx().span_err(
675 source.ident.span,
676 "`crate` in paths can only be used in start position",
677 );
678 return;
679 }
680 }
681 kw::Super => {
682 let valid_prefix = module_path.iter().enumerate().all(|(i, seg)| {
685 let name = seg.ident.name;
686 name == kw::Super || (name == kw::SelfLower && i == 0)
687 });
688
689 if !valid_prefix {
690 self.r.dcx().span_err(
691 source.ident.span,
692 "`super` in paths can only be used in start position, after `self`, or after another `super`",
693 );
694 return;
695 }
696 }
697 kw::SelfLower
699 if let Some(parent) = module_path.last()
700 && parent.ident.name == kw::PathRoot
701 && !self.r.path_root_is_crate_root(parent.ident) =>
702 {
703 self.r.dcx().span_err(use_tree.span(), "extern prelude cannot be imported");
704 return;
705 }
706 _ => (),
707 }
708
709 if let Some(parent) = module_path.last()
712 && parent.ident.name == kw::SelfLower
713 && module_path.len() > 1
714 {
715 self.r.dcx().span_err(
716 parent.ident.span,
717 "`self` in paths can only be used in start position or last position",
718 );
719 return;
720 }
721
722 if rename.is_none() && ident.is_path_segment_keyword() {
724 let ident = use_tree.ident();
725 self.r.dcx().emit_err(diagnostics::UnnamedImport {
726 span: ident.span,
727 sugg: diagnostics::UnnamedImportSugg { span: ident.span, ident },
728 });
729 return;
730 }
731
732 let kind = ImportKind::Single {
733 source: source.ident,
734 target: ident,
735 decls: Default::default(),
736 nested,
737 id,
738 def_id: feed.def_id(),
739 };
740
741 self.add_import(module_path, kind, use_tree.span(), item, root_span, item.id, vis);
742 }
743 ast::UseTreeKind::Glob(_) => {
744 if !ast::attr::contains_name(&item.attrs, sym::prelude_import) {
745 let kind =
746 ImportKind::Glob { max_vis: CmCell::new(None), id, def_id: feed.def_id() };
747 self.add_import(prefix, kind, use_tree.span(), item, root_span, item.id, vis);
748 } else {
749 let path_res =
751 self.r.cm().maybe_resolve_path(&prefix, None, &self.parent_scope, None);
752 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = path_res {
753 self.r.prelude = Some(module);
754 } else {
755 self.r.dcx().span_err(use_tree.span(), "cannot resolve a prelude import");
756 }
757 }
758 }
759 ast::UseTreeKind::Nested { ref items, .. } => {
760 for tree in items {
761 let id = tree.id;
762 let feed = self.create_def(id, None, DefKind::Use, use_tree.span());
763 self.build_reduced_graph_for_use_tree(
764 item,
765 &tree.inner,
766 id,
767 &prefix,
768 true,
769 false,
770 vis,
771 root_span,
772 feed,
773 );
774 }
775
776 if items.is_empty()
780 && !prefix.is_empty()
781 && (prefix.len() > 1 || prefix[0].ident.name != kw::PathRoot)
782 {
783 let new_span = prefix[prefix.len() - 1].ident.span;
784 let tree = ast::UseTree {
785 prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
786 kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))),
787 };
788 let vis = Visibility::Restricted(
789 self.parent_scope.module.nearest_parent_mod().expect_local(),
790 );
791 self.build_reduced_graph_for_use_tree(
792 item, &tree, id, &prefix, true, true, vis, root_span, feed,
793 );
794 }
795 }
796 }
797 }
798
799 fn build_reduced_graph_for_struct_variant(
800 &mut self,
801 fields: &[ast::FieldDef],
802 ident: Ident,
803 feed: TyCtxtFeed<'tcx, LocalDefId>,
804 adt_res: Res,
805 adt_vis: Visibility,
806 adt_span: Span,
807 ) {
808 let parent_scope = &self.parent_scope;
809 let parent = parent_scope.module.expect_local();
810 let expansion = parent_scope.expansion;
811
812 self.r.define_local(parent, ident, TypeNS, adt_res, adt_vis, adt_span, expansion);
814 self.r.feed_visibility(feed, adt_vis);
815 let def_id = feed.key();
816
817 self.insert_field_idents(def_id, fields);
819 self.insert_field_visibilities_local(def_id.to_def_id(), fields);
820 }
821
822 fn build_reduced_graph_for_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
824 let parent_scope = &self.parent_scope;
825 let parent = parent_scope.module.expect_local();
826 let expansion = parent_scope.expansion;
827 let sp = item.span;
828 let vis = self.resolve_visibility(&item.vis);
829 let local_def_id = feed.key();
830 let def_id = local_def_id.to_def_id();
831 let def_kind = self.r.tcx.def_kind(def_id);
832 let res = Res::Def(def_kind, def_id);
833
834 self.r.feed_visibility(feed, vis);
835
836 match item.kind {
837 ItemKind::Use(ref use_tree) => {
838 self.build_reduced_graph_for_use_tree(
839 item,
840 use_tree,
841 item.id,
842 &[],
843 false,
844 false,
845 vis,
846 use_tree.span(),
847 feed,
848 );
849 }
850
851 ItemKind::ExternCrate(orig_name, ident) => {
852 self.build_reduced_graph_for_extern_crate(
853 orig_name,
854 item,
855 ident,
856 local_def_id,
857 vis,
858 );
859 }
860
861 ItemKind::Mod(_, ident, ref mod_kind) => {
862 self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
863
864 if let ast::ModKind::Loaded(_, Inline::No { had_parse_error: Err(_) }, _) = mod_kind
865 {
866 self.r.mods_with_parse_errors.insert(def_id);
867 }
868 let module = self.r.new_local_module(
869 Some(parent),
870 ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
871 expansion.to_expn_id(),
872 item.span,
873 parent.no_implicit_prelude
874 || ast::attr::contains_name(&item.attrs, sym::no_implicit_prelude),
875 );
876 self.parent_scope.module = module.to_module();
877 if let Some(directive) = OnUnknownData::from_attrs(self.r, &item.attrs) {
878 self.r.on_unknown_data.insert(local_def_id, directive);
879 }
880 }
881
882 ItemKind::Const(ConstItem { ident, .. })
884 | ItemKind::Delegation(Delegation { ident, .. })
885 | ItemKind::Static(StaticItem { ident, .. }) => {
886 self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
887 }
888 ItemKind::Fn(Fn { ident, .. }) => {
889 self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
890
891 self.define_macro(item, feed);
894 }
895
896 ItemKind::TyAlias(TyAlias { ident, .. })
898 | ItemKind::TraitAlias(TraitAlias { ident, .. }) => {
899 self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
900 }
901
902 ItemKind::Enum(ident, _, _) | ItemKind::Trait(ast::Trait { ident, .. }) => {
903 self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
904
905 let module = self.r.new_local_module(
906 Some(parent),
907 ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
908 expansion.to_expn_id(),
909 item.span,
910 parent.no_implicit_prelude,
911 );
912 self.parent_scope.module = module.to_module();
913 }
914
915 ItemKind::Struct(ident, ref generics, ref vdata) => {
917 self.build_reduced_graph_for_struct_variant(
918 vdata.fields(),
919 ident,
920 feed,
921 res,
922 vis,
923 sp,
924 );
925
926 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) {
929 let mut ctor_vis = if vis.is_public()
932 && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
933 {
934 Visibility::Restricted(CRATE_MOD_ID)
935 } else {
936 vis
937 };
938
939 let mut field_visibilities = Vec::with_capacity(vdata.fields().len());
940
941 for field in vdata.fields() {
942 let field_vis = self
946 .r
947 .try_resolve_visibility(&self.parent_scope, &field.vis, false)
948 .unwrap_or(Visibility::Public);
949 if ctor_vis.greater_than(field_vis, self.r.tcx) {
950 ctor_vis = field_vis;
951 }
952 field_visibilities.push(field_vis.to_mod_id());
953 }
954 let feed = self.create_def(
956 ctor_node_id,
957 None,
958 DefKind::Ctor(CtorOf::Struct, ctor_kind),
959 item.span,
960 );
961
962 let ctor_def_id = feed.key();
963 let ctor_res = self.res(ctor_def_id);
964 self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, sp, expansion);
965 self.r.feed_visibility(feed, ctor_vis);
966 self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());
968
969 let ctor =
970 StructCtor { res: ctor_res, vis: ctor_vis.to_mod_id(), field_visibilities };
971 self.r.struct_ctors.insert(local_def_id, ctor);
972 }
973 self.r.struct_generics.insert(local_def_id, generics.clone());
974 }
975
976 ItemKind::Union(ident, _, ref vdata) => {
977 self.build_reduced_graph_for_struct_variant(
978 vdata.fields(),
979 ident,
980 feed,
981 res,
982 vis,
983 sp,
984 );
985 }
986
987 ItemKind::Impl { .. }
989 | ItemKind::ForeignMod(..)
990 | ItemKind::GlobalAsm(..)
991 | ItemKind::ConstBlock(..)
992 | ItemKind::TestBinderConstraints(..) => {}
993
994 ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
995 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
996 }
997 }
998 }
999
1000 fn build_reduced_graph_for_extern_crate(
1001 &mut self,
1002 orig_name: Option<Symbol>,
1003 item: &Item,
1004 orig_ident: Ident,
1005 local_def_id: LocalDefId,
1006 vis: Visibility,
1007 ) {
1008 let sp = item.span;
1009 let parent_scope = self.parent_scope;
1010 let parent = parent_scope.module;
1011 let expansion = parent_scope.expansion;
1012
1013 let (used, module, decl) = if orig_name.is_none() && orig_ident.name == kw::SelfLower {
1014 self.r.dcx().emit_err(diagnostics::ExternCrateSelfRequiresRenaming { span: sp });
1015 return;
1016 } else if orig_name == Some(kw::SelfLower) {
1017 Some(self.r.graph_root.to_module())
1018 } else {
1019 let tcx = self.r.tcx;
1020 let crate_id = self.r.cstore_mut().process_extern_crate(
1021 self.r.tcx,
1022 item,
1023 local_def_id,
1024 &tcx.definitions_untracked(),
1025 );
1026 crate_id.map(|crate_id| {
1027 self.r.extern_crate_map.insert(local_def_id, crate_id);
1028 self.r.expect_module(crate_id.as_def_id())
1029 })
1030 }
1031 .map(|module| {
1032 let used = self.process_macro_use_imports(item, module);
1033 let decl = self.r.arenas.new_pub_def_decl(module.res().unwrap(), sp, expansion);
1034 (used, Some(ModuleOrUniformRoot::Module(module)), decl)
1035 })
1036 .unwrap_or((true, None, self.r.dummy_decl));
1037 let import = self.r.arenas.alloc_import(ImportData {
1038 kind: ImportKind::ExternCrate {
1039 source: orig_name,
1040 target: orig_ident,
1041 id: item.id,
1042 def_id: local_def_id,
1043 },
1044 root_id: item.id,
1045 parent_scope,
1046 imported_module: CmCell::new(module),
1047 has_attributes: !item.attrs.is_empty(),
1048 use_span_with_attributes: item.span_with_attributes(),
1049 use_span: item.span,
1050 root_span: item.span,
1051 span: item.span,
1052 module_path: Vec::new(),
1053 vis,
1054 vis_span: item.vis.span,
1055 on_unknown_attr: OnUnknownData::from_attrs(self.r, &item.attrs),
1056 });
1057 if used {
1058 self.r.import_use_map.insert(import, Used::Other);
1059 }
1060 self.r.potentially_unused_imports.push(import);
1061 let import_decl = self.r.new_import_decl(decl, import);
1062 let ident = IdentKey::new(orig_ident);
1063 if ident.name != kw::Underscore && parent == self.r.graph_root.to_module() {
1064 if let Some(entry) = self.r.extern_prelude.get(&ident)
1067 && expansion != LocalExpnId::ROOT
1068 && orig_name.is_some()
1069 && entry.item_decl.is_none()
1070 {
1071 self.r.dcx().emit_err(
1072 diagnostics::MacroExpandedExternCrateCannotShadowExternArguments {
1073 span: item.span,
1074 },
1075 );
1076 }
1077
1078 use indexmap::map::Entry;
1079 match self.r.extern_prelude.entry(ident) {
1080 Entry::Occupied(mut occupied) => {
1081 let entry = occupied.get_mut();
1082 if entry.item_decl.is_some() {
1083 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern crate `{0}` already in extern prelude",
orig_ident))
})format!("extern crate `{orig_ident}` already in extern prelude");
1084 self.r.tcx.dcx().span_delayed_bug(item.span, msg);
1085 } else {
1086 entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
1087 }
1088 entry
1089 }
1090 Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
1091 item_decl: Some((import_decl, orig_ident.span, true)),
1092 flag_decl: None,
1093 }),
1094 };
1095 }
1096 self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
1097 }
1098
1099 pub(crate) fn build_reduced_graph_for_foreign_item(
1101 &mut self,
1102 item: &ForeignItem,
1103 ident: Ident,
1104 feed: TyCtxtFeed<'tcx, LocalDefId>,
1105 ) {
1106 let local_def_id = feed.key();
1107 let def_id = local_def_id.to_def_id();
1108 let ns = match item.kind {
1109 ForeignItemKind::Fn(..) => ValueNS,
1110 ForeignItemKind::Static(..) => ValueNS,
1111 ForeignItemKind::TyAlias(..) => TypeNS,
1112 ForeignItemKind::MacCall(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1113 };
1114 let parent = self.parent_scope.module.expect_local();
1115 let expansion = self.parent_scope.expansion;
1116 let vis = self.resolve_visibility(&item.vis);
1117 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1118 self.r.feed_visibility(feed, vis);
1119 }
1120
1121 fn build_reduced_graph_for_block(&mut self, block: &Block) {
1122 let parent = self.parent_scope.module.expect_local();
1123 let expansion = self.parent_scope.expansion;
1124 if self.block_needs_anonymous_module(block) {
1125 let module = self.r.new_local_module(
1126 Some(parent),
1127 ModuleKind::Block,
1128 expansion.to_expn_id(),
1129 block.span,
1130 parent.no_implicit_prelude,
1131 );
1132 self.r.block_map.insert(block.id, module);
1133 self.parent_scope.module = module.to_module(); }
1135 }
1136
1137 fn add_macro_use_decl(
1138 &mut self,
1139 name: Symbol,
1140 decl: Decl<'ra>,
1141 span: Span,
1142 allow_shadowing: bool,
1143 ) {
1144 if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
1145 self.r.dcx().emit_err(diagnostics::MacroUseNameAlreadyInUse { span, name });
1146 }
1147 }
1148
1149 fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1151 let mut import_all = None;
1152 let mut single_imports = ThinVec::new();
1153 if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
1154 AttributeParser::parse_limited_sym(self.r.tcx.sess, &item.attrs, &[sym::macro_use])
1155 {
1156 if self.parent_scope.module.expect_local().parent.is_some() {
1157 self.r.dcx().emit_err(diagnostics::ExternCrateLoadingMacroNotAtCrateRoot {
1158 span: item.span,
1159 });
1160 }
1161 if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1162 && orig_name == kw::SelfLower
1163 {
1164 self.r.dcx().emit_err(diagnostics::MacroUseExternCrateSelf { span });
1165 }
1166
1167 match arguments {
1168 MacroUseArgs::UseAll => import_all = Some(span),
1169 MacroUseArgs::UseSpecific(imports) => single_imports = imports,
1170 }
1171 }
1172
1173 let macro_use_import = |this: &Self, span, warn_private| {
1174 this.r.arenas.alloc_import(ImportData {
1175 kind: ImportKind::MacroUse { warn_private },
1176 root_id: item.id,
1177 parent_scope: this.parent_scope,
1178 imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
1179 use_span_with_attributes: item.span_with_attributes(),
1180 has_attributes: !item.attrs.is_empty(),
1181 use_span: item.span,
1182 root_span: span,
1183 span,
1184 module_path: Vec::new(),
1185 vis: Visibility::Restricted(CRATE_MOD_ID),
1186 vis_span: item.vis.span,
1187 on_unknown_attr: OnUnknownData::from_attrs(this.r, &item.attrs),
1188 })
1189 };
1190
1191 let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1192 if let Some(span) = import_all {
1193 let import = macro_use_import(self, span, false);
1194 self.r.potentially_unused_imports.push(import);
1195 module.for_each_child_mut(self, |this, ident, _, ns, binding| {
1196 if ns == MacroNS {
1197 let import =
1198 if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
1199 import
1200 } else {
1201 if this.r.macro_use_prelude.contains_key(&ident.name) {
1204 return;
1206 }
1207 macro_use_import(this, span, true)
1208 };
1209 let import_decl = this.r.new_import_decl(binding, import);
1210 this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
1211 }
1212 });
1213 } else {
1214 for ident in single_imports.iter().cloned() {
1215 let result = self.r.cm().maybe_resolve_ident_in_module(
1216 ModuleOrUniformRoot::Module(module),
1217 ident,
1218 MacroNS,
1219 &self.parent_scope,
1220 None,
1221 );
1222 if let Ok(binding) = result {
1223 let import = macro_use_import(self, ident.span, false);
1224 self.r.potentially_unused_imports.push(import);
1225 let import_decl = self.r.new_import_decl(binding, import);
1226 self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
1227 } else {
1228 self.r.dcx().emit_err(diagnostics::ImportedMacroNotFound { span: ident.span });
1229 }
1230 }
1231 }
1232 import_all.is_some() || !single_imports.is_empty()
1233 }
1234
1235 pub(crate) fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
1237 for attr in attrs {
1238 if attr.has_name(sym::macro_escape) {
1239 let inner_attribute = #[allow(non_exhaustive_omitted_patterns)] match attr.style {
ast::AttrStyle::Inner => true,
_ => false,
}matches!(attr.style, ast::AttrStyle::Inner);
1240 self.r.dcx().emit_warn(diagnostics::MacroExternDeprecated {
1241 span: attr.span,
1242 inner_attribute,
1243 });
1244 } else if !attr.has_name(sym::macro_use) {
1245 continue;
1246 }
1247
1248 if !attr.is_word() {
1249 self.r.dcx().emit_err(diagnostics::ArgumentsMacroUseNotAllowed { span: attr.span });
1250 }
1251 return true;
1252 }
1253
1254 false
1255 }
1256
1257 pub(crate) fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
1258 let invoc_id = id.placeholder_to_expn_id();
1259 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1260 if !old_parent_scope.is_none() {
{
::core::panicking::panic_fmt(format_args!("invocation data is reset for an invocation"));
}
};assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
1261 invoc_id
1262 }
1263
1264 pub(crate) fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
1267 let invoc_id = self.visit_invoc(id);
1268 let module = self.parent_scope.module.expect_local();
1269 module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
1270 self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1271 }
1272
1273 fn proc_macro_stub(
1274 &self,
1275 item: &ast::Item,
1276 fn_ident: Ident,
1277 ) -> Option<(MacroKind, Ident, Span)> {
1278 if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1279 return Some((MacroKind::Bang, fn_ident, item.span));
1280 } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1281 return Some((MacroKind::Attr, fn_ident, item.span));
1282 } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1283 && let Some(meta_item_inner) =
1284 attr.meta_item_list().and_then(|list| list.get(0).cloned())
1285 && let Some(ident) = meta_item_inner.ident()
1286 {
1287 return Some((MacroKind::Derive, ident, ident.span));
1288 }
1289 None
1290 }
1291
1292 fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1296 if !ident.as_str().starts_with('_') {
1297 self.r.unused_macros.insert(def_id, (node_id, ident));
1298 if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
1299 let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
1300 self.r.unused_macro_rules.insert(node_id, value);
1301 }
1302 }
1303 }
1304
1305 fn define_macro(
1306 &mut self,
1307 item: &ast::Item,
1308 feed: TyCtxtFeed<'tcx, LocalDefId>,
1309 ) -> MacroRulesScopeRef<'ra> {
1310 let parent_scope = self.parent_scope;
1311 let expansion = parent_scope.expansion;
1312 let def_id = feed.key();
1313 let (res, orig_ident, span, macro_rules) = match &item.kind {
1314 ItemKind::MacroDef(ident, def) => {
1315 (self.res(def_id), *ident, item.span, def.macro_rules)
1316 }
1317 ItemKind::Fn(ast::Fn { ident: fn_ident, .. }) => {
1318 match self.proc_macro_stub(item, *fn_ident) {
1319 Some((macro_kind, ident, span)) => {
1320 let macro_kinds = macro_kind.into();
1321 let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1322 self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
1323 self.r.proc_macro_stubs.insert(def_id);
1324 (res, ident, span, false)
1325 }
1326 None => return parent_scope.macro_rules,
1327 }
1328 }
1329 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1330 };
1331
1332 self.r.local_macro_def_scopes.insert(def_id, parent_scope.module.expect_local());
1333
1334 if macro_rules {
1335 let ident = IdentKey::new(orig_ident);
1336 self.r.macro_names.insert(ident);
1337 let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1338 let vis = if is_macro_export {
1339 Visibility::Public
1340 } else {
1341 Visibility::Restricted(CRATE_MOD_ID)
1342 };
1343 let decl = self.r.arenas.new_def_decl(
1344 res,
1345 vis.to_mod_id(),
1346 span,
1347 expansion,
1348 Some(parent_scope.module),
1349 );
1350 self.r.all_macro_rules.insert(ident.name);
1351 if is_macro_export {
1352 let import = self.r.arenas.alloc_import(ImportData {
1353 kind: ImportKind::MacroExport,
1354 root_id: item.id,
1355 parent_scope: ParentScope {
1356 module: self.r.graph_root.to_module(),
1357 ..parent_scope
1358 },
1359 imported_module: CmCell::new(None),
1360 has_attributes: false,
1361 use_span_with_attributes: span,
1362 use_span: span,
1363 root_span: span,
1364 span,
1365 module_path: Vec::new(),
1366 vis,
1367 vis_span: item.vis.span,
1368 on_unknown_attr: OnUnknownData::from_attrs(self.r, &item.attrs),
1369 });
1370 self.r.import_use_map.insert(import, Used::Other);
1371 let import_decl = self.r.new_import_decl(decl, import);
1372 self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
1373 } else {
1374 self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
1375 self.insert_unused_macro(orig_ident, def_id, item.id);
1376 }
1377 self.r.feed_visibility(feed, vis);
1378 let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
1379 self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
1380 parent_macro_rules_scope: parent_scope.macro_rules,
1381 decl,
1382 ident,
1383 orig_ident_span: orig_ident.span,
1384 }),
1385 ));
1386 self.r.macro_rules_scopes.insert(def_id, scope);
1387 scope
1388 } else {
1389 let module = parent_scope.module.expect_local();
1390 let vis = match item.kind {
1391 ItemKind::Fn(..) => self
1394 .r
1395 .try_resolve_visibility(&self.parent_scope, &item.vis, false)
1396 .unwrap_or(Visibility::Public),
1397 _ => self.resolve_visibility(&item.vis),
1398 };
1399 if !vis.is_public() {
1400 self.insert_unused_macro(orig_ident, def_id, item.id);
1401 }
1402 self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1403 self.r.feed_visibility(feed, vis);
1404 self.parent_scope.macro_rules
1405 }
1406 }
1407}
1408
1409impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
1410 pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
1411 let orig_module_scope = self.parent_scope.module;
1412 self.parent_scope.macro_rules = match item.kind {
1413 ItemKind::MacroDef(..) => {
1414 let macro_rules_scope = self.define_macro(item, feed);
1415 visit::walk_item(self, item);
1416 macro_rules_scope
1417 }
1418 _ => {
1419 let orig_macro_rules_scope = self.parent_scope.macro_rules;
1420 self.build_reduced_graph_for_item(item, feed);
1421 match item.kind {
1422 ItemKind::Mod(..) => {
1423 self.visit_vis(&item.vis);
1426 item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1427 for elem in &item.attrs {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};visit::walk_list!(self, visit_attribute, &item.attrs);
1428 }
1429 _ => visit::walk_item(self, item),
1430 }
1431 match item.kind {
1432 ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1433 self.parent_scope.macro_rules
1434 }
1435 _ => orig_macro_rules_scope,
1436 }
1437 }
1438 };
1439 self.parent_scope.module = orig_module_scope;
1440 }
1441
1442 pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
1445 self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
1446 }
1447
1448 pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
1449 let orig_current_module = self.parent_scope.module;
1450 let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1451 self.build_reduced_graph_for_block(block);
1452 visit::walk_block(self, block);
1453 self.parent_scope.module = orig_current_module;
1454 self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1455 }
1456
1457 pub(crate) fn brg_visit_assoc_item(
1458 &mut self,
1459 item: &'a AssocItem,
1460 ctxt: AssocCtxt,
1461 ident: Ident,
1462 ns: Namespace,
1463 feed: TyCtxtFeed<'tcx, LocalDefId>,
1464 ) {
1465 let vis = self.resolve_visibility(&item.vis);
1466 let local_def_id = feed.key();
1467 let def_id = local_def_id.to_def_id();
1468
1469 if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
AssocCtxt::Impl { of_trait: true } => true,
_ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1470 && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
ast::VisibilityKind::Inherited => true,
_ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1471 {
1472 self.r.feed_visibility(feed, vis);
1476 }
1477
1478 if ctxt == AssocCtxt::Trait {
1479 let parent = self.parent_scope.module.expect_local();
1480 let expansion = self.parent_scope.expansion;
1481 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1482 } else if !#[allow(non_exhaustive_omitted_patterns)] match &item.kind {
AssocItemKind::Delegation(d) if d.source == DelegationSource::Glob =>
true,
_ => false,
}matches!(&item.kind, AssocItemKind::Delegation(d) if d.source == DelegationSource::Glob)
1483 && ident.name != kw::Underscore
1484 {
1485 let impl_def_id = self.r.tcx.local_parent(local_def_id);
1487 let key = BindingKey::new(IdentKey::new(ident), ns);
1488 self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1489 }
1490
1491 visit::walk_assoc_item(self, item, ctxt);
1492 }
1493
1494 pub(crate) fn visit_assoc_item_mac_call(
1495 &mut self,
1496 item: &'a Item<AssocItemKind>,
1497 ctxt: AssocCtxt,
1498 ) {
1499 match ctxt {
1500 AssocCtxt::Trait => {
1501 self.visit_invoc_in_module(item.id);
1502 }
1503 AssocCtxt::Impl { .. } => {
1504 let invoc_id = item.id.placeholder_to_expn_id();
1505 if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1506 self.r
1507 .impl_unexpanded_invocations
1508 .entry(self.r.invocation_parent(invoc_id))
1509 .or_default()
1510 .insert(invoc_id);
1511 }
1512 self.visit_invoc(item.id);
1513 }
1514 }
1515 }
1516
1517 pub(crate) fn brg_visit_field_def(
1518 &mut self,
1519 sf: &'a ast::FieldDef,
1520 feed: TyCtxtFeed<'tcx, LocalDefId>,
1521 ) {
1522 let vis = self.resolve_visibility(&sf.vis);
1523 self.r.feed_visibility(feed, vis);
1524 visit::walk_field_def(self, sf);
1525 }
1526
1527 pub(crate) fn brg_visit_variant(
1530 &mut self,
1531 variant: &'a ast::Variant,
1532 feed: TyCtxtFeed<'tcx, LocalDefId>,
1533 ) {
1534 let parent = self.parent_scope.module.expect_local();
1535 let expn_id = self.parent_scope.expansion;
1536 let ident = variant.ident;
1537
1538 let def_id = feed.key();
1540 let vis = self.resolve_visibility(&variant.vis);
1541 self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1542 self.r.feed_visibility(feed, vis);
1543
1544 let ctor_vis =
1546 if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1547 Visibility::Restricted(CRATE_MOD_ID)
1548 } else {
1549 vis
1550 };
1551
1552 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
1554 let feed = self.create_def(
1555 ctor_node_id,
1556 None,
1557 DefKind::Ctor(CtorOf::Variant, ctor_kind),
1558 variant.span,
1559 );
1560 let ctor_def_id = feed.key();
1561 let ctor_res = self.res(ctor_def_id);
1562 self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1563 self.r.feed_visibility(feed, ctor_vis);
1564 }
1565
1566 self.insert_field_idents(def_id, variant.data.fields());
1568 self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1569
1570 visit::walk_variant(self, variant);
1571 }
1572}