From 47799de35a118ffc5a24a414fd003428f850fae4 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 14 Jul 2021 00:48:51 +0200 Subject: [PATCH 1/7] Separate Definitions and CrateStore from ResolverOutputs. --- compiler/rustc_interface/src/passes.rs | 11 ++- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 +- compiler/rustc_middle/src/hir/map/mod.rs | 12 ++-- compiler/rustc_middle/src/hir/mod.rs | 17 ++--- compiler/rustc_middle/src/query/mod.rs | 1 + compiler/rustc_middle/src/ty/context.rs | 74 +++++++++----------- compiler/rustc_middle/src/ty/mod.rs | 3 - compiler/rustc_resolve/src/lib.rs | 25 +++---- 8 files changed, 72 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 389e6483f30ff..42520c1d032a1 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -13,6 +13,7 @@ use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, PResult}; use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand}; use rustc_hir::def_id::{StableCrateId, LOCAL_CRATE}; +use rustc_hir::definitions::Definitions; use rustc_hir::Crate; use rustc_lint::{EarlyCheckNode, LintStore}; use rustc_metadata::creader::CStore; @@ -28,7 +29,7 @@ use rustc_plugin_impl as plugin; use rustc_query_impl::{OnDiskCache, Queries as TcxQueries}; use rustc_resolve::{Resolver, ResolverArenas}; use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType}; -use rustc_session::cstore::{MetadataLoader, MetadataLoaderDyn}; +use rustc_session::cstore::{CrateStoreDyn, MetadataLoader, MetadataLoaderDyn}; use rustc_session::output::{filename_for_input, filename_for_metadata}; use rustc_session::search_paths::PathKind; use rustc_session::{Limit, Session}; @@ -136,7 +137,9 @@ mod boxed_resolver { f((&mut *resolver).as_mut().unwrap()) } - pub fn to_resolver_outputs(resolver: Rc>) -> ResolverOutputs { + pub fn to_resolver_outputs( + resolver: Rc>, + ) -> (Definitions, Box, ResolverOutputs) { match Rc::try_unwrap(resolver) { Ok(resolver) => { let mut resolver = resolver.into_inner(); @@ -826,7 +829,7 @@ pub fn create_global_ctxt<'tcx>( let sess = &compiler.session(); let krate = resolver.borrow_mut().access(|resolver| lower_to_hir(sess, resolver, krate, hir_arena)); - let resolver_outputs = BoxedResolver::to_resolver_outputs(resolver); + let (definitions, cstore, resolver_outputs) = BoxedResolver::to_resolver_outputs(resolver); let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess); @@ -851,6 +854,8 @@ pub fn create_global_ctxt<'tcx>( sess, lint_store, arena, + definitions, + cstore, resolver_outputs, krate, dep_graph, diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 50c09aaf8d445..746ab510be8df 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -429,7 +429,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.definitions_untracked().def_path_table(); if self.is_proc_macro { for def_index in std::iter::once(CRATE_DEF_INDEX) .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) @@ -450,7 +450,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_def_path_hash_map(&mut self) -> LazyValue> { self.lazy(DefPathHashMapRef::BorrowedFromTcx( - self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), + self.tcx.definitions_untracked().def_path_hash_to_def_index_map(), )) } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 0f1597e66e7b8..73aa23ce2b2db 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -170,7 +170,7 @@ impl<'hir> Map<'hir> { 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_untracked().def_key(def_id) } pub fn def_path_from_hir_id(self, id: HirId) -> Option { @@ -179,13 +179,13 @@ 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) + self.tcx.definitions_untracked().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_untracked().def_path_hash(def_id) } #[inline] @@ -222,7 +222,7 @@ impl<'hir> Map<'hir> { // Create a dependency to the crate to be sure we re-execute this when the amount of // definitions change. self.tcx.ensure().hir_crate(()); - self.tcx.untracked_resolutions.definitions.iter_local_def_id() + self.tcx.definitions_untracked().iter_local_def_id() } pub fn opt_def_kind(self, local_def_id: LocalDefId) -> Option { @@ -1100,7 +1100,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { upstream_crates.hash_stable(&mut hcx, &mut stable_hasher); source_file_names.hash_stable(&mut hcx, &mut stable_hasher); if tcx.sess.opts.debugging_opts.incremental_relative_spans { - let definitions = &tcx.untracked_resolutions.definitions; + let definitions = &tcx.definitions_untracked(); let mut owner_spans: Vec<_> = krate .owners .iter_enumerated() @@ -1131,7 +1131,7 @@ fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> { .crates(()) .iter() .map(|&cnum| { - let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); + let stable_crate_id = tcx.stable_crate_id(cnum); let hash = tcx.crate_hash(cnum); (stable_crate_id, hash) }) diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 34ed5788c54c0..8068e6dff95a6 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -7,7 +7,7 @@ pub mod nested_filter; pub mod place; use crate::ty::query::Providers; -use crate::ty::{ImplSubject, TyCtxt}; +use crate::ty::{DefIdTree, ImplSubject, TyCtxt}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -104,23 +104,20 @@ pub fn provide(providers: &mut Providers) { }; providers.hir_owner_nodes = |tcx, id| tcx.hir_crate(()).owners[id].map(|i| &i.nodes); providers.hir_owner_parent = |tcx, id| { - // Accessing the def_key is ok since its value is hashed as part of `id`'s DefPathHash. - let parent = tcx.untracked_resolutions.definitions.def_key(id).parent; - let parent = parent.map_or(CRATE_HIR_ID, |local_def_index| { - let def_id = LocalDefId { local_def_index }; - let mut parent_hir_id = tcx.hir().local_def_id_to_hir_id(def_id); + // Accessing the local_parent is ok since its value is hashed as part of `id`'s DefPathHash. + tcx.opt_local_parent(id).map_or(CRATE_HIR_ID, |parent| { + let mut parent_hir_id = tcx.hir().local_def_id_to_hir_id(parent); if let Some(local_id) = tcx.hir_crate(()).owners[parent_hir_id.owner].unwrap().parenting.get(&id) { parent_hir_id.local_id = *local_id; } parent_hir_id - }); - parent + }) }; providers.hir_attrs = |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs); - providers.source_span = |tcx, def_id| tcx.resolutions(()).definitions.def_span(def_id); + providers.source_span = |tcx, def_id| tcx.definitions_untracked().def_span(def_id); providers.def_span = |tcx, def_id| { let def_id = def_id.expect_local(); let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); @@ -150,7 +147,7 @@ pub fn provide(providers: &mut Providers) { providers.all_local_trait_impls = |tcx, ()| &tcx.resolutions(()).trait_impls; providers.expn_that_defined = |tcx, id| { let id = id.expect_local(); - tcx.resolutions(()).definitions.expansion_that_defined(id) + tcx.definitions_untracked().expansion_that_defined(id) }; providers.in_scope_traits_map = |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map(|owner_info| &owner_info.trait_map); diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index caa1d4cd34eee..ce075805aef80 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -31,6 +31,7 @@ rustc_queries! { /// This span is meant for dep-tracking rather than diagnostics. It should not be used outside /// of rustc_middle::hir::source_map. query source_span(key: LocalDefId) -> Span { + eval_always desc { "get the source span" } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 4cd25a616264f..5d020f429c064 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -50,6 +50,7 @@ use rustc_middle::mir::FakeReadCause; use rustc_query_system::ich::StableHashingContext; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_session::config::{CrateType, OutputFilenames}; +use rustc_session::cstore::CrateStoreDyn; use rustc_session::lint::{Level, Lint}; use rustc_session::Limit; use rustc_session::Session; @@ -177,7 +178,8 @@ impl<'tcx> CtxtInterners<'tcx> { &self, kind: TyKind<'tcx>, sess: &Session, - resolutions: &ty::ResolverOutputs, + definitions: &rustc_hir::definitions::Definitions, + cstore: &CrateStoreDyn, ) -> Ty<'tcx> { Ty(Interned::new_unchecked( self.type_ @@ -192,11 +194,7 @@ impl<'tcx> CtxtInterners<'tcx> { Fingerprint::ZERO } else { let mut hasher = StableHasher::new(); - let mut hcx = StableHashingContext::ignore_spans( - sess, - &resolutions.definitions, - &*resolutions.cstore, - ); + let mut hcx = StableHashingContext::ignore_spans(sess, definitions, cstore); kind.hash_stable(&mut hcx, &mut hasher); hasher.finish() }; @@ -934,9 +932,10 @@ impl<'tcx> CommonTypes<'tcx> { fn new( interners: &CtxtInterners<'tcx>, sess: &Session, - resolutions: &ty::ResolverOutputs, + definitions: &rustc_hir::definitions::Definitions, + cstore: &CrateStoreDyn, ) -> CommonTypes<'tcx> { - let mk = |ty| interners.intern_ty(ty, sess, resolutions); + let mk = |ty| interners.intern_ty(ty, sess, definitions, cstore); CommonTypes { unit: mk(Tuple(List::empty())), @@ -1057,6 +1056,9 @@ pub struct GlobalCtxt<'tcx> { /// Common consts, pre-interned for your convenience. pub consts: CommonConsts<'tcx>, + definitions: rustc_hir::definitions::Definitions, + cstore: Box, + /// Output of the resolver. pub(crate) untracked_resolutions: ty::ResolverOutputs, @@ -1218,7 +1220,9 @@ impl<'tcx> TyCtxt<'tcx> { s: &'tcx Session, lint_store: Lrc, arena: &'tcx WorkerLocal>, - resolutions: ty::ResolverOutputs, + definitions: rustc_hir::definitions::Definitions, + cstore: Box, + untracked_resolutions: ty::ResolverOutputs, krate: &'tcx hir::Crate<'tcx>, dep_graph: DepGraph, on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, @@ -1231,7 +1235,7 @@ impl<'tcx> TyCtxt<'tcx> { s.fatal(&err); }); let interners = CtxtInterners::new(arena); - let common_types = CommonTypes::new(&interners, s, &resolutions); + let common_types = CommonTypes::new(&interners, s, &definitions, &*cstore); let common_lifetimes = CommonLifetimes::new(&interners); let common_consts = CommonConsts::new(&interners, &common_types); @@ -1241,7 +1245,9 @@ impl<'tcx> TyCtxt<'tcx> { arena, interners, dep_graph, - untracked_resolutions: resolutions, + definitions, + cstore, + untracked_resolutions, prof: s.prof.clone(), types: common_types, lifetimes: common_lifetimes, @@ -1342,9 +1348,9 @@ impl<'tcx> TyCtxt<'tcx> { 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) + self.definitions.def_key(id) } else { - self.untracked_resolutions.cstore.def_key(id) + self.cstore.def_key(id) } } @@ -1356,9 +1362,9 @@ impl<'tcx> TyCtxt<'tcx> { 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.definitions.def_path(id) } else { - self.untracked_resolutions.cstore.def_path(id) + self.cstore.def_path(id) } } @@ -1366,9 +1372,9 @@ impl<'tcx> TyCtxt<'tcx> { 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) } } @@ -1377,7 +1383,7 @@ impl<'tcx> TyCtxt<'tcx> { if crate_num == LOCAL_CRATE { self.sess.local_stable_crate_id() } else { - self.untracked_resolutions.cstore.stable_crate_id(crate_num) + self.cstore.stable_crate_id(crate_num) } } @@ -1388,7 +1394,7 @@ impl<'tcx> TyCtxt<'tcx> { if stable_crate_id == self.sess.local_stable_crate_id() { LOCAL_CRATE } else { - self.untracked_resolutions.cstore.stable_crate_id_to_crate_num(stable_crate_id) + self.cstore.stable_crate_id_to_crate_num(stable_crate_id) } } @@ -1403,16 +1409,12 @@ impl<'tcx> TyCtxt<'tcx> { // If this is a DefPathHash from the local crate, we can look up the // DefId in the tcx's `Definitions`. if stable_crate_id == self.sess.local_stable_crate_id() { - self.untracked_resolutions - .definitions - .local_def_path_hash_to_def_id(hash, err) - .to_def_id() + self.definitions.local_def_path_hash_to_def_id(hash, err).to_def_id() } else { // If this is a DefPathHash from an upstream crate, let the CrateStore map // it to a DefId. - let cstore = &self.untracked_resolutions.cstore; - let cnum = cstore.stable_crate_id_to_crate_num(stable_crate_id); - cstore.def_path_hash_to_def_id(cnum, hash) + let cnum = self.cstore.stable_crate_id_to_crate_num(stable_crate_id); + self.cstore.def_path_hash_to_def_id(cnum, hash) } } @@ -1424,7 +1426,7 @@ 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; + let cstore = &self.cstore; (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate)) }; @@ -1440,30 +1442,24 @@ impl<'tcx> TyCtxt<'tcx> { /// 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_untracked(self) -> &'tcx ty::CrateStoreDyn { - &*self.untracked_resolutions.cstore + pub fn cstore_untracked(self) -> &'tcx CrateStoreDyn { + &*self.cstore } /// Note that this is *untracked* and should only be used within the query /// system if the result is otherwise tracked through queries pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { - &self.untracked_resolutions.definitions + &self.definitions } #[inline(always)] pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { - let resolutions = &self.gcx.untracked_resolutions; - StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) + StableHashingContext::new(self.sess, &self.definitions, &*self.cstore) } #[inline(always)] pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { - let resolutions = &self.gcx.untracked_resolutions; - StableHashingContext::ignore_spans( - self.sess, - &resolutions.definitions, - &*resolutions.cstore, - ) + StableHashingContext::ignore_spans(self.sess, &self.definitions, &*self.cstore) } pub fn serialize_query_result_cache(self, encoder: FileEncoder) -> FileEncodeResult { @@ -2254,7 +2250,7 @@ impl<'tcx> TyCtxt<'tcx> { #[allow(rustc::usage_of_ty_tykind)] #[inline] pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { - self.interners.intern_ty(st, self.sess, &self.gcx.untracked_resolutions) + self.interners.intern_ty(st, self.sess, &self.definitions, &*self.cstore) } #[inline] diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index b386ed68dd246..826d85c186697 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -39,7 +39,6 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap}; use rustc_hir::Node; use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; -use rustc_session::cstore::CrateStoreDyn; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; use rustc_target::abi::{Align, VariantIdx}; @@ -133,8 +132,6 @@ pub type RegisteredTools = FxHashSet; #[derive(Debug)] pub struct ResolverOutputs { - pub definitions: rustc_hir::definitions::Definitions, - pub cstore: Box, pub visibilities: FxHashMap, /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error. pub has_pub_restricted: bool, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 92a65fe249f4c..5e8e0e1efe3e1 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -47,7 +47,7 @@ use rustc_middle::span_bug; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, ResolverOutputs}; use rustc_query_system::ich::StableHashingContext; -use rustc_session::cstore::{CrateStore, MetadataLoaderDyn}; +use rustc_session::cstore::{CrateStore, CrateStoreDyn, MetadataLoaderDyn}; use rustc_session::lint::LintBuffer; use rustc_session::Session; use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}; @@ -1439,9 +1439,10 @@ impl<'a> Resolver<'a> { Default::default() } - pub fn into_outputs(self) -> ResolverOutputs { + pub fn into_outputs(self) -> (Definitions, Box, ResolverOutputs) { let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); let definitions = self.definitions; + let cstore = Box::new(self.crate_loader.into_cstore()); let visibilities = self.visibilities; let has_pub_restricted = self.has_pub_restricted; let extern_crate_map = self.extern_crate_map; @@ -1452,9 +1453,7 @@ impl<'a> Resolver<'a> { let main_def = self.main_def; let confused_type_with_std_module = self.confused_type_with_std_module; let access_levels = self.access_levels; - ResolverOutputs { - definitions, - cstore: Box::new(self.crate_loader.into_cstore()), + let resolutions = ResolverOutputs { visibilities, has_pub_restricted, access_levels, @@ -1473,15 +1472,15 @@ impl<'a> Resolver<'a> { proc_macros, confused_type_with_std_module, registered_tools: self.registered_tools, - } + }; + (definitions, cstore, resolutions) } - pub fn clone_outputs(&self) -> ResolverOutputs { + pub fn clone_outputs(&self) -> (Definitions, Box, ResolverOutputs) { let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); - ResolverOutputs { - definitions: self.definitions.clone(), - access_levels: self.access_levels.clone(), - cstore: Box::new(self.cstore().clone()), + let definitions = self.definitions.clone(); + let cstore = Box::new(self.cstore().clone()); + let resolutions = ResolverOutputs { visibilities: self.visibilities.clone(), has_pub_restricted: self.has_pub_restricted, extern_crate_map: self.extern_crate_map.clone(), @@ -1499,7 +1498,9 @@ impl<'a> Resolver<'a> { proc_macros, confused_type_with_std_module: self.confused_type_with_std_module.clone(), registered_tools: self.registered_tools.clone(), - } + access_levels: self.access_levels.clone(), + }; + (definitions, cstore, resolutions) } pub fn cstore(&self) -> &CStore { From 603746a35e35827b7a25604145832e9dc8057ece Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 5 Jul 2021 22:26:23 +0200 Subject: [PATCH 2/7] Make ResolverAstLowering a struct. --- Cargo.lock | 2 +- compiler/rustc_ast_lowering/Cargo.toml | 1 + compiler/rustc_ast_lowering/src/asm.rs | 4 +- compiler/rustc_ast_lowering/src/expr.rs | 6 +- compiler/rustc_ast_lowering/src/index.rs | 4 +- compiler/rustc_ast_lowering/src/item.rs | 14 +- compiler/rustc_ast_lowering/src/lib.rs | 355 ++++++++++-------- compiler/rustc_ast_lowering/src/pat.rs | 4 +- compiler/rustc_ast_lowering/src/path.rs | 1 + compiler/rustc_hir/src/def.rs | 42 ++- compiler/rustc_interface/src/passes.rs | 19 +- compiler/rustc_middle/src/ty/mod.rs | 29 +- compiler/rustc_resolve/Cargo.toml | 1 - compiler/rustc_resolve/src/access_levels.rs | 1 - .../rustc_resolve/src/build_reduced_graph.rs | 8 +- compiler/rustc_resolve/src/check_unused.rs | 1 - compiler/rustc_resolve/src/def_collector.rs | 1 - compiler/rustc_resolve/src/late.rs | 3 +- .../rustc_resolve/src/late/diagnostics.rs | 1 - compiler/rustc_resolve/src/lib.rs | 117 ++---- compiler/rustc_resolve/src/macros.rs | 1 - src/librustdoc/lib.rs | 1 - .../passes/collect_intra_doc_links/early.rs | 1 - 23 files changed, 354 insertions(+), 263 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5716ee2fc1499..c47ce54e6b376 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3569,6 +3569,7 @@ dependencies = [ "rustc_errors", "rustc_hir", "rustc_index", + "rustc_middle", "rustc_query_system", "rustc_session", "rustc_span", @@ -4386,7 +4387,6 @@ dependencies = [ "bitflags", "rustc_arena", "rustc_ast", - "rustc_ast_lowering", "rustc_ast_pretty", "rustc_attr", "rustc_data_structures", diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index 7989af24d9986..e344d8a7637c4 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -14,6 +14,7 @@ rustc_hir = { path = "../rustc_hir" } rustc_target = { path = "../rustc_target" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_index = { path = "../rustc_index" } +rustc_middle = { path = "../rustc_middle" } rustc_query_system = { path = "../rustc_query_system" } rustc_span = { path = "../rustc_span" } rustc_errors = { path = "../rustc_errors" } diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 6c055645ef3e9..46e6ee9468ca8 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -1,4 +1,4 @@ -use crate::{ImplTraitContext, ImplTraitPosition, ParamMode}; +use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt}; use super::LoweringContext; @@ -243,7 +243,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Wrap the expression in an AnonConst. let parent_def_id = self.current_hir_id_owner; let node_id = self.resolver.next_node_id(); - self.resolver.create_def( + self.create_def( parent_def_id, node_id, DefPathData::AnonConst, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 3a33a9debaadb..1e863f6395bc1 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1,6 +1,6 @@ -use crate::{FnDeclKind, ImplTraitPosition}; - +use super::ResolverAstLoweringExt; use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; +use crate::{FnDeclKind, ImplTraitPosition}; use rustc_ast::attr; use rustc_ast::ptr::P as AstP; @@ -358,7 +358,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let node_id = self.resolver.next_node_id(); // Add a definition for the in-band const def. - self.resolver.create_def( + self.create_def( parent_def_id, node_id, DefPathData::AnonConst, diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 4da09c4ef486e..4be22020ba153 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -6,6 +6,7 @@ use rustc_hir::definitions; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::*; use rustc_index::vec::{Idx, IndexVec}; +use rustc_middle::span_bug; use rustc_session::Session; use rustc_span::source_map::SourceMap; use rustc_span::{Span, DUMMY_SP}; @@ -75,7 +76,8 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { // owner of that node. if cfg!(debug_assertions) { if hir_id.owner != self.owner { - panic!( + span_bug!( + span, "inconsistent DepNode at `{:?}` for `{:?}`: \ current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})", self.source_map.span_to_diagnostic_string(span), diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 4244e67482cad..49ba2876d1ff0 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1,4 +1,5 @@ -use super::{AstOwner, ImplTraitContext, ImplTraitPosition, ResolverAstLowering}; +use super::ResolverAstLoweringExt; +use super::{AstOwner, ImplTraitContext, ImplTraitPosition}; use super::{LoweringContext, ParamMode}; use crate::{Arena, FnDeclKind}; @@ -11,8 +12,11 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::definitions::Definitions; use rustc_hir::PredicateOrigin; use rustc_index::vec::{Idx, IndexVec}; +use rustc_middle::ty::ResolverOutputs; +use rustc_session::cstore::CrateStoreDyn; use rustc_session::Session; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::{kw, sym, Ident}; @@ -24,7 +28,9 @@ use std::iter; pub(super) struct ItemLowerer<'a, 'hir> { pub(super) sess: &'a Session, - pub(super) resolver: &'a mut dyn ResolverAstLowering, + pub(super) definitions: &'a mut Definitions, + pub(super) cstore: &'a CrateStoreDyn, + pub(super) resolver: &'a mut ResolverOutputs, pub(super) arena: &'hir Arena<'hir>, pub(super) ast_index: &'a IndexVec>, pub(super) owners: &'a mut IndexVec>>, @@ -59,6 +65,8 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { let mut lctx = LoweringContext { // Pseudo-globals. sess: &self.sess, + definitions: self.definitions, + cstore: self.cstore, resolver: self.resolver, arena: self.arena, @@ -136,7 +144,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { let def_id = self.resolver.local_def_id(item.id); let parent_id = { - let parent = self.resolver.definitions().def_key(def_id).parent; + let parent = self.definitions.def_key(def_id).parent; let local_def_index = parent.unwrap(); LocalDefId { local_def_index } }; diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6fe95a21fa42a..f7acb08abde25 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -51,12 +51,14 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_errors::{struct_span_err, Applicability}; use rustc_hir as hir; -use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res}; -use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID}; -use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; +use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; +use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::definitions::{DefPathData, Definitions}; use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate}; use rustc_index::vec::{Idx, IndexVec}; +use rustc_middle::ty::ResolverOutputs; use rustc_query_system::ich::StableHashingContext; +use rustc_session::cstore::CrateStoreDyn; use rustc_session::parse::feature_err; use rustc_session::Session; use rustc_span::hygiene::{ExpnId, MacroKind}; @@ -87,7 +89,9 @@ struct LoweringContext<'a, 'hir: 'a> { /// Used to assign IDs to HIR nodes that do not directly correspond to AST nodes. sess: &'a Session, - resolver: &'a mut dyn ResolverAstLowering, + definitions: &'a mut Definitions, + cstore: &'a CrateStoreDyn, + resolver: &'a mut ResolverOutputs, /// Used to allocate HIR nodes. arena: &'hir Arena<'hir>, @@ -134,46 +138,6 @@ struct LoweringContext<'a, 'hir: 'a> { allow_into_future: Option>, } -/// Resolution for a lifetime appearing in a type. -#[derive(Copy, Clone, Debug)] -pub enum LifetimeRes { - /// Successfully linked the lifetime to a generic parameter. - Param { - /// Id of the generic parameter that introduced it. - param: LocalDefId, - /// Id of the introducing place. That can be: - /// - an item's id, for the item's generic parameters; - /// - a TraitRef's ref_id, identifying the `for<...>` binder; - /// - a BareFn type's id; - /// - a Path's id when this path has parenthesized generic args. - /// - /// This information is used for impl-trait lifetime captures, to know when to or not to - /// capture any given lifetime. - binder: NodeId, - }, - /// Created a generic parameter for an anonymous lifetime. - Fresh { - /// Id of the generic parameter that introduced it. - param: LocalDefId, - /// Id of the introducing place. See `Param`. - binder: NodeId, - }, - /// This variant is used for anonymous lifetimes that we did not resolve during - /// late resolution. Shifting the work to the HIR lifetime resolver. - Anonymous { - /// Id of the introducing place. See `Param`. - binder: NodeId, - /// Whether this lifetime was spelled or elided. - elided: bool, - }, - /// Explicit `'static` lifetime. - Static, - /// Resolution failure. - Error, - /// HACK: This is used to recover the NodeId of an elided lifetime. - ElidedAnchor { start: NodeId, end: NodeId }, -} - /// When we lower a lifetime, it is inserted in `captures`, and the resolution is modified so /// to point to the lifetime parameter impl-trait will generate. /// When traversing `for<...>` binders, they are inserted in `binders_to_ignore` so we know *not* @@ -196,54 +160,96 @@ struct LifetimeCaptureContext { binders_to_ignore: FxHashSet, } -pub trait ResolverAstLowering { - fn def_key(&self, id: DefId) -> DefKey; +trait ResolverAstLoweringExt { + fn legacy_const_generic_args(&self, expr: &Expr) -> Option>; + fn get_partial_res(&self, id: NodeId) -> Option; + fn get_import_res(&self, id: NodeId) -> PerNS>>; + fn get_label_res(&self, id: NodeId) -> Option; + fn get_lifetime_res(&self, id: NodeId) -> Option; + fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>; + fn next_node_id(&mut self) -> NodeId; + fn opt_local_def_id(&self, node: NodeId) -> Option; + fn local_def_id(&self, node: NodeId) -> LocalDefId; + fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind; +} - fn def_span(&self, id: LocalDefId) -> Span; +impl ResolverAstLoweringExt for ResolverOutputs { + fn legacy_const_generic_args(&self, expr: &Expr) -> Option> { + if let ExprKind::Path(None, path) = &expr.kind { + // Don't perform legacy const generics rewriting if the path already + // has generic arguments. + if path.segments.last().unwrap().args.is_some() { + return None; + } - fn item_generics_num_lifetimes(&self, def: DefId) -> usize; + let partial_res = self.partial_res_map.get(&expr.id)?; + if partial_res.unresolved_segments() != 0 { + return None; + } - fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option>; + if let Res::Def(DefKind::Fn, def_id) = partial_res.base_res() { + // We only support cross-crate argument rewriting. Uses + // within the same crate should be updated to use the new + // const generics style. + if def_id.is_local() { + return None; + } + + if let Some(v) = self.legacy_const_generic_args.get(&def_id) { + return v.clone(); + } + } + } + + None + } /// Obtains resolution for a `NodeId` with a single resolution. - fn get_partial_res(&self, id: NodeId) -> Option; + fn get_partial_res(&self, id: NodeId) -> Option { + self.partial_res_map.get(&id).copied() + } /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`. - fn get_import_res(&self, id: NodeId) -> PerNS>>; + fn get_import_res(&self, id: NodeId) -> PerNS>> { + self.import_res_map.get(&id).copied().unwrap_or_default() + } /// Obtains resolution for a label with the given `NodeId`. - fn get_label_res(&self, id: NodeId) -> Option; + fn get_label_res(&self, id: NodeId) -> Option { + self.label_res_map.get(&id).copied() + } /// Obtains resolution for a lifetime with the given `NodeId`. - fn get_lifetime_res(&self, id: NodeId) -> Option; + fn get_lifetime_res(&self, id: NodeId) -> Option { + self.lifetimes_res_map.get(&id).copied() + } /// Obtain the list of lifetimes parameters to add to an item. - fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>; - - fn create_stable_hashing_context(&self) -> StableHashingContext<'_>; - - fn definitions(&self) -> &Definitions; - - fn next_node_id(&mut self) -> NodeId; - - fn take_trait_map(&mut self, node: NodeId) -> Option>; - - fn opt_local_def_id(&self, node: NodeId) -> Option; + fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> { + self.extra_lifetime_params_map.remove(&id).unwrap_or_default() + } - fn local_def_id(&self, node: NodeId) -> LocalDefId; + fn next_node_id(&mut self) -> NodeId { + let next = self + .next_node_id + .as_usize() + .checked_add(1) + .expect("input too large; ran out of NodeIds"); + self.next_node_id = NodeId::from_usize(next); + self.next_node_id + } - fn def_path_hash(&self, def_id: DefId) -> DefPathHash; + fn opt_local_def_id(&self, node: NodeId) -> Option { + self.node_id_to_def_id.get(&node).copied() + } - fn create_def( - &mut self, - parent: LocalDefId, - node_id: ast::NodeId, - data: DefPathData, - expn_id: ExpnId, - span: Span, - ) -> 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)) + } - fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind; + fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind { + self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang) + } } /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree, @@ -353,7 +359,7 @@ enum AstOwner<'a> { } fn index_crate<'a>( - resolver: &dyn ResolverAstLowering, + resolver: &ResolverOutputs, krate: &'a Crate, ) -> IndexVec> { let mut indexer = Indexer { resolver, index: IndexVec::new() }; @@ -363,7 +369,7 @@ fn index_crate<'a>( return indexer.index; struct Indexer<'s, 'a> { - resolver: &'s dyn ResolverAstLowering, + resolver: &'s ResolverOutputs, index: IndexVec>, } @@ -399,29 +405,33 @@ fn index_crate<'a>( /// Compute the hash for the HIR of the full crate. /// This hash will then be part of the crate_hash which is stored in the metadata. fn compute_hir_hash( - resolver: &mut dyn ResolverAstLowering, + sess: &Session, + definitions: &Definitions, + cstore: &CrateStoreDyn, owners: &IndexVec>>, ) -> Fingerprint { let mut hir_body_nodes: Vec<_> = owners .iter_enumerated() .filter_map(|(def_id, info)| { let info = info.as_owner()?; - let def_path_hash = resolver.definitions().def_path_hash(def_id); + let def_path_hash = definitions.def_path_hash(def_id); Some((def_path_hash, info)) }) .collect(); hir_body_nodes.sort_unstable_by_key(|bn| bn.0); let mut stable_hasher = StableHasher::new(); - let mut hcx = resolver.create_stable_hashing_context(); + let mut hcx = StableHashingContext::new(sess, definitions, cstore); hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher); stable_hasher.finish() } -pub fn lower_crate<'a, 'hir>( - sess: &'a Session, - krate: &'a Crate, - resolver: &'a mut dyn ResolverAstLowering, +pub fn lower_crate<'hir>( + sess: &Session, + krate: &Crate, + definitions: &mut Definitions, + cstore: &CrateStoreDyn, + resolver: &mut ResolverOutputs, arena: &'hir Arena<'hir>, ) -> &'hir hir::Crate<'hir> { let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering"); @@ -429,14 +439,22 @@ pub fn lower_crate<'a, 'hir>( let ast_index = index_crate(resolver, krate); let mut owners = - IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, resolver.definitions().def_index_count()); + IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, definitions.def_index_count()); for def_id in ast_index.indices() { - item::ItemLowerer { sess, resolver, arena, ast_index: &ast_index, owners: &mut owners } - .lower_node(def_id); + item::ItemLowerer { + sess, + definitions, + cstore, + resolver, + arena, + ast_index: &ast_index, + owners: &mut owners, + } + .lower_node(def_id); } - let hir_hash = compute_hir_hash(resolver, &owners); + let hir_hash = compute_hir_hash(sess, definitions, cstore, &owners); let krate = hir::Crate { owners, hir_hash }; arena.alloc(krate) } @@ -457,6 +475,40 @@ enum ParenthesizedGenericArgs { } impl<'a, 'hir> LoweringContext<'a, 'hir> { + fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { + StableHashingContext::new(self.sess, self.definitions, self.cstore) + } + + fn create_def( + &mut self, + parent: LocalDefId, + node_id: ast::NodeId, + data: DefPathData, + expn_id: ExpnId, + span: Span, + ) -> LocalDefId { + assert!( + !self.resolver.node_id_to_def_id.contains_key(&node_id), + "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", + node_id, + data, + self.definitions.def_key(self.resolver.node_id_to_def_id[&node_id]), + ); + + let def_id = self.definitions.create_def(parent, data, expn_id, span); + + // Some things for which we allocate `LocalDefId`s don't correspond to + // anything in the AST, so they don't have a `NodeId`. For these cases + // we don't need a mapping from `NodeId` to `LocalDefId`. + if node_id != ast::DUMMY_NODE_ID { + debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); + self.resolver.node_id_to_def_id.insert(node_id, def_id); + } + assert_eq!(self.resolver.def_id_to_node_id.push(node_id), def_id); + + def_id + } + #[instrument(level = "debug", skip(self, f))] fn with_hir_id_owner( &mut self, @@ -518,8 +570,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { bodies.sort_by_key(|(k, _)| *k); let bodies = SortedMap::from_presorted_elements(bodies); let (hash_including_bodies, hash_without_bodies) = self.hash_owner(node, &bodies); - let (nodes, parenting) = - index::index_hir(self.sess, self.resolver.definitions(), node, &bodies); + let (nodes, parenting) = index::index_hir(self.sess, self.definitions, node, &bodies); let nodes = hir::OwnerNodes { hash_including_bodies, hash_without_bodies, @@ -528,7 +579,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { local_id_to_def_id, }; let attrs = { - let mut hcx = self.resolver.create_stable_hashing_context(); + let mut hcx = self.create_stable_hashing_context(); let mut stable_hasher = StableHasher::new(); attrs.hash_stable(&mut hcx, &mut stable_hasher); let hash = stable_hasher.finish(); @@ -545,7 +596,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { node: hir::OwnerNode<'hir>, bodies: &SortedMap>, ) -> (Fingerprint, Fingerprint) { - let mut hcx = self.resolver.create_stable_hashing_context(); + let mut hcx = self.create_stable_hashing_context(); let mut stable_hasher = StableHasher::new(); hcx.with_hir_bodies(true, node.def_id(), bodies, |hcx| { node.hash_stable(hcx, &mut stable_hasher) @@ -588,7 +639,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.local_id_to_def_id.insert(local_id, def_id); } - if let Some(traits) = self.resolver.take_trait_map(ast_node_id) { + if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) { self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice()); } @@ -648,7 +699,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { allow_internal_unstable, reason, self.sess.edition(), - self.resolver.create_stable_hashing_context(), + self.create_stable_hashing_context(), ) } @@ -941,7 +992,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let parent_def_id = self.current_hir_id_owner; let impl_trait_node_id = self.resolver.next_node_id(); - self.resolver.create_def( + self.create_def( parent_def_id, impl_trait_node_id, DefPathData::ImplTrait, @@ -1053,7 +1104,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let node_id = self.resolver.next_node_id(); // Add a definition for the in-band const def. - self.resolver.create_def( + self.create_def( parent_def_id, node_id, DefPathData::AnonConst, @@ -1567,7 +1618,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let inner_node_id = self.resolver.next_node_id(); // Add a definition for the in scope lifetime def. - self.resolver.create_def( + self.create_def( opaque_ty_def_id, inner_node_id, DefPathData::LifetimeNs(name), @@ -1757,74 +1808,80 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { LifetimeRes::Param { mut param, binder } => { debug_assert_ne!(ident.name, kw::UnderscoreLifetime); let p_name = ParamName::Plain(ident); - if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) = - &mut self.captured_lifetimes - && !binders_to_ignore.contains(&binder) - { - match captures.entry(param) { - Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), - Entry::Vacant(v) => { - let p_id = self.resolver.next_node_id(); - let p_def_id = self.resolver.create_def( - *parent_def_id, - p_id, - DefPathData::LifetimeNs(p_name.ident().name), - ExpnId::root(), - span.with_parent(None), - ); - - v.insert((span, p_id, p_name, res)); - param = p_def_id; + if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { + if !captured_lifetimes.binders_to_ignore.contains(&binder) { + match captured_lifetimes.captures.entry(param) { + Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), + Entry::Vacant(v) => { + let p_id = self.resolver.next_node_id(); + let p_def_id = self.create_def( + captured_lifetimes.parent_def_id, + p_id, + DefPathData::LifetimeNs(p_name.ident().name), + ExpnId::root(), + span.with_parent(None), + ); + + v.insert((span, p_id, p_name, res)); + param = p_def_id; + } } } + + self.captured_lifetimes = Some(captured_lifetimes); } hir::LifetimeName::Param(param, p_name) } LifetimeRes::Fresh { mut param, binder } => { debug_assert_eq!(ident.name, kw::UnderscoreLifetime); - if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) = - &mut self.captured_lifetimes - && !binders_to_ignore.contains(&binder) - { - match captures.entry(param) { - Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), - Entry::Vacant(v) => { - let p_id = self.resolver.next_node_id(); - let p_def_id = self.resolver.create_def( - *parent_def_id, - p_id, - DefPathData::LifetimeNs(kw::UnderscoreLifetime), - ExpnId::root(), - span.with_parent(None), - ); - - v.insert((span, p_id, ParamName::Fresh, res)); - param = p_def_id; + if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { + if !captured_lifetimes.binders_to_ignore.contains(&binder) { + match captured_lifetimes.captures.entry(param) { + Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), + Entry::Vacant(v) => { + let p_id = self.resolver.next_node_id(); + let p_def_id = self.create_def( + captured_lifetimes.parent_def_id, + p_id, + DefPathData::LifetimeNs(kw::UnderscoreLifetime), + ExpnId::root(), + span.with_parent(None), + ); + + v.insert((span, p_id, ParamName::Fresh, res)); + param = p_def_id; + } } } + + self.captured_lifetimes = Some(captured_lifetimes); } hir::LifetimeName::Param(param, ParamName::Fresh) } LifetimeRes::Anonymous { binder, elided } => { - if let Some(LifetimeCaptureContext { parent_def_id, captures, binders_to_ignore }) = - &mut self.captured_lifetimes - && !binders_to_ignore.contains(&binder) - { - let p_id = self.resolver.next_node_id(); - let p_def_id = self.resolver.create_def( - *parent_def_id, - p_id, - DefPathData::LifetimeNs(kw::UnderscoreLifetime), - ExpnId::root(), - span.with_parent(None), - ); - captures.insert(p_def_id, (span, p_id, ParamName::Fresh, res)); - hir::LifetimeName::Param(p_def_id, ParamName::Fresh) - } else if elided { + let mut l_name = None; + if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { + if !captured_lifetimes.binders_to_ignore.contains(&binder) { + let p_id = self.resolver.next_node_id(); + let p_def_id = self.create_def( + captured_lifetimes.parent_def_id, + p_id, + DefPathData::LifetimeNs(kw::UnderscoreLifetime), + ExpnId::root(), + span.with_parent(None), + ); + captured_lifetimes + .captures + .insert(p_def_id, (span, p_id, ParamName::Fresh, res)); + l_name = Some(hir::LifetimeName::Param(p_def_id, ParamName::Fresh)); + } + self.captured_lifetimes = Some(captured_lifetimes); + }; + l_name.unwrap_or(if elided { hir::LifetimeName::Implicit } else { hir::LifetimeName::Underscore - } + }) } LifetimeRes::Static => hir::LifetimeName::Static, LifetimeRes::Error => hir::LifetimeName::Error, diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index 95bf947854faf..bd2e76e5528da 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -1,6 +1,6 @@ -use crate::ImplTraitPosition; - +use super::ResolverAstLoweringExt; use super::{ImplTraitContext, LoweringContext, ParamMode}; +use crate::ImplTraitPosition; use rustc_ast::ptr::P; use rustc_ast::*; diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index ac63a075ac65f..13d3c9521b383 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -1,5 +1,6 @@ use crate::ImplTraitPosition; +use super::ResolverAstLoweringExt; use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs}; use super::{ImplTraitContext, LoweringContext, ParamMode}; diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 414f627259196..3927523f4c6ab 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -1,9 +1,9 @@ -use crate::def_id::DefId; use crate::hir; use rustc_ast as ast; use rustc_ast::NodeId; use rustc_macros::HashStable_Generic; +use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::hygiene::MacroKind; use rustc_span::Symbol; @@ -711,3 +711,43 @@ impl Res { matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..)) } } + +/// Resolution for a lifetime appearing in a type. +#[derive(Copy, Clone, Debug)] +pub enum LifetimeRes { + /// Successfully linked the lifetime to a generic parameter. + Param { + /// Id of the generic parameter that introduced it. + param: LocalDefId, + /// Id of the introducing place. That can be: + /// - an item's id, for the item's generic parameters; + /// - a TraitRef's ref_id, identifying the `for<...>` binder; + /// - a BareFn type's id; + /// - a Path's id when this path has parenthesized generic args. + /// + /// This information is used for impl-trait lifetime captures, to know when to or not to + /// capture any given lifetime. + binder: NodeId, + }, + /// Created a generic parameter for an anonymous lifetime. + Fresh { + /// Id of the generic parameter that introduced it. + param: LocalDefId, + /// Id of the introducing place. See `Param`. + binder: NodeId, + }, + /// This variant is used for anonymous lifetimes that we did not resolve during + /// late resolution. Shifting the work to the HIR lifetime resolver. + Anonymous { + /// Id of the introducing place. See `Param`. + binder: NodeId, + /// Whether this lifetime was spelled or elided. + elided: bool, + }, + /// Explicit `'static` lifetime. + Static, + /// Resolution failure. + Error, + /// HACK: This is used to recover the NodeId of an elided lifetime. + ElidedAnchor { start: NodeId, end: NodeId }, +} diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 42520c1d032a1..adeb384787ef8 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -481,14 +481,17 @@ pub fn configure_and_expand( Ok(krate) } -pub fn lower_to_hir<'res, 'tcx>( - sess: &'tcx Session, - resolver: &'res mut Resolver<'_>, +fn lower_to_hir<'tcx>( + sess: &Session, + definitions: &mut Definitions, + cstore: &CrateStoreDyn, + resolver: &mut ResolverOutputs, krate: Rc, arena: &'tcx rustc_ast_lowering::Arena<'tcx>, ) -> &'tcx Crate<'tcx> { // Lower AST to HIR. - let hir_crate = rustc_ast_lowering::lower_crate(sess, &*krate, resolver, arena); + let hir_crate = + rustc_ast_lowering::lower_crate(sess, &krate, definitions, cstore, resolver, arena); // Drop AST to free memory sess.time("drop_ast", || std::mem::drop(krate)); @@ -826,10 +829,14 @@ pub fn create_global_ctxt<'tcx>( // incr. comp. yet. dep_graph.assert_ignored(); + let (mut definitions, cstore, mut resolver_outputs) = + BoxedResolver::to_resolver_outputs(resolver); + let sess = &compiler.session(); + + // Lower AST to HIR. let krate = - resolver.borrow_mut().access(|resolver| lower_to_hir(sess, resolver, krate, hir_arena)); - let (definitions, cstore, resolver_outputs) = BoxedResolver::to_resolver_outputs(resolver); + lower_to_hir(sess, &mut definitions, &*cstore, &mut resolver_outputs, krate, hir_arena); let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess); diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 826d85c186697..e0cb0cb9709ff 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -27,6 +27,7 @@ pub use adt::*; pub use assoc::*; pub use generics::*; use rustc_ast as ast; +use rustc_ast::node_id::NodeMap; use rustc_attr as attr; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; @@ -34,11 +35,13 @@ use rustc_data_structures::intern::{Interned, WithStableHash}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::tagged_ptr::CopyTaggedPtr; use rustc_hir as hir; -use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; +use rustc_hir::def::{CtorKind, CtorOf, DefKind, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap}; use rustc_hir::Node; +use rustc_index::vec::IndexVec; use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; +use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; use rustc_target::abi::{Align, VariantIdx}; @@ -153,6 +156,30 @@ pub struct ResolverOutputs { /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`. pub confused_type_with_std_module: FxHashMap, pub registered_tools: RegisteredTools, + pub item_generics_num_lifetimes: FxHashMap, + + pub legacy_const_generic_args: FxHashMap>>, + + /// Resolutions for nodes that have a single resolution. + pub partial_res_map: NodeMap, + /// Resolutions for import nodes, which have multiple resolutions in different namespaces. + pub import_res_map: NodeMap>>>, + /// Resolutions for labels (node IDs of their corresponding blocks or loops). + pub label_res_map: NodeMap, + /// Resolutions for lifetimes. + pub lifetimes_res_map: NodeMap, + /// Lifetime parameters that lowering will have to introduce. + pub extra_lifetime_params_map: NodeMap>, + + pub next_node_id: ast::NodeId, + + pub node_id_to_def_id: FxHashMap, + pub def_id_to_node_id: IndexVec, + + pub trait_map: NodeMap>, + /// A small map keeping true kinds of built-in macros that appear to be fn-like on + /// the surface (`macro` items in libcore), but are actually attributes or derives. + pub builtin_macro_kinds: FxHashMap, } #[derive(Clone, Copy, Debug)] diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index b2178ff59954b..8bd8eb488b707 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -12,7 +12,6 @@ tracing = "0.1" rustc_ast = { path = "../rustc_ast" } rustc_arena = { path = "../rustc_arena" } rustc_middle = { path = "../rustc_middle" } -rustc_ast_lowering = { path = "../rustc_ast_lowering" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_resolve/src/access_levels.rs b/compiler/rustc_resolve/src/access_levels.rs index 61a9b644cb8f5..3fba923d9fdf4 100644 --- a/compiler/rustc_resolve/src/access_levels.rs +++ b/compiler/rustc_resolve/src/access_levels.rs @@ -5,7 +5,6 @@ use rustc_ast::Crate; use rustc_ast::EnumDef; use rustc_ast::ForeignMod; use rustc_ast::NodeId; -use rustc_ast_lowering::ResolverAstLowering; use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::CRATE_DEF_ID; use rustc_middle::middle::privacy::AccessLevel; diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index f8fa7a0941d00..8cca958fc630e 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -16,7 +16,6 @@ use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, VisResolutionError use rustc_ast::visit::{self, AssocCtxt, Visitor}; use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind}; use rustc_ast::{Block, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId}; -use rustc_ast_lowering::ResolverAstLowering; use rustc_attr as attr; use rustc_data_structures::sync::Lrc; use rustc_errors::{struct_span_err, Applicability}; @@ -27,7 +26,7 @@ use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_metadata::creader::LoadedMacro; use rustc_middle::bug; use rustc_middle::metadata::ModChild; -use rustc_middle::ty; +use rustc_middle::ty::{self, DefIdTree}; use rustc_session::cstore::CrateStore; use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; use rustc_span::source_map::{respan, Spanned}; @@ -112,10 +111,7 @@ impl<'a> Resolver<'a> { loop { match self.get_module(def_id) { Some(module) => return module, - None => { - def_id.index = - self.def_key(def_id).parent.expect("non-root `DefId` without parent") - } + None => def_id = self.parent(def_id), } } } diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index 5dc720e0abc9f..f2f6f1d895e32 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -30,7 +30,6 @@ use crate::Resolver; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{self, Visitor}; -use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{pluralize, MultiSpan}; use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index f9aff7fd68685..52706fbb9e6ec 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -2,7 +2,6 @@ use crate::{ImplTraitContext, Resolver}; use rustc_ast::visit::{self, FnKind}; use rustc_ast::walk_list; use rustc_ast::*; -use rustc_ast_lowering::ResolverAstLowering; use rustc_expand::expand::AstFragment; use rustc_hir::def_id::LocalDefId; use rustc_hir::definitions::*; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 23c1767cb9051..381073a3f6663 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -15,11 +15,10 @@ use crate::{ResolutionError, Resolver, Segment, UseError}; use rustc_ast::ptr::P; use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; use rustc_ast::*; -use rustc_ast_lowering::{LifetimeRes, ResolverAstLowering}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_errors::DiagnosticId; use rustc_hir::def::Namespace::{self, *}; -use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS}; +use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS}; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::definitions::DefPathData; use rustc_hir::{PrimTy, TraitCandidate}; diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index d2306254e3142..ef54ae514011c 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -11,7 +11,6 @@ use rustc_ast::{ self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind, NodeId, Path, Ty, TyKind, }; -use rustc_ast_lowering::ResolverAstLowering; use rustc_ast_pretty::pprust::path_segment_to_string; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_errors::{ diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 5e8e0e1efe3e1..eb58f17fc7e03 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -27,17 +27,16 @@ use rustc_arena::{DroplessArena, TypedArena}; use rustc_ast::node_id::NodeMap; use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID}; use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path}; -use rustc_ast_lowering::{LifetimeRes, ResolverAstLowering}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::sync::Lrc; 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, PartialRes}; -use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefPathHash, LocalDefId}; +use rustc_hir::def::{self, CtorOf, DefKind, LifetimeRes, PartialRes}; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; -use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; +use rustc_hir::definitions::{DefPathData, Definitions}; use rustc_hir::TraitCandidate; use rustc_index::vec::IndexVec; use rustc_metadata::creader::{CStore, CrateLoader}; @@ -1121,85 +1120,15 @@ impl<'a, 'b> DefIdTree for &'a Resolver<'b> { } } -/// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that -/// the resolver is no longer needed as all the relevant information is inline. -impl ResolverAstLowering for Resolver<'_> { - fn def_key(&self, id: DefId) -> DefKey { - if let Some(id) = id.as_local() { - self.definitions.def_key(id) - } else { - self.cstore().def_key(id) - } - } - - #[inline] - fn def_span(&self, id: LocalDefId) -> Span { - self.definitions.def_span(id) - } - - fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { - if let Some(def_id) = def_id.as_local() { - self.item_generics_num_lifetimes[&def_id] - } else { - self.cstore().item_generics_num_lifetimes(def_id, self.session) - } - } - - fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { - self.legacy_const_generic_args(expr) - } - - fn get_partial_res(&self, id: NodeId) -> Option { - self.partial_res_map.get(&id).cloned() - } - - fn get_import_res(&self, id: NodeId) -> PerNS> { - self.import_res_map.get(&id).cloned().unwrap_or_default() - } - - fn get_label_res(&self, id: NodeId) -> Option { - self.label_res_map.get(&id).cloned() - } - - fn get_lifetime_res(&self, id: NodeId) -> Option { - self.lifetimes_res_map.get(&id).copied() - } - - fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> { - self.extra_lifetime_params_map.remove(&id).unwrap_or_default() - } - - fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { - StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) - } - - fn definitions(&self) -> &Definitions { - &self.definitions - } - - fn next_node_id(&mut self) -> NodeId { - self.next_node_id() - } - - fn take_trait_map(&mut self, node: NodeId) -> Option> { - self.trait_map.remove(&node) - } - +impl Resolver<'_> { fn opt_local_def_id(&self, node: NodeId) -> Option { self.node_id_to_def_id.get(&node).copied() } - fn local_def_id(&self, node: NodeId) -> LocalDefId { + pub fn local_def_id(&self, node: NodeId) -> LocalDefId { self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) } - fn def_path_hash(&self, def_id: DefId) -> DefPathHash { - match def_id.as_local() { - Some(def_id) => self.definitions.def_path_hash(def_id), - None => self.cstore().def_path_hash(def_id), - } - } - /// Adds a definition with a parent definition. fn create_def( &mut self, @@ -1231,8 +1160,12 @@ impl ResolverAstLowering for Resolver<'_> { def_id } - fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind { - self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang) + fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { + if let Some(def_id) = def_id.as_local() { + self.item_generics_num_lifetimes[&def_id] + } else { + self.cstore().item_generics_num_lifetimes(def_id, self.session) + } } } @@ -1472,6 +1405,18 @@ impl<'a> Resolver<'a> { proc_macros, confused_type_with_std_module, registered_tools: self.registered_tools, + item_generics_num_lifetimes: self.item_generics_num_lifetimes, + legacy_const_generic_args: self.legacy_const_generic_args, + partial_res_map: self.partial_res_map, + import_res_map: self.import_res_map, + label_res_map: self.label_res_map, + lifetimes_res_map: self.lifetimes_res_map, + extra_lifetime_params_map: self.extra_lifetime_params_map, + next_node_id: self.next_node_id, + node_id_to_def_id: self.node_id_to_def_id, + def_id_to_node_id: self.def_id_to_node_id, + trait_map: self.trait_map, + builtin_macro_kinds: self.builtin_macro_kinds, }; (definitions, cstore, resolutions) } @@ -1499,10 +1444,26 @@ impl<'a> Resolver<'a> { confused_type_with_std_module: self.confused_type_with_std_module.clone(), registered_tools: self.registered_tools.clone(), access_levels: self.access_levels.clone(), + item_generics_num_lifetimes: self.item_generics_num_lifetimes.clone(), + 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.clone(), + 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(), }; (definitions, cstore, resolutions) } + fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { + StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) + } + pub fn cstore(&self) -> &CStore { self.crate_loader.cstore() } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 3fb34cdcd9bd9..f6c13b6870a66 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -7,7 +7,6 @@ use crate::{BuiltinMacroState, Determinacy}; use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet}; use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment}; use rustc_ast::{self as ast, Inline, ItemKind, ModKind, NodeId}; -use rustc_ast_lowering::ResolverAstLowering; use rustc_ast_pretty::pprust; use rustc_attr::StabilityLevel; use rustc_data_structures::fx::FxHashSet; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index ea842a85070d8..54b851660416a 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -36,7 +36,6 @@ extern crate tracing; // Dependencies listed in Cargo.toml do not need `extern crate`. extern crate rustc_ast; -extern crate rustc_ast_lowering; extern crate rustc_ast_pretty; extern crate rustc_attr; extern crate rustc_const_eval; diff --git a/src/librustdoc/passes/collect_intra_doc_links/early.rs b/src/librustdoc/passes/collect_intra_doc_links/early.rs index a38c44bc88855..38cfd7a27ddb4 100644 --- a/src/librustdoc/passes/collect_intra_doc_links/early.rs +++ b/src/librustdoc/passes/collect_intra_doc_links/early.rs @@ -5,7 +5,6 @@ use crate::passes::collect_intra_doc_links::{Disambiguator, PreprocessedMarkdown use rustc_ast::visit::{self, AssocCtxt, Visitor}; use rustc_ast::{self as ast, ItemKind}; -use rustc_ast_lowering::ResolverAstLowering; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::Namespace::*; use rustc_hir::def::{DefKind, Namespace, Res}; From b676edd641dbd1049702e63dc027f92daa849d23 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 18 Jul 2021 20:09:20 +0200 Subject: [PATCH 3/7] Do not modify the resolver outputs. --- compiler/rustc_ast_lowering/src/asm.rs | 2 +- compiler/rustc_ast_lowering/src/expr.rs | 4 +- compiler/rustc_ast_lowering/src/item.rs | 36 ++++---- compiler/rustc_ast_lowering/src/lib.rs | 116 +++++++++++++----------- 4 files changed, 83 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 46e6ee9468ca8..1a125a9751bcf 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -242,7 +242,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Wrap the expression in an AnonConst. let parent_def_id = self.current_hir_id_owner; - let node_id = self.resolver.next_node_id(); + let node_id = self.next_node_id(); self.create_def( parent_def_id, node_id, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1e863f6395bc1..619debba6da20 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -355,7 +355,7 @@ impl<'hir> LoweringContext<'_, 'hir> { for (idx, arg) in args.into_iter().enumerate() { if legacy_args_idx.contains(&idx) { let parent_def_id = self.current_hir_id_owner; - let node_id = self.resolver.next_node_id(); + let node_id = self.next_node_id(); // Add a definition for the in-band const def. self.create_def( @@ -724,7 +724,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; // `::std::task::Poll::Ready(result) => break result` - let loop_node_id = self.resolver.next_node_id(); + let loop_node_id = self.next_node_id(); let loop_hir_id = self.lower_node_id(loop_node_id); let ready_arm = { let x_ident = Ident::with_dummy_span(sym::result); diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 49ba2876d1ff0..81a55ce8a4334 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -62,6 +62,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { owner: NodeId, f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>, ) { + let next_node_id = self.resolver.next_node_id; let mut lctx = LoweringContext { // Pseudo-globals. sess: &self.sess, @@ -79,6 +80,8 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { node_id_to_local_id: Default::default(), local_id_to_def_id: SortedMap::new(), trait_map: Default::default(), + local_node_id_to_def_id: FxHashMap::default(), + next_node_id, // Lowering state. catch_scope: None, @@ -126,8 +129,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { #[instrument(level = "debug", skip(self, c))] fn lower_crate(&mut self, c: &Crate) { - debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID); - + debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID); self.with_lctx(CRATE_NODE_ID, |lctx| { let module = lctx.lower_mod(&c.items, &c.spans); lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs); @@ -141,7 +143,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { } fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) { - let def_id = self.resolver.local_def_id(item.id); + let def_id = self.resolver.node_id_to_def_id[&item.id]; let parent_id = { let parent = self.definitions.def_key(def_id).parent; @@ -185,7 +187,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> { - let mut node_ids = smallvec![hir::ItemId { def_id: self.resolver.local_def_id(i.id) }]; + let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }]; if let ItemKind::Use(ref use_tree) = &i.kind { self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids); } @@ -201,7 +203,7 @@ impl<'hir> LoweringContext<'_, 'hir> { match tree.kind { UseTreeKind::Nested(ref nested_vec) => { for &(ref nested, id) in nested_vec { - vec.push(hir::ItemId { def_id: self.resolver.local_def_id(id) }); + vec.push(hir::ItemId { def_id: self.local_def_id(id) }); self.lower_item_id_use_tree(nested, id, vec); } } @@ -210,7 +212,7 @@ impl<'hir> LoweringContext<'_, 'hir> { for (_, &id) in iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2]) { - vec.push(hir::ItemId { def_id: self.resolver.local_def_id(id) }); + vec.push(hir::ItemId { def_id: self.local_def_id(id) }); } } } @@ -475,7 +477,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => { let body = P(self.lower_mac_args(body)); - let macro_kind = self.resolver.decl_macro_kind(self.resolver.local_def_id(id)); + let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id)); hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind) } ItemKind::MacCall(..) => { @@ -535,7 +537,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Essentially a single `use` which imports two names is desugared into // two imports. for new_node_id in [id1, id2] { - let new_id = self.resolver.local_def_id(new_node_id); + let new_id = self.local_def_id(new_node_id); let Some(res) = resolutions.next() else { // Associate an HirId to both ids even if there is no resolution. let _old = self.children.insert( @@ -548,7 +550,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let ident = *ident; let mut path = path.clone(); for seg in &mut path.segments { - seg.id = self.resolver.next_node_id(); + seg.id = self.next_node_id(); } let span = path.span; @@ -611,13 +613,13 @@ impl<'hir> LoweringContext<'_, 'hir> { // Add all the nested `PathListItem`s to the HIR. for &(ref use_tree, id) in trees { - let new_hir_id = self.resolver.local_def_id(id); + let new_hir_id = self.local_def_id(id); let mut prefix = prefix.clone(); // Give the segments new node-ids since they are being cloned. for seg in &mut prefix.segments { - seg.id = self.resolver.next_node_id(); + seg.id = self.next_node_id(); } // Each `use` import is an item and thus are owners of the @@ -691,7 +693,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef { hir::ForeignItemRef { - id: hir::ForeignItemId { def_id: self.resolver.local_def_id(i.id) }, + id: hir::ForeignItemId { def_id: self.local_def_id(i.id) }, ident: self.lower_ident(i.ident), span: self.lower_span(i.span), } @@ -847,7 +849,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::MacCall(..) => unimplemented!(), }; - let id = hir::TraitItemId { def_id: self.resolver.local_def_id(i.id) }; + let id = hir::TraitItemId { def_id: self.local_def_id(i.id) }; let defaultness = hir::Defaultness::Default { has_value: has_default }; hir::TraitItemRef { id, @@ -927,7 +929,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let has_value = true; let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); hir::ImplItemRef { - id: hir::ImplItemId { def_id: self.resolver.local_def_id(i.id) }, + id: hir::ImplItemId { def_id: self.local_def_id(i.id) }, ident: self.lower_ident(i.ident), span: self.lower_span(i.span), defaultness, @@ -1339,7 +1341,7 @@ impl<'hir> LoweringContext<'_, 'hir> { generics .params .iter() - .any(|p| def_id == self.resolver.local_def_id(p.id).to_def_id()) + .any(|p| def_id == self.local_def_id(p.id).to_def_id()) } // Either the `bounded_ty` is not a plain type parameter, or // it's not found in the generic type parameters list. @@ -1443,7 +1445,7 @@ impl<'hir> LoweringContext<'_, 'hir> { match kind { GenericParamKind::Const { .. } => None, GenericParamKind::Type { .. } => { - let def_id = self.resolver.local_def_id(id).to_def_id(); + let def_id = self.local_def_id(id).to_def_id(); let ty_path = self.arena.alloc(hir::Path { span: param_span, res: Res::Def(DefKind::TyParam, def_id), @@ -1466,7 +1468,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let res = self.resolver.get_lifetime_res(id).unwrap_or_else(|| { panic!("Missing resolution for lifetime {:?} at {:?}", id, ident.span) }); - let lt_id = self.resolver.next_node_id(); + let lt_id = self.next_node_id(); let lifetime = self.new_named_lifetime_with_res(lt_id, ident_span, ident, res); Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { lifetime, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index f7acb08abde25..6903e02f3a5b8 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -133,6 +133,10 @@ struct LoweringContext<'a, 'hir: 'a> { /// NodeIds that are lowered inside the current HIR owner. node_id_to_local_id: FxHashMap, + // The next_node_id is reset for each item. + next_node_id: ast::NodeId, + local_node_id_to_def_id: FxHashMap, + allow_try_trait: Option>, allow_gen_future: Option>, allow_into_future: Option>, @@ -167,9 +171,6 @@ trait ResolverAstLoweringExt { fn get_label_res(&self, id: NodeId) -> Option; fn get_lifetime_res(&self, id: NodeId) -> Option; fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>; - fn next_node_id(&mut self) -> NodeId; - fn opt_local_def_id(&self, node: NodeId) -> Option; - fn local_def_id(&self, node: NodeId) -> LocalDefId; fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind; } @@ -229,24 +230,6 @@ impl ResolverAstLoweringExt for ResolverOutputs { self.extra_lifetime_params_map.remove(&id).unwrap_or_default() } - fn next_node_id(&mut self) -> NodeId { - let next = self - .next_node_id - .as_usize() - .checked_add(1) - .expect("input too large; ran out of NodeIds"); - self.next_node_id = NodeId::from_usize(next); - self.next_node_id - } - - fn opt_local_def_id(&self, node: NodeId) -> Option { - self.node_id_to_def_id.get(&node).copied() - } - - fn local_def_id(&self, node: NodeId) -> LocalDefId { - self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) - } - fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind { self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang) } @@ -359,17 +342,17 @@ enum AstOwner<'a> { } fn index_crate<'a>( - resolver: &ResolverOutputs, + node_id_to_def_id: &FxHashMap, krate: &'a Crate, ) -> IndexVec> { - let mut indexer = Indexer { resolver, index: IndexVec::new() }; + let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() }; indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner); indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate); visit::walk_crate(&mut indexer, krate); return indexer.index; struct Indexer<'s, 'a> { - resolver: &'s ResolverOutputs, + node_id_to_def_id: &'s FxHashMap, index: IndexVec>, } @@ -380,21 +363,21 @@ fn index_crate<'a>( } fn visit_item(&mut self, item: &'a ast::Item) { - let def_id = self.resolver.local_def_id(item.id); + let def_id = self.node_id_to_def_id[&item.id]; self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); self.index[def_id] = AstOwner::Item(item); visit::walk_item(self, item) } fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) { - let def_id = self.resolver.local_def_id(item.id); + let def_id = self.node_id_to_def_id[&item.id]; self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); self.index[def_id] = AstOwner::AssocItem(item, ctxt); visit::walk_assoc_item(self, item, ctxt); } fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) { - let def_id = self.resolver.local_def_id(item.id); + let def_id = self.node_id_to_def_id[&item.id]; self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); self.index[def_id] = AstOwner::ForeignItem(item); visit::walk_foreign_item(self, item); @@ -436,7 +419,7 @@ pub fn lower_crate<'hir>( ) -> &'hir hir::Crate<'hir> { let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering"); - let ast_index = index_crate(resolver, krate); + let ast_index = index_crate(&resolver.node_id_to_def_id, krate); let mut owners = IndexVec::from_fn_n(|_| hir::MaybeOwner::Phantom, definitions.def_index_count()); @@ -488,11 +471,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: Span, ) -> LocalDefId { assert!( - !self.resolver.node_id_to_def_id.contains_key(&node_id), + self.opt_local_def_id(node_id).is_none(), "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", node_id, data, - self.definitions.def_key(self.resolver.node_id_to_def_id[&node_id]), + self.definitions.def_key(self.local_def_id(node_id)), ); let def_id = self.definitions.create_def(parent, data, expn_id, span); @@ -502,20 +485,41 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // we don't need a mapping from `NodeId` to `LocalDefId`. if node_id != ast::DUMMY_NODE_ID { debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); - self.resolver.node_id_to_def_id.insert(node_id, def_id); + self.local_node_id_to_def_id.insert(node_id, def_id); } - assert_eq!(self.resolver.def_id_to_node_id.push(node_id), def_id); def_id } + fn next_node_id(&mut self) -> NodeId { + let next = self + .next_node_id + .as_usize() + .checked_add(1) + .expect("input too large; ran out of NodeIds"); + self.next_node_id = NodeId::from_usize(next); + self.next_node_id + } + + fn opt_local_def_id(&self, node: NodeId) -> Option { + if node <= self.resolver.next_node_id { + self.resolver.node_id_to_def_id.get(&node).copied() + } else { + self.local_node_id_to_def_id.get(&node).copied() + } + } + + fn local_def_id(&self, node: NodeId) -> LocalDefId { + self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) + } + #[instrument(level = "debug", skip(self, f))] fn with_hir_id_owner( &mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>, ) { - let def_id = self.resolver.local_def_id(owner); + let def_id = self.local_def_id(owner); let current_attrs = std::mem::take(&mut self.attrs); let current_bodies = std::mem::take(&mut self.bodies); @@ -527,6 +531,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1)); let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs); let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds); + // Do not reset `next_node_id` and `node_id_to_def_id` as we want to refer to the + // subdefinitions' nodes. // Always allocate the first `HirId` for the owner itself. let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0)); @@ -633,7 +639,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.item_local_id_counter.increment_by(1); assert_ne!(local_id, hir::ItemLocalId::new(0)); - if let Some(def_id) = self.resolver.opt_local_def_id(ast_node_id) { + if let Some(def_id) = self.opt_local_def_id(ast_node_id) { // Do not override a `MaybeOwner::Owner` that may already here. self.children.entry(def_id).or_insert(hir::MaybeOwner::NonOwner(hir_id)); self.local_id_to_def_id.insert(local_id, def_id); @@ -649,7 +655,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn next_id(&mut self) -> hir::HirId { - let node_id = self.resolver.next_node_id(); + let node_id = self.next_node_id(); self.lower_node_id(node_id) } @@ -991,7 +997,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // constructing the HIR for `impl bounds...` and then lowering that. let parent_def_id = self.current_hir_id_owner; - let impl_trait_node_id = self.resolver.next_node_id(); + let impl_trait_node_id = self.next_node_id(); self.create_def( parent_def_id, impl_trait_node_id, @@ -1001,7 +1007,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); self.with_dyn_type_scope(false, |this| { - let node_id = this.resolver.next_node_id(); + let node_id = this.next_node_id(); let ty = this.lower_ty( &Ty { id: node_id, @@ -1101,7 +1107,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Construct an AnonConst where the expr is the "ty"'s path. let parent_def_id = self.current_hir_id_owner; - let node_id = self.resolver.next_node_id(); + let node_id = self.next_node_id(); // Add a definition for the in-band const def. self.create_def( @@ -1180,7 +1186,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert_eq!(start.plus(1), end); start } else { - self.resolver.next_node_id() + self.next_node_id() }; let span = self.sess.source_map().next_point(t.span.shrink_to_lo()); Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id } @@ -1323,7 +1329,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // frequently opened issues show. let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None); - let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id); + let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id); let mut collected_lifetimes = FxHashMap::default(); self.with_hir_id_owner(opaque_ty_node_id, |lctx| { @@ -1341,7 +1347,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let lifetime_defs = lctx.arena.alloc_from_iter(collected_lifetimes.iter().map( |(_, &(span, p_id, p_name, _))| { let hir_id = lctx.lower_node_id(p_id); - debug_assert_ne!(lctx.resolver.opt_local_def_id(p_id), None); + debug_assert_ne!(lctx.opt_local_def_id(p_id), None); let kind = if p_name.ident().name == kw::UnderscoreLifetime { hir::LifetimeParamKind::Elided @@ -1380,7 +1386,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let lifetimes = self.arena.alloc_from_iter(collected_lifetimes.into_iter().map( |(_, (span, _, p_name, res))| { - let id = self.resolver.next_node_id(); + let id = self.next_node_id(); let ident = Ident::new(p_name.ident().name, span); let l = self.new_named_lifetime_with_res(id, span, ident, res); hir::GenericArg::Lifetime(l) @@ -1489,7 +1495,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { FnRetTy::Ty(ref ty) => { let context = match fn_node_id { Some(fn_node_id) if kind.impl_trait_return_allowed() => { - let fn_def_id = self.resolver.local_def_id(fn_node_id); + let fn_def_id = self.local_def_id(fn_node_id); ImplTraitContext::ReturnPositionOpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id), } @@ -1563,8 +1569,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None); - let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id); - let fn_def_id = self.resolver.local_def_id(fn_node_id); + let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id); + let fn_def_id = self.local_def_id(fn_node_id); // When we create the opaque type for this async fn, it is going to have // to capture all the lifetimes involved in the signature (including in the @@ -1614,8 +1620,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug!(?extra_lifetime_params); for (ident, outer_node_id, outer_res) in extra_lifetime_params { let Ident { name, span } = ident; - let outer_def_id = self.resolver.local_def_id(outer_node_id); - let inner_node_id = self.resolver.next_node_id(); + let outer_def_id = self.local_def_id(outer_node_id); + let inner_node_id = self.next_node_id(); // Add a definition for the in scope lifetime def. self.create_def( @@ -1665,7 +1671,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let generic_params = this.arena.alloc_from_iter(captures.iter().map(|(_, &(span, p_id, p_name, _))| { let hir_id = this.lower_node_id(p_id); - debug_assert_ne!(this.resolver.opt_local_def_id(p_id), None); + debug_assert_ne!(this.opt_local_def_id(p_id), None); let kind = if p_name.ident().name == kw::UnderscoreLifetime { hir::LifetimeParamKind::Elided @@ -1717,7 +1723,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // generate `'_`. let generic_args = self.arena.alloc_from_iter(captures.into_iter().map(|(_, (span, _, p_name, res))| { - let id = self.resolver.next_node_id(); + let id = self.next_node_id(); let ident = Ident::new(p_name.ident().name, span); let l = self.new_named_lifetime_with_res(id, span, ident, res); hir::GenericArg::Lifetime(l) @@ -1811,9 +1817,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { if !captured_lifetimes.binders_to_ignore.contains(&binder) { match captured_lifetimes.captures.entry(param) { - Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), + Entry::Occupied(o) => param = self.local_def_id(o.get().1), Entry::Vacant(v) => { - let p_id = self.resolver.next_node_id(); + let p_id = self.next_node_id(); let p_def_id = self.create_def( captured_lifetimes.parent_def_id, p_id, @@ -1837,9 +1843,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { if !captured_lifetimes.binders_to_ignore.contains(&binder) { match captured_lifetimes.captures.entry(param) { - Entry::Occupied(o) => param = self.resolver.local_def_id(o.get().1), + Entry::Occupied(o) => param = self.local_def_id(o.get().1), Entry::Vacant(v) => { - let p_id = self.resolver.next_node_id(); + let p_id = self.next_node_id(); let p_def_id = self.create_def( captured_lifetimes.parent_def_id, p_id, @@ -1862,7 +1868,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let mut l_name = None; if let Some(mut captured_lifetimes) = self.captured_lifetimes.take() { if !captured_lifetimes.binders_to_ignore.contains(&binder) { - let p_id = self.resolver.next_node_id(); + let p_id = self.next_node_id(); let p_def_id = self.create_def( captured_lifetimes.parent_def_id, p_id, @@ -2011,7 +2017,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { bounds: &[GenericBound], ) -> (hir::GenericParam<'hir>, Option>, hir::TyKind<'hir>) { // Add a definition for the in-band `Param`. - let def_id = self.resolver.local_def_id(node_id); + let def_id = self.local_def_id(node_id); let hir_bounds = self.lower_param_bounds(bounds, ImplTraitContext::Universal); // Set the name to `impl Bound1 + Bound2`. From 34e4d72929c33bb126e0b1b199faab9031e0f3de Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 30 May 2022 18:49:17 +0200 Subject: [PATCH 4/7] Separate `source_span` and `expn_that_defined` from `Definitions`. --- compiler/rustc_ast_lowering/src/asm.rs | 10 +--- compiler/rustc_ast_lowering/src/expr.rs | 9 +-- compiler/rustc_ast_lowering/src/lib.rs | 48 +++++----------- compiler/rustc_hir/src/definitions.rs | 56 ++----------------- compiler/rustc_middle/src/hir/map/mod.rs | 5 +- compiler/rustc_middle/src/hir/mod.rs | 7 ++- compiler/rustc_middle/src/query/mod.rs | 3 - compiler/rustc_middle/src/ty/context.rs | 50 +++++++++++++++-- compiler/rustc_middle/src/ty/mod.rs | 6 +- .../rustc_query_impl/src/on_disk_cache.rs | 5 +- compiler/rustc_query_system/src/ich/hcx.rs | 11 +++- compiler/rustc_resolve/src/diagnostics.rs | 21 +++---- compiler/rustc_resolve/src/lib.rs | 39 +++++++++++-- 13 files changed, 135 insertions(+), 135 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 1a125a9751bcf..aab9b90e4b7e5 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -11,7 +11,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::definitions::DefPathData; use rustc_session::parse::feature_err; -use rustc_span::{sym, ExpnId, Span}; +use rustc_span::{sym, Span}; use rustc_target::asm; use std::collections::hash_map::Entry; use std::fmt::Write; @@ -243,13 +243,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Wrap the expression in an AnonConst. let parent_def_id = self.current_hir_id_owner; let node_id = self.next_node_id(); - self.create_def( - parent_def_id, - node_id, - DefPathData::AnonConst, - ExpnId::root(), - *op_sp, - ); + self.create_def(parent_def_id, node_id, DefPathData::AnonConst); let anon_const = AnonConst { id: node_id, value: P(expr) }; hir::InlineAsmOperand::SymFn { anon_const: self.lower_anon_const(&anon_const), diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 619debba6da20..d6b27f267e054 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -11,7 +11,6 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::definitions::DefPathData; -use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; use rustc_span::symbol::{sym, Ident}; use rustc_span::DUMMY_SP; @@ -358,13 +357,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let node_id = self.next_node_id(); // Add a definition for the in-band const def. - self.create_def( - parent_def_id, - node_id, - DefPathData::AnonConst, - ExpnId::root(), - arg.span, - ); + self.create_def(parent_def_id, node_id, DefPathData::AnonConst); let anon_const = AnonConst { id: node_id, value: arg }; generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const))); diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6903e02f3a5b8..d56b2fd5d0b50 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -61,7 +61,7 @@ use rustc_query_system::ich::StableHashingContext; use rustc_session::cstore::CrateStoreDyn; use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::hygiene::{ExpnId, MacroKind}; +use rustc_span::hygiene::MacroKind; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; @@ -391,6 +391,7 @@ fn compute_hir_hash( sess: &Session, definitions: &Definitions, cstore: &CrateStoreDyn, + resolver: &ResolverOutputs, owners: &IndexVec>>, ) -> Fingerprint { let mut hir_body_nodes: Vec<_> = owners @@ -404,7 +405,7 @@ fn compute_hir_hash( hir_body_nodes.sort_unstable_by_key(|bn| bn.0); let mut stable_hasher = StableHasher::new(); - let mut hcx = StableHashingContext::new(sess, definitions, cstore); + let mut hcx = StableHashingContext::new(sess, definitions, cstore, &resolver.source_span); hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher); stable_hasher.finish() } @@ -437,7 +438,7 @@ pub fn lower_crate<'hir>( .lower_node(def_id); } - let hir_hash = compute_hir_hash(sess, definitions, cstore, &owners); + let hir_hash = compute_hir_hash(sess, definitions, cstore, resolver, &owners); let krate = hir::Crate { owners, hir_hash }; arena.alloc(krate) } @@ -459,7 +460,12 @@ enum ParenthesizedGenericArgs { impl<'a, 'hir> LoweringContext<'a, 'hir> { fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { - StableHashingContext::new(self.sess, self.definitions, self.cstore) + StableHashingContext::new( + self.sess, + self.definitions, + self.cstore, + &self.resolver.source_span, + ) } fn create_def( @@ -467,8 +473,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { parent: LocalDefId, node_id: ast::NodeId, data: DefPathData, - expn_id: ExpnId, - span: Span, ) -> LocalDefId { assert!( self.opt_local_def_id(node_id).is_none(), @@ -478,7 +482,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.definitions.def_key(self.local_def_id(node_id)), ); - let def_id = self.definitions.create_def(parent, data, expn_id, span); + let def_id = self.definitions.create_def(parent, data); // Some things for which we allocate `LocalDefId`s don't correspond to // anything in the AST, so they don't have a `NodeId`. For these cases @@ -998,13 +1002,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let parent_def_id = self.current_hir_id_owner; let impl_trait_node_id = self.next_node_id(); - self.create_def( - parent_def_id, - impl_trait_node_id, - DefPathData::ImplTrait, - ExpnId::root(), - constraint.span, - ); + self.create_def(parent_def_id, impl_trait_node_id, DefPathData::ImplTrait); self.with_dyn_type_scope(false, |this| { let node_id = this.next_node_id(); @@ -1110,13 +1108,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let node_id = self.next_node_id(); // Add a definition for the in-band const def. - self.create_def( - parent_def_id, - node_id, - DefPathData::AnonConst, - ExpnId::root(), - ty.span, - ); + self.create_def(parent_def_id, node_id, DefPathData::AnonConst); let span = self.lower_span(ty.span); let path_expr = Expr { @@ -1624,13 +1616,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let inner_node_id = self.next_node_id(); // Add a definition for the in scope lifetime def. - self.create_def( - opaque_ty_def_id, - inner_node_id, - DefPathData::LifetimeNs(name), - ExpnId::root(), - span.with_parent(None), - ); + self.create_def(opaque_ty_def_id, inner_node_id, DefPathData::LifetimeNs(name)); let (p_name, inner_res) = match outer_res { // Input lifetime like `'a`: @@ -1824,8 +1810,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { captured_lifetimes.parent_def_id, p_id, DefPathData::LifetimeNs(p_name.ident().name), - ExpnId::root(), - span.with_parent(None), ); v.insert((span, p_id, p_name, res)); @@ -1850,8 +1834,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { captured_lifetimes.parent_def_id, p_id, DefPathData::LifetimeNs(kw::UnderscoreLifetime), - ExpnId::root(), - span.with_parent(None), ); v.insert((span, p_id, ParamName::Fresh, res)); @@ -1873,8 +1855,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { captured_lifetimes.parent_def_id, p_id, DefPathData::LifetimeNs(kw::UnderscoreLifetime), - ExpnId::root(), - span.with_parent(None), ); captured_lifetimes .captures diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 5c32dd372dde1..5f8801cc4e20d 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -11,9 +11,7 @@ use crate::def_path_hash_map::DefPathHashMap; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::StableHasher; use rustc_index::vec::IndexVec; -use rustc_span::hygiene::ExpnId; use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::Span; use std::fmt::{self, Write}; use std::hash::Hash; @@ -101,11 +99,6 @@ pub struct Definitions { table: DefPathTable, next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>, - /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. - expansions_that_defined: FxHashMap, - - def_id_to_span: IndexVec, - /// The [StableCrateId] of the local crate. stable_crate_id: StableCrateId, } @@ -323,7 +316,7 @@ impl Definitions { } /// Adds a root definition (no parent) and a few other reserved definitions. - pub fn new(stable_crate_id: StableCrateId, crate_span: Span) -> Definitions { + pub fn new(stable_crate_id: StableCrateId) -> Definitions { let key = DefKey { parent: None, disambiguated_data: DisambiguatedDefPathData { @@ -340,30 +333,12 @@ impl Definitions { let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) }; assert_eq!(root.local_def_index, CRATE_DEF_INDEX); - let mut def_id_to_span = IndexVec::new(); - // A relative span's parent must be an absolute span. - debug_assert_eq!(crate_span.data_untracked().parent, None); - let _root = def_id_to_span.push(crate_span); - debug_assert_eq!(_root, root); - - Definitions { - table, - next_disambiguator: Default::default(), - expansions_that_defined: Default::default(), - def_id_to_span, - stable_crate_id, - } + Definitions { table, next_disambiguator: Default::default(), stable_crate_id } } /// Adds a definition with a parent definition. - pub fn create_def( - &mut self, - parent: LocalDefId, - data: DefPathData, - expn_id: ExpnId, - span: Span, - ) -> LocalDefId { - debug!("create_def(parent={:?}, data={:?}, expn_id={:?})", parent, data, expn_id); + pub fn create_def(&mut self, parent: LocalDefId, data: DefPathData) -> LocalDefId { + debug!("create_def(parent={:?}, data={:?})", parent, data); // The root node must be created with `create_root_def()`. assert!(data != DefPathData::CrateRoot); @@ -386,28 +361,7 @@ impl Definitions { debug!("create_def: after disambiguation, key = {:?}", key); // Create the definition. - let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) }; - - if expn_id != ExpnId::root() { - self.expansions_that_defined.insert(def_id, expn_id); - } - - // A relative span's parent must be an absolute span. - debug_assert_eq!(span.data_untracked().parent, None); - let _id = self.def_id_to_span.push(span); - debug_assert_eq!(_id, def_id); - - def_id - } - - pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId { - self.expansions_that_defined.get(&id).copied().unwrap_or_else(ExpnId::root) - } - - /// Retrieves the span of the given `DefId` if `DefId` is in the local crate. - #[inline] - pub fn def_span(&self, def_id: LocalDefId) -> Span { - self.def_id_to_span[def_id] + LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) } } pub fn iter_local_def_id(&self) -> impl Iterator + '_ { diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 73aa23ce2b2db..9d77d640a15a6 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1078,6 +1078,8 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { let upstream_crates = upstream_crates(tcx); + let resolutions = tcx.resolutions(()); + // We hash the final, remapped names of all local source files so we // don't have to include the path prefix remapping commandline args. // If we included the full mapping in the SVH, we could only have @@ -1107,7 +1109,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { .filter_map(|(def_id, info)| { let _ = info.as_owner()?; let def_path_hash = definitions.def_path_hash(def_id); - let span = definitions.def_span(def_id); + let span = resolutions.source_span[def_id]; debug_assert_eq!(span.parent(), None); Some((def_path_hash, span)) }) @@ -1118,7 +1120,6 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher); tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher); // Hash visibility information since it does not appear in HIR. - let resolutions = tcx.resolutions(()); resolutions.visibilities.hash_stable(&mut hcx, &mut stable_hasher); resolutions.has_pub_restricted.hash_stable(&mut hcx, &mut stable_hasher); diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 8068e6dff95a6..09b142e0c415d 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -13,7 +13,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::*; use rustc_query_system::ich::StableHashingContext; -use rustc_span::DUMMY_SP; +use rustc_span::{ExpnId, DUMMY_SP}; /// Top-level HIR node for current owner. This only contains the node for which /// `HirId::local_id == 0`, and excludes bodies. @@ -117,7 +117,8 @@ pub fn provide(providers: &mut Providers) { }; providers.hir_attrs = |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs); - providers.source_span = |tcx, def_id| tcx.definitions_untracked().def_span(def_id); + providers.source_span = + |tcx, def_id| tcx.resolutions(()).source_span.get(def_id).copied().unwrap_or(DUMMY_SP); providers.def_span = |tcx, def_id| { let def_id = def_id.expect_local(); let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); @@ -147,7 +148,7 @@ pub fn provide(providers: &mut Providers) { providers.all_local_trait_impls = |tcx, ()| &tcx.resolutions(()).trait_impls; providers.expn_that_defined = |tcx, id| { let id = id.expect_local(); - tcx.definitions_untracked().expansion_that_defined(id) + tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root()) }; providers.in_scope_traits_map = |tcx, id| tcx.hir_crate(()).owners[id].as_owner().map(|owner_info| &owner_info.trait_map); diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index ce075805aef80..e0b4eced075e9 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -31,7 +31,6 @@ rustc_queries! { /// This span is meant for dep-tracking rather than diagnostics. It should not be used outside /// of rustc_middle::hir::source_map. query source_span(key: LocalDefId) -> Span { - eval_always desc { "get the source span" } } @@ -272,8 +271,6 @@ rustc_queries! { } query expn_that_defined(key: DefId) -> rustc_span::ExpnId { - // This query reads from untracked data in definitions. - eval_always desc { |tcx| "expansion that defined `{}`", tcx.def_path_str(key) } separate_provide_extern } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 5d020f429c064..4464a0211fc2d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -180,6 +180,7 @@ impl<'tcx> CtxtInterners<'tcx> { sess: &Session, definitions: &rustc_hir::definitions::Definitions, cstore: &CrateStoreDyn, + source_span: &IndexVec, ) -> Ty<'tcx> { Ty(Interned::new_unchecked( self.type_ @@ -194,7 +195,12 @@ impl<'tcx> CtxtInterners<'tcx> { Fingerprint::ZERO } else { let mut hasher = StableHasher::new(); - let mut hcx = StableHashingContext::ignore_spans(sess, definitions, cstore); + let mut hcx = StableHashingContext::ignore_spans( + sess, + definitions, + cstore, + source_span, + ); kind.hash_stable(&mut hcx, &mut hasher); hasher.finish() }; @@ -934,8 +940,9 @@ impl<'tcx> CommonTypes<'tcx> { sess: &Session, definitions: &rustc_hir::definitions::Definitions, cstore: &CrateStoreDyn, + source_span: &IndexVec, ) -> CommonTypes<'tcx> { - let mk = |ty| interners.intern_ty(ty, sess, definitions, cstore); + let mk = |ty| interners.intern_ty(ty, sess, definitions, cstore, source_span); CommonTypes { unit: mk(Tuple(List::empty())), @@ -1235,7 +1242,14 @@ impl<'tcx> TyCtxt<'tcx> { s.fatal(&err); }); let interners = CtxtInterners::new(arena); - let common_types = CommonTypes::new(&interners, s, &definitions, &*cstore); + let common_types = CommonTypes::new( + &interners, + s, + &definitions, + &*cstore, + // This is only used to create a stable hashing context. + &untracked_resolutions.source_span, + ); let common_lifetimes = CommonLifetimes::new(&interners); let common_consts = CommonConsts::new(&interners, &common_types); @@ -1452,14 +1466,31 @@ impl<'tcx> TyCtxt<'tcx> { &self.definitions } + /// Note that this is *untracked* and should only be used within the query + /// system if the result is otherwise tracked through queries + #[inline] + pub fn source_span_untracked(self, def_id: LocalDefId) -> Span { + self.untracked_resolutions.source_span.get(def_id).copied().unwrap_or(DUMMY_SP) + } + #[inline(always)] pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { - StableHashingContext::new(self.sess, &self.definitions, &*self.cstore) + StableHashingContext::new( + self.sess, + &self.definitions, + &*self.cstore, + &self.untracked_resolutions.source_span, + ) } #[inline(always)] pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { - StableHashingContext::ignore_spans(self.sess, &self.definitions, &*self.cstore) + StableHashingContext::ignore_spans( + self.sess, + &self.definitions, + &*self.cstore, + &self.untracked_resolutions.source_span, + ) } pub fn serialize_query_result_cache(self, encoder: FileEncoder) -> FileEncodeResult { @@ -2250,7 +2281,14 @@ impl<'tcx> TyCtxt<'tcx> { #[allow(rustc::usage_of_ty_tykind)] #[inline] pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { - self.interners.intern_ty(st, self.sess, &self.definitions, &*self.cstore) + self.interners.intern_ty( + st, + self.sess, + &self.definitions, + &*self.cstore, + // This is only used to create a stable hashing context. + &self.untracked_resolutions.source_span, + ) } #[inline] diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e0cb0cb9709ff..26b45c5c644d0 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -43,7 +43,7 @@ use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::{ExpnId, Span}; use rustc_target::abi::{Align, VariantIdx}; pub use subst::*; pub use vtable::*; @@ -138,6 +138,10 @@ pub struct ResolverOutputs { pub visibilities: FxHashMap, /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error. pub has_pub_restricted: bool, + /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. + pub expn_that_defined: FxHashMap, + /// Reference span for definitions. + pub source_span: IndexVec, pub access_levels: AccessLevels, pub extern_crate_map: FxHashMap, pub maybe_unused_trait_imports: FxIndexSet, diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index c2c876f7f1a12..166fd1d272d75 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -689,8 +689,7 @@ impl<'a, 'tcx> Decodable> for Span { let dlo = u32::decode(decoder); let dto = u32::decode(decoder); - let enclosing = - decoder.tcx.definitions_untracked().def_span(parent.unwrap()).data_untracked(); + let enclosing = decoder.tcx.source_span_untracked(parent.unwrap()).data_untracked(); let span = Span::new( enclosing.lo + BytePos::from_u32(dlo), enclosing.lo + BytePos::from_u32(dto), @@ -887,7 +886,7 @@ where } if let Some(parent) = span_data.parent { - let enclosing = s.tcx.definitions_untracked().def_span(parent).data_untracked(); + let enclosing = s.tcx.source_span(parent).data_untracked(); if enclosing.contains(span_data) { TAG_RELATIVE_SPAN.encode(s); (span_data.lo - enclosing.lo).to_u32().encode(s); diff --git a/compiler/rustc_query_system/src/ich/hcx.rs b/compiler/rustc_query_system/src/ich/hcx.rs index 03ef8578eb701..d120742ffe36b 100644 --- a/compiler/rustc_query_system/src/ich/hcx.rs +++ b/compiler/rustc_query_system/src/ich/hcx.rs @@ -7,6 +7,7 @@ use rustc_data_structures::sync::Lrc; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::definitions::{DefPathHash, Definitions}; +use rustc_index::vec::IndexVec; use rustc_session::cstore::CrateStore; use rustc_session::Session; use rustc_span::source_map::SourceMap; @@ -26,6 +27,7 @@ fn compute_ignored_attr_names() -> FxHashSet { pub struct StableHashingContext<'a> { definitions: &'a Definitions, cstore: &'a dyn CrateStore, + source_span: &'a IndexVec, // The value of `-Z incremental-ignore-spans`. // This field should only be used by `debug_opts_incremental_ignore_span` incremental_ignore_spans: bool, @@ -56,6 +58,7 @@ impl<'a> StableHashingContext<'a> { sess: &'a Session, definitions: &'a Definitions, cstore: &'a dyn CrateStore, + source_span: &'a IndexVec, always_ignore_spans: bool, ) -> Self { let hash_spans_initial = @@ -65,6 +68,7 @@ impl<'a> StableHashingContext<'a> { body_resolver: BodyResolver::Forbidden, definitions, cstore, + source_span, incremental_ignore_spans: sess.opts.debugging_opts.incremental_ignore_spans, caching_source_map: None, raw_source_map: sess.source_map(), @@ -77,11 +81,13 @@ impl<'a> StableHashingContext<'a> { sess: &'a Session, definitions: &'a Definitions, cstore: &'a dyn CrateStore, + source_span: &'a IndexVec, ) -> Self { Self::new_with_or_without_spans( sess, definitions, cstore, + source_span, /*always_ignore_spans=*/ false, ) } @@ -91,9 +97,10 @@ impl<'a> StableHashingContext<'a> { sess: &'a Session, definitions: &'a Definitions, cstore: &'a dyn CrateStore, + source_span: &'a IndexVec, ) -> Self { let always_ignore_spans = true; - Self::new_with_or_without_spans(sess, definitions, cstore, always_ignore_spans) + Self::new_with_or_without_spans(sess, definitions, cstore, source_span, always_ignore_spans) } /// Allow hashing @@ -198,7 +205,7 @@ impl<'a> rustc_span::HashStableContext for StableHashingContext<'a> { #[inline] fn def_span(&self, def_id: LocalDefId) -> Span { - self.definitions.def_span(def_id) + self.source_span[def_id] } #[inline] diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 3b70b90c87182..e7c8886f0544a 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -10,8 +10,9 @@ use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed use rustc_feature::BUILTIN_ATTRIBUTES; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS}; -use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::PrimTy; +use rustc_index::vec::IndexVec; use rustc_middle::bug; use rustc_middle::ty::DefIdTree; use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE; @@ -130,8 +131,8 @@ impl<'a> Resolver<'a> { }; if !candidates.is_empty() { show_candidates( - &self.definitions, - self.session, + &self.session, + &self.source_span, &mut err, span, &candidates, @@ -693,8 +694,8 @@ impl<'a> Resolver<'a> { err.span_help(span, &help_msg); } show_candidates( - &self.definitions, - self.session, + &self.session, + &self.source_span, &mut err, Some(span), &import_suggestions, @@ -1474,8 +1475,8 @@ impl<'a> Resolver<'a> { let import_suggestions = self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected); show_candidates( - &self.definitions, - self.session, + &self.session, + &self.source_span, err, None, &import_suggestions, @@ -2444,8 +2445,8 @@ enum IsPattern { /// entities with that name in all crates. This method allows outputting the /// results of this search in a programmer-friendly way fn show_candidates( - definitions: &rustc_hir::definitions::Definitions, session: &Session, + source_span: &IndexVec, err: &mut Diagnostic, // This is `None` if all placement locations are inside expansions use_placement_span: Option, @@ -2555,7 +2556,7 @@ fn show_candidates( ); if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) { - let span = definitions.def_span(local_def_id); + let span = source_span[local_def_id]; let span = session.source_map().guess_head_span(span); let mut multi_span = MultiSpan::from_span(span); multi_span.push_span_label(span, "not accessible".to_string()); @@ -2584,7 +2585,7 @@ fn show_candidates( let mut spans = Vec::new(); for (name, _, def_id, _) in &inaccessible_path_strings { if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) { - let span = definitions.def_span(local_def_id); + let span = source_span[local_def_id]; let span = session.source_map().guess_head_span(span); spans.push((name, span)); } else { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index eb58f17fc7e03..b04a5ef8161a9 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -872,6 +872,10 @@ pub struct Resolver<'a> { session: &'a Session, definitions: Definitions, + /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. + expn_that_defined: FxHashMap, + /// Reference span for definitions. + source_span: IndexVec, graph_root: Module<'a>, @@ -1146,7 +1150,17 @@ impl Resolver<'_> { self.definitions.def_key(self.node_id_to_def_id[&node_id]), ); - let def_id = self.definitions.create_def(parent, data, expn_id, span); + let def_id = self.definitions.create_def(parent, data); + + // Create the definition. + if expn_id != ExpnId::root() { + self.expn_that_defined.insert(def_id, expn_id); + } + + // A relative span's parent must be an absolute span. + debug_assert_eq!(span.data_untracked().parent, None); + let _id = self.source_span.push(span); + debug_assert_eq!(_id, def_id); // Some things for which we allocate `LocalDefId`s don't correspond to // anything in the AST, so they don't have a `NodeId`. For these cases @@ -1196,7 +1210,7 @@ impl<'a> Resolver<'a> { &mut FxHashMap::default(), ); - let definitions = Definitions::new(session.local_stable_crate_id(), krate.spans.inner_span); + let definitions = Definitions::new(session.local_stable_crate_id()); let mut visibilities = FxHashMap::default(); visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); @@ -1209,6 +1223,10 @@ impl<'a> Resolver<'a> { let mut invocation_parents = FxHashMap::default(); invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential)); + let mut source_span = IndexVec::default(); + let _id = source_span.push(krate.spans.inner_span); + debug_assert_eq!(_id, CRATE_DEF_ID); + let mut extern_prelude: FxHashMap> = session .opts .externs @@ -1233,6 +1251,8 @@ impl<'a> Resolver<'a> { session, definitions, + expn_that_defined: Default::default(), + source_span, // The outermost module has def ID 0; this is not reflected in the // AST. @@ -1376,6 +1396,8 @@ impl<'a> Resolver<'a> { let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); let definitions = self.definitions; let cstore = Box::new(self.crate_loader.into_cstore()); + let source_span = self.source_span; + let expn_that_defined = self.expn_that_defined; let visibilities = self.visibilities; let has_pub_restricted = self.has_pub_restricted; let extern_crate_map = self.extern_crate_map; @@ -1387,6 +1409,8 @@ impl<'a> Resolver<'a> { let confused_type_with_std_module = self.confused_type_with_std_module; let access_levels = self.access_levels; let resolutions = ResolverOutputs { + source_span, + expn_that_defined, visibilities, has_pub_restricted, access_levels, @@ -1426,6 +1450,8 @@ impl<'a> Resolver<'a> { let definitions = self.definitions.clone(); let cstore = Box::new(self.cstore().clone()); let resolutions = ResolverOutputs { + source_span: self.source_span.clone(), + 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(), @@ -1461,7 +1487,12 @@ impl<'a> Resolver<'a> { } fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { - StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) + StableHashingContext::new( + self.session, + &self.definitions, + self.crate_loader.cstore(), + &self.source_span, + ) } pub fn cstore(&self) -> &CStore { @@ -1892,7 +1923,7 @@ impl<'a> Resolver<'a> { /// Retrieves the span of the given `DefId` if `DefId` is in the local crate. #[inline] pub fn opt_span(&self, def_id: DefId) -> Option { - def_id.as_local().map(|def_id| self.definitions.def_span(def_id)) + def_id.as_local().map(|def_id| self.source_span[def_id]) } /// Checks if an expression refers to a function marked with From 52f22c7d01f68c6015fca73dc3623040d6a5dc9d Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 15 Jun 2022 19:19:53 +0200 Subject: [PATCH 5/7] Remove unused item_generics_num_lifetimes. --- compiler/rustc_middle/src/ty/mod.rs | 1 - compiler/rustc_resolve/src/lib.rs | 2 -- 2 files changed, 3 deletions(-) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 26b45c5c644d0..1855f1883d410 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -160,7 +160,6 @@ pub struct ResolverOutputs { /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`. pub confused_type_with_std_module: FxHashMap, pub registered_tools: RegisteredTools, - pub item_generics_num_lifetimes: FxHashMap, pub legacy_const_generic_args: FxHashMap>>, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index b04a5ef8161a9..23f4446ab428a 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1429,7 +1429,6 @@ impl<'a> Resolver<'a> { proc_macros, confused_type_with_std_module, registered_tools: self.registered_tools, - item_generics_num_lifetimes: self.item_generics_num_lifetimes, legacy_const_generic_args: self.legacy_const_generic_args, partial_res_map: self.partial_res_map, import_res_map: self.import_res_map, @@ -1470,7 +1469,6 @@ impl<'a> Resolver<'a> { confused_type_with_std_module: self.confused_type_with_std_module.clone(), registered_tools: self.registered_tools.clone(), access_levels: self.access_levels.clone(), - item_generics_num_lifetimes: self.item_generics_num_lifetimes.clone(), 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(), From 8ffbd814afd5bcb0534eef7d69af8df3a641d3ec Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 15 Jun 2022 19:41:41 +0200 Subject: [PATCH 6/7] Update next_node_id. --- compiler/rustc_ast_lowering/src/lib.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index d56b2fd5d0b50..ec1a48a91c53c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -496,13 +496,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn next_node_id(&mut self) -> NodeId { - let next = self - .next_node_id - .as_usize() - .checked_add(1) - .expect("input too large; ran out of NodeIds"); - self.next_node_id = NodeId::from_usize(next); - self.next_node_id + 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 } fn opt_local_def_id(&self, node: NodeId) -> Option { From ae5959f4bab2d48e909cc5af6b906526ab83cc3d Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 15 Jun 2022 19:42:43 +0200 Subject: [PATCH 7/7] Consume resolutions for lowering separately. --- compiler/rustc_ast_lowering/src/item.rs | 9 +++---- compiler/rustc_ast_lowering/src/lib.rs | 33 +++++++++++-------------- compiler/rustc_interface/src/passes.rs | 32 ++++++++++++++++++------ compiler/rustc_middle/src/ty/mod.rs | 5 ++++ compiler/rustc_resolve/src/lib.rs | 16 +++++++++--- 5 files changed, 59 insertions(+), 36 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 81a55ce8a4334..717918116e595 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -15,7 +15,7 @@ use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::definitions::Definitions; use rustc_hir::PredicateOrigin; use rustc_index::vec::{Idx, IndexVec}; -use rustc_middle::ty::ResolverOutputs; +use rustc_middle::ty::{ResolverAstLowering, ResolverOutputs}; use rustc_session::cstore::CrateStoreDyn; use rustc_session::Session; use rustc_span::source_map::DesugaringKind; @@ -30,7 +30,8 @@ pub(super) struct ItemLowerer<'a, 'hir> { pub(super) sess: &'a Session, pub(super) definitions: &'a mut Definitions, pub(super) cstore: &'a CrateStoreDyn, - pub(super) resolver: &'a mut ResolverOutputs, + pub(super) resolutions: &'a ResolverOutputs, + pub(super) resolver: &'a mut ResolverAstLowering, pub(super) arena: &'hir Arena<'hir>, pub(super) ast_index: &'a IndexVec>, pub(super) owners: &'a mut IndexVec>>, @@ -62,12 +63,12 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { owner: NodeId, f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>, ) { - let next_node_id = self.resolver.next_node_id; let mut lctx = LoweringContext { // Pseudo-globals. sess: &self.sess, definitions: self.definitions, cstore: self.cstore, + resolutions: self.resolutions, resolver: self.resolver, arena: self.arena, @@ -80,8 +81,6 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { node_id_to_local_id: Default::default(), local_id_to_def_id: SortedMap::new(), trait_map: Default::default(), - local_node_id_to_def_id: FxHashMap::default(), - next_node_id, // Lowering state. catch_scope: None, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index ec1a48a91c53c..d3eb3f29b1c3b 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -56,7 +56,7 @@ use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::definitions::{DefPathData, Definitions}; use rustc_hir::{ConstArg, GenericArg, ItemLocalId, ParamName, TraitCandidate}; use rustc_index::vec::{Idx, IndexVec}; -use rustc_middle::ty::ResolverOutputs; +use rustc_middle::ty::{ResolverAstLowering, ResolverOutputs}; use rustc_query_system::ich::StableHashingContext; use rustc_session::cstore::CrateStoreDyn; use rustc_session::parse::feature_err; @@ -91,7 +91,8 @@ struct LoweringContext<'a, 'hir: 'a> { definitions: &'a mut Definitions, cstore: &'a CrateStoreDyn, - resolver: &'a mut ResolverOutputs, + resolutions: &'a ResolverOutputs, + resolver: &'a mut ResolverAstLowering, /// Used to allocate HIR nodes. arena: &'hir Arena<'hir>, @@ -133,10 +134,6 @@ struct LoweringContext<'a, 'hir: 'a> { /// NodeIds that are lowered inside the current HIR owner. node_id_to_local_id: FxHashMap, - // The next_node_id is reset for each item. - next_node_id: ast::NodeId, - local_node_id_to_def_id: FxHashMap, - allow_try_trait: Option>, allow_gen_future: Option>, allow_into_future: Option>, @@ -174,7 +171,7 @@ trait ResolverAstLoweringExt { fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind; } -impl ResolverAstLoweringExt for ResolverOutputs { +impl ResolverAstLoweringExt for ResolverAstLowering { fn legacy_const_generic_args(&self, expr: &Expr) -> Option> { if let ExprKind::Path(None, path) = &expr.kind { // Don't perform legacy const generics rewriting if the path already @@ -415,7 +412,8 @@ pub fn lower_crate<'hir>( krate: &Crate, definitions: &mut Definitions, cstore: &CrateStoreDyn, - resolver: &mut ResolverOutputs, + resolutions: &ResolverOutputs, + mut resolver: ResolverAstLowering, arena: &'hir Arena<'hir>, ) -> &'hir hir::Crate<'hir> { let _prof_timer = sess.prof.verbose_generic_activity("hir_lowering"); @@ -430,7 +428,8 @@ pub fn lower_crate<'hir>( sess, definitions, cstore, - resolver, + resolutions, + resolver: &mut resolver, arena, ast_index: &ast_index, owners: &mut owners, @@ -438,7 +437,7 @@ pub fn lower_crate<'hir>( .lower_node(def_id); } - let hir_hash = compute_hir_hash(sess, definitions, cstore, resolver, &owners); + let hir_hash = compute_hir_hash(sess, definitions, cstore, resolutions, &owners); let krate = hir::Crate { owners, hir_hash }; arena.alloc(krate) } @@ -464,7 +463,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.sess, self.definitions, self.cstore, - &self.resolver.source_span, + &self.resolutions.source_span, ) } @@ -489,25 +488,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // we don't need a mapping from `NodeId` to `LocalDefId`. if node_id != ast::DUMMY_NODE_ID { debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); - self.local_node_id_to_def_id.insert(node_id, def_id); + self.resolver.node_id_to_def_id.insert(node_id, def_id); } def_id } fn next_node_id(&mut self) -> NodeId { - let start = self.next_node_id; + let start = self.resolver.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); + self.resolver.next_node_id = ast::NodeId::from_u32(next); start } fn opt_local_def_id(&self, node: NodeId) -> Option { - if node <= self.resolver.next_node_id { - self.resolver.node_id_to_def_id.get(&node).copied() - } else { - self.local_node_id_to_def_id.get(&node).copied() - } + self.resolver.node_id_to_def_id.get(&node).copied() } fn local_def_id(&self, node: NodeId) -> LocalDefId { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index adeb384787ef8..19f086b3a4426 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -21,7 +21,7 @@ use rustc_metadata::{encode_metadata, EncodedMetadata}; use rustc_middle::arena::Arena; use rustc_middle::dep_graph::DepGraph; use rustc_middle::ty::query::{ExternProviders, Providers}; -use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, ResolverOutputs, TyCtxt}; +use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, TyCtxt}; use rustc_mir_build as mir_build; use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr}; use rustc_passes::{self, hir_stats, layout_test}; @@ -139,7 +139,8 @@ mod boxed_resolver { pub fn to_resolver_outputs( resolver: Rc>, - ) -> (Definitions, Box, ResolverOutputs) { + ) -> (Definitions, Box, ty::ResolverOutputs, ty::ResolverAstLowering) + { match Rc::try_unwrap(resolver) { Ok(resolver) => { let mut resolver = resolver.into_inner(); @@ -485,13 +486,21 @@ fn lower_to_hir<'tcx>( sess: &Session, definitions: &mut Definitions, cstore: &CrateStoreDyn, - resolver: &mut ResolverOutputs, + resolutions: &ty::ResolverOutputs, + resolver: ty::ResolverAstLowering, krate: Rc, arena: &'tcx rustc_ast_lowering::Arena<'tcx>, ) -> &'tcx Crate<'tcx> { // Lower AST to HIR. - let hir_crate = - rustc_ast_lowering::lower_crate(sess, &krate, definitions, cstore, resolver, arena); + let hir_crate = rustc_ast_lowering::lower_crate( + sess, + &krate, + definitions, + cstore, + resolutions, + resolver, + arena, + ); // Drop AST to free memory sess.time("drop_ast", || std::mem::drop(krate)); @@ -829,14 +838,21 @@ pub fn create_global_ctxt<'tcx>( // incr. comp. yet. dep_graph.assert_ignored(); - let (mut definitions, cstore, mut resolver_outputs) = + let (mut definitions, cstore, resolver_outputs, resolver_for_lowering) = BoxedResolver::to_resolver_outputs(resolver); let sess = &compiler.session(); // Lower AST to HIR. - let krate = - lower_to_hir(sess, &mut definitions, &*cstore, &mut resolver_outputs, krate, hir_arena); + let krate = lower_to_hir( + sess, + &mut definitions, + &*cstore, + &resolver_outputs, + resolver_for_lowering, + krate, + hir_arena, + ); let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess); diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 1855f1883d410..749feb850b098 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -160,7 +160,12 @@ pub struct ResolverOutputs { /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`. pub confused_type_with_std_module: FxHashMap, pub registered_tools: RegisteredTools, +} +/// Resolutions that should only be used for lowering. +/// This struct is meant to be consumed by lowering. +#[derive(Debug)] +pub struct ResolverAstLowering { pub legacy_const_generic_args: FxHashMap>>, /// Resolutions for nodes that have a single resolution. diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 23f4446ab428a..ddf2a53b47d27 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1392,7 +1392,9 @@ impl<'a> Resolver<'a> { Default::default() } - pub fn into_outputs(self) -> (Definitions, Box, ResolverOutputs) { + pub fn into_outputs( + self, + ) -> (Definitions, Box, ResolverOutputs, ty::ResolverAstLowering) { let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); let definitions = self.definitions; let cstore = Box::new(self.crate_loader.into_cstore()); @@ -1429,6 +1431,8 @@ impl<'a> Resolver<'a> { proc_macros, confused_type_with_std_module, registered_tools: self.registered_tools, + }; + let resolutions_lowering = ty::ResolverAstLowering { legacy_const_generic_args: self.legacy_const_generic_args, partial_res_map: self.partial_res_map, import_res_map: self.import_res_map, @@ -1441,10 +1445,12 @@ impl<'a> Resolver<'a> { trait_map: self.trait_map, builtin_macro_kinds: self.builtin_macro_kinds, }; - (definitions, cstore, resolutions) + (definitions, cstore, resolutions, resolutions_lowering) } - pub fn clone_outputs(&self) -> (Definitions, Box, ResolverOutputs) { + pub fn clone_outputs( + &self, + ) -> (Definitions, Box, ResolverOutputs, ty::ResolverAstLowering) { let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); let definitions = self.definitions.clone(); let cstore = Box::new(self.cstore().clone()); @@ -1469,6 +1475,8 @@ impl<'a> Resolver<'a> { confused_type_with_std_module: self.confused_type_with_std_module.clone(), registered_tools: self.registered_tools.clone(), access_levels: self.access_levels.clone(), + }; + let resolutions_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(), @@ -1481,7 +1489,7 @@ impl<'a> Resolver<'a> { trait_map: self.trait_map.clone(), builtin_macro_kinds: self.builtin_macro_kinds.clone(), }; - (definitions, cstore, resolutions) + (definitions, cstore, resolutions, resolutions_lowering) } fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {