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