Make ResolverAstLowering a struct.

This commit is contained in:
Camille GILLOT 2021-07-05 22:26:23 +02:00
parent 47799de35a
commit 603746a35e
23 changed files with 352 additions and 261 deletions

View File

@ -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",

View File

@ -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" }

View File

@ -1,4 +1,4 @@
use crate::{ImplTraitContext, ImplTraitPosition, ParamMode};
use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt};
use super::LoweringContext;
@ -243,7 +243,7 @@ pub(crate) fn lower_inline_asm(
// 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,

View File

@ -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 @@ fn lower_legacy_const_generics(
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,

View File

@ -6,6 +6,7 @@
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 @@ fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'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),

View File

@ -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_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 @@
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<LocalDefId, AstOwner<'a>>,
pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
@ -59,6 +65,8 @@ fn with_lctx(
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 @@ fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
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 }
};

View File

@ -51,12 +51,14 @@
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<Lrc<[Symbol]>>,
}
/// 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<NodeId>,
}
pub trait ResolverAstLowering {
fn def_key(&self, id: DefId) -> DefKey;
trait ResolverAstLoweringExt {
fn legacy_const_generic_args(&self, expr: &Expr) -> Option<Vec<usize>>;
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes>;
fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>>;
fn get_label_res(&self, id: NodeId) -> Option<NodeId>;
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
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<LocalDefId>;
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<Vec<usize>> {
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<Vec<usize>>;
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<PartialRes>;
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
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<Option<Res<NodeId>>>;
fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
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<NodeId>;
fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
self.label_res_map.get(&id).copied()
}
/// Obtains resolution for a lifetime with the given `NodeId`.
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
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 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<'_>;
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 definitions(&self) -> &Definitions;
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
self.node_id_to_def_id.get(&node).copied()
}
fn next_node_id(&mut self) -> NodeId;
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 take_trait_map(&mut self, node: NodeId) -> Option<Vec<hir::TraitCandidate>>;
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId>;
fn local_def_id(&self, node: NodeId) -> LocalDefId;
fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
fn create_def(
&mut self,
parent: LocalDefId,
node_id: ast::NodeId,
data: DefPathData,
expn_id: ExpnId,
span: Span,
) -> LocalDefId;
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<LocalDefId, AstOwner<'a>> {
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<LocalDefId, AstOwner<'a>>,
}
@ -399,29 +405,33 @@ fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
/// 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<LocalDefId, hir::MaybeOwner<&hir::OwnerInfo<'_>>>,
) -> 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 @@ fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInf
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 @@ fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInf
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 @@ fn hash_owner(
node: hir::OwnerNode<'hir>,
bodies: &SortedMap<hir::ItemLocalId, &'hir hir::Body<'hir>>,
) -> (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 @@ fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
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 @@ fn mark_span_with_reason(
allow_internal_unstable,
reason,
self.sess.edition(),
self.resolver.create_stable_hashing_context(),
self.create_stable_hashing_context(),
)
}
@ -941,7 +992,7 @@ fn lower_assoc_ty_constraint(
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 @@ fn lower_generic_arg(
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 @@ fn lower_async_fn_ret_ty(
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 @@ fn new_named_lifetime_with_res(
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),
);
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;
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),
);
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;
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,

View File

@ -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::*;

View File

@ -1,5 +1,6 @@
use crate::ImplTraitPosition;
use super::ResolverAstLoweringExt;
use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs};
use super::{ImplTraitContext, LoweringContext, ParamMode};

View File

@ -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 @@ pub fn expected_in_unit_struct_pat(&self) -> bool {
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 },
}

View File

@ -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<ast::Crate>,
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);

View File

@ -27,6 +27,7 @@
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::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<Span, Span>,
pub registered_tools: RegisteredTools,
pub item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
/// Resolutions for nodes that have a single resolution.
pub partial_res_map: NodeMap<hir::def::PartialRes>,
/// Resolutions for import nodes, which have multiple resolutions in different namespaces.
pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
/// Resolutions for labels (node IDs of their corresponding blocks or loops).
pub label_res_map: NodeMap<ast::NodeId>,
/// Resolutions for lifetimes.
pub lifetimes_res_map: NodeMap<LifetimeRes>,
/// Lifetime parameters that lowering will have to introduce.
pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
pub next_node_id: ast::NodeId,
pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
/// 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<LocalDefId, MacroKind>,
}
#[derive(Clone, Copy, Debug)]

View File

@ -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" }

View File

@ -5,7 +5,6 @@
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;

View File

@ -16,7 +16,6 @@
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_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 @@ pub fn get_nearest_non_block_module(&mut self, mut def_id: DefId) -> Module<'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),
}
}
}

View File

@ -30,7 +30,6 @@
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};

View File

@ -2,7 +2,6 @@
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::*;

View File

@ -15,11 +15,10 @@
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};

View File

@ -11,7 +11,6 @@
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::{

View File

@ -27,17 +27,16 @@
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 @@ fn opt_parent(self, id: DefId) -> Option<DefId> {
}
}
/// 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<Vec<usize>> {
self.legacy_const_generic_args(expr)
}
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
self.partial_res_map.get(&id).cloned()
}
fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res>> {
self.import_res_map.get(&id).cloned().unwrap_or_default()
}
fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
self.label_res_map.get(&id).cloned()
}
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
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<Vec<TraitCandidate>> {
self.trait_map.remove(&node)
}
impl Resolver<'_> {
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
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 @@ fn create_def(
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 @@ pub fn into_outputs(self) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs)
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 @@ pub fn clone_outputs(&self) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs
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()
}

View File

@ -7,7 +7,6 @@
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;

View File

@ -36,7 +36,6 @@
// 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;

View File

@ -5,7 +5,6 @@
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};