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