Auto merge of #107765 - petrochenkov:nomoclone, r=oli-obk

rustc/rustdoc: Perform name resolver cleanups enabled by #94857

Unblocks https://github.com/rust-lang/rust/pull/105462.
r? `@oli-obk`
This commit is contained in:
bors 2023-02-14 05:59:44 +00:00
commit e9ab7872fd
23 changed files with 102 additions and 325 deletions

View File

@ -92,7 +92,7 @@ pub fn enumerated_keys_and_path_hashes(
/// The definition table containing node definitions.
/// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
/// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct Definitions {
table: DefPathTable,
next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,

View File

@ -3460,7 +3460,7 @@ pub struct Upvar {
// The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
// has length > 0 if the trait is found through an chain of imports, starting with the
// import/use statement in the scope where the trait is used.
#[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
#[derive(Encodable, Decodable, Debug, HashStable_Generic)]
pub struct TraitCandidate {
pub def_id: DefId,
pub import_ids: SmallVec<[LocalDefId; 1]>,

View File

@ -35,13 +35,11 @@
use rustc_trait_selection::traits;
use std::any::Any;
use std::cell::RefCell;
use std::ffi::OsString;
use std::io::{self, BufWriter, Write};
use std::marker::PhantomPinned;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, LazyLock};
use std::{env, fs, iter};
@ -131,21 +129,12 @@ pub fn access<F: for<'a> FnOnce(&mut Resolver<'a>) -> R, R>(&mut self, f: F) ->
f((&mut *resolver).as_mut().unwrap())
}
pub fn to_resolver_outputs(resolver: Rc<RefCell<BoxedResolver>>) -> ty::ResolverOutputs {
match Rc::try_unwrap(resolver) {
Ok(resolver) => {
let mut resolver = resolver.into_inner();
// SAFETY: The resolver doesn't need to be pinned.
let mut resolver = unsafe {
resolver
.0
.as_mut()
.map_unchecked_mut(|boxed_resolver| &mut boxed_resolver.resolver)
};
resolver.take().unwrap().into_outputs()
}
Err(resolver) => resolver.borrow_mut().access(|resolver| resolver.clone_outputs()),
}
pub fn into_outputs(mut self) -> ty::ResolverOutputs {
// SAFETY: The resolver doesn't need to be pinned.
let mut resolver = unsafe {
self.0.as_mut().map_unchecked_mut(|boxed_resolver| &mut boxed_resolver.resolver)
};
resolver.take().unwrap().into_outputs()
}
}
}

View File

@ -21,7 +21,6 @@
use rustc_span::Symbol;
use std::any::Any;
use std::cell::{RefCell, RefMut};
use std::rc::Rc;
use std::sync::Arc;
/// Represent the result of a query.
@ -88,7 +87,7 @@ pub struct Queries<'tcx> {
parse: Query<ast::Crate>,
crate_name: Query<Symbol>,
register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
expansion: Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>,
expansion: Query<(Lrc<ast::Crate>, BoxedResolver, Lrc<LintStore>)>,
dep_graph: Query<DepGraph>,
// This just points to what's in `gcx_cell`.
gcx: Query<&'tcx GlobalCtxt<'tcx>>,
@ -171,8 +170,7 @@ fn crate_name(&self) -> Result<QueryResult<'_, Symbol>> {
pub fn expansion(
&self,
) -> Result<QueryResult<'_, (Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>>
{
) -> Result<QueryResult<'_, (Lrc<ast::Crate>, BoxedResolver, Lrc<LintStore>)>> {
trace!("expansion");
self.expansion.compute(|| {
let crate_name = *self.crate_name()?.borrow();
@ -188,7 +186,7 @@ pub fn expansion(
let krate = resolver.access(|resolver| {
passes::configure_and_expand(sess, &lint_store, krate, crate_name, resolver)
})?;
Ok((Lrc::new(krate), Rc::new(RefCell::new(resolver)), lint_store))
Ok((Lrc::new(krate), resolver, lint_store))
})
}
@ -217,7 +215,7 @@ pub fn global_ctxt(&'tcx self) -> Result<QueryResult<'_, &'tcx GlobalCtxt<'tcx>>
untracked,
global_ctxt: untracked_resolutions,
ast_lowering: untracked_resolver_for_lowering,
} = BoxedResolver::to_resolver_outputs(resolver);
} = resolver.into_outputs();
let gcx = passes::create_global_ctxt(
self.compiler,

View File

@ -8,7 +8,7 @@
use rustc_ast::{self as ast, *};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{Lrc, ReadGuard};
use rustc_data_structures::sync::ReadGuard;
use rustc_expand::base::SyntaxExtension;
use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
use rustc_hir::definitions::Definitions;
@ -30,11 +30,10 @@
use std::ops::Fn;
use std::path::Path;
use std::time::Duration;
use std::{cmp, env};
use std::{cmp, env, iter};
#[derive(Clone)]
pub struct CStore {
metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
metas: IndexVec<CrateNum, Option<Box<CrateMetadata>>>,
injected_panic_runtime: Option<CrateNum>,
/// This crate needs an allocator and either provides it itself, or finds it in a dependency.
/// If the above is true, then this field denotes the kind of the found allocator.
@ -153,7 +152,7 @@ pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
self.metas[cnum] = Some(Lrc::new(data));
self.metas[cnum] = Some(Box::new(data));
}
pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
@ -245,7 +244,7 @@ pub fn new(sess: &Session) -> CStore {
// order to make array indices in `metas` match with the
// corresponding `CrateNum`. This first entry will always remain
// `None`.
metas: IndexVec::from_elem_n(None, 1),
metas: IndexVec::from_iter(iter::once(None)),
injected_panic_runtime: None,
allocator_kind: None,
alloc_error_handler_kind: None,

View File

@ -1169,15 +1169,9 @@ fn get_traits(self) -> impl Iterator<Item = DefId> + 'a {
}
/// Decodes all trait impls in the crate (for rustdoc).
fn get_trait_impls(self) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + 'a {
self.cdata.trait_impls.iter().flat_map(move |(&(trait_cnum_raw, trait_index), impls)| {
let trait_def_id = DefId {
krate: self.cnum_map[CrateNum::from_u32(trait_cnum_raw)],
index: trait_index,
};
impls.decode(self).map(move |(impl_index, simplified_self_ty)| {
(trait_def_id, self.local_def_id(impl_index), simplified_self_ty)
})
fn get_trait_impls(self) -> impl Iterator<Item = DefId> + 'a {
self.cdata.trait_impls.values().flat_map(move |impls| {
impls.decode(self).map(move |(impl_index, _)| self.local_def_id(impl_index))
})
}

View File

@ -304,6 +304,7 @@ fn into_args(self) -> (DefId, SimplifiedType) {
extra_filename => { cdata.root.extra_filename.clone() }
traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) }
trait_impls_in_crate => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) }
implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) }
crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) }
@ -608,20 +609,6 @@ pub fn get_proc_macro_quoted_span_untracked(
) -> Span {
self.get_crate_data(cnum).get_proc_macro_quoted_span(id, sess)
}
/// Decodes all trait impls in the crate (for rustdoc).
pub fn trait_impls_in_crate_untracked(
&self,
cnum: CrateNum,
) -> impl Iterator<Item = (DefId, DefId, Option<SimplifiedType>)> + '_ {
self.get_crate_data(cnum).get_trait_impls()
}
pub fn is_doc_hidden_untracked(&self, def_id: DefId) -> bool {
self.get_crate_data(def_id.krate)
.get_attr_flags(def_id.index)
.contains(AttrFlags::IS_DOC_HIDDEN)
}
}
impl CrateStore for CStore {

View File

@ -2256,6 +2256,22 @@ pub fn provide(providers: &mut Providers) {
traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
tcx.arena.alloc_slice(&traits)
},
trait_impls_in_crate: |tcx, cnum| {
assert_eq!(cnum, LOCAL_CRATE);
let mut trait_impls = Vec::new();
for id in tcx.hir().items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Impl)
&& tcx.impl_trait_ref(id.owner_id).is_some()
{
trait_impls.push(id.owner_id.to_def_id())
}
}
// Bring everything into deterministic order.
trait_impls.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
tcx.arena.alloc_slice(&trait_impls)
},
..*providers
}

View File

@ -1836,6 +1836,11 @@
separate_provide_extern
}
query trait_impls_in_crate(_: CrateNum) -> &'tcx [DefId] {
desc { "fetching all trait impls in a crate" }
separate_provide_extern
}
/// The list of symbols exported from the given crate.
///
/// - All names contained in `exported_symbols(cnum)` are guaranteed to

View File

@ -187,6 +187,7 @@ pub struct ResolverGlobalCtxt {
pub registered_tools: RegisteredTools,
pub doc_link_resolutions: FxHashMap<LocalDefId, DocLinkResMap>,
pub doc_link_traits_in_scope: FxHashMap<LocalDefId, Vec<DefId>>,
pub all_macro_rules: FxHashMap<Symbol, Res<ast::NodeId>>,
}
/// Resolutions that should only be used for lowering.

View File

@ -1251,6 +1251,7 @@ fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> {
};
let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
self.r.set_binding_parent_module(binding, parent_scope.module);
self.r.all_macro_rules.insert(ident.name, res);
if is_macro_export {
let import = self.r.arenas.alloc_import(Import {
kind: ImportKind::MacroExport,

View File

@ -29,7 +29,7 @@ fn level(self) -> Level {
}
}
pub struct EffectiveVisibilitiesVisitor<'r, 'a> {
pub(crate) struct EffectiveVisibilitiesVisitor<'r, 'a> {
r: &'r mut Resolver<'a>,
def_effective_visibilities: EffectiveVisibilities,
/// While walking import chains we need to track effective visibilities per-binding, and def id
@ -78,7 +78,7 @@ impl<'r, 'a> EffectiveVisibilitiesVisitor<'r, 'a> {
/// Fills the `Resolver::effective_visibilities` table with public & exported items
/// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we
/// need access to a TyCtxt for that.
pub fn compute_effective_visibilities<'c>(r: &'r mut Resolver<'a>, krate: &'c Crate) {
pub(crate) fn compute_effective_visibilities<'c>(r: &'r mut Resolver<'a>, krate: &'c Crate) {
let mut visitor = EffectiveVisibilitiesVisitor {
r,
def_effective_visibilities: Default::default(),

View File

@ -33,7 +33,7 @@
/// Contains data for specific kinds of imports.
#[derive(Clone)]
pub enum ImportKind<'a> {
pub(crate) enum ImportKind<'a> {
Single {
/// `source` in `use prefix::source as target`.
source: Ident,
@ -157,11 +157,11 @@ pub(crate) struct Import<'a> {
}
impl<'a> Import<'a> {
pub fn is_glob(&self) -> bool {
pub(crate) fn is_glob(&self) -> bool {
matches!(self.kind, ImportKind::Glob { .. })
}
pub fn is_nested(&self) -> bool {
pub(crate) fn is_nested(&self) -> bool {
match self.kind {
ImportKind::Single { nested, .. } => nested,
_ => false,
@ -405,7 +405,7 @@ struct UnresolvedImportError {
candidates: Option<Vec<ImportSuggestion>>,
}
pub struct ImportResolver<'a, 'b> {
pub(crate) struct ImportResolver<'a, 'b> {
pub r: &'a mut Resolver<'b>,
}
@ -420,7 +420,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
/// Resolves all imports for the crate. This method performs the fixed-
/// point iteration.
pub fn resolve_imports(&mut self) {
pub(crate) fn resolve_imports(&mut self) {
let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
while self.r.indeterminate_imports.len() < prev_num_indeterminates {
prev_num_indeterminates = self.r.indeterminate_imports.len();
@ -433,7 +433,7 @@ pub fn resolve_imports(&mut self) {
}
}
pub fn finalize_imports(&mut self) {
pub(crate) fn finalize_imports(&mut self) {
for module in self.r.arenas.local_modules().iter() {
self.finalize_resolutions_in(module);
}

View File

@ -56,7 +56,7 @@ struct BindingInfo {
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PatternSource {
pub(crate) enum PatternSource {
Match,
Let,
For,
@ -70,7 +70,7 @@ enum IsRepeatExpr {
}
impl PatternSource {
pub fn descr(self) -> &'static str {
fn descr(self) -> &'static str {
match self {
PatternSource::Match => "match binding",
PatternSource::Let => "let binding",
@ -2374,9 +2374,8 @@ fn resolve_item(&mut self, item: &'ast Item) {
// Maintain macro_rules scopes in the same way as during early resolution
// for diagnostics and doc links.
if macro_def.macro_rules {
let (macro_rules_scope, _) =
self.r.macro_rules_scope(self.r.local_def_id(item.id));
self.parent_scope.macro_rules = macro_rules_scope;
let def_id = self.r.local_def_id(item.id);
self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
}
}

View File

@ -2626,7 +2626,7 @@ fn add_missing_lifetime_specifiers_label(
}
/// Report lifetime/lifetime shadowing as an error.
pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
let mut err = struct_span_err!(
sess,
shadower.span,
@ -2641,7 +2641,7 @@ pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
/// Shadowing involving a label is only a warning for historical reasons.
//FIXME: make this a proper lint.
pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
let name = shadower.name;
let shadower = shadower.span;
let mut err = sess.struct_span_warn(

View File

@ -21,8 +21,6 @@
#[macro_use]
extern crate tracing;
pub use rustc_hir::def::{Namespace, PerNS};
use rustc_arena::{DroplessArena, TypedArena};
use rustc_ast::node_id::NodeMap;
use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
@ -32,8 +30,8 @@
use rustc_data_structures::sync::{Lrc, RwLock};
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed};
use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind};
use rustc_hir::def::Namespace::*;
use rustc_hir::def::{self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, PartialRes};
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, PartialRes, PerNS};
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId};
use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::{DefPathData, Definitions};
@ -86,7 +84,7 @@ enum Weak {
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Determinacy {
enum Determinacy {
Determined,
Undetermined,
}
@ -257,7 +255,7 @@ enum VisResolutionError<'a> {
/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
/// segments' which don't have the rest of an AST or HIR `PathSegment`.
#[derive(Clone, Copy, Debug)]
pub struct Segment {
struct Segment {
ident: Ident,
id: Option<NodeId>,
/// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
@ -380,7 +378,7 @@ fn same_def(lhs: Self, rhs: Self) -> bool {
}
}
#[derive(Clone, Debug)]
#[derive(Debug)]
enum PathResult<'a> {
Module(ModuleOrUniformRoot<'a>),
NonModule(PartialRes),
@ -435,7 +433,7 @@ enum ModuleKind {
impl ModuleKind {
/// Get name of the module.
pub fn name(&self) -> Option<Symbol> {
fn name(&self) -> Option<Symbol> {
match self {
ModuleKind::Block => None,
ModuleKind::Def(.., name) => Some(*name),
@ -471,7 +469,7 @@ struct BindingKey {
/// * curly-braced block with statements
///
/// You can use [`ModuleData::kind`] to determine the kind of module this is.
pub struct ModuleData<'a> {
struct ModuleData<'a> {
/// The direct parent module (it may not be a `mod`, however).
parent: Option<Module<'a>>,
/// What kind of module this is, because this may not be a `mod`.
@ -570,7 +568,7 @@ fn res(&self) -> Option<Res> {
}
// Public for rustdoc.
pub fn def_id(&self) -> DefId {
fn def_id(&self) -> DefId {
self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
}
@ -628,7 +626,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// Records a possibly-private value, type, or module definition.
#[derive(Clone, Debug)]
pub struct NameBinding<'a> {
struct NameBinding<'a> {
kind: NameBindingKind<'a>,
ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
expansion: LocalExpnId,
@ -636,7 +634,7 @@ pub struct NameBinding<'a> {
vis: ty::Visibility<DefId>,
}
pub trait ToNameBinding<'a> {
trait ToNameBinding<'a> {
fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
}
@ -840,9 +838,9 @@ fn may_appear_after(
}
#[derive(Default, Clone)]
pub struct ExternPreludeEntry<'a> {
struct ExternPreludeEntry<'a> {
extern_crate_item: Option<&'a NameBinding<'a>>,
pub introduced_by_item: bool,
introduced_by_item: bool,
}
/// Used for better errors for E0773
@ -1049,6 +1047,7 @@ pub struct Resolver<'a> {
effective_visibilities: EffectiveVisibilities,
doc_link_resolutions: FxHashMap<LocalDefId, DocLinkResMap>,
doc_link_traits_in_scope: FxHashMap<LocalDefId, Vec<DefId>>,
all_macro_rules: FxHashMap<Symbol, Res>,
}
/// Nothing really interesting here; it just provides memory for the rest of the crate.
@ -1147,7 +1146,7 @@ fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
self.node_id_to_def_id.get(&node).copied()
}
pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
fn local_def_id(&self, node: NodeId) -> LocalDefId {
self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
}
@ -1199,10 +1198,6 @@ fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
self.cstore().item_generics_num_lifetimes(def_id, self.session)
}
}
pub fn sess(&self) -> &'a Session {
self.session
}
}
impl<'a> Resolver<'a> {
@ -1379,6 +1374,7 @@ pub fn new(
effective_visibilities: Default::default(),
doc_link_resolutions: Default::default(),
doc_link_traits_in_scope: Default::default(),
all_macro_rules: Default::default(),
};
let root_parent_scope = ParentScope::module(graph_root, &resolver);
@ -1399,14 +1395,14 @@ fn new_module(
self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
}
pub fn next_node_id(&mut self) -> NodeId {
fn next_node_id(&mut self) -> NodeId {
let start = self.next_node_id;
let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
self.next_node_id = ast::NodeId::from_u32(next);
start
}
pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
let start = self.next_node_id;
let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
self.next_node_id = ast::NodeId::from_usize(end);
@ -1457,6 +1453,7 @@ pub fn into_outputs(self) -> ResolverOutputs {
registered_tools: self.registered_tools,
doc_link_resolutions: self.doc_link_resolutions,
doc_link_traits_in_scope: self.doc_link_traits_in_scope,
all_macro_rules: self.all_macro_rules,
};
let ast_lowering = ty::ResolverAstLowering {
legacy_const_generic_args: self.legacy_const_generic_args,
@ -1475,57 +1472,11 @@ pub fn into_outputs(self) -> ResolverOutputs {
ResolverOutputs { global_ctxt, ast_lowering, untracked }
}
pub fn clone_outputs(&self) -> ResolverOutputs {
let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
let definitions = self.untracked.definitions.clone();
let cstore = Box::new(self.cstore().clone());
let untracked =
Untracked { cstore, source_span: self.untracked.source_span.clone(), definitions };
let global_ctxt = ResolverGlobalCtxt {
expn_that_defined: self.expn_that_defined.clone(),
visibilities: self.visibilities.clone(),
has_pub_restricted: self.has_pub_restricted,
extern_crate_map: self.extern_crate_map.clone(),
reexport_map: self.reexport_map.clone(),
glob_map: self.glob_map.clone(),
maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
extern_prelude: self
.extern_prelude
.iter()
.map(|(ident, entry)| (ident.name, entry.introduced_by_item))
.collect(),
main_def: self.main_def,
trait_impls: self.trait_impls.clone(),
proc_macros,
confused_type_with_std_module: self.confused_type_with_std_module.clone(),
registered_tools: self.registered_tools.clone(),
effective_visibilities: self.effective_visibilities.clone(),
doc_link_resolutions: self.doc_link_resolutions.clone(),
doc_link_traits_in_scope: self.doc_link_traits_in_scope.clone(),
};
let ast_lowering = ty::ResolverAstLowering {
legacy_const_generic_args: self.legacy_const_generic_args.clone(),
partial_res_map: self.partial_res_map.clone(),
import_res_map: self.import_res_map.clone(),
label_res_map: self.label_res_map.clone(),
lifetimes_res_map: self.lifetimes_res_map.clone(),
extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
next_node_id: self.next_node_id,
node_id_to_def_id: self.node_id_to_def_id.clone(),
def_id_to_node_id: self.def_id_to_node_id.clone(),
trait_map: self.trait_map.clone(),
builtin_macro_kinds: self.builtin_macro_kinds.clone(),
lifetime_elision_allowed: self.lifetime_elision_allowed.clone(),
};
ResolverOutputs { global_ctxt, ast_lowering, untracked }
}
fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
StableHashingContext::new(self.session, &self.untracked)
}
pub fn crate_loader(&mut self) -> CrateLoader<'_> {
fn crate_loader(&mut self) -> CrateLoader<'_> {
CrateLoader::new(
&self.session,
&*self.metadata_loader,
@ -1536,7 +1487,7 @@ pub fn crate_loader(&mut self) -> CrateLoader<'_> {
)
}
pub fn cstore(&self) -> &CStore {
fn cstore(&self) -> &CStore {
self.untracked.cstore.as_any().downcast_ref().unwrap()
}
@ -1968,24 +1919,15 @@ fn resolve_rustdoc_path(
}
}
/// For rustdoc.
pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
match scope.get() {
MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
_ => unreachable!(),
}
}
/// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
#[inline]
pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
fn opt_span(&self, def_id: DefId) -> Option<Span> {
def_id.as_local().map(|def_id| self.untracked.source_span[def_id])
}
/// Retrieves the name of the given `DefId`.
#[inline]
pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
let def_key = match def_id.as_local() {
Some(def_id) => self.untracked.definitions.read().def_key(def_id),
None => self.cstore().def_key(def_id),
@ -1996,7 +1938,7 @@ pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
/// Checks if an expression refers to a function marked with
/// `#[rustc_legacy_const_generics]` and returns the argument index list
/// from the attribute.
pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
if let ExprKind::Path(None, path) = &expr.kind {
// Don't perform legacy const generics rewriting if the path already
// has generic arguments.

View File

@ -39,7 +39,7 @@
/// Binding produced by a `macro_rules` item.
/// Not modularized, can shadow previous `macro_rules` bindings, etc.
#[derive(Debug)]
pub struct MacroRulesBinding<'a> {
pub(crate) struct MacroRulesBinding<'a> {
pub(crate) binding: &'a NameBinding<'a>,
/// `macro_rules` scope into which the `macro_rules` item was planted.
pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'a>,
@ -52,7 +52,7 @@ pub struct MacroRulesBinding<'a> {
/// Some macro invocations need to introduce `macro_rules` scopes too because they
/// can potentially expand into macro definitions.
#[derive(Copy, Clone, Debug)]
pub enum MacroRulesScope<'a> {
pub(crate) enum MacroRulesScope<'a> {
/// Empty "root" scope at the crate start containing no names.
Empty,
/// The scope introduced by a `macro_rules!` macro definition.

View File

@ -1,4 +1,3 @@
use rustc_ast::NodeId;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::{self, Lrc};
use rustc_data_structures::unord::UnordSet;
@ -17,7 +16,7 @@
use rustc_session::lint;
use rustc_session::Session;
use rustc_span::symbol::sym;
use rustc_span::{source_map, Span, Symbol};
use rustc_span::{source_map, Span};
use std::cell::RefCell;
use std::mem;
@ -32,15 +31,8 @@
pub(crate) use rustc_session::config::{Input, Options, UnstableOptions};
pub(crate) struct ResolverCaches {
pub(crate) all_trait_impls: Option<Vec<DefId>>,
pub(crate) all_macro_rules: FxHashMap<Symbol, Res<NodeId>>,
pub(crate) extern_doc_reachable: DefIdSet,
}
pub(crate) struct DocContext<'tcx> {
pub(crate) tcx: TyCtxt<'tcx>,
pub(crate) resolver_caches: ResolverCaches,
/// Used for normalization.
///
/// Most of this logic is copied from rustc_lint::late.
@ -111,12 +103,6 @@ pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId>
_ => None,
}
}
pub(crate) fn with_all_trait_impls(&mut self, f: impl FnOnce(&mut Self, &[DefId])) {
let all_trait_impls = self.resolver_caches.all_trait_impls.take();
f(self, all_trait_impls.as_ref().expect("`all_trait_impls` are already borrowed"));
self.resolver_caches.all_trait_impls = all_trait_impls;
}
}
/// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
@ -305,7 +291,6 @@ pub(crate) fn create_config(
pub(crate) fn run_global_ctxt(
tcx: TyCtxt<'_>,
resolver_caches: ResolverCaches,
show_coverage: bool,
render_options: RenderOptions,
output_format: OutputFormat,
@ -339,7 +324,6 @@ pub(crate) fn run_global_ctxt(
let mut ctxt = DocContext {
tcx,
resolver_caches,
param_env: ParamEnv::empty(),
external_traits: Default::default(),
active_extern_traits: Default::default(),
@ -354,9 +338,9 @@ pub(crate) fn run_global_ctxt(
show_coverage,
};
ctxt.cache
.effective_visibilities
.init(mem::take(&mut ctxt.resolver_caches.extern_doc_reachable));
for cnum in tcx.crates(()) {
crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
}
// Small hack to force the Sized trait to be present.
//

View File

@ -82,7 +82,6 @@
use rustc_session::{early_error, early_warn};
use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
use crate::passes::collect_intra_doc_links;
/// A macro to create a FxHashMap.
///
@ -793,30 +792,14 @@ fn main_args(at_args: &[String]) -> MainResult {
}
compiler.enter(|queries| {
let resolver_caches = {
let expansion = abort_on_err(queries.expansion(), sess);
let (krate, resolver, _) = &*expansion.borrow();
let resolver_caches = resolver.borrow_mut().access(|resolver| {
collect_intra_doc_links::early_resolve_intra_doc_links(resolver, krate)
});
resolver_caches
};
let mut gcx = abort_on_err(queries.global_ctxt(), sess);
if sess.diagnostic().has_errors_or_lint_errors().is_some() {
sess.fatal("Compilation failed, aborting rustdoc");
}
let mut gcx = abort_on_err(queries.global_ctxt(), sess);
gcx.enter(|tcx| {
let (krate, render_opts, mut cache) = sess.time("run_global_ctxt", || {
core::run_global_ctxt(
tcx,
resolver_caches,
show_coverage,
render_options,
output_format,
)
core::run_global_ctxt(tcx, show_coverage, render_options, output_format)
});
info!("finished with rustc");

View File

@ -24,6 +24,7 @@
use smallvec::{smallvec, SmallVec};
use std::borrow::Cow;
use std::mem;
use std::ops::Range;
use crate::clean::{self, utils::find_nearest_parent_module};
@ -34,9 +35,6 @@
use crate::passes::Pass;
use crate::visit::DocVisitor;
mod early;
pub(crate) use early::early_resolve_intra_doc_links;
pub(crate) const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
name: "collect-intra-doc-links",
run: collect_intra_doc_links,
@ -1616,7 +1614,7 @@ fn resolution_failure(
// ignore duplicates
let mut variants_seen = SmallVec::<[_; 3]>::new();
for mut failure in kinds {
let variant = std::mem::discriminant(&failure);
let variant = mem::discriminant(&failure);
if variants_seen.contains(&variant) {
continue;
}
@ -1686,7 +1684,7 @@ fn split(path: &str) -> Option<(&str, &str)> {
if !path_str.contains("::") {
if disambiguator.map_or(true, |d| d.ns() == MacroNS)
&& let Some(&res) = collector.cx.resolver_caches.all_macro_rules
&& let Some(&res) = collector.cx.tcx.resolutions(()).all_macro_rules
.get(&Symbol::intern(path_str))
{
diag.note(format!(

View File

@ -1,72 +0,0 @@
use crate::core::ResolverCaches;
use crate::visit_lib::early_lib_embargo_visit_item;
use rustc_ast::visit::{self, Visitor};
use rustc_ast::{self as ast, ItemKind};
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::Res;
use rustc_hir::def_id::{DefId, DefIdSet};
use rustc_resolve::Resolver;
use rustc_span::Symbol;
pub(crate) fn early_resolve_intra_doc_links(
resolver: &mut Resolver<'_>,
krate: &ast::Crate,
) -> ResolverCaches {
let mut link_resolver = EarlyDocLinkResolver {
resolver,
all_trait_impls: Default::default(),
all_macro_rules: Default::default(),
extern_doc_reachable: Default::default(),
};
visit::walk_crate(&mut link_resolver, krate);
link_resolver.process_extern_impls();
ResolverCaches {
all_trait_impls: Some(link_resolver.all_trait_impls),
all_macro_rules: link_resolver.all_macro_rules,
extern_doc_reachable: link_resolver.extern_doc_reachable,
}
}
struct EarlyDocLinkResolver<'r, 'ra> {
resolver: &'r mut Resolver<'ra>,
all_trait_impls: Vec<DefId>,
all_macro_rules: FxHashMap<Symbol, Res<ast::NodeId>>,
/// This set is used as a seed for `effective_visibilities`, which are then extended by some
/// more items using `lib_embargo_visit_item` during doc inlining.
extern_doc_reachable: DefIdSet,
}
impl<'ra> EarlyDocLinkResolver<'_, 'ra> {
fn process_extern_impls(&mut self) {
for cnum in self.resolver.cstore().crates_untracked() {
early_lib_embargo_visit_item(
self.resolver,
&mut self.extern_doc_reachable,
cnum.as_def_id(),
true,
);
for (_, impl_def_id, _) in self.resolver.cstore().trait_impls_in_crate_untracked(cnum) {
self.all_trait_impls.push(impl_def_id);
}
}
}
}
impl Visitor<'_> for EarlyDocLinkResolver<'_, '_> {
fn visit_item(&mut self, item: &ast::Item) {
match &item.kind {
ItemKind::Impl(impl_) if impl_.of_trait.is_some() => {
self.all_trait_impls.push(self.resolver.local_def_id(item.id).to_def_id());
}
ItemKind::MacroDef(macro_def) if macro_def.macro_rules => {
let (_, res) = self.resolver.macro_rules_scope(self.resolver.local_def_id(item.id));
self.all_macro_rules.insert(item.ident.name, res);
}
_ => {}
}
visit::walk_item(self, item);
}
}

View File

@ -45,18 +45,20 @@ pub(crate) fn collect_trait_impls(mut krate: Crate, cx: &mut DocContext<'_>) ->
let mut new_items_local = Vec::new();
// External trait impls.
cx.with_all_trait_impls(|cx, all_trait_impls| {
{
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_extern_trait_impls");
for &impl_def_id in all_trait_impls.iter().skip_while(|def_id| def_id.is_local()) {
inline::build_impl(cx, None, impl_def_id, None, &mut new_items_external);
for &cnum in cx.tcx.crates(()) {
for &impl_def_id in cx.tcx.trait_impls_in_crate(cnum) {
inline::build_impl(cx, None, impl_def_id, None, &mut new_items_external);
}
}
});
}
// Local trait impls.
cx.with_all_trait_impls(|cx, all_trait_impls| {
{
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_local_trait_impls");
let mut attr_buf = Vec::new();
for &impl_def_id in all_trait_impls.iter().take_while(|def_id| def_id.is_local()) {
for &impl_def_id in cx.tcx.trait_impls_in_crate(LOCAL_CRATE) {
let mut parent = Some(cx.tcx.parent(impl_def_id));
while let Some(did) = parent {
attr_buf.extend(
@ -76,7 +78,7 @@ pub(crate) fn collect_trait_impls(mut krate: Crate, cx: &mut DocContext<'_>) ->
inline::build_impl(cx, None, impl_def_id, Some(&attr_buf), &mut new_items_local);
attr_buf.clear();
}
});
}
cx.tcx.sess.prof.generic_activity("build_primitive_trait_impls").run(|| {
for def_id in PrimitiveType::all_impls(cx.tcx) {

View File

@ -1,8 +1,7 @@
use crate::core::DocContext;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, DefIdSet};
use rustc_middle::ty::TyCtxt;
use rustc_resolve::Resolver;
// FIXME: this may not be exhaustive, but is sufficient for rustdocs current uses
@ -26,10 +25,6 @@ impl RustdocEffectiveVisibilities {
define_method!(is_directly_public);
define_method!(is_exported);
define_method!(is_reachable);
pub(crate) fn init(&mut self, extern_public: DefIdSet) {
self.extern_public = extern_public;
}
}
pub(crate) fn lib_embargo_visit_item(cx: &mut DocContext<'_>, def_id: DefId) {
@ -42,17 +37,6 @@ pub(crate) fn lib_embargo_visit_item(cx: &mut DocContext<'_>, def_id: DefId) {
.visit_item(def_id)
}
pub(crate) fn early_lib_embargo_visit_item(
resolver: &Resolver<'_>,
extern_public: &mut DefIdSet,
def_id: DefId,
is_mod: bool,
) {
assert!(!def_id.is_local());
EarlyLibEmbargoVisitor { resolver, extern_public, visited_mods: Default::default() }
.visit_item(def_id, is_mod)
}
/// Similar to `librustc_privacy::EmbargoVisitor`, but also takes
/// specific rustdoc annotations into account (i.e., `doc(hidden)`)
struct LibEmbargoVisitor<'a, 'tcx> {
@ -63,14 +47,6 @@ struct LibEmbargoVisitor<'a, 'tcx> {
visited_mods: DefIdSet,
}
struct EarlyLibEmbargoVisitor<'r, 'ra> {
resolver: &'r Resolver<'ra>,
// Effective visibilities for reachable nodes
extern_public: &'r mut DefIdSet,
// Keeps track of already visited modules, in case a module re-exports its parent
visited_mods: DefIdSet,
}
impl LibEmbargoVisitor<'_, '_> {
fn visit_mod(&mut self, def_id: DefId) {
if !self.visited_mods.insert(def_id) {
@ -95,28 +71,3 @@ fn visit_item(&mut self, def_id: DefId) {
}
}
}
impl EarlyLibEmbargoVisitor<'_, '_> {
fn visit_mod(&mut self, def_id: DefId) {
if !self.visited_mods.insert(def_id) {
return;
}
for item in self.resolver.cstore().module_children_untracked(def_id, self.resolver.sess()) {
if let Some(def_id) = item.res.opt_def_id() {
if item.vis.is_public() {
self.visit_item(def_id, matches!(item.res, Res::Def(DefKind::Mod, _)));
}
}
}
}
fn visit_item(&mut self, def_id: DefId, is_mod: bool) {
if !self.resolver.cstore().is_doc_hidden_untracked(def_id) {
self.extern_public.insert(def_id);
if is_mod {
self.visit_mod(def_id);
}
}
}
}