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::StructCtor;
35use crate::imports::{ImportData, ImportKind, OnUnknownData};
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.tcx, item),
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 }
867
868 ItemKind::Const(ConstItem { ident, .. })
870 | ItemKind::Delegation(Delegation { ident, .. })
871 | ItemKind::Static(StaticItem { ident, .. }) => {
872 self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
873 }
874 ItemKind::Fn(Fn { ident, .. }) => {
875 self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
876
877 self.define_macro(item, feed);
880 }
881
882 ItemKind::TyAlias(TyAlias { ident, .. })
884 | ItemKind::TraitAlias(TraitAlias { ident, .. }) => {
885 self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
886 }
887
888 ItemKind::Enum(ident, _, _) | ItemKind::Trait(ast::Trait { ident, .. }) => {
889 self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
890
891 let module = self.r.new_local_module(
892 Some(parent),
893 ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
894 expansion.to_expn_id(),
895 item.span,
896 parent.no_implicit_prelude,
897 );
898 self.parent_scope.module = module.to_module();
899 }
900
901 ItemKind::Struct(ident, ref generics, ref vdata) => {
903 self.build_reduced_graph_for_struct_variant(
904 vdata.fields(),
905 ident,
906 feed,
907 res,
908 vis,
909 sp,
910 );
911
912 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) {
915 let mut ctor_vis = if vis.is_public()
918 && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
919 {
920 Visibility::Restricted(CRATE_DEF_ID)
921 } else {
922 vis
923 };
924
925 let mut field_visibilities = Vec::with_capacity(vdata.fields().len());
926
927 for field in vdata.fields() {
928 let field_vis = self
932 .r
933 .try_resolve_visibility(&self.parent_scope, &field.vis, false)
934 .unwrap_or(Visibility::Public);
935 if ctor_vis.greater_than(field_vis, self.r.tcx) {
936 ctor_vis = field_vis;
937 }
938 field_visibilities.push(field_vis.to_def_id());
939 }
940 let feed = self.create_def(
942 ctor_node_id,
943 None,
944 DefKind::Ctor(CtorOf::Struct, ctor_kind),
945 item.span,
946 );
947
948 let ctor_def_id = feed.key();
949 let ctor_res = self.res(ctor_def_id);
950 self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, sp, expansion);
951 self.r.feed_visibility(feed, ctor_vis);
952 self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());
954
955 let ctor =
956 StructCtor { res: ctor_res, vis: ctor_vis.to_def_id(), field_visibilities };
957 self.r.struct_ctors.insert(local_def_id, ctor);
958 }
959 self.r.struct_generics.insert(local_def_id, generics.clone());
960 }
961
962 ItemKind::Union(ident, _, ref vdata) => {
963 self.build_reduced_graph_for_struct_variant(
964 vdata.fields(),
965 ident,
966 feed,
967 res,
968 vis,
969 sp,
970 );
971 }
972
973 ItemKind::Impl { .. }
975 | ItemKind::ForeignMod(..)
976 | ItemKind::GlobalAsm(..)
977 | ItemKind::ConstBlock(..) => {}
978
979 ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
980 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
981 }
982 }
983 }
984
985 fn build_reduced_graph_for_extern_crate(
986 &mut self,
987 orig_name: Option<Symbol>,
988 item: &Item,
989 orig_ident: Ident,
990 local_def_id: LocalDefId,
991 vis: Visibility,
992 ) {
993 let sp = item.span;
994 let parent_scope = self.parent_scope;
995 let parent = parent_scope.module;
996 let expansion = parent_scope.expansion;
997
998 let (used, module, decl) = if orig_name.is_none() && orig_ident.name == kw::SelfLower {
999 self.r.dcx().emit_err(diagnostics::ExternCrateSelfRequiresRenaming { span: sp });
1000 return;
1001 } else if orig_name == Some(kw::SelfLower) {
1002 Some(self.r.graph_root.to_module())
1003 } else {
1004 let tcx = self.r.tcx;
1005 let crate_id = self.r.cstore_mut().process_extern_crate(
1006 self.r.tcx,
1007 item,
1008 local_def_id,
1009 &tcx.definitions_untracked(),
1010 );
1011 crate_id.map(|crate_id| {
1012 self.r.extern_crate_map.insert(local_def_id, crate_id);
1013 self.r.expect_module(crate_id.as_def_id())
1014 })
1015 }
1016 .map(|module| {
1017 let used = self.process_macro_use_imports(item, module);
1018 let decl = self.r.arenas.new_pub_def_decl(module.res().unwrap(), sp, expansion);
1019 (used, Some(ModuleOrUniformRoot::Module(module)), decl)
1020 })
1021 .unwrap_or((true, None, self.r.dummy_decl));
1022 let import = self.r.arenas.alloc_import(ImportData {
1023 kind: ImportKind::ExternCrate {
1024 source: orig_name,
1025 target: orig_ident,
1026 id: item.id,
1027 def_id: local_def_id,
1028 },
1029 root_id: item.id,
1030 parent_scope,
1031 imported_module: CmCell::new(module),
1032 has_attributes: !item.attrs.is_empty(),
1033 use_span_with_attributes: item.span_with_attributes(),
1034 use_span: item.span,
1035 root_span: item.span,
1036 span: item.span,
1037 module_path: Vec::new(),
1038 vis,
1039 vis_span: item.vis.span,
1040 on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
1041 });
1042 if used {
1043 self.r.import_use_map.insert(import, Used::Other);
1044 }
1045 self.r.potentially_unused_imports.push(import);
1046 let import_decl = self.r.new_import_decl(decl, import);
1047 let ident = IdentKey::new(orig_ident);
1048 if ident.name != kw::Underscore && parent == self.r.graph_root.to_module() {
1049 if let Some(entry) = self.r.extern_prelude.get(&ident)
1052 && expansion != LocalExpnId::ROOT
1053 && orig_name.is_some()
1054 && entry.item_decl.is_none()
1055 {
1056 self.r.dcx().emit_err(
1057 diagnostics::MacroExpandedExternCrateCannotShadowExternArguments {
1058 span: item.span,
1059 },
1060 );
1061 }
1062
1063 use indexmap::map::Entry;
1064 match self.r.extern_prelude.entry(ident) {
1065 Entry::Occupied(mut occupied) => {
1066 let entry = occupied.get_mut();
1067 if entry.item_decl.is_some() {
1068 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");
1069 self.r.tcx.dcx().span_delayed_bug(item.span, msg);
1070 } else {
1071 entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
1072 }
1073 entry
1074 }
1075 Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
1076 item_decl: Some((import_decl, orig_ident.span, true)),
1077 flag_decl: None,
1078 }),
1079 };
1080 }
1081 self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
1082 }
1083
1084 pub(crate) fn build_reduced_graph_for_foreign_item(
1086 &mut self,
1087 item: &ForeignItem,
1088 ident: Ident,
1089 feed: TyCtxtFeed<'tcx, LocalDefId>,
1090 ) {
1091 let local_def_id = feed.key();
1092 let def_id = local_def_id.to_def_id();
1093 let ns = match item.kind {
1094 ForeignItemKind::Fn(..) => ValueNS,
1095 ForeignItemKind::Static(..) => ValueNS,
1096 ForeignItemKind::TyAlias(..) => TypeNS,
1097 ForeignItemKind::MacCall(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1098 };
1099 let parent = self.parent_scope.module.expect_local();
1100 let expansion = self.parent_scope.expansion;
1101 let vis = self.resolve_visibility(&item.vis);
1102 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1103 self.r.feed_visibility(feed, vis);
1104 }
1105
1106 fn build_reduced_graph_for_block(&mut self, block: &Block) {
1107 let parent = self.parent_scope.module.expect_local();
1108 let expansion = self.parent_scope.expansion;
1109 if self.block_needs_anonymous_module(block) {
1110 let module = self.r.new_local_module(
1111 Some(parent),
1112 ModuleKind::Block,
1113 expansion.to_expn_id(),
1114 block.span,
1115 parent.no_implicit_prelude,
1116 );
1117 self.r.block_map.insert(block.id, module);
1118 self.parent_scope.module = module.to_module(); }
1120 }
1121
1122 fn add_macro_use_decl(
1123 &mut self,
1124 name: Symbol,
1125 decl: Decl<'ra>,
1126 span: Span,
1127 allow_shadowing: bool,
1128 ) {
1129 if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
1130 self.r.dcx().emit_err(diagnostics::MacroUseNameAlreadyInUse { span, name });
1131 }
1132 }
1133
1134 fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1136 let mut import_all = None;
1137 let mut single_imports = ThinVec::new();
1138 if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
1139 AttributeParser::parse_limited(self.r.tcx.sess, &item.attrs, &[sym::macro_use])
1140 {
1141 if self.parent_scope.module.expect_local().parent.is_some() {
1142 self.r.dcx().emit_err(diagnostics::ExternCrateLoadingMacroNotAtCrateRoot {
1143 span: item.span,
1144 });
1145 }
1146 if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1147 && orig_name == kw::SelfLower
1148 {
1149 self.r.dcx().emit_err(diagnostics::MacroUseExternCrateSelf { span });
1150 }
1151
1152 match arguments {
1153 MacroUseArgs::UseAll => import_all = Some(span),
1154 MacroUseArgs::UseSpecific(imports) => single_imports = imports,
1155 }
1156 }
1157
1158 let macro_use_import = |this: &Self, span, warn_private| {
1159 this.r.arenas.alloc_import(ImportData {
1160 kind: ImportKind::MacroUse { warn_private },
1161 root_id: item.id,
1162 parent_scope: this.parent_scope,
1163 imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
1164 use_span_with_attributes: item.span_with_attributes(),
1165 has_attributes: !item.attrs.is_empty(),
1166 use_span: item.span,
1167 root_span: span,
1168 span,
1169 module_path: Vec::new(),
1170 vis: Visibility::Restricted(CRATE_DEF_ID),
1171 vis_span: item.vis.span,
1172 on_unknown_attr: OnUnknownData::from_attrs(this.r.tcx, item),
1173 })
1174 };
1175
1176 let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1177 if let Some(span) = import_all {
1178 let import = macro_use_import(self, span, false);
1179 self.r.potentially_unused_imports.push(import);
1180 module.for_each_child_mut(self, |this, ident, _, ns, binding| {
1181 if ns == MacroNS {
1182 let import =
1183 if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
1184 import
1185 } else {
1186 if this.r.macro_use_prelude.contains_key(&ident.name) {
1189 return;
1191 }
1192 macro_use_import(this, span, true)
1193 };
1194 let import_decl = this.r.new_import_decl(binding, import);
1195 this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
1196 }
1197 });
1198 } else {
1199 for ident in single_imports.iter().cloned() {
1200 let result = self.r.cm().maybe_resolve_ident_in_module(
1201 ModuleOrUniformRoot::Module(module),
1202 ident,
1203 MacroNS,
1204 &self.parent_scope,
1205 None,
1206 );
1207 if let Ok(binding) = result {
1208 let import = macro_use_import(self, ident.span, false);
1209 self.r.potentially_unused_imports.push(import);
1210 let import_decl = self.r.new_import_decl(binding, import);
1211 self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
1212 } else {
1213 self.r.dcx().emit_err(diagnostics::ImportedMacroNotFound { span: ident.span });
1214 }
1215 }
1216 }
1217 import_all.is_some() || !single_imports.is_empty()
1218 }
1219
1220 pub(crate) fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
1222 for attr in attrs {
1223 if attr.has_name(sym::macro_escape) {
1224 let inner_attribute = #[allow(non_exhaustive_omitted_patterns)] match attr.style {
ast::AttrStyle::Inner => true,
_ => false,
}matches!(attr.style, ast::AttrStyle::Inner);
1225 self.r.dcx().emit_warn(diagnostics::MacroExternDeprecated {
1226 span: attr.span,
1227 inner_attribute,
1228 });
1229 } else if !attr.has_name(sym::macro_use) {
1230 continue;
1231 }
1232
1233 if !attr.is_word() {
1234 self.r.dcx().emit_err(diagnostics::ArgumentsMacroUseNotAllowed { span: attr.span });
1235 }
1236 return true;
1237 }
1238
1239 false
1240 }
1241
1242 pub(crate) fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
1243 let invoc_id = id.placeholder_to_expn_id();
1244 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1245 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");
1246 invoc_id
1247 }
1248
1249 pub(crate) fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
1252 let invoc_id = self.visit_invoc(id);
1253 let module = self.parent_scope.module.expect_local();
1254 module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
1255 self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1256 }
1257
1258 fn proc_macro_stub(
1259 &self,
1260 item: &ast::Item,
1261 fn_ident: Ident,
1262 ) -> Option<(MacroKind, Ident, Span)> {
1263 if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1264 return Some((MacroKind::Bang, fn_ident, item.span));
1265 } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1266 return Some((MacroKind::Attr, fn_ident, item.span));
1267 } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1268 && let Some(meta_item_inner) =
1269 attr.meta_item_list().and_then(|list| list.get(0).cloned())
1270 && let Some(ident) = meta_item_inner.ident()
1271 {
1272 return Some((MacroKind::Derive, ident, ident.span));
1273 }
1274 None
1275 }
1276
1277 fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1281 if !ident.as_str().starts_with('_') {
1282 self.r.unused_macros.insert(def_id, (node_id, ident));
1283 if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
1284 let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
1285 self.r.unused_macro_rules.insert(node_id, value);
1286 }
1287 }
1288 }
1289
1290 fn define_macro(
1291 &mut self,
1292 item: &ast::Item,
1293 feed: TyCtxtFeed<'tcx, LocalDefId>,
1294 ) -> MacroRulesScopeRef<'ra> {
1295 let parent_scope = self.parent_scope;
1296 let expansion = parent_scope.expansion;
1297 let def_id = feed.key();
1298 let (res, orig_ident, span, macro_rules) = match &item.kind {
1299 ItemKind::MacroDef(ident, def) => {
1300 (self.res(def_id), *ident, item.span, def.macro_rules)
1301 }
1302 ItemKind::Fn(ast::Fn { ident: fn_ident, .. }) => {
1303 match self.proc_macro_stub(item, *fn_ident) {
1304 Some((macro_kind, ident, span)) => {
1305 let macro_kinds = macro_kind.into();
1306 let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1307 self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
1308 self.r.proc_macro_stubs.insert(def_id);
1309 (res, ident, span, false)
1310 }
1311 None => return parent_scope.macro_rules,
1312 }
1313 }
1314 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1315 };
1316
1317 self.r.local_macro_def_scopes.insert(def_id, parent_scope.module.expect_local());
1318
1319 if macro_rules {
1320 let ident = IdentKey::new(orig_ident);
1321 self.r.macro_names.insert(ident);
1322 let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1323 let vis = if is_macro_export {
1324 Visibility::Public
1325 } else {
1326 Visibility::Restricted(CRATE_DEF_ID)
1327 };
1328 let decl = self.r.arenas.new_def_decl(
1329 res,
1330 vis.to_def_id(),
1331 span,
1332 expansion,
1333 Some(parent_scope.module),
1334 );
1335 self.r.all_macro_rules.insert(ident.name);
1336 if is_macro_export {
1337 let import = self.r.arenas.alloc_import(ImportData {
1338 kind: ImportKind::MacroExport,
1339 root_id: item.id,
1340 parent_scope: ParentScope {
1341 module: self.r.graph_root.to_module(),
1342 ..parent_scope
1343 },
1344 imported_module: CmCell::new(None),
1345 has_attributes: false,
1346 use_span_with_attributes: span,
1347 use_span: span,
1348 root_span: span,
1349 span,
1350 module_path: Vec::new(),
1351 vis,
1352 vis_span: item.vis.span,
1353 on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
1354 });
1355 self.r.import_use_map.insert(import, Used::Other);
1356 let import_decl = self.r.new_import_decl(decl, import);
1357 self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
1358 } else {
1359 self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
1360 self.insert_unused_macro(orig_ident, def_id, item.id);
1361 }
1362 self.r.feed_visibility(feed, vis);
1363 let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
1364 self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
1365 parent_macro_rules_scope: parent_scope.macro_rules,
1366 decl,
1367 ident,
1368 orig_ident_span: orig_ident.span,
1369 }),
1370 ));
1371 self.r.macro_rules_scopes.insert(def_id, scope);
1372 scope
1373 } else {
1374 let module = parent_scope.module.expect_local();
1375 let vis = match item.kind {
1376 ItemKind::Fn(..) => self
1379 .r
1380 .try_resolve_visibility(&self.parent_scope, &item.vis, false)
1381 .unwrap_or(Visibility::Public),
1382 _ => self.resolve_visibility(&item.vis),
1383 };
1384 if !vis.is_public() {
1385 self.insert_unused_macro(orig_ident, def_id, item.id);
1386 }
1387 self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1388 self.r.feed_visibility(feed, vis);
1389 self.parent_scope.macro_rules
1390 }
1391 }
1392}
1393
1394impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
1395 pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
1396 let orig_module_scope = self.parent_scope.module;
1397 self.parent_scope.macro_rules = match item.kind {
1398 ItemKind::MacroDef(..) => {
1399 let macro_rules_scope = self.define_macro(item, feed);
1400 visit::walk_item(self, item);
1401 macro_rules_scope
1402 }
1403 _ => {
1404 let orig_macro_rules_scope = self.parent_scope.macro_rules;
1405 self.build_reduced_graph_for_item(item, feed);
1406 match item.kind {
1407 ItemKind::Mod(..) => {
1408 self.visit_vis(&item.vis);
1411 item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1412 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);
1413 }
1414 _ => visit::walk_item(self, item),
1415 }
1416 match item.kind {
1417 ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1418 self.parent_scope.macro_rules
1419 }
1420 _ => orig_macro_rules_scope,
1421 }
1422 }
1423 };
1424 self.parent_scope.module = orig_module_scope;
1425 }
1426
1427 pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
1430 self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
1431 }
1432
1433 pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
1434 let orig_current_module = self.parent_scope.module;
1435 let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1436 self.build_reduced_graph_for_block(block);
1437 visit::walk_block(self, block);
1438 self.parent_scope.module = orig_current_module;
1439 self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1440 }
1441
1442 pub(crate) fn brg_visit_assoc_item(
1443 &mut self,
1444 item: &'a AssocItem,
1445 ctxt: AssocCtxt,
1446 ident: Ident,
1447 ns: Namespace,
1448 feed: TyCtxtFeed<'tcx, LocalDefId>,
1449 ) {
1450 let vis = self.resolve_visibility(&item.vis);
1451 let local_def_id = feed.key();
1452 let def_id = local_def_id.to_def_id();
1453
1454 if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
AssocCtxt::Impl { of_trait: true } => true,
_ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1455 && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
ast::VisibilityKind::Inherited => true,
_ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1456 {
1457 self.r.feed_visibility(feed, vis);
1461 }
1462
1463 if ctxt == AssocCtxt::Trait {
1464 let parent = self.parent_scope.module.expect_local();
1465 let expansion = self.parent_scope.expansion;
1466 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1467 } 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)
1468 && ident.name != kw::Underscore
1469 {
1470 let impl_def_id = self.r.tcx.local_parent(local_def_id);
1472 let key = BindingKey::new(IdentKey::new(ident), ns);
1473 self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1474 }
1475
1476 visit::walk_assoc_item(self, item, ctxt);
1477 }
1478
1479 pub(crate) fn visit_assoc_item_mac_call(
1480 &mut self,
1481 item: &'a Item<AssocItemKind>,
1482 ctxt: AssocCtxt,
1483 ) {
1484 match ctxt {
1485 AssocCtxt::Trait => {
1486 self.visit_invoc_in_module(item.id);
1487 }
1488 AssocCtxt::Impl { .. } => {
1489 let invoc_id = item.id.placeholder_to_expn_id();
1490 if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1491 self.r
1492 .impl_unexpanded_invocations
1493 .entry(self.r.invocation_parent(invoc_id))
1494 .or_default()
1495 .insert(invoc_id);
1496 }
1497 self.visit_invoc(item.id);
1498 }
1499 }
1500 }
1501
1502 pub(crate) fn brg_visit_field_def(
1503 &mut self,
1504 sf: &'a ast::FieldDef,
1505 feed: TyCtxtFeed<'tcx, LocalDefId>,
1506 ) {
1507 let vis = self.resolve_visibility(&sf.vis);
1508 self.r.feed_visibility(feed, vis);
1509 visit::walk_field_def(self, sf);
1510 }
1511
1512 pub(crate) fn brg_visit_variant(
1515 &mut self,
1516 variant: &'a ast::Variant,
1517 feed: TyCtxtFeed<'tcx, LocalDefId>,
1518 ) {
1519 let parent = self.parent_scope.module.expect_local();
1520 let expn_id = self.parent_scope.expansion;
1521 let ident = variant.ident;
1522
1523 let def_id = feed.key();
1525 let vis = self.resolve_visibility(&variant.vis);
1526 self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1527 self.r.feed_visibility(feed, vis);
1528
1529 let ctor_vis =
1531 if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1532 Visibility::Restricted(CRATE_DEF_ID)
1533 } else {
1534 vis
1535 };
1536
1537 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
1539 let feed = self.create_def(
1540 ctor_node_id,
1541 None,
1542 DefKind::Ctor(CtorOf::Variant, ctor_kind),
1543 variant.span,
1544 );
1545 let ctor_def_id = feed.key();
1546 let ctor_res = self.res(ctor_def_id);
1547 self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1548 self.r.feed_visibility(feed, ctor_vis);
1549 }
1550
1551 self.insert_field_idents(def_id, variant.data.fields());
1553 self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1554
1555 visit::walk_variant(self, variant);
1556 }
1557}