Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl DefPathTable {
/// 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>,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]>,
Expand Down
23 changes: 6 additions & 17 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,11 @@ use rustc_target::spec::PanicStrategy;
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};

Expand Down Expand Up @@ -131,21 +129,12 @@ mod boxed_resolver {
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()
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_interface/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ use rustc_span::symbol::sym;
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.
Expand Down Expand Up @@ -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>>,
Expand Down Expand Up @@ -171,8 +170,7 @@ impl<'tcx> Queries<'tcx> {

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();
Expand All @@ -188,7 +186,7 @@ impl<'tcx> Queries<'tcx> {
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))
})
}

Expand Down Expand Up @@ -217,7 +215,7 @@ impl<'tcx> Queries<'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,
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use rustc_ast::expand::allocator::AllocatorKind;
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;
Expand All @@ -30,11 +30,10 @@ use proc_macro::bridge::client::ProcMacro;
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.
Expand Down Expand Up @@ -153,7 +152,7 @@ impl CStore {

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)> {
Expand Down Expand Up @@ -245,7 +244,7 @@ impl 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,
Expand Down
12 changes: 3 additions & 9 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1169,15 +1169,9 @@ impl<'a, 'tcx> CrateMetadataRef<'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))
})
}

Expand Down
15 changes: 1 addition & 14 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ provide! { tcx, def_id, other, cdata,
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) }

Expand Down Expand Up @@ -608,20 +609,6 @@ impl CStore {
) -> 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 {
Expand Down
16 changes: 16 additions & 0 deletions compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_middle/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1836,6 +1836,11 @@ rustc_queries! {
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
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,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.
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_resolve/src/build_reduced_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
};
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,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_resolve/src/effective_visibilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl ParentId<'_> {
}
}

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
Expand Down Expand Up @@ -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(),
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type Res = def::Res<NodeId>;

/// 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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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>,
}

Expand All @@ -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();
Expand All @@ -433,7 +433,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
}
}

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);
}
Expand Down
9 changes: 4 additions & 5 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ struct BindingInfo {
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PatternSource {
pub(crate) enum PatternSource {
Match,
Let,
For,
Expand All @@ -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",
Expand Down Expand Up @@ -2374,9 +2374,8 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
// 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];
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2626,7 +2626,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
}

/// 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,
Expand All @@ -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(
Expand Down
Loading