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