Revert "Reduce the amount of untracked state in TyCtxt"

This commit is contained in:
Camille Gillot 2021-06-01 09:05:22 +02:00 committed by GitHub
parent c9c1f8be3f
commit 0f0f3138cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 255 additions and 234 deletions

View File

@ -3677,7 +3677,6 @@ dependencies = [
"rustc_incremental",
"rustc_index",
"rustc_llvm",
"rustc_metadata",
"rustc_middle",
"rustc_serialize",
"rustc_session",

View File

@ -1,6 +1,6 @@
use rustc_span::symbol::{sym, Symbol};
#[derive(Clone, Debug, Copy, HashStable_Generic)]
#[derive(Clone, Copy)]
pub enum AllocatorKind {
Global,
Default,

View File

@ -43,7 +43,7 @@ use rustc_ast::walk_list;
use rustc_ast::{self as ast, *};
use rustc_ast_pretty::pprust;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
use rustc_errors::{struct_span_err, Applicability};
use rustc_hir as hir;
@ -198,7 +198,7 @@ pub trait ResolverAstLowering {
fn next_node_id(&mut self) -> NodeId;
fn take_trait_map(&mut self) -> NodeMap<Vec<hir::TraitCandidate>>;
fn trait_map(&self) -> &NodeMap<Vec<hir::TraitCandidate>>;
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
@ -501,13 +501,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let proc_macros =
c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
for (k, v) in self.resolver.take_trait_map().into_iter() {
if let Some(Some(hir_id)) = self.node_id_to_hir_id.get(k) {
let map = trait_map.entry(hir_id.owner).or_default();
map.insert(hir_id.local_id, v.into_boxed_slice());
}
}
let trait_map = self
.resolver
.trait_map()
.iter()
.filter_map(|(&k, v)| {
self.node_id_to_hir_id.get(k).and_then(|id| id.as_ref()).map(|id| (*id, v.clone()))
})
.collect();
let mut def_id_to_hir_id = IndexVec::default();

View File

@ -19,7 +19,7 @@ pub(crate) fn codegen(
});
if any_dynamic_crate {
false
} else if let Some(kind) = tcx.allocator_kind(()) {
} else if let Some(kind) = tcx.allocator_kind() {
codegen_inner(module, unwind_context, kind);
true
} else {

View File

@ -14,7 +14,6 @@ extern crate rustc_fs_util;
extern crate rustc_hir;
extern crate rustc_incremental;
extern crate rustc_index;
extern crate rustc_metadata;
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_target;

View File

@ -10,7 +10,7 @@ pub(crate) fn write_metadata<O: WriteMetadata>(tcx: TyCtxt<'_>, object: &mut O)
use std::io::Write;
let metadata = tcx.encode_metadata();
let mut compressed = rustc_metadata::METADATA_HEADER.to_vec();
let mut compressed = tcx.metadata_encoding_version();
FrameEncoder::new(&mut compressed).write_all(&metadata.raw_data).unwrap();
object.add_rustc_section(

View File

@ -27,7 +27,6 @@ rustc_hir = { path = "../rustc_hir" }
rustc_incremental = { path = "../rustc_incremental" }
rustc_index = { path = "../rustc_index" }
rustc_llvm = { path = "../rustc_llvm" }
rustc_metadata = { path = "../rustc_metadata" }
rustc_session = { path = "../rustc_session" }
rustc_serialize = { path = "../rustc_serialize" }
rustc_target = { path = "../rustc_target" }

View File

@ -63,7 +63,7 @@ pub fn write_compressed_metadata<'tcx>(
let section_name = if tcx.sess.target.is_like_osx { "__DATA,.rustc" } else { ".rustc" };
let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
let mut compressed = rustc_metadata::METADATA_HEADER.to_vec();
let mut compressed = tcx.metadata_encoding_version();
FrameEncoder::new(&mut compressed).write_all(&metadata.raw_data).unwrap();
let llmeta = common::bytes_in_context(metadata_llcx, &compressed);

View File

@ -180,7 +180,7 @@ fn exported_symbols_provider_local(
symbols.push((exported_symbol, SymbolExportLevel::C));
}
if tcx.allocator_kind(()).is_some() {
if tcx.allocator_kind().is_some() {
for method in ALLOCATOR_METHODS {
let symbol_name = format!("__rust_{}", method.name);
let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));

View File

@ -517,7 +517,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
});
let allocator_module = if any_dynamic_crate {
None
} else if let Some(kind) = tcx.allocator_kind(()) {
} else if let Some(kind) = tcx.allocator_kind() {
let llmod_id =
cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
let mut modules = backend.new_metadata(tcx, &llmod_id);

View File

@ -550,3 +550,35 @@ pub fn hash_stable_hashmap<HCX, K, V, R, SK, F>(
entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
entries.hash_stable(hcx, hasher);
}
/// A vector container that makes sure that its items are hashed in a stable
/// order.
#[derive(Debug)]
pub struct StableVec<T>(Vec<T>);
impl<T> StableVec<T> {
pub fn new(v: Vec<T>) -> Self {
StableVec(v)
}
}
impl<T> ::std::ops::Deref for StableVec<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.0
}
}
impl<T, HCX> HashStable<HCX> for StableVec<T>
where
T: HashStable<HCX> + ToStableHashKey<HCX>,
{
fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
let StableVec(ref v) = *self;
let mut sorted: Vec<_> = v.iter().map(|x| x.to_stable_hash_key(hcx)).collect();
sorted.sort_unstable();
sorted.hash_stable(hcx, hasher);
}
}

View File

@ -43,7 +43,6 @@ macro_rules! arena_types {
[] stmt: rustc_hir::Stmt<$tcx>,
[] field_def: rustc_hir::FieldDef<$tcx>,
[] trait_item_ref: rustc_hir::TraitItemRef,
[] trait_candidate: rustc_hir::TraitCandidate,
[] ty: rustc_hir::Ty<$tcx>,
[] type_binding: rustc_hir::TypeBinding<$tcx>,
[] variant: rustc_hir::Variant<$tcx>,

View File

@ -25,7 +25,7 @@ use tracing::debug;
/// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
/// stores the `DefIndex` of its parent.
/// There is one `DefPathTable` for each crate.
#[derive(Clone, Default, Debug)]
#[derive(Clone, Default)]
pub struct DefPathTable {
index_to_key: IndexVec<DefIndex, DefKey>,
def_path_hashes: IndexVec<DefIndex, DefPathHash>,
@ -107,7 +107,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(Clone)]
pub struct Definitions {
table: DefPathTable,

View File

@ -1,7 +1,7 @@
// ignore-tidy-filelength
use crate::def::{CtorKind, DefKind, Res};
use crate::def_id::DefId;
crate use crate::hir_id::{HirId, ItemLocalId};
crate use crate::hir_id::HirId;
use crate::{itemlikevisit, LangItem};
use rustc_ast::util::parser::ExprPrecedence;
@ -10,7 +10,6 @@ use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObject
pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
pub use rustc_ast::{CaptureBy, Movability, Mutability};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
use rustc_macros::HashStable_Generic;
use rustc_span::source_map::Spanned;
@ -659,9 +658,7 @@ pub struct Crate<'hir> {
/// they are declared in the static array generated by proc_macro_harness.
pub proc_macros: Vec<HirId>,
/// Map indicating what traits are in scope for places where this
/// is relevant; generated by resolve.
pub trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, Box<[TraitCandidate]>>>,
pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
/// Collected attributes from HIR nodes.
pub attrs: BTreeMap<HirId, &'hir [Attribute]>,

View File

@ -524,7 +524,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
Ok(vec![self.tcx.crate_name(cnum).to_string()])
Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
}
fn path_qualified(
self,

View File

@ -799,7 +799,7 @@ pub fn create_global_ctxt<'tcx>(
query_result_on_disk_cache,
queries.as_dyn(),
&crate_name,
outputs,
&outputs,
)
})
});

View File

@ -922,7 +922,7 @@ impl<'tcx> LateContext<'tcx> {
}
fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
Ok(vec![self.tcx.crate_name(cnum)])
Ok(vec![self.tcx.original_crate_name(cnum)])
}
fn path_qualified(

View File

@ -51,12 +51,6 @@ pub struct CStore {
unused_externs: Vec<Symbol>,
}
impl std::fmt::Debug for CStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CStore").finish_non_exhaustive()
}
}
pub struct CrateLoader<'a> {
// Immutable configuration.
sess: &'a Session,

View File

@ -31,5 +31,3 @@ mod rmeta;
pub mod creader;
pub mod dynamic_lib;
pub mod locator;
pub use rmeta::METADATA_HEADER;

View File

@ -1,7 +1,7 @@
use crate::creader::{CStore, LoadedMacro};
use crate::foreign_modules;
use crate::native_libs;
use crate::rmeta::encoder;
use crate::rmeta::{self, encoder};
use rustc_ast as ast;
use rustc_ast::expand::allocator::AllocatorKind;
@ -187,8 +187,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
foreign_modules => { cdata.get_foreign_modules(tcx) }
crate_hash => { cdata.root.hash }
crate_host_hash => { cdata.host_hash }
crate_name => { cdata.root.name }
is_private_dep => { cdata.private_dep }
original_crate_name => { cdata.root.name }
extra_filename => { cdata.root.extra_filename.clone() }
@ -205,6 +204,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
let r = *cdata.dep_kind.lock();
r
}
crate_name => { cdata.root.name }
item_children => {
let mut result = SmallVec::<[_; 8]>::new();
cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
@ -477,6 +477,10 @@ impl CrateStore for CStore {
self.get_crate_data(cnum).root.name
}
fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
self.get_crate_data(cnum).private_dep
}
fn stable_crate_id_untracked(&self, cnum: CrateNum) -> StableCrateId {
self.get_crate_data(cnum).root.stable_crate_id
}
@ -524,6 +528,10 @@ impl CrateStore for CStore {
encoder::encode_metadata(tcx)
}
fn metadata_encoding_version(&self) -> &[u8] {
rmeta::METADATA_HEADER
}
fn allocator_kind(&self) -> Option<AllocatorKind> {
self.allocator_kind()
}

View File

@ -445,7 +445,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
}
fn encode_def_path_table(&mut self) {
let table = self.tcx.resolutions(()).definitions.def_path_table();
let table = self.tcx.hir().definitions().def_path_table();
if self.is_proc_macro {
for def_index in std::iter::once(CRATE_DEF_INDEX)
.chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
@ -1062,7 +1062,7 @@ impl EncodeContext<'a, 'tcx> {
let data = ModData {
reexports,
expansion: tcx.resolutions(()).definitions.expansion_that_defined(local_def_id),
expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
};
record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
@ -1673,7 +1673,7 @@ impl EncodeContext<'a, 'tcx> {
.iter()
.map(|&cnum| {
let dep = CrateDep {
name: self.tcx.crate_name(cnum),
name: self.tcx.original_crate_name(cnum),
hash: self.tcx.crate_hash(cnum),
host_hash: self.tcx.crate_host_hash(cnum),
kind: self.tcx.dep_kind(cnum),
@ -1754,7 +1754,7 @@ impl EncodeContext<'a, 'tcx> {
.map(|(trait_def_id, mut impls)| {
// Bring everything into deterministic order for hashing
impls.sort_by_cached_key(|&(index, _)| {
tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
});
TraitImpls {

View File

@ -51,7 +51,7 @@ const METADATA_VERSION: u8 = 5;
/// This header is followed by the position of the `CrateRoot`,
/// which is encoded as a 32-bit big-endian unsigned integer,
/// and further followed by the rustc version string.
pub const METADATA_HEADER: &[u8; 8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
crate const METADATA_HEADER: &[u8; 8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
/// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
/// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).

View File

@ -285,7 +285,7 @@ pub type DepNode = rustc_query_system::dep_graph::DepNode<DepKind>;
// required that their size stay the same, but we don't want to change
// it inadvertently. This assert just ensures we're aware of any change.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
static_assert_size!(DepNode, 18);
static_assert_size!(DepNode, 17);
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
static_assert_size!(DepNode, 24);

View File

@ -9,7 +9,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::svh::Svh;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
use rustc_hir::definitions::{DefKey, DefPath, Definitions};
use rustc_hir::intravisit;
use rustc_hir::intravisit::Visitor;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
@ -154,9 +154,13 @@ impl<'hir> Map<'hir> {
self.tcx.hir_crate(())
}
#[inline]
pub fn definitions(&self) -> &'hir Definitions {
&self.tcx.definitions
}
pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
// Accessing the DefKey is ok, since it is part of DefPathHash.
self.tcx.untracked_resolutions.definitions.def_key(def_id)
self.tcx.definitions.def_key(def_id)
}
pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
@ -164,14 +168,7 @@ impl<'hir> Map<'hir> {
}
pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
// Accessing the DefPath is ok, since it is part of DefPathHash.
self.tcx.untracked_resolutions.definitions.def_path(def_id)
}
#[inline]
pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
// Accessing the DefPathHash is ok, it is incr. comp. stable.
self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
self.tcx.definitions.def_path(def_id)
}
#[inline]
@ -187,26 +184,16 @@ impl<'hir> Map<'hir> {
#[inline]
pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
// Create a dependency to the owner to ensure the query gets re-executed when the amount of
// children changes.
self.tcx.ensure().hir_owner_nodes(hir_id.owner);
self.tcx.untracked_resolutions.definitions.opt_hir_id_to_local_def_id(hir_id)
self.tcx.definitions.opt_hir_id_to_local_def_id(hir_id)
}
#[inline]
pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
let ret = self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id);
// Create a dependency to the owner to ensure the query gets re-executed when the amount of
// children changes.
self.tcx.ensure().hir_owner_nodes(ret.owner);
ret
self.tcx.definitions.local_def_id_to_hir_id(def_id)
}
pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
// Create a dependency to the crate to be sure we reexcute this when the amount of
// definitions change.
self.tcx.ensure().hir_crate(());
self.tcx.untracked_resolutions.definitions.iter_local_def_id()
self.tcx.definitions.iter_local_def_id()
}
pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
@ -945,15 +932,9 @@ impl<'hir> intravisit::Map<'hir> for Map<'hir> {
pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tcx> {
let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
// We can access untracked state since we are an eval_always query.
let hcx = tcx.create_stable_hashing_context();
let mut collector = NodeCollector::root(
tcx.sess,
&**tcx.arena,
tcx.untracked_crate,
&tcx.untracked_resolutions.definitions,
hcx,
);
let mut collector =
NodeCollector::root(tcx.sess, &**tcx.arena, tcx.untracked_crate, &tcx.definitions, hcx);
intravisit::walk_crate(&mut collector, tcx.untracked_crate);
let map = collector.finalize_and_compute_crate_hash();
@ -963,7 +944,6 @@ pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tc
pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
assert_eq!(crate_num, LOCAL_CRATE);
// We can access untracked state since we are an eval_always query.
let mut hcx = tcx.create_stable_hashing_context();
let mut hir_body_nodes: Vec<_> = tcx
@ -971,7 +951,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
.map
.iter_enumerated()
.filter_map(|(def_id, hod)| {
let def_path_hash = tcx.untracked_resolutions.definitions.def_path_hash(def_id);
let def_path_hash = tcx.definitions.def_path_hash(def_id);
let mut hasher = StableHasher::new();
hod.as_ref()?.hash_stable(&mut hcx, &mut hasher);
AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id }
@ -988,7 +968,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
},
);
let upstream_crates = upstream_crates(&*tcx.untracked_resolutions.cstore);
let upstream_crates = upstream_crates(&*tcx.cstore);
// We hash the final, remapped names of all local source files so we
// don't have to include the path prefix remapping commandline args.

View File

@ -182,7 +182,7 @@ pub type MetadataLoaderDyn = dyn MetadataLoader + Sync;
/// that it's *not* tracked for dependency information throughout compilation
/// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
/// during resolve)
pub trait CrateStore: std::fmt::Debug {
pub trait CrateStore {
fn as_any(&self) -> &dyn Any;
// resolve
@ -199,6 +199,7 @@ pub trait CrateStore: std::fmt::Debug {
// "queries" used in resolve that aren't tracked for incremental compilation
fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool;
fn stable_crate_id_untracked(&self, cnum: CrateNum) -> StableCrateId;
fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
@ -208,6 +209,7 @@ pub trait CrateStore: std::fmt::Debug {
// utility functions
fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata;
fn metadata_encoding_version(&self) -> &[u8];
fn allocator_kind(&self) -> Option<AllocatorKind>;
}

View File

@ -49,7 +49,7 @@ impl<'tcx> ExportedSymbol<'tcx> {
pub fn metadata_symbol_name(tcx: TyCtxt<'_>) -> String {
format!(
"rust_metadata_{}_{:08x}",
tcx.crate_name(LOCAL_CRATE),
tcx.original_crate_name(LOCAL_CRATE),
tcx.sess.local_stable_crate_id().to_u64(),
)
}

View File

@ -14,12 +14,6 @@ rustc_queries! {
desc { "trigger a delay span bug" }
}
query resolutions(_: ()) -> &'tcx ty::ResolverOutputs {
eval_always
no_hash
desc { "get the resolver outputs" }
}
/// Represents crate as a whole (as distinct from the top-level crate module).
/// If you call `hir_crate` (e.g., indirectly by calling `tcx.hir().krate()`),
/// we will have to assume that any change means that you need to be recompiled.
@ -1133,12 +1127,14 @@ rustc_queries! {
desc { "computing whether impls specialize one another" }
}
query in_scope_traits_map(_: LocalDefId)
-> Option<&'tcx FxHashMap<ItemLocalId, Box<[TraitCandidate]>>> {
-> Option<&'tcx FxHashMap<ItemLocalId, StableVec<TraitCandidate>>> {
eval_always
desc { "traits in scope at a block" }
}
query module_exports(def_id: LocalDefId) -> Option<&'tcx [Export<LocalDefId>]> {
desc { |tcx| "looking up items exported by `{}`", tcx.def_path_str(def_id.to_def_id()) }
eval_always
}
query impl_defaultness(def_id: DefId) -> hir::Defaultness {
@ -1252,6 +1248,10 @@ rustc_queries! {
eval_always
desc { "looking up the hash of a host version of a crate" }
}
query original_crate_name(_: CrateNum) -> Symbol {
eval_always
desc { "looking up the original name a crate" }
}
query extra_filename(_: CrateNum) -> String {
eval_always
desc { "looking up the extra filename for a crate" }
@ -1328,6 +1328,7 @@ rustc_queries! {
}
query visibility(def_id: DefId) -> ty::Visibility {
eval_always
desc { |tcx| "computing visibility of `{}`", tcx.def_path_str(def_id) }
}
@ -1352,6 +1353,8 @@ rustc_queries! {
desc { |tcx| "collecting child items of `{}`", tcx.def_path_str(def_id) }
}
query extern_mod_stmt_cnum(def_id: LocalDefId) -> Option<CrateNum> {
// This depends on untracked global state (`tcx.extern_crate_map`)
eval_always
desc { |tcx| "computing crate imported by `{}`", tcx.def_path_str(def_id.to_def_id()) }
}
@ -1412,26 +1415,22 @@ rustc_queries! {
eval_always
desc { "generating a postorder list of CrateNums" }
}
/// Returns whether or not the crate with CrateNum 'cnum'
/// is marked as a private dependency
query is_private_dep(c: CrateNum) -> bool {
desc { "check whether crate {} is a private dependency", c }
}
query allocator_kind(_: ()) -> Option<AllocatorKind> {
desc { "allocator kind for the current crate" }
}
query upvars_mentioned(def_id: DefId) -> Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>> {
desc { |tcx| "collecting upvars mentioned in `{}`", tcx.def_path_str(def_id) }
eval_always
}
query maybe_unused_trait_import(def_id: LocalDefId) -> bool {
eval_always
desc { |tcx| "maybe_unused_trait_import for `{}`", tcx.def_path_str(def_id.to_def_id()) }
}
query maybe_unused_extern_crates(_: ()) -> &'tcx [(LocalDefId, Span)] {
eval_always
desc { "looking up all possibly unused extern crates" }
}
query names_imported_by_glob_use(def_id: LocalDefId) -> &'tcx FxHashSet<Symbol> {
query names_imported_by_glob_use(def_id: LocalDefId)
-> &'tcx FxHashSet<Symbol> {
eval_always
desc { |tcx| "names_imported_by_glob_use for `{}`", tcx.def_path_str(def_id.to_def_id()) }
}
@ -1441,6 +1440,7 @@ rustc_queries! {
desc { "calculating the stability index for the local crate" }
}
query all_crate_nums(_: ()) -> &'tcx [CrateNum] {
eval_always
desc { "fetching all foreign CrateNum instances" }
}

View File

@ -2,12 +2,13 @@
use crate::arena::Arena;
use crate::dep_graph::DepGraph;
use crate::hir::exports::ExportMap;
use crate::hir::place::Place as HirPlace;
use crate::ich::{NodeIdHashingMode, StableHashingContext};
use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
use crate::lint::{struct_lint_level, LintDiagnosticBuilder, LintLevelSource};
use crate::middle;
use crate::middle::cstore::EncodedMetadata;
use crate::middle::cstore::{CrateStoreDyn, EncodedMetadata};
use crate::middle::resolve_lifetime::{self, LifetimeScopeForPath, ObjectLifetimeDefault};
use crate::middle::stability;
use crate::mir::interpret::{self, Allocation, ConstValue, Scalar};
@ -20,22 +21,24 @@ use crate::ty::TyKind::*;
use crate::ty::{
self, AdtDef, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig, Const, ConstVid,
DefIdTree, ExistentialPredicate, FloatTy, FloatVar, FloatVid, GenericParamDefKind, InferConst,
InferTy, IntTy, IntVar, IntVid, List, ParamConst, ParamTy, PolyFnSig, Predicate,
PredicateInner, PredicateKind, ProjectionTy, Region, RegionKind, ReprOptions,
TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, UintTy,
InferTy, IntTy, IntVar, IntVid, List, MainDefinition, ParamConst, ParamTy, PolyFnSig,
Predicate, PredicateInner, PredicateKind, ProjectionTy, Region, RegionKind, ReprOptions,
TraitObjectVisitor, Ty, TyKind, TyS, TyVar, TyVid, TypeAndMut, UintTy, Visibility,
};
use rustc_ast as ast;
use rustc_ast::expand::allocator::AllocatorKind;
use rustc_attr as attr;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::profiling::SelfProfilerRef;
use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableVec};
use rustc_data_structures::steal::Steal;
use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
use rustc_hir::definitions::Definitions;
use rustc_hir::intravisit::Visitor;
use rustc_hir::lang_items::LangItem;
use rustc_hir::{
@ -934,6 +937,8 @@ pub struct GlobalCtxt<'tcx> {
interners: CtxtInterners<'tcx>,
pub(crate) cstore: Box<CrateStoreDyn>,
pub sess: &'tcx Session,
/// This only ever stores a `LintStore` but we don't want a dependency on that type here.
@ -955,10 +960,21 @@ pub struct GlobalCtxt<'tcx> {
/// Common consts, pre-interned for your convenience.
pub consts: CommonConsts<'tcx>,
/// Output of the resolver.
pub(crate) untracked_resolutions: ty::ResolverOutputs,
/// Visibilities produced by resolver.
pub visibilities: FxHashMap<LocalDefId, Visibility>,
/// Resolutions of `extern crate` items produced by resolver.
extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
/// Map indicating what traits are in scope for places where this
/// is relevant; generated by resolve.
trait_map: FxHashMap<LocalDefId, FxHashMap<ItemLocalId, StableVec<TraitCandidate>>>,
/// Export map produced by name resolution.
export_map: ExportMap<LocalDefId>,
pub(crate) untracked_crate: &'tcx hir::Crate<'tcx>,
pub(crate) definitions: Definitions,
/// This provides access to the incremental compilation on-disk cache for query results.
/// Do not access this directly. It is only meant to be used by
@ -969,6 +985,15 @@ pub struct GlobalCtxt<'tcx> {
pub queries: &'tcx dyn query::QueryEngine<'tcx>,
pub query_caches: query::QueryCaches<'tcx>,
maybe_unused_trait_imports: FxHashSet<LocalDefId>,
maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
/// A map of glob use to a set of names it actually imports. Currently only
/// used in save-analysis.
pub(crate) glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
/// Extern prelude entries. The value is `true` if the entry was introduced
/// via `extern crate` item and not `--extern` option or compiler built-in.
pub extern_prelude: FxHashMap<Symbol, bool>,
// Internal caches for metadata decoding. No need to track deps on this.
pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
pub pred_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Predicate<'tcx>>>,
@ -984,7 +1009,7 @@ pub struct GlobalCtxt<'tcx> {
/// The definite name of the current crate after taking into account
/// attributes, commandline parameters, etc.
crate_name: Symbol,
pub crate_name: Symbol,
/// Data layout specification for the current target.
pub data_layout: TargetDataLayout,
@ -1001,6 +1026,8 @@ pub struct GlobalCtxt<'tcx> {
layout_interner: ShardedHashMap<&'tcx Layout, ()>,
output_filenames: Arc<OutputFilenames>,
pub main_def: Option<MainDefinition>,
}
impl<'tcx> TyCtxt<'tcx> {
@ -1112,7 +1139,7 @@ impl<'tcx> TyCtxt<'tcx> {
on_disk_cache: Option<query::OnDiskCache<'tcx>>,
queries: &'tcx dyn query::QueryEngine<'tcx>,
crate_name: &str,
output_filenames: OutputFilenames,
output_filenames: &OutputFilenames,
) -> GlobalCtxt<'tcx> {
let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| {
s.fatal(&err);
@ -1121,19 +1148,35 @@ impl<'tcx> TyCtxt<'tcx> {
let common_types = CommonTypes::new(&interners);
let common_lifetimes = CommonLifetimes::new(&interners);
let common_consts = CommonConsts::new(&interners, &common_types);
let cstore = resolutions.cstore;
let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
for (hir_id, v) in krate.trait_map.iter() {
let map = trait_map.entry(hir_id.owner).or_default();
map.insert(hir_id.local_id, StableVec::new(v.to_vec()));
}
GlobalCtxt {
sess: s,
lint_store,
cstore,
arena,
interners,
dep_graph,
untracked_resolutions: resolutions,
prof: s.prof.clone(),
types: common_types,
lifetimes: common_lifetimes,
consts: common_consts,
visibilities: resolutions.visibilities,
extern_crate_map: resolutions.extern_crate_map,
trait_map,
export_map: resolutions.export_map,
maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports,
maybe_unused_extern_crates: resolutions.maybe_unused_extern_crates,
glob_map: resolutions.glob_map,
extern_prelude: resolutions.extern_prelude,
untracked_crate: krate,
definitions: resolutions.definitions,
on_disk_cache,
queries,
query_caches: query::QueryCaches::default(),
@ -1147,7 +1190,8 @@ impl<'tcx> TyCtxt<'tcx> {
stability_interner: Default::default(),
const_stability_interner: Default::default(),
alloc_map: Lock::new(interpret::AllocMap::new()),
output_filenames: Arc::new(output_filenames),
output_filenames: Arc::new(output_filenames.clone()),
main_def: resolutions.main_def,
}
}
@ -1206,17 +1250,16 @@ impl<'tcx> TyCtxt<'tcx> {
self.all_crate_nums(())
}
pub fn allocator_kind(self) -> Option<AllocatorKind> {
self.cstore.allocator_kind()
}
pub fn features(self) -> &'tcx rustc_feature::Features {
self.features_query(())
}
pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey {
// Accessing the DefKey is ok, since it is part of DefPathHash.
if let Some(id) = id.as_local() {
self.untracked_resolutions.definitions.def_key(id)
} else {
self.untracked_resolutions.cstore.def_key(id)
}
if let Some(id) = id.as_local() { self.hir().def_key(id) } else { self.cstore.def_key(id) }
}
/// Converts a `DefId` into its fully expanded `DefPath` (every
@ -1225,21 +1268,25 @@ impl<'tcx> TyCtxt<'tcx> {
/// Note that if `id` is not local to this crate, the result will
/// be a non-local `DefPath`.
pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
// Accessing the DefPath is ok, since it is part of DefPathHash.
if let Some(id) = id.as_local() {
self.untracked_resolutions.definitions.def_path(id)
self.hir().def_path(id)
} else {
self.untracked_resolutions.cstore.def_path(id)
self.cstore.def_path(id)
}
}
/// Returns whether or not the crate with CrateNum 'cnum'
/// is marked as a private dependency
pub fn is_private_dep(self, cnum: CrateNum) -> bool {
if cnum == LOCAL_CRATE { false } else { self.cstore.crate_is_private_dep_untracked(cnum) }
}
#[inline]
pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
// Accessing the DefPathHash is ok, it is incr. comp. stable.
if let Some(def_id) = def_id.as_local() {
self.untracked_resolutions.definitions.def_path_hash(def_id)
self.definitions.def_path_hash(def_id)
} else {
self.untracked_resolutions.cstore.def_path_hash(def_id)
self.cstore.def_path_hash(def_id)
}
}
@ -1251,10 +1298,9 @@ impl<'tcx> TyCtxt<'tcx> {
let (crate_name, stable_crate_id) = if def_id.is_local() {
(self.crate_name, self.sess.local_stable_crate_id())
} else {
let cstore = &self.untracked_resolutions.cstore;
(
cstore.crate_name_untracked(def_id.krate),
cstore.stable_crate_id_untracked(def_id.krate),
self.cstore.crate_name_untracked(def_id.krate),
self.def_path_hash(def_id.krate.as_def_id()).stable_crate_id(),
)
};
@ -1268,36 +1314,33 @@ impl<'tcx> TyCtxt<'tcx> {
)
}
pub fn metadata_encoding_version(self) -> Vec<u8> {
self.cstore.metadata_encoding_version().to_vec()
}
pub fn encode_metadata(self) -> EncodedMetadata {
let _prof_timer = self.prof.verbose_generic_activity("generate_crate_metadata");
self.untracked_resolutions.cstore.encode_metadata(self)
self.cstore.encode_metadata(self)
}
// Note that this is *untracked* and should only be used within the query
// system if the result is otherwise tracked through queries
pub fn cstore_as_any(self) -> &'tcx dyn Any {
self.untracked_resolutions.cstore.as_any()
self.cstore.as_any()
}
#[inline(always)]
pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> {
let krate = self.gcx.untracked_crate;
let resolutions = &self.gcx.untracked_resolutions;
StableHashingContext::new(self.sess, krate, &resolutions.definitions, &*resolutions.cstore)
StableHashingContext::new(self.sess, krate, &self.definitions, &*self.cstore)
}
#[inline(always)]
pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> {
let krate = self.gcx.untracked_crate;
let resolutions = &self.gcx.untracked_resolutions;
StableHashingContext::ignore_spans(
self.sess,
krate,
&resolutions.definitions,
&*resolutions.cstore,
)
StableHashingContext::ignore_spans(self.sess, krate, &self.definitions, &*self.cstore)
}
pub fn serialize_query_result_cache(self, encoder: &mut FileEncoder) -> FileEncodeResult {
@ -2619,10 +2662,8 @@ impl<'tcx> TyCtxt<'tcx> {
struct_lint_level(self.sess, lint, level, src, None, decorate);
}
pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> {
let map = self.in_scope_traits_map(id.owner)?;
let candidates = map.get(&id.local_id)?;
Some(&*candidates)
pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec<TraitCandidate>> {
self.in_scope_traits_map(id.owner).and_then(|map| map.get(&id.local_id))
}
pub fn named_region(self, id: HirId) -> Option<resolve_lifetime::Region> {
@ -2752,20 +2793,16 @@ fn ptr_eq<T, U>(t: *const T, u: *const U) -> bool {
}
pub fn provide(providers: &mut ty::query::Providers) {
providers.in_scope_traits_map = |tcx, id| tcx.hir_crate(()).trait_map.get(&id);
providers.resolutions = |tcx, ()| &tcx.untracked_resolutions;
providers.module_exports = |tcx, id| tcx.resolutions(()).export_map.get(&id).map(|v| &v[..]);
providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id);
providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]);
providers.crate_name = |tcx, id| {
assert_eq!(id, LOCAL_CRATE);
tcx.crate_name
};
providers.maybe_unused_trait_import =
|tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id);
providers.maybe_unused_extern_crates =
|tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
providers.names_imported_by_glob_use = |tcx, id| {
tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
};
providers.maybe_unused_trait_import = |tcx, id| tcx.maybe_unused_trait_imports.contains(&id);
providers.maybe_unused_extern_crates = |tcx, ()| &tcx.maybe_unused_extern_crates[..];
providers.names_imported_by_glob_use =
|tcx, id| tcx.arena.alloc(tcx.glob_map.get(&id).cloned().unwrap_or_default());
providers.lookup_stability = |tcx, id| {
let id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
@ -2779,10 +2816,8 @@ pub fn provide(providers: &mut ty::query::Providers) {
let id = tcx.hir().local_def_id_to_hir_id(id.expect_local());
tcx.stability().local_deprecation_entry(id)
};
providers.extern_mod_stmt_cnum =
|tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned();
providers.all_crate_nums =
|tcx, ()| tcx.arena.alloc_slice(&tcx.resolutions(()).cstore.crates_untracked());
providers.extern_mod_stmt_cnum = |tcx, id| tcx.extern_crate_map.get(&id).cloned();
providers.all_crate_nums = |tcx, ()| tcx.arena.alloc_slice(&tcx.cstore.crates_untracked());
providers.output_filenames = |tcx, ()| tcx.output_filenames.clone();
providers.features_query = |tcx, ()| tcx.sess.features_untracked();
providers.is_panic_runtime = |tcx, cnum| {
@ -2798,9 +2833,4 @@ pub fn provide(providers: &mut ty::query::Providers) {
// We want to check if the panic handler was defined in this crate
tcx.lang_items().panic_impl().map_or(false, |did| did.is_local())
};
providers.is_private_dep = |_tcx, cnum| {
assert_eq!(cnum, LOCAL_CRATE);
false
};
providers.allocator_kind = |tcx, ()| tcx.resolutions(()).cstore.allocator_kind();
}

View File

@ -112,7 +112,6 @@ mod sty;
// Data types
#[derive(Debug)]
pub struct ResolverOutputs {
pub definitions: rustc_hir::definitions::Definitions,
pub cstore: Box<CrateStoreDyn>,
@ -128,7 +127,7 @@ pub struct ResolverOutputs {
pub main_def: Option<MainDefinition>,
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy)]
pub struct MainDefinition {
pub res: Res<ast::NodeId>,
pub is_import: bool,
@ -1619,7 +1618,7 @@ impl<'tcx> TyCtxt<'tcx> {
fn item_name_from_def_id(self, def_id: DefId) -> Option<Symbol> {
if def_id.index == CRATE_DEF_INDEX {
Some(self.crate_name(def_id.krate))
Some(self.original_crate_name(def_id.krate))
} else {
let def_key = self.def_key(def_id);
match def_key.disambiguated_data.data {
@ -1867,7 +1866,7 @@ impl<'tcx> TyCtxt<'tcx> {
match scope.as_local() {
// Parsing and expansion aren't incremental, so we don't
// need to go through a query for the same-crate case.
Some(scope) => self.resolutions(()).definitions.expansion_that_defined(scope),
Some(scope) => self.hir().definitions().expansion_that_defined(scope),
None => self.expn_that_defined(scope),
}
}
@ -1887,7 +1886,7 @@ impl<'tcx> TyCtxt<'tcx> {
match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
{
Some(actual_expansion) => {
self.resolutions(()).definitions.parent_module_of_macro_def(actual_expansion)
self.hir().definitions().parent_module_of_macro_def(actual_expansion)
}
None => self.parent_module(block).to_def_id(),
};

View File

@ -452,7 +452,7 @@ pub trait PrettyPrinter<'tcx>:
}
// Re-exported `extern crate` (#43189).
DefPathData::CrateRoot => {
data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
}
_ => {}
}
@ -2313,7 +2313,7 @@ fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
&mut FxHashMap::default();
for symbol_set in tcx.resolutions(()).glob_map.values() {
for symbol_set in tcx.glob_map.values() {
for symbol in symbol_set {
unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);

View File

@ -33,8 +33,8 @@ use crate::traits::{self, ImplSource};
use crate::ty::subst::{GenericArg, SubstsRef};
use crate::ty::util::AlwaysRequiresDrop;
use crate::ty::{self, AdtSizedConstraint, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt};
use rustc_ast::expand::allocator::AllocatorKind;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_data_structures::stable_hasher::StableVec;
use rustc_data_structures::steal::Steal;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::Lrc;

View File

@ -641,11 +641,7 @@ impl<'sess> OnDiskCache<'sess> {
debug_assert_ne!(krate, LOCAL_CRATE);
// Try to find a definition in the current session, using the previous `DefIndex`
// as an initial guess.
let opt_def_id = tcx.untracked_resolutions.cstore.def_path_hash_to_def_id(
krate,
raw_def_id.index,
hash,
);
let opt_def_id = tcx.cstore.def_path_hash_to_def_id(krate, raw_def_id.index, hash);
debug!("def_path_to_def_id({:?}): opt_def_id = {:?}", hash, opt_def_id);
e.insert(opt_def_id);
opt_def_id

View File

@ -88,7 +88,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
}
fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
self.path.push_str(&self.tcx.crate_name(cnum).as_str());
self.path.push_str(&self.tcx.original_crate_name(cnum).as_str());
Ok(self)
}

View File

@ -147,22 +147,19 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(De
Some((tcx.hir().local_def_id(hir_id).to_def_id(), EntryFnType::Start))
} else if let Some((hir_id, _)) = visitor.attr_main_fn {
Some((tcx.hir().local_def_id(hir_id).to_def_id(), EntryFnType::Main))
} else {
if let Some(main_def) = tcx.resolutions(()).main_def {
if let Some(def_id) = main_def.opt_fn_def_id() {
if main_def.is_import && !tcx.features().imported_main {
let span = main_def.span;
feature_err(
&tcx.sess.parse_sess,
sym::imported_main,
span,
"using an imported function as entry point `main` is experimental",
)
.emit();
}
return Some((def_id, EntryFnType::Main));
}
} else if let Some(def_id) = tcx.main_def.and_then(|main_def| main_def.opt_fn_def_id()) {
if tcx.main_def.unwrap().is_import && !tcx.features().imported_main {
let span = tcx.main_def.unwrap().span;
feature_err(
&tcx.sess.parse_sess,
sym::imported_main,
span,
"using an imported function as entry point `main` is experimental",
)
.emit();
}
Some((def_id, EntryFnType::Main))
} else {
no_main_err(tcx, visitor);
None
}
@ -212,7 +209,7 @@ fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
err.note(&note);
}
if let Some(main_def) = tcx.resolutions(()).main_def {
if let Some(main_def) = tcx.main_def {
if main_def.opt_fn_def_id().is_none() {
// There is something at `crate::main`, but it is not a function definition.
err.span_label(main_def.span, &format!("non-function item at `crate::main` is found"));

View File

@ -2030,7 +2030,7 @@ pub fn provide(providers: &mut Providers) {
fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility {
let def_id = def_id.expect_local();
match tcx.resolutions(()).visibilities.get(&def_id) {
match tcx.visibilities.get(&def_id) {
Some(vis) => *vis,
None => {
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);

View File

@ -61,7 +61,7 @@ impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> {
match def_key.disambiguated_data.data {
DefPathData::CrateRoot => {
crate_name = self.tcx.crate_name(def_id.krate).as_str();
crate_name = self.tcx.original_crate_name(def_id.krate).as_str();
name = &*crate_name;
dis = "";
end_index = 3;

View File

@ -108,7 +108,7 @@ pub fn print_stats(tcx: TyCtxt<'_>) {
queries.iter().filter(|q| q.local_def_id_keys.is_some()).collect();
def_id_density.sort_by_key(|q| q.local_def_id_keys.unwrap());
eprintln!("\nLocal DefId density:");
let total = tcx.resolutions(()).definitions.def_index_count() as f64;
let total = tcx.hir().definitions().def_index_count() as f64;
for q in def_id_density.iter().rev() {
let local = q.local_def_id_keys.unwrap();
eprintln!(" {} - {} = ({}%)", q.name, local, (local as f64 * 100.0) / total);

View File

@ -910,8 +910,6 @@ pub struct Resolver<'a> {
extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
export_map: ExportMap<LocalDefId>,
trait_map: NodeMap<Vec<TraitCandidate>>,
#[cfg(debug_assertions)]
took_trait_map: bool,
/// A map from nodes to anonymous modules.
/// Anonymous modules are pseudo-modules that are implicitly created around items
@ -1140,13 +1138,8 @@ impl ResolverAstLowering for Resolver<'_> {
self.next_node_id()
}
fn take_trait_map(&mut self) -> NodeMap<Vec<TraitCandidate>> {
#[cfg(debug_assertions)]
{
debug_assert!(!self.took_trait_map);
self.took_trait_map = true;
}
std::mem::take(&mut self.trait_map)
fn trait_map(&self) -> &NodeMap<Vec<TraitCandidate>> {
&self.trait_map
}
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
@ -1294,8 +1287,6 @@ impl<'a> Resolver<'a> {
extern_crate_map: Default::default(),
export_map: FxHashMap::default(),
trait_map: Default::default(),
#[cfg(debug_assertions)]
took_trait_map: false,
underscore_disambiguator: 0,
empty_module,
module_map,

View File

@ -254,7 +254,7 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> {
}
fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
self.write_str(&self.tcx.crate_name(cnum).as_str())?;
self.write_str(&self.tcx.original_crate_name(cnum).as_str())?;
Ok(self)
}
fn path_qualified(

View File

@ -594,7 +594,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> {
self.push("C");
let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
self.push_disambiguator(stable_crate_id.to_u64());
let name = self.tcx.crate_name(cnum).as_str();
let name = self.tcx.original_crate_name(cnum).as_str();
self.push_ident(&name);
Ok(self)
}

View File

@ -6,7 +6,6 @@ use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt, WithConstness};
use rustc_middle::ty::{ToPredicate, TypeFoldable};
use rustc_session::DiagnosticMessageId;
use rustc_span::def_id::LOCAL_CRATE;
use rustc_span::Span;
#[derive(Copy, Clone, Debug)]
@ -232,8 +231,7 @@ pub fn report_autoderef_recursion_limit_error<'tcx>(tcx: TyCtxt<'tcx>, span: Spa
.span_label(span, "deref recursion limit reached")
.help(&format!(
"consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
suggested_limit,
tcx.crate_name(LOCAL_CRATE),
suggested_limit, tcx.crate_name,
))
.emit();
}

View File

@ -21,7 +21,6 @@ use rustc_middle::ty::{
Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
};
use rustc_middle::ty::{TypeAndMut, TypeckResults};
use rustc_span::def_id::LOCAL_CRATE;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
use rustc_target::spec::abi;
@ -2314,8 +2313,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
let suggested_limit = current_limit * 2;
err.help(&format!(
"consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
suggested_limit,
self.tcx.crate_name(LOCAL_CRATE),
suggested_limit, self.tcx.crate_name,
));
}

View File

@ -1,11 +1,12 @@
use rustc_data_structures::fx::FxIndexSet;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
use rustc_middle::hir::map as hir_map;
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{
self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, WithConstness,
};
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use rustc_trait_selection::traits;
@ -387,6 +388,11 @@ fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamE
tcx.param_env(def_id).with_reveal_all_normalized(tcx)
}
fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
assert_eq!(crate_num, LOCAL_CRATE);
tcx.crate_name
}
fn instance_def_size_estimate<'tcx>(
tcx: TyCtxt<'tcx>,
instance_def: ty::InstanceDef<'tcx>,
@ -532,6 +538,7 @@ pub fn provide(providers: &mut ty::query::Providers) {
param_env,
param_env_reveal_all_normalized,
trait_of_item,
original_crate_name,
instance_def_size_estimate,
issue33140_self_ty,
impl_defaultness,

View File

@ -116,8 +116,6 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) {
crates_to_lint: &mut crates_to_lint,
});
let extern_prelude = &tcx.resolutions(()).extern_prelude;
for extern_crate in &crates_to_lint {
let def_id = extern_crate.def_id.expect_local();
let id = tcx.hir().local_def_id_to_hir_id(def_id);
@ -157,7 +155,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) {
// If the extern crate isn't in the extern prelude,
// there is no way it can be written as an `use`.
let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
if !extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
if !tcx.extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
continue;
}

View File

@ -527,7 +527,7 @@ fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::St
}
fn build_macro(cx: &mut DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
let imported_from = cx.tcx.crate_name(did.krate);
let imported_from = cx.tcx.original_crate_name(did.krate);
match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
LoadedMacro::MacroDef(def, _) => {
let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {

View File

@ -9,7 +9,6 @@ use rustc_hir::Node;
use rustc_middle::middle::privacy::AccessLevel;
use rustc_middle::ty::TyCtxt;
use rustc_span;
use rustc_span::def_id::LOCAL_CRATE;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Symbol};
@ -77,7 +76,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
&Spanned { span, node: hir::VisibilityKind::Public },
hir::CRATE_HIR_ID,
&krate.item,
self.cx.tcx.crate_name(LOCAL_CRATE),
self.cx.tcx.crate_name,
);
// Attach the crate's exported macros to the top-level module.
// In the case of macros 2.0 (`pub macro`), and for built-in `derive`s or attributes as

View File

@ -21,7 +21,7 @@ extern "C" {
}
#[cfg(not(cfail1))]
#[rustc_dirty(cfg = "cfail2")]
#[rustc_dirty(cfg = "cfail2", except = "hir_owner_nodes")]
#[rustc_clean(cfg = "cfail3")]
extern "C" {
pub fn change_function_name2(c: i64) -> i32;
@ -112,7 +112,7 @@ extern "C" {
}
#[cfg(not(cfail1))]
#[rustc_dirty(cfg = "cfail2")]
#[rustc_dirty(cfg = "cfail2", except = "hir_owner_nodes")]
#[rustc_clean(cfg = "cfail3")]
extern "rust-call" {
pub fn change_calling_convention(c: i32);
@ -125,7 +125,7 @@ extern "C" {
}
#[cfg(not(cfail1))]
#[rustc_dirty(cfg = "cfail2")]
#[rustc_dirty(cfg = "cfail2", except = "hir_owner_nodes")]
#[rustc_clean(cfg = "cfail3")]
extern "C" {
pub fn make_function_public(c: i32);
@ -138,7 +138,7 @@ extern "C" {
}
#[cfg(not(cfail1))]
#[rustc_dirty(cfg = "cfail2")]
#[rustc_dirty(cfg = "cfail2", except = "hir_owner_nodes")]
#[rustc_clean(cfg = "cfail3")]
extern "C" {
pub fn add_function1(c: i32);

View File

@ -23,7 +23,7 @@ impl Foo {
}
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,associated_item_def_ids")]
#[rustc_clean(cfg="cfail2", except="hir_owner,associated_item_def_ids")]
#[rustc_clean(cfg="cfail3")]
impl Foo {
#[rustc_clean(cfg="cfail3")]
@ -85,7 +85,7 @@ impl Foo {
}
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
impl Foo {
#[rustc_clean(cfg="cfail2", except="associated_item,hir_owner,hir_owner_nodes")]
@ -100,7 +100,7 @@ impl Foo {
}
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(cfg="cfail2", except="type_of,predicates_of,promoted_mir")]
@ -135,7 +135,7 @@ impl Foo {
}
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,associated_item_def_ids")]
#[rustc_clean(cfg="cfail2", except="hir_owner,associated_item_def_ids")]
#[rustc_clean(cfg="cfail3")]
impl Foo {
#[rustc_clean(cfg="cfail2")]
@ -468,7 +468,7 @@ impl Bar<u32> {
}
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
impl Bar<u64> {
#[rustc_clean(cfg="cfail2", except="fn_sig,optimized_mir,typeck")]

View File

@ -24,7 +24,7 @@
type ChangePrimitiveType = i32;
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangePrimitiveType = i64;
@ -35,7 +35,7 @@ type ChangePrimitiveType = i64;
type ChangeMutability = &'static i32;
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangeMutability = &'static mut i32;
@ -60,7 +60,7 @@ struct Struct2;
type ChangeTypeStruct = Struct1;
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangeTypeStruct = Struct2;
@ -71,7 +71,7 @@ type ChangeTypeStruct = Struct2;
type ChangeTypeTuple = (u32, u64);
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangeTypeTuple = (u32, i64);
@ -91,7 +91,7 @@ enum Enum2 {
type ChangeTypeEnum = Enum1;
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangeTypeEnum = Enum2;
@ -102,7 +102,7 @@ type ChangeTypeEnum = Enum2;
type AddTupleField = (i32, i64);
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type AddTupleField = (i32, i64, i16);
@ -113,7 +113,7 @@ type AddTupleField = (i32, i64, i16);
type ChangeNestedTupleField = (i32, (i64, i16));
#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")]
#[rustc_clean(cfg="cfail2", except="hir_owner")]
#[rustc_clean(cfg="cfail3")]
type ChangeNestedTupleField = (i32, (i64, i8));