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::diagnostics::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, errors,
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(errors::UnnamedImport {
710 span: ident.span,
711 sugg: errors::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(errors::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 errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
1058 );
1059 }
1060
1061 use indexmap::map::Entry;
1062 match self.r.extern_prelude.entry(ident) {
1063 Entry::Occupied(mut occupied) => {
1064 let entry = occupied.get_mut();
1065 if entry.item_decl.is_some() {
1066 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");
1067 self.r.tcx.dcx().span_delayed_bug(item.span, msg);
1068 } else {
1069 entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
1070 }
1071 entry
1072 }
1073 Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
1074 item_decl: Some((import_decl, orig_ident.span, true)),
1075 flag_decl: None,
1076 }),
1077 };
1078 }
1079 self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
1080 }
1081
1082 pub(crate) fn build_reduced_graph_for_foreign_item(
1084 &mut self,
1085 item: &ForeignItem,
1086 ident: Ident,
1087 feed: TyCtxtFeed<'tcx, LocalDefId>,
1088 ) {
1089 let local_def_id = feed.key();
1090 let def_id = local_def_id.to_def_id();
1091 let ns = match item.kind {
1092 ForeignItemKind::Fn(..) => ValueNS,
1093 ForeignItemKind::Static(..) => ValueNS,
1094 ForeignItemKind::TyAlias(..) => TypeNS,
1095 ForeignItemKind::MacCall(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1096 };
1097 let parent = self.parent_scope.module.expect_local();
1098 let expansion = self.parent_scope.expansion;
1099 let vis = self.resolve_visibility(&item.vis);
1100 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1101 self.r.feed_visibility(feed, vis);
1102 }
1103
1104 fn build_reduced_graph_for_block(&mut self, block: &Block) {
1105 let parent = self.parent_scope.module.expect_local();
1106 let expansion = self.parent_scope.expansion;
1107 if self.block_needs_anonymous_module(block) {
1108 let module = self.r.new_local_module(
1109 Some(parent),
1110 ModuleKind::Block,
1111 expansion.to_expn_id(),
1112 block.span,
1113 parent.no_implicit_prelude,
1114 );
1115 self.r.block_map.insert(block.id, module);
1116 self.parent_scope.module = module.to_module(); }
1118 }
1119
1120 fn add_macro_use_decl(
1121 &mut self,
1122 name: Symbol,
1123 decl: Decl<'ra>,
1124 span: Span,
1125 allow_shadowing: bool,
1126 ) {
1127 if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
1128 self.r.dcx().emit_err(errors::MacroUseNameAlreadyInUse { span, name });
1129 }
1130 }
1131
1132 fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1134 let mut import_all = None;
1135 let mut single_imports = ThinVec::new();
1136 if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
1137 AttributeParser::parse_limited(self.r.tcx.sess, &item.attrs, &[sym::macro_use])
1138 {
1139 if self.parent_scope.module.expect_local().parent.is_some() {
1140 self.r
1141 .dcx()
1142 .emit_err(errors::ExternCrateLoadingMacroNotAtCrateRoot { span: item.span });
1143 }
1144 if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1145 && orig_name == kw::SelfLower
1146 {
1147 self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span });
1148 }
1149
1150 match arguments {
1151 MacroUseArgs::UseAll => import_all = Some(span),
1152 MacroUseArgs::UseSpecific(imports) => single_imports = imports,
1153 }
1154 }
1155
1156 let macro_use_import = |this: &Self, span, warn_private| {
1157 this.r.arenas.alloc_import(ImportData {
1158 kind: ImportKind::MacroUse { warn_private },
1159 root_id: item.id,
1160 parent_scope: this.parent_scope,
1161 imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
1162 use_span_with_attributes: item.span_with_attributes(),
1163 has_attributes: !item.attrs.is_empty(),
1164 use_span: item.span,
1165 root_span: span,
1166 span,
1167 module_path: Vec::new(),
1168 vis: Visibility::Restricted(CRATE_DEF_ID),
1169 vis_span: item.vis.span,
1170 on_unknown_attr: OnUnknownData::from_attrs(this.r.tcx, item),
1171 })
1172 };
1173
1174 let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1175 if let Some(span) = import_all {
1176 let import = macro_use_import(self, span, false);
1177 self.r.potentially_unused_imports.push(import);
1178 module.for_each_child_mut(self, |this, ident, _, ns, binding| {
1179 if ns == MacroNS {
1180 let import =
1181 if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
1182 import
1183 } else {
1184 if this.r.macro_use_prelude.contains_key(&ident.name) {
1187 return;
1189 }
1190 macro_use_import(this, span, true)
1191 };
1192 let import_decl = this.r.new_import_decl(binding, import);
1193 this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
1194 }
1195 });
1196 } else {
1197 for ident in single_imports.iter().cloned() {
1198 let result = self.r.cm().maybe_resolve_ident_in_module(
1199 ModuleOrUniformRoot::Module(module),
1200 ident,
1201 MacroNS,
1202 &self.parent_scope,
1203 None,
1204 );
1205 if let Ok(binding) = result {
1206 let import = macro_use_import(self, ident.span, false);
1207 self.r.potentially_unused_imports.push(import);
1208 let import_decl = self.r.new_import_decl(binding, import);
1209 self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
1210 } else {
1211 self.r.dcx().emit_err(errors::ImportedMacroNotFound { span: ident.span });
1212 }
1213 }
1214 }
1215 import_all.is_some() || !single_imports.is_empty()
1216 }
1217
1218 pub(crate) fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
1220 for attr in attrs {
1221 if attr.has_name(sym::macro_escape) {
1222 let inner_attribute = #[allow(non_exhaustive_omitted_patterns)] match attr.style {
ast::AttrStyle::Inner => true,
_ => false,
}matches!(attr.style, ast::AttrStyle::Inner);
1223 self.r
1224 .dcx()
1225 .emit_warn(errors::MacroExternDeprecated { span: attr.span, inner_attribute });
1226 } else if !attr.has_name(sym::macro_use) {
1227 continue;
1228 }
1229
1230 if !attr.is_word() {
1231 self.r.dcx().emit_err(errors::ArgumentsMacroUseNotAllowed { span: attr.span });
1232 }
1233 return true;
1234 }
1235
1236 false
1237 }
1238
1239 pub(crate) fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
1240 let invoc_id = id.placeholder_to_expn_id();
1241 let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1242 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");
1243 invoc_id
1244 }
1245
1246 pub(crate) fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
1249 let invoc_id = self.visit_invoc(id);
1250 let module = self.parent_scope.module.expect_local();
1251 module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
1252 self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1253 }
1254
1255 fn proc_macro_stub(
1256 &self,
1257 item: &ast::Item,
1258 fn_ident: Ident,
1259 ) -> Option<(MacroKind, Ident, Span)> {
1260 if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1261 return Some((MacroKind::Bang, fn_ident, item.span));
1262 } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1263 return Some((MacroKind::Attr, fn_ident, item.span));
1264 } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1265 && let Some(meta_item_inner) =
1266 attr.meta_item_list().and_then(|list| list.get(0).cloned())
1267 && let Some(ident) = meta_item_inner.ident()
1268 {
1269 return Some((MacroKind::Derive, ident, ident.span));
1270 }
1271 None
1272 }
1273
1274 fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1278 if !ident.as_str().starts_with('_') {
1279 self.r.unused_macros.insert(def_id, (node_id, ident));
1280 if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
1281 let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
1282 self.r.unused_macro_rules.insert(node_id, value);
1283 }
1284 }
1285 }
1286
1287 fn define_macro(
1288 &mut self,
1289 item: &ast::Item,
1290 feed: TyCtxtFeed<'tcx, LocalDefId>,
1291 ) -> MacroRulesScopeRef<'ra> {
1292 let parent_scope = self.parent_scope;
1293 let expansion = parent_scope.expansion;
1294 let def_id = feed.key();
1295 let (res, orig_ident, span, macro_rules) = match &item.kind {
1296 ItemKind::MacroDef(ident, def) => {
1297 (self.res(def_id), *ident, item.span, def.macro_rules)
1298 }
1299 ItemKind::Fn(ast::Fn { ident: fn_ident, .. }) => {
1300 match self.proc_macro_stub(item, *fn_ident) {
1301 Some((macro_kind, ident, span)) => {
1302 let macro_kinds = macro_kind.into();
1303 let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1304 self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
1305 self.r.proc_macro_stubs.insert(def_id);
1306 (res, ident, span, false)
1307 }
1308 None => return parent_scope.macro_rules,
1309 }
1310 }
1311 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1312 };
1313
1314 self.r.local_macro_def_scopes.insert(def_id, parent_scope.module.expect_local());
1315
1316 if macro_rules {
1317 let ident = IdentKey::new(orig_ident);
1318 self.r.macro_names.insert(ident);
1319 let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1320 let vis = if is_macro_export {
1321 Visibility::Public
1322 } else {
1323 Visibility::Restricted(CRATE_DEF_ID)
1324 };
1325 let decl = self.r.arenas.new_def_decl(
1326 res,
1327 vis.to_def_id(),
1328 span,
1329 expansion,
1330 Some(parent_scope.module),
1331 );
1332 self.r.all_macro_rules.insert(ident.name);
1333 if is_macro_export {
1334 let import = self.r.arenas.alloc_import(ImportData {
1335 kind: ImportKind::MacroExport,
1336 root_id: item.id,
1337 parent_scope: ParentScope {
1338 module: self.r.graph_root.to_module(),
1339 ..parent_scope
1340 },
1341 imported_module: CmCell::new(None),
1342 has_attributes: false,
1343 use_span_with_attributes: span,
1344 use_span: span,
1345 root_span: span,
1346 span,
1347 module_path: Vec::new(),
1348 vis,
1349 vis_span: item.vis.span,
1350 on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
1351 });
1352 self.r.import_use_map.insert(import, Used::Other);
1353 let import_decl = self.r.new_import_decl(decl, import);
1354 self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
1355 } else {
1356 self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
1357 self.insert_unused_macro(orig_ident, def_id, item.id);
1358 }
1359 self.r.feed_visibility(feed, vis);
1360 let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
1361 self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
1362 parent_macro_rules_scope: parent_scope.macro_rules,
1363 decl,
1364 ident,
1365 orig_ident_span: orig_ident.span,
1366 }),
1367 ));
1368 self.r.macro_rules_scopes.insert(def_id, scope);
1369 scope
1370 } else {
1371 let module = parent_scope.module.expect_local();
1372 let vis = match item.kind {
1373 ItemKind::Fn(..) => self
1376 .r
1377 .try_resolve_visibility(&self.parent_scope, &item.vis, false)
1378 .unwrap_or(Visibility::Public),
1379 _ => self.resolve_visibility(&item.vis),
1380 };
1381 if !vis.is_public() {
1382 self.insert_unused_macro(orig_ident, def_id, item.id);
1383 }
1384 self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1385 self.r.feed_visibility(feed, vis);
1386 self.parent_scope.macro_rules
1387 }
1388 }
1389}
1390
1391impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
1392 pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
1393 let orig_module_scope = self.parent_scope.module;
1394 self.parent_scope.macro_rules = match item.kind {
1395 ItemKind::MacroDef(..) => {
1396 let macro_rules_scope = self.define_macro(item, feed);
1397 visit::walk_item(self, item);
1398 macro_rules_scope
1399 }
1400 _ => {
1401 let orig_macro_rules_scope = self.parent_scope.macro_rules;
1402 self.build_reduced_graph_for_item(item, feed);
1403 match item.kind {
1404 ItemKind::Mod(..) => {
1405 self.visit_vis(&item.vis);
1408 item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1409 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);
1410 }
1411 _ => visit::walk_item(self, item),
1412 }
1413 match item.kind {
1414 ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1415 self.parent_scope.macro_rules
1416 }
1417 _ => orig_macro_rules_scope,
1418 }
1419 }
1420 };
1421 self.parent_scope.module = orig_module_scope;
1422 }
1423
1424 pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
1427 self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
1428 }
1429
1430 pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
1431 let orig_current_module = self.parent_scope.module;
1432 let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1433 self.build_reduced_graph_for_block(block);
1434 visit::walk_block(self, block);
1435 self.parent_scope.module = orig_current_module;
1436 self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1437 }
1438
1439 pub(crate) fn brg_visit_assoc_item(
1440 &mut self,
1441 item: &'a AssocItem,
1442 ctxt: AssocCtxt,
1443 ident: Ident,
1444 ns: Namespace,
1445 feed: TyCtxtFeed<'tcx, LocalDefId>,
1446 ) {
1447 let vis = self.resolve_visibility(&item.vis);
1448 let local_def_id = feed.key();
1449 let def_id = local_def_id.to_def_id();
1450
1451 if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
AssocCtxt::Impl { of_trait: true } => true,
_ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1452 && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
ast::VisibilityKind::Inherited => true,
_ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1453 {
1454 self.r.feed_visibility(feed, vis);
1458 }
1459
1460 if ctxt == AssocCtxt::Trait {
1461 let parent = self.parent_scope.module.expect_local();
1462 let expansion = self.parent_scope.expansion;
1463 self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1464 } 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)
1465 && ident.name != kw::Underscore
1466 {
1467 let impl_def_id = self.r.tcx.local_parent(local_def_id);
1469 let key = BindingKey::new(IdentKey::new(ident), ns);
1470 self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1471 }
1472
1473 visit::walk_assoc_item(self, item, ctxt);
1474 }
1475
1476 pub(crate) fn visit_assoc_item_mac_call(
1477 &mut self,
1478 item: &'a Item<AssocItemKind>,
1479 ctxt: AssocCtxt,
1480 ) {
1481 match ctxt {
1482 AssocCtxt::Trait => {
1483 self.visit_invoc_in_module(item.id);
1484 }
1485 AssocCtxt::Impl { .. } => {
1486 let invoc_id = item.id.placeholder_to_expn_id();
1487 if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1488 self.r
1489 .impl_unexpanded_invocations
1490 .entry(self.r.invocation_parent(invoc_id))
1491 .or_default()
1492 .insert(invoc_id);
1493 }
1494 self.visit_invoc(item.id);
1495 }
1496 }
1497 }
1498
1499 pub(crate) fn brg_visit_field_def(
1500 &mut self,
1501 sf: &'a ast::FieldDef,
1502 feed: TyCtxtFeed<'tcx, LocalDefId>,
1503 ) {
1504 let vis = self.resolve_visibility(&sf.vis);
1505 self.r.feed_visibility(feed, vis);
1506 visit::walk_field_def(self, sf);
1507 }
1508
1509 pub(crate) fn brg_visit_variant(
1512 &mut self,
1513 variant: &'a ast::Variant,
1514 feed: TyCtxtFeed<'tcx, LocalDefId>,
1515 ) {
1516 let parent = self.parent_scope.module.expect_local();
1517 let expn_id = self.parent_scope.expansion;
1518 let ident = variant.ident;
1519
1520 let def_id = feed.key();
1522 let vis = self.resolve_visibility(&variant.vis);
1523 self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1524 self.r.feed_visibility(feed, vis);
1525
1526 let ctor_vis =
1528 if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1529 Visibility::Restricted(CRATE_DEF_ID)
1530 } else {
1531 vis
1532 };
1533
1534 if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
1536 let feed = self.create_def(
1537 ctor_node_id,
1538 None,
1539 DefKind::Ctor(CtorOf::Variant, ctor_kind),
1540 variant.span,
1541 );
1542 let ctor_def_id = feed.key();
1543 let ctor_res = self.res(ctor_def_id);
1544 self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1545 self.r.feed_visibility(feed, ctor_vis);
1546 }
1547
1548 self.insert_field_idents(def_id, variant.data.fields());
1550 self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1551
1552 visit::walk_variant(self, variant);
1553 }
1554}