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