//! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
//! that fragment into the module structures that are already partially built.
//!
//! Items from the fragment are placed into modules,
//! unexpanded macros in the fragment are visited and registered.
//! Imports are also considered items and placed into modules here, but not resolved yet.

use std::sync::Arc;

use rustc_ast::visit::{self, AssocCtxt, Visitor, WalkItemKind};
use rustc_ast::{
    self as ast, AssocItem, AssocItemKind, Block, ConstItem, DUMMY_NODE_ID, Delegation,
    DelegationSource, Fn, ForeignItem, ForeignItemKind, Inline, Item, ItemKind, NodeId, StaticItem,
    StmtKind, TraitAlias, TyAlias,
};
use rustc_attr_parsing::AttributeParser;
use rustc_expand::base::{ResolverExpand, SyntaxExtension, SyntaxExtensionKind};
use rustc_hir::Attribute;
use rustc_hir::attrs::{AttributeKind, MacroUseArgs};
use rustc_hir::def::{self, *};
use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
use rustc_index::bit_set::DenseBitSet;
use rustc_metadata::creader::LoadedMacro;
use rustc_middle::metadata::{ModChild, Reexport};
use rustc_middle::ty::{TyCtxtFeed, Visibility};
use rustc_middle::{bug, span_bug};
use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind};
use rustc_span::{Ident, Span, Symbol, kw, sym};
use thin_vec::ThinVec;
use tracing::debug;

use crate::Namespace::{MacroNS, TypeNS, ValueNS};
use crate::def_collector::DefCollector;
use crate::diagnostics::StructCtor;
use crate::imports::{ImportData, ImportKind, OnUnknownData};
use crate::macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
use crate::ref_mut::CmCell;
use crate::{
    BindingKey, Decl, DeclData, DeclKind, DelayedVisResolutionError, ExternModule,
    ExternPreludeEntry, Finalize, IdentKey, LocalModule, Module, ModuleKind, ModuleOrUniformRoot,
    ParentScope, PathResult, Res, Resolver, Segment, Used, VisResolutionError, errors,
};

impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
    /// Attempt to put the declaration with the given name and namespace into the module,
    /// and report an error in case of a collision.
    pub(crate) fn plant_decl_into_local_module(
        &mut self,
        ident: IdentKey,
        orig_ident_span: Span,
        ns: Namespace,
        decl: Decl<'ra>,
    ) {
        if let Err(old_decl) =
            self.try_plant_decl_into_local_module(ident, orig_ident_span, ns, decl)
        {
            self.report_conflict(ident, ns, old_decl, decl);
        }
    }

    /// Create a name definition from the given components, and put it into the local module.
    fn define_local(
        &mut self,
        parent: LocalModule<'ra>,
        orig_ident: Ident,
        ns: Namespace,
        res: Res,
        vis: Visibility,
        span: Span,
        expn_id: LocalExpnId,
    ) {
        let decl =
            self.arenas.new_def_decl(res, vis.to_def_id(), span, expn_id, Some(parent.to_module()));
        let ident = IdentKey::new(orig_ident);
        self.plant_decl_into_local_module(ident, orig_ident.span, ns, decl);
    }

    /// Create a name definition from the given components, and put it into the extern module.
    fn define_extern(
        &self,
        parent: ExternModule<'ra>,
        ident: IdentKey,
        orig_ident_span: Span,
        ns: Namespace,
        child_index: usize,
        res: Res,
        vis: Visibility<DefId>,
        span: Span,
        expansion: LocalExpnId,
        ambiguity: Option<(Decl<'ra>, bool)>,
    ) {
        let decl = self.arenas.alloc_decl(DeclData {
            kind: DeclKind::Def(res),
            ambiguity: CmCell::new(ambiguity),
            initial_vis: vis,
            ambiguity_vis_max: CmCell::new(None),
            ambiguity_vis_min: CmCell::new(None),
            span,
            expansion,
            parent_module: Some(parent.to_module()),
        });
        // Even if underscore names cannot be looked up, we still need to add them to modules,
        // because they can be fetched by glob imports from those modules, and bring traits
        // into scope both directly and through glob imports.
        let key =
            BindingKey::new_disambiguated(ident, ns, || (child_index + 1).try_into().unwrap()); // 0 indicates no underscore
        if self
            .resolution_or_default(parent.to_module(), key, orig_ident_span)
            .borrow_mut_unchecked()
            .non_glob_decl
            .replace(decl)
            .is_some()
        {
            span_bug!(span, "an external binding was already defined");
        }
    }

    /// Walks up the tree of definitions starting at `def_id`,
    /// stopping at the first encountered module.
    /// Parent block modules for arbitrary def-ids are not recorded for the local crate,
    /// and are not preserved in metadata for foreign crates, so block modules are never
    /// returned by this function.
    ///
    /// For the local crate ignoring block modules may be incorrect, so use this method with care.
    ///
    /// For foreign crates block modules can be ignored without introducing observable differences,
    /// moreover they has to be ignored right now because they are not kept in metadata.
    /// Foreign parent modules are used for resolving names used by foreign macros with def-site
    /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and
    /// block module parents being unreachable from other crates.
    /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`,
    /// but they cannot use def-site hygiene, so the assumption holds
    /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>).
    pub(crate) fn get_nearest_non_block_module(&self, mut def_id: DefId) -> Module<'ra> {
        loop {
            match self.get_module(def_id) {
                Some(module) => return module,
                None => def_id = self.tcx.parent(def_id),
            }
        }
    }

    pub(crate) fn expect_module(&self, def_id: DefId) -> Module<'ra> {
        self.get_module(def_id).expect("argument `DefId` is not a module")
    }

    /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum,
    /// or trait), then this function returns that module's resolver representation, otherwise it
    /// returns `None`.
    pub(crate) fn get_module(&self, def_id: DefId) -> Option<Module<'ra>> {
        match def_id.as_local() {
            Some(local_def_id) => self.local_module_map.get(&local_def_id).map(|m| m.to_module()),
            None => {
                if let module @ Some(..) = self.extern_module_map.borrow().get(&def_id) {
                    return module.map(|m| m.to_module());
                }

                // Query `def_kind` is not used because query system overhead is too expensive here.
                let def_kind = self.cstore().def_kind_untracked(def_id);
                if def_kind.is_module_like() {
                    let parent = self.tcx.opt_parent(def_id).map(|parent_id| {
                        self.get_nearest_non_block_module(parent_id).expect_extern()
                    });
                    // Query `expn_that_defined` is not used because
                    // hashing spans in its result is expensive.
                    let expn_id = self.cstore().expn_that_defined_untracked(self.tcx, def_id);
                    let module = self.new_extern_module(
                        parent,
                        ModuleKind::Def(
                            def_kind,
                            def_id,
                            DUMMY_NODE_ID,
                            Some(self.tcx.item_name(def_id)),
                        ),
                        expn_id,
                        self.def_span(def_id),
                        // FIXME: Account for `#[no_implicit_prelude]` attributes.
                        parent.is_some_and(|module| module.no_implicit_prelude),
                    );
                    return Some(module.to_module());
                }

                None
            }
        }
    }

    pub(crate) fn expn_def_scope(&self, expn_id: ExpnId) -> Module<'ra> {
        match expn_id.expn_data().macro_def_id {
            Some(def_id) => self.macro_def_scope(def_id),
            None => expn_id
                .as_local()
                .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied())
                .unwrap_or(self.graph_root)
                .to_module(),
        }
    }

    pub(crate) fn macro_def_scope(&self, def_id: DefId) -> Module<'ra> {
        if let Some(id) = def_id.as_local() {
            self.local_macro_def_scopes[&id].to_module()
        } else {
            self.get_nearest_non_block_module(def_id)
        }
    }

    /// Gets the `SyntaxExtension` corresponding to `res`.
    pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra Arc<SyntaxExtension>> {
        match res {
            Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
            Res::NonMacroAttr(_) => Some(self.non_macro_attr),
            _ => None,
        }
    }

    pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra Arc<SyntaxExtension> {
        // Local macros are always compiled.
        match def_id.as_local() {
            Some(local_def_id) => self.local_macro_map[&local_def_id],
            None => self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
                let loaded_macro = self.cstore().load_macro_untracked(self.tcx, def_id);
                let ext = match loaded_macro {
                    LoadedMacro::MacroDef { def, ident, attrs, span, edition } => {
                        self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition)
                    }
                    LoadedMacro::ProcMacro(ext) => ext,
                };

                self.arenas.alloc_macro(ext)
            }),
        }
    }

    /// Add every proc macro accessible from the current crate to the `macro_map` so diagnostics can
    /// find them for suggestions.
    pub(crate) fn register_macros_for_all_crates(&mut self) {
        if !self.all_crate_macros_already_registered {
            for def_id in self.cstore().all_proc_macro_def_ids(self.tcx) {
                self.get_macro_by_def_id(def_id);
            }
            self.all_crate_macros_already_registered = true;
        }
    }

    pub(crate) fn try_resolve_visibility(
        &mut self,
        parent_scope: &ParentScope<'ra>,
        vis: &ast::Visibility,
        finalize: bool,
    ) -> Result<Visibility, VisResolutionError> {
        match vis.kind {
            ast::VisibilityKind::Public => Ok(Visibility::Public),
            ast::VisibilityKind::Inherited => {
                Ok(match parent_scope.module.expect_local().kind {
                    // Any inherited visibility resolved directly inside an enum or trait
                    // (i.e. variants, fields, and trait items) inherits from the visibility
                    // of the enum or trait.
                    ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _, _) => {
                        self.tcx.visibility(def_id).expect_local()
                    }
                    // Otherwise, the visibility is restricted to the nearest parent `mod` item.
                    _ => Visibility::Restricted(
                        parent_scope.module.nearest_parent_mod().expect_local(),
                    ),
                })
            }
            ast::VisibilityKind::Restricted { ref path, id, .. } => {
                // For visibilities we are not ready to provide correct implementation of "uniform
                // paths" right now, so on 2018 edition we only allow module-relative paths for now.
                // On 2015 edition visibilities are resolved as crate-relative by default,
                // so we are prepending a root segment if necessary.
                let ident = path.segments.get(0).expect("empty path in visibility").ident;
                let crate_root = if ident.is_path_segment_keyword() {
                    None
                } else if ident.span.is_rust_2015() {
                    Some(Segment::from_ident(Ident::new(
                        kw::PathRoot,
                        path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
                    )))
                } else {
                    return Err(VisResolutionError::Relative2018(
                        ident.span,
                        path.as_ref().clone(),
                    ));
                };
                let segments = crate_root
                    .into_iter()
                    .chain(path.segments.iter().map(|seg| seg.into()))
                    .collect::<Vec<_>>();
                let expected_found_error = |res| {
                    Err(VisResolutionError::ExpectedFound(
                        path.span,
                        Segment::names_to_string(&segments),
                        res,
                    ))
                };
                match self.cm().resolve_path(
                    &segments,
                    None,
                    parent_scope,
                    finalize.then(|| Finalize::new(id, path.span)),
                    None,
                    None,
                ) {
                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
                        let res = module.res().expect("visibility resolved to unnamed block");
                        if module.is_normal() {
                            match res {
                                Res::Err => {
                                    if finalize {
                                        self.record_partial_res(id, PartialRes::new(res));
                                    }
                                    Ok(Visibility::Public)
                                }
                                _ => {
                                    let vis = Visibility::Restricted(res.def_id());
                                    if self.is_accessible_from(vis, parent_scope.module) {
                                        if finalize {
                                            self.record_partial_res(id, PartialRes::new(res));
                                        }
                                        Ok(vis.expect_local())
                                    } else {
                                        Err(VisResolutionError::AncestorOnly(path.span))
                                    }
                                }
                            }
                        } else {
                            expected_found_error(res)
                        }
                    }
                    PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
                    PathResult::NonModule(partial_res) => {
                        expected_found_error(partial_res.expect_full_res())
                    }
                    PathResult::Failed { label, suggestion, message, segment, .. } => {
                        Err(VisResolutionError::FailedToResolve(
                            segment.span,
                            segment.name,
                            label,
                            suggestion,
                            message,
                        ))
                    }
                    PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
                }
            }
        }
    }

    pub(crate) fn build_reduced_graph_external(&self, module: ExternModule<'ra>) {
        let def_id = module.def_id();
        let children = self.tcx.module_children(def_id);
        for (i, child) in children.iter().enumerate() {
            self.build_reduced_graph_for_external_crate_res(child, module, i, None)
        }
        for (i, child) in
            self.cstore().ambig_module_children_untracked(self.tcx, def_id).enumerate()
        {
            self.build_reduced_graph_for_external_crate_res(
                &child.main,
                module,
                children.len() + i,
                Some(&child.second),
            )
        }
    }

    /// Builds the reduced graph for a single item in an external crate.
    fn build_reduced_graph_for_external_crate_res(
        &self,
        child: &ModChild,
        parent: ExternModule<'ra>,
        child_index: usize,
        ambig_child: Option<&ModChild>,
    ) {
        let child_span = |this: &Self, reexport_chain: &[Reexport], res: def::Res<_>| {
            this.def_span(
                reexport_chain
                    .first()
                    .and_then(|reexport| reexport.id())
                    .unwrap_or_else(|| res.def_id()),
            )
        };
        let ModChild { ident: orig_ident, res, vis, ref reexport_chain } = *child;
        let ident = IdentKey::new(orig_ident);
        let span = child_span(self, reexport_chain, res);
        let res = res.expect_non_local();
        let expansion = LocalExpnId::ROOT;
        let ambig = ambig_child.map(|ambig_child| {
            let ModChild { ident: _, res, vis, ref reexport_chain } = *ambig_child;
            let span = child_span(self, reexport_chain, res);
            let res = res.expect_non_local();
            // External ambiguities always report the `AMBIGUOUS_GLOB_IMPORTS` lint at the moment.
            (self.arenas.new_def_decl(res, vis, span, expansion, Some(parent.to_module())), true)
        });

        // Record primary definitions.
        let define_extern = |ns| {
            self.define_extern(
                parent,
                ident,
                orig_ident.span,
                ns,
                child_index,
                res,
                vis,
                span,
                expansion,
                ambig,
            )
        };
        match res {
            Res::Def(
                DefKind::Mod
                | DefKind::Enum
                | DefKind::Trait
                | DefKind::Struct
                | DefKind::Union
                | DefKind::Variant
                | DefKind::TyAlias
                | DefKind::ForeignTy
                | DefKind::OpaqueTy
                | DefKind::TraitAlias
                | DefKind::AssocTy,
                _,
            )
            | Res::PrimTy(..)
            | Res::ToolMod => define_extern(TypeNS),
            Res::Def(
                DefKind::Fn
                | DefKind::AssocFn
                | DefKind::Static { .. }
                | DefKind::Const { .. }
                | DefKind::AssocConst { .. }
                | DefKind::Ctor(..),
                _,
            ) => define_extern(ValueNS),
            Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => define_extern(MacroNS),
            Res::Def(
                DefKind::TyParam
                | DefKind::ConstParam
                | DefKind::ExternCrate
                | DefKind::Use
                | DefKind::ForeignMod
                | DefKind::AnonConst
                | DefKind::InlineConst
                | DefKind::Field
                | DefKind::LifetimeParam
                | DefKind::GlobalAsm
                | DefKind::Closure
                | DefKind::SyntheticCoroutineBody
                | DefKind::Impl { .. },
                _,
            )
            | Res::Local(..)
            | Res::SelfTyParam { .. }
            | Res::SelfTyAlias { .. }
            | Res::SelfCtor(..)
            | Res::OpenMod(..)
            | Res::Err => bug!("unexpected resolution: {:?}", res),
        }
    }
}

impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for DefCollector<'_, 'ra, 'tcx> {
    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
        self.r
    }
}

impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
    fn res(&self, def_id: impl Into<DefId>) -> Res {
        let def_id = def_id.into();
        Res::Def(self.r.tcx.def_kind(def_id), def_id)
    }

    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> Visibility {
        match self.r.try_resolve_visibility(&self.parent_scope, vis, true) {
            Ok(vis) => vis,
            Err(error) => {
                self.r.delayed_vis_resolution_errors.push(DelayedVisResolutionError {
                    vis: vis.clone(),
                    parent_scope: self.parent_scope,
                    error,
                });
                Visibility::Public
            }
        }
    }

    fn insert_field_idents(&mut self, def_id: LocalDefId, fields: &[ast::FieldDef]) {
        if fields.iter().any(|field| field.is_placeholder) {
            // The fields are not expanded yet.
            return;
        }
        let field_name = |i, field: &ast::FieldDef| {
            field.ident.unwrap_or_else(|| Ident::from_str_and_span(&format!("{i}"), field.span))
        };
        let field_names: Vec<_> =
            fields.iter().enumerate().map(|(i, field)| field_name(i, field)).collect();
        let defaults = fields
            .iter()
            .enumerate()
            .filter_map(|(i, field)| field.default.as_ref().map(|_| field_name(i, field).name))
            .collect();
        self.r.field_names.insert(def_id, field_names);
        self.r.field_defaults.insert(def_id, defaults);
    }

    fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {
        let field_vis = fields
            .iter()
            .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span)))
            .collect();
        self.r.field_visibility_spans.insert(def_id, field_vis);
    }

    fn block_needs_anonymous_module(&self, block: &Block) -> bool {
        // If any statements are items, we need to create an anonymous module
        block
            .stmts
            .iter()
            .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
    }

    // Add an import to the current module.
    fn add_import(
        &mut self,
        module_path: Vec<Segment>,
        kind: ImportKind<'ra>,
        span: Span,
        item: &ast::Item,
        root_span: Span,
        root_id: NodeId,
        vis: Visibility,
    ) {
        let current_module = self.parent_scope.module.expect_local();
        let import = self.r.arenas.alloc_import(ImportData {
            kind,
            parent_scope: self.parent_scope,
            module_path,
            imported_module: CmCell::new(None),
            span,
            use_span: item.span,
            use_span_with_attributes: item.span_with_attributes(),
            has_attributes: !item.attrs.is_empty(),
            root_span,
            root_id,
            vis,
            vis_span: item.vis.span,
            on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
        });

        self.r.indeterminate_imports.push(import);
        match import.kind {
            ImportKind::Single { target, .. } => {
                // Don't add underscore imports to `single_imports`
                // because they cannot define any usable names.
                if target.name != kw::Underscore {
                    self.r.per_ns(|this, ns| {
                        let key = BindingKey::new(IdentKey::new(target), ns);
                        this.resolution_or_default(current_module.to_module(), key, target.span)
                            .borrow_mut(this)
                            .single_imports
                            .insert(import);
                    });
                }
            }
            ImportKind::Glob { .. } => current_module.globs.borrow_mut(self.r).push(import),
            _ => unreachable!(),
        }
    }

    fn build_reduced_graph_for_use_tree(
        &mut self,
        // This particular use tree
        use_tree: &ast::UseTree,
        id: NodeId,
        parent_prefix: &[Segment],
        nested: bool,
        list_stem: bool,
        // The whole `use` item
        item: &Item,
        vis: Visibility,
        root_span: Span,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) {
        debug!(
            "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
            parent_prefix, use_tree, nested
        );

        // Top level use tree reuses the item's id and list stems reuse their parent
        // use tree's ids, so in both cases their visibilities are already filled.
        if nested && !list_stem {
            self.r.feed_visibility(feed, vis);
        }

        let mut prefix_iter = parent_prefix
            .iter()
            .cloned()
            .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
            .peekable();

        // On 2015 edition imports are resolved as crate-relative by default,
        // so prefixes are prepended with crate root segment if necessary.
        // The root is prepended lazily, when the first non-empty prefix or terminating glob
        // appears, so imports in braced groups can have roots prepended independently.
        let crate_root = match prefix_iter.peek() {
            Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => {
                Some(seg.ident.span.ctxt())
            }
            None if let ast::UseTreeKind::Glob(span) = use_tree.kind
                && span.is_rust_2015() =>
            {
                Some(span.ctxt())
            }
            _ => None,
        }
        .map(|ctxt| {
            Segment::from_ident(Ident::new(
                kw::PathRoot,
                use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
            ))
        });

        let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
        debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);

        match use_tree.kind {
            ast::UseTreeKind::Simple(rename) => {
                let mut module_path = prefix;
                let source = module_path.pop().unwrap();

                // If the identifier is `self` without a rename,
                // then it is replaced with the parent identifier.
                let ident = if source.ident.name == kw::SelfLower
                    && rename.is_none()
                    && let Some(parent) = module_path.last()
                {
                    Ident::new(parent.ident.name, source.ident.span)
                } else {
                    use_tree.ident()
                };

                match source.ident.name {
                    kw::DollarCrate => {
                        if !module_path.is_empty() {
                            self.r.dcx().span_err(
                                source.ident.span,
                                "`$crate` in paths can only be used in start position",
                            );
                            return;
                        }
                    }
                    kw::Crate => {
                        if !module_path.is_empty() {
                            self.r.dcx().span_err(
                                source.ident.span,
                                "`crate` in paths can only be used in start position",
                            );
                            return;
                        }
                    }
                    kw::Super => {
                        // Allow `self::super` as a valid prefix - `self` at position 0
                        // followed by any number of `super` segments.
                        let valid_prefix = module_path.iter().enumerate().all(|(i, seg)| {
                            let name = seg.ident.name;
                            name == kw::Super || (name == kw::SelfLower && i == 0)
                        });

                        if !valid_prefix {
                            self.r.dcx().span_err(
                                source.ident.span,
                                "`super` in paths can only be used in start position, after `self`, or after another `super`",
                            );
                            return;
                        }
                    }
                    // Deny `use ::{self};` after edition 2015
                    kw::SelfLower
                        if let Some(parent) = module_path.last()
                            && parent.ident.name == kw::PathRoot
                            && !self.r.path_root_is_crate_root(parent.ident) =>
                    {
                        self.r.dcx().span_err(use_tree.span(), "extern prelude cannot be imported");
                        return;
                    }
                    _ => (),
                }

                // Deny `use ...::self::source [as target];` or `use ...::self::self [as target];`,
                // but allow `use self::source [as target];` and `use self::self as target;`.
                if let Some(parent) = module_path.last()
                    && parent.ident.name == kw::SelfLower
                    && module_path.len() > 1
                {
                    self.r.dcx().span_err(
                        parent.ident.span,
                        "`self` in paths can only be used in start position or last position",
                    );
                    return;
                }

                // Deny importing path-kw without renaming
                if rename.is_none() && ident.is_path_segment_keyword() {
                    let ident = use_tree.ident();
                    self.r.dcx().emit_err(errors::UnnamedImport {
                        span: ident.span,
                        sugg: errors::UnnamedImportSugg { span: ident.span, ident },
                    });
                    return;
                }

                let kind = ImportKind::Single {
                    source: source.ident,
                    target: ident,
                    decls: Default::default(),
                    nested,
                    id,
                    def_id: feed.def_id(),
                };

                self.add_import(module_path, kind, use_tree.span(), item, root_span, item.id, vis);
            }
            ast::UseTreeKind::Glob(_) => {
                if !ast::attr::contains_name(&item.attrs, sym::prelude_import) {
                    let kind =
                        ImportKind::Glob { max_vis: CmCell::new(None), id, def_id: feed.def_id() };
                    self.add_import(prefix, kind, use_tree.span(), item, root_span, item.id, vis);
                } else {
                    // Resolve the prelude import early.
                    let path_res =
                        self.r.cm().maybe_resolve_path(&prefix, None, &self.parent_scope, None);
                    if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = path_res {
                        self.r.prelude = Some(module);
                    } else {
                        self.r.dcx().span_err(use_tree.span(), "cannot resolve a prelude import");
                    }
                }
            }
            ast::UseTreeKind::Nested { ref items, .. } => {
                for &(ref tree, id) in items {
                    self.with_owner(id, None, DefKind::Use, use_tree.span(), |this, feed| {
                        this.build_reduced_graph_for_use_tree(
                            // This particular use tree
                            tree, id, &prefix, true, false, // The whole `use` item
                            item, vis, root_span, feed,
                        )
                    });
                }

                // Empty groups `a::b::{}` are turned into synthetic `self` imports
                // `a::b::c::{self as _}`, so that their prefixes are correctly
                // resolved and checked for privacy/stability/etc.
                if items.is_empty()
                    && !prefix.is_empty()
                    && (prefix.len() > 1 || prefix[0].ident.name != kw::PathRoot)
                {
                    let new_span = prefix[prefix.len() - 1].ident.span;
                    let tree = ast::UseTree {
                        prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
                        kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))),
                    };
                    self.build_reduced_graph_for_use_tree(
                        // This particular use tree
                        &tree,
                        id,
                        &prefix,
                        true,
                        true,
                        // The whole `use` item
                        item,
                        Visibility::Restricted(
                            self.parent_scope.module.nearest_parent_mod().expect_local(),
                        ),
                        root_span,
                        feed,
                    );
                }
            }
        }
    }

    fn build_reduced_graph_for_struct_variant(
        &mut self,
        fields: &[ast::FieldDef],
        ident: Ident,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
        adt_res: Res,
        adt_vis: Visibility,
        adt_span: Span,
    ) {
        let parent_scope = &self.parent_scope;
        let parent = parent_scope.module.expect_local();
        let expansion = parent_scope.expansion;

        // Define a name in the type namespace if it is not anonymous.
        self.r.define_local(parent, ident, TypeNS, adt_res, adt_vis, adt_span, expansion);
        self.r.feed_visibility(feed, adt_vis);
        let def_id = feed.key();

        // Record field names for error reporting.
        self.insert_field_idents(def_id, fields);
        self.insert_field_visibilities_local(def_id.to_def_id(), fields);
    }

    /// Constructs the reduced graph for one item.
    fn build_reduced_graph_for_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
        let parent_scope = &self.parent_scope;
        let parent = parent_scope.module.expect_local();
        let expansion = parent_scope.expansion;
        let sp = item.span;
        let vis = self.resolve_visibility(&item.vis);
        let local_def_id = feed.key();
        let def_id = local_def_id.to_def_id();
        let def_kind = self.r.tcx.def_kind(def_id);
        let res = Res::Def(def_kind, def_id);

        self.r.feed_visibility(feed, vis);

        match item.kind {
            ItemKind::Use(ref use_tree) => {
                self.build_reduced_graph_for_use_tree(
                    // This particular use tree
                    use_tree,
                    item.id,
                    &[],
                    false,
                    false,
                    // The whole `use` item
                    item,
                    vis,
                    use_tree.span(),
                    feed,
                );
            }

            ItemKind::ExternCrate(orig_name, ident) => {
                self.build_reduced_graph_for_extern_crate(
                    orig_name,
                    item,
                    ident,
                    local_def_id,
                    vis,
                );
            }

            ItemKind::Mod(_, ident, ref mod_kind) => {
                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);

                if let ast::ModKind::Loaded(_, Inline::No { had_parse_error: Err(_) }, _) = mod_kind
                {
                    self.r.mods_with_parse_errors.insert(def_id);
                }
                let module = self.r.new_local_module(
                    Some(parent),
                    ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
                    expansion.to_expn_id(),
                    item.span,
                    parent.no_implicit_prelude
                        || ast::attr::contains_name(&item.attrs, sym::no_implicit_prelude),
                );
                self.parent_scope.module = module.to_module();
            }

            // These items live in the value namespace.
            ItemKind::Const(ConstItem { ident, .. })
            | ItemKind::Delegation(Delegation { ident, .. })
            | ItemKind::Static(StaticItem { ident, .. }) => {
                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
            }
            ItemKind::Fn(Fn { ident, .. }) => {
                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);

                // Functions introducing procedural macros reserve a slot
                // in the macro namespace as well (see #52225).
                self.define_macro(item, feed);
            }

            // These items live in the type namespace.
            ItemKind::TyAlias(TyAlias { ident, .. })
            | ItemKind::TraitAlias(TraitAlias { ident, .. }) => {
                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
            }

            ItemKind::Enum(ident, _, _) | ItemKind::Trait(ast::Trait { ident, .. }) => {
                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);

                let module = self.r.new_local_module(
                    Some(parent),
                    ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
                    expansion.to_expn_id(),
                    item.span,
                    parent.no_implicit_prelude,
                );
                self.parent_scope.module = module.to_module();
            }

            // These items live in both the type and value namespaces.
            ItemKind::Struct(ident, ref generics, ref vdata) => {
                self.build_reduced_graph_for_struct_variant(
                    vdata.fields(),
                    ident,
                    feed,
                    res,
                    vis,
                    sp,
                );

                // If this is a tuple or unit struct, define a name
                // in the value namespace as well.
                if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) {
                    // If the structure is marked as non_exhaustive then lower the visibility
                    // to within the crate.
                    let mut ctor_vis = if vis.is_public()
                        && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
                    {
                        Visibility::Restricted(CRATE_DEF_ID)
                    } else {
                        vis
                    };

                    let mut field_visibilities = Vec::with_capacity(vdata.fields().len());

                    for field in vdata.fields() {
                        // NOTE: The field may be an expansion placeholder, but expansion sets
                        // correct visibilities for unnamed field placeholders specifically, so the
                        // constructor visibility should still be determined correctly.
                        let field_vis = self
                            .r
                            .try_resolve_visibility(&self.parent_scope, &field.vis, false)
                            .unwrap_or(Visibility::Public);
                        if ctor_vis.greater_than(field_vis, self.r.tcx) {
                            ctor_vis = field_vis;
                        }
                        field_visibilities.push(field_vis.to_def_id());
                    }
                    // If this is a unit or tuple-like struct, register the constructor.
                    let feed = self.create_def(
                        ctor_node_id,
                        None,
                        DefKind::Ctor(CtorOf::Struct, ctor_kind),
                        item.span,
                    );

                    let ctor_def_id = feed.key();
                    let ctor_res = self.res(ctor_def_id);
                    self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, sp, expansion);
                    self.r.feed_visibility(feed, ctor_vis);
                    // We need the field visibility spans also for the constructor for E0603.
                    self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());

                    let ctor =
                        StructCtor { res: ctor_res, vis: ctor_vis.to_def_id(), field_visibilities };
                    self.r.struct_ctors.insert(local_def_id, ctor);
                }
                self.r.struct_generics.insert(local_def_id, generics.clone());
            }

            ItemKind::Union(ident, _, ref vdata) => {
                self.build_reduced_graph_for_struct_variant(
                    vdata.fields(),
                    ident,
                    feed,
                    res,
                    vis,
                    sp,
                );
            }

            // These items do not add names to modules.
            ItemKind::Impl { .. }
            | ItemKind::ForeignMod(..)
            | ItemKind::GlobalAsm(..)
            | ItemKind::ConstBlock(..) => {}

            ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
                unreachable!()
            }
        }
    }

    fn build_reduced_graph_for_extern_crate(
        &mut self,
        orig_name: Option<Symbol>,
        item: &Item,
        orig_ident: Ident,
        local_def_id: LocalDefId,
        vis: Visibility,
    ) {
        let sp = item.span;
        let parent_scope = self.parent_scope;
        let parent = parent_scope.module;
        let expansion = parent_scope.expansion;

        let (used, module, decl) = if orig_name.is_none() && orig_ident.name == kw::SelfLower {
            self.r.dcx().emit_err(errors::ExternCrateSelfRequiresRenaming { span: sp });
            return;
        } else if orig_name == Some(kw::SelfLower) {
            Some(self.r.graph_root.to_module())
        } else {
            let tcx = self.r.tcx;
            let crate_id = self.r.cstore_mut().process_extern_crate(
                self.r.tcx,
                item,
                local_def_id,
                &tcx.definitions_untracked(),
            );
            crate_id.map(|crate_id| {
                self.r.extern_crate_map.insert(local_def_id, crate_id);
                self.r.expect_module(crate_id.as_def_id())
            })
        }
        .map(|module| {
            let used = self.process_macro_use_imports(item, module);
            let decl = self.r.arenas.new_pub_def_decl(module.res().unwrap(), sp, expansion);
            (used, Some(ModuleOrUniformRoot::Module(module)), decl)
        })
        .unwrap_or((true, None, self.r.dummy_decl));
        let import = self.r.arenas.alloc_import(ImportData {
            kind: ImportKind::ExternCrate {
                source: orig_name,
                target: orig_ident,
                id: item.id,
                def_id: local_def_id,
            },
            root_id: item.id,
            parent_scope,
            imported_module: CmCell::new(module),
            has_attributes: !item.attrs.is_empty(),
            use_span_with_attributes: item.span_with_attributes(),
            use_span: item.span,
            root_span: item.span,
            span: item.span,
            module_path: Vec::new(),
            vis,
            vis_span: item.vis.span,
            on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
        });
        if used {
            self.r.import_use_map.insert(import, Used::Other);
        }
        self.r.potentially_unused_imports.push(import);
        let import_decl = self.r.new_import_decl(decl, import);
        let ident = IdentKey::new(orig_ident);
        if ident.name != kw::Underscore && parent == self.r.graph_root.to_module() {
            // FIXME: this error is technically unnecessary now when extern prelude is split into
            // two scopes, remove it with lang team approval.
            if let Some(entry) = self.r.extern_prelude.get(&ident)
                && expansion != LocalExpnId::ROOT
                && orig_name.is_some()
                && entry.item_decl.is_none()
            {
                self.r.dcx().emit_err(
                    errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
                );
            }

            use indexmap::map::Entry;
            match self.r.extern_prelude.entry(ident) {
                Entry::Occupied(mut occupied) => {
                    let entry = occupied.get_mut();
                    if entry.item_decl.is_some() {
                        let msg = format!("extern crate `{orig_ident}` already in extern prelude");
                        self.r.tcx.dcx().span_delayed_bug(item.span, msg);
                    } else {
                        entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
                    }
                    entry
                }
                Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
                    item_decl: Some((import_decl, orig_ident.span, true)),
                    flag_decl: None,
                }),
            };
        }
        self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
    }

    /// Constructs the reduced graph for one foreign item.
    pub(crate) fn build_reduced_graph_for_foreign_item(
        &mut self,
        item: &ForeignItem,
        ident: Ident,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) {
        let local_def_id = feed.key();
        let def_id = local_def_id.to_def_id();
        let ns = match item.kind {
            ForeignItemKind::Fn(..) => ValueNS,
            ForeignItemKind::Static(..) => ValueNS,
            ForeignItemKind::TyAlias(..) => TypeNS,
            ForeignItemKind::MacCall(..) => unreachable!(),
        };
        let parent = self.parent_scope.module.expect_local();
        let expansion = self.parent_scope.expansion;
        let vis = self.resolve_visibility(&item.vis);
        self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
        self.r.feed_visibility(feed, vis);
    }

    fn build_reduced_graph_for_block(&mut self, block: &Block) {
        let parent = self.parent_scope.module.expect_local();
        let expansion = self.parent_scope.expansion;
        if self.block_needs_anonymous_module(block) {
            let module = self.r.new_local_module(
                Some(parent),
                ModuleKind::Block,
                expansion.to_expn_id(),
                block.span,
                parent.no_implicit_prelude,
            );
            self.r.block_map.insert(block.id, module);
            self.parent_scope.module = module.to_module(); // Descend into the block.
        }
    }

    fn add_macro_use_decl(
        &mut self,
        name: Symbol,
        decl: Decl<'ra>,
        span: Span,
        allow_shadowing: bool,
    ) {
        if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
            self.r.dcx().emit_err(errors::MacroUseNameAlreadyInUse { span, name });
        }
    }

    /// Returns `true` if we should consider the underlying `extern crate` to be used.
    fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
        let mut import_all = None;
        let mut single_imports = ThinVec::new();
        if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
            AttributeParser::parse_limited(self.r.tcx.sess, &item.attrs, &[sym::macro_use])
        {
            if self.parent_scope.module.expect_local().parent.is_some() {
                self.r
                    .dcx()
                    .emit_err(errors::ExternCrateLoadingMacroNotAtCrateRoot { span: item.span });
            }
            if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
                && orig_name == kw::SelfLower
            {
                self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span });
            }

            match arguments {
                MacroUseArgs::UseAll => import_all = Some(span),
                MacroUseArgs::UseSpecific(imports) => single_imports = imports,
            }
        }

        let macro_use_import = |this: &Self, span, warn_private| {
            this.r.arenas.alloc_import(ImportData {
                kind: ImportKind::MacroUse { warn_private },
                root_id: item.id,
                parent_scope: this.parent_scope,
                imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
                use_span_with_attributes: item.span_with_attributes(),
                has_attributes: !item.attrs.is_empty(),
                use_span: item.span,
                root_span: span,
                span,
                module_path: Vec::new(),
                vis: Visibility::Restricted(CRATE_DEF_ID),
                vis_span: item.vis.span,
                on_unknown_attr: OnUnknownData::from_attrs(this.r.tcx, item),
            })
        };

        let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
        if let Some(span) = import_all {
            let import = macro_use_import(self, span, false);
            self.r.potentially_unused_imports.push(import);
            module.for_each_child_mut(self, |this, ident, _, ns, binding| {
                if ns == MacroNS {
                    let import =
                        if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
                            import
                        } else {
                            // FIXME: This branch is used for reporting the `private_macro_use` lint
                            // and should eventually be removed.
                            if this.r.macro_use_prelude.contains_key(&ident.name) {
                                // Do not override already existing entries with compatibility entries.
                                return;
                            }
                            macro_use_import(this, span, true)
                        };
                    let import_decl = this.r.new_import_decl(binding, import);
                    this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
                }
            });
        } else {
            for ident in single_imports.iter().cloned() {
                let result = self.r.cm().maybe_resolve_ident_in_module(
                    ModuleOrUniformRoot::Module(module),
                    ident,
                    MacroNS,
                    &self.parent_scope,
                    None,
                );
                if let Ok(binding) = result {
                    let import = macro_use_import(self, ident.span, false);
                    self.r.potentially_unused_imports.push(import);
                    let import_decl = self.r.new_import_decl(binding, import);
                    self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
                } else {
                    self.r.dcx().emit_err(errors::ImportedMacroNotFound { span: ident.span });
                }
            }
        }
        import_all.is_some() || !single_imports.is_empty()
    }

    /// Returns `true` if this attribute list contains `macro_use`.
    pub(crate) fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
        for attr in attrs {
            if attr.has_name(sym::macro_escape) {
                let inner_attribute = matches!(attr.style, ast::AttrStyle::Inner);
                self.r
                    .dcx()
                    .emit_warn(errors::MacroExternDeprecated { span: attr.span, inner_attribute });
            } else if !attr.has_name(sym::macro_use) {
                continue;
            }

            if !attr.is_word() {
                self.r.dcx().emit_err(errors::ArgumentsMacroUseNotAllowed { span: attr.span });
            }
            return true;
        }

        false
    }

    pub(crate) fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
        let invoc_id = id.placeholder_to_expn_id();
        let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
        assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
        invoc_id
    }

    /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`)
    /// directly into its parent scope's module.
    pub(crate) fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
        let invoc_id = self.visit_invoc(id);
        let module = self.parent_scope.module.expect_local();
        module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
        self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
    }

    fn proc_macro_stub(
        &self,
        item: &ast::Item,
        fn_ident: Ident,
    ) -> Option<(MacroKind, Ident, Span)> {
        if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
            return Some((MacroKind::Bang, fn_ident, item.span));
        } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
            return Some((MacroKind::Attr, fn_ident, item.span));
        } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
            && let Some(meta_item_inner) =
                attr.meta_item_list().and_then(|list| list.get(0).cloned())
            && let Some(ident) = meta_item_inner.ident()
        {
            return Some((MacroKind::Derive, ident, ident.span));
        }
        None
    }

    // Mark the given macro as unused unless its name starts with `_`.
    // Macro uses will remove items from this set, and the remaining
    // items will be reported as `unused_macros`.
    fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
        if !ident.as_str().starts_with('_') {
            self.r.unused_macros.insert(def_id, (node_id, ident));
            if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
                let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
                self.r.unused_macro_rules.insert(node_id, value);
            }
        }
    }

    fn define_macro(
        &mut self,
        item: &ast::Item,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) -> MacroRulesScopeRef<'ra> {
        let parent_scope = self.parent_scope;
        let expansion = parent_scope.expansion;
        let def_id = feed.key();
        let (res, orig_ident, span, macro_rules) = match &item.kind {
            ItemKind::MacroDef(ident, def) => {
                (self.res(def_id), *ident, item.span, def.macro_rules)
            }
            ItemKind::Fn(ast::Fn { ident: fn_ident, .. }) => {
                match self.proc_macro_stub(item, *fn_ident) {
                    Some((macro_kind, ident, span)) => {
                        let macro_kinds = macro_kind.into();
                        let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
                        self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
                        self.r.proc_macro_stubs.insert(def_id);
                        (res, ident, span, false)
                    }
                    None => return parent_scope.macro_rules,
                }
            }
            _ => unreachable!(),
        };

        self.r.local_macro_def_scopes.insert(def_id, parent_scope.module.expect_local());

        if macro_rules {
            let ident = IdentKey::new(orig_ident);
            self.r.macro_names.insert(ident);
            let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
            let vis = if is_macro_export {
                Visibility::Public
            } else {
                Visibility::Restricted(CRATE_DEF_ID)
            };
            let decl = self.r.arenas.new_def_decl(
                res,
                vis.to_def_id(),
                span,
                expansion,
                Some(parent_scope.module),
            );
            self.r.all_macro_rules.insert(ident.name);
            if is_macro_export {
                let import = self.r.arenas.alloc_import(ImportData {
                    kind: ImportKind::MacroExport,
                    root_id: item.id,
                    parent_scope: ParentScope {
                        module: self.r.graph_root.to_module(),
                        ..parent_scope
                    },
                    imported_module: CmCell::new(None),
                    has_attributes: false,
                    use_span_with_attributes: span,
                    use_span: span,
                    root_span: span,
                    span,
                    module_path: Vec::new(),
                    vis,
                    vis_span: item.vis.span,
                    on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
                });
                self.r.import_use_map.insert(import, Used::Other);
                let import_decl = self.r.new_import_decl(decl, import);
                self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
            } else {
                self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
                self.insert_unused_macro(orig_ident, def_id, item.id);
            }
            self.r.feed_visibility(feed, vis);
            let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
                self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
                    parent_macro_rules_scope: parent_scope.macro_rules,
                    decl,
                    ident,
                    orig_ident_span: orig_ident.span,
                }),
            ));
            self.r.macro_rules_scopes.insert(def_id, scope);
            scope
        } else {
            let module = parent_scope.module.expect_local();
            let vis = match item.kind {
                // Visibilities must not be resolved non-speculatively twice
                // and we already resolved this one as a `fn` item visibility.
                ItemKind::Fn(..) => self
                    .r
                    .try_resolve_visibility(&self.parent_scope, &item.vis, false)
                    .unwrap_or(Visibility::Public),
                _ => self.resolve_visibility(&item.vis),
            };
            if !vis.is_public() {
                self.insert_unused_macro(orig_ident, def_id, item.id);
            }
            self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
            self.r.feed_visibility(feed, vis);
            self.parent_scope.macro_rules
        }
    }
}

impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
    pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
        let orig_module_scope = self.parent_scope.module;
        self.parent_scope.macro_rules = match item.kind {
            ItemKind::MacroDef(..) => {
                let macro_rules_scope = self.define_macro(item, feed);
                visit::walk_item(self, item);
                macro_rules_scope
            }
            _ => {
                let orig_macro_rules_scope = self.parent_scope.macro_rules;
                self.build_reduced_graph_for_item(item, feed);
                match item.kind {
                    ItemKind::Mod(..) => {
                        // Visit attributes after items for backward compatibility.
                        // This way they can use `macro_rules` defined later.
                        self.visit_vis(&item.vis);
                        item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
                        visit::walk_list!(self, visit_attribute, &item.attrs);
                    }
                    _ => visit::walk_item(self, item),
                }
                match item.kind {
                    ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
                        self.parent_scope.macro_rules
                    }
                    _ => orig_macro_rules_scope,
                }
            }
        };
        self.parent_scope.module = orig_module_scope;
    }

    /// Handle a macro call that itself can produce new `macro_rules` items
    /// in the current module.
    pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
        self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
    }

    pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
        let orig_current_module = self.parent_scope.module;
        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
        self.build_reduced_graph_for_block(block);
        visit::walk_block(self, block);
        self.parent_scope.module = orig_current_module;
        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
    }

    pub(crate) fn brg_visit_assoc_item(
        &mut self,
        item: &'a AssocItem,
        ctxt: AssocCtxt,
        ident: Ident,
        ns: Namespace,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) {
        let vis = self.resolve_visibility(&item.vis);
        let local_def_id = feed.key();
        let def_id = local_def_id.to_def_id();

        if !(matches!(ctxt, AssocCtxt::Impl { of_trait: true })
            && matches!(item.vis.kind, ast::VisibilityKind::Inherited))
        {
            // Trait impl item visibility is inherited from its trait when not specified
            // explicitly. In that case we cannot determine it here in early resolve,
            // so we leave a hole in the visibility table to be filled later.
            self.r.feed_visibility(feed, vis);
        }

        if ctxt == AssocCtxt::Trait {
            let parent = self.parent_scope.module.expect_local();
            let expansion = self.parent_scope.expansion;
            self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
        } else if !matches!(&item.kind, AssocItemKind::Delegation(d) if d.source == DelegationSource::Glob)
            && ident.name != kw::Underscore
        {
            // Don't add underscore names, they cannot be looked up anyway.
            let impl_def_id = self.r.tcx.local_parent(local_def_id);
            let key = BindingKey::new(IdentKey::new(ident), ns);
            self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
        }

        visit::walk_assoc_item(self, item, ctxt);
    }

    pub(crate) fn visit_assoc_item_mac_call(
        &mut self,
        item: &'a Item<AssocItemKind>,
        ctxt: AssocCtxt,
    ) {
        match ctxt {
            AssocCtxt::Trait => {
                self.visit_invoc_in_module(item.id);
            }
            AssocCtxt::Impl { .. } => {
                let invoc_id = item.id.placeholder_to_expn_id();
                if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
                    self.r
                        .impl_unexpanded_invocations
                        .entry(self.r.invocation_parent(invoc_id))
                        .or_default()
                        .insert(invoc_id);
                }
                self.visit_invoc(item.id);
            }
        }
    }

    pub(crate) fn brg_visit_field_def(
        &mut self,
        sf: &'a ast::FieldDef,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) {
        let vis = self.resolve_visibility(&sf.vis);
        self.r.feed_visibility(feed, vis);
        visit::walk_field_def(self, sf);
    }

    // Constructs the reduced graph for one variant. Variants exist in the
    // type and value namespaces.
    pub(crate) fn brg_visit_variant(
        &mut self,
        variant: &'a ast::Variant,
        feed: TyCtxtFeed<'tcx, LocalDefId>,
    ) {
        let parent = self.parent_scope.module.expect_local();
        let expn_id = self.parent_scope.expansion;
        let ident = variant.ident;

        // Define a name in the type namespace.
        let def_id = feed.key();
        let vis = self.resolve_visibility(&variant.vis);
        self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
        self.r.feed_visibility(feed, vis);

        // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
        let ctor_vis =
            if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
                Visibility::Restricted(CRATE_DEF_ID)
            } else {
                vis
            };

        // Define a constructor name in the value namespace.
        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
            let feed = self.create_def(
                ctor_node_id,
                None,
                DefKind::Ctor(CtorOf::Variant, ctor_kind),
                variant.span,
            );
            let ctor_def_id = feed.key();
            let ctor_res = self.res(ctor_def_id);
            self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
            self.r.feed_visibility(feed, ctor_vis);
        }

        // Record field names for error reporting.
        self.insert_field_idents(def_id, variant.data.fields());
        self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());

        visit::walk_variant(self, variant);
    }
}
