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