Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

resolve: Feed the def_kind query immediately on DefId creation #118188

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions compiler/rustc_ast_lowering/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
parent_def_id.def_id,
node_id,
DefPathData::AnonConst,
DefKind::AnonConst,
*op_sp,
);
let anon_const = AnonConst { id: node_id, value: P(expr) };
Expand Down
10 changes: 8 additions & 2 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_ast::ptr::P as AstP;
use rustc_ast::*;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::definitions::DefPathData;
use rustc_session::errors::report_lit_error;
use rustc_span::source_map::{respan, Spanned};
Expand Down Expand Up @@ -395,7 +395,13 @@ 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.def_id, node_id, DefPathData::AnonConst, f.span);
self.create_def(
parent_def_id.def_id,
node_id,
DefPathData::AnonConst,
DefKind::AnonConst,
f.span,
);

let anon_const = AnonConst { id: node_id, value: arg };
generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
Expand Down
14 changes: 11 additions & 3 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
ItemKind::MacroDef(MacroDef { body, macro_rules }) => {
let body = P(self.lower_delim_args(body));
let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
let DefKind::Macro(macro_kind) = self.tcx.def_kind(self.local_def_id(id)) else {
unreachable!()
};
let macro_def = self.arena.alloc(ast::MacroDef { body, macro_rules: *macro_rules });
hir::ItemKind::Macro(macro_def, macro_kind)
}
Expand Down Expand Up @@ -1399,6 +1401,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.local_def_id(parent_node_id),
param_node_id,
DefPathData::TypeNs(sym::host),
DefKind::ConstParam,
span,
);
self.host_param_id = Some(def_id);
Expand Down Expand Up @@ -1457,8 +1460,13 @@ impl<'hir> LoweringContext<'_, 'hir> {

if let Some((span, hir_id, def_id)) = host_param_parts {
let const_node_id = self.next_node_id();
let anon_const: LocalDefId =
self.create_def(def_id, const_node_id, DefPathData::AnonConst, span);
let anon_const = self.create_def(
def_id,
const_node_id,
DefPathData::AnonConst,
DefKind::AnonConst,
span,
);

let const_id = self.next_id();
let const_expr_id = self.next_id();
Expand Down
23 changes: 14 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ use rustc_middle::{
ty::{ResolverAstLowering, TyCtxt},
};
use rustc_session::parse::{add_feature_diagnostics, feature_err};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{DesugaringKind, Span, DUMMY_SP};
use smallvec::SmallVec;
Expand Down Expand Up @@ -153,7 +152,6 @@ trait ResolverAstLoweringExt {
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes>;
fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;
fn remap_extra_lifetime_params(&mut self, from: NodeId, to: NodeId);
fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind;
}

impl ResolverAstLoweringExt for ResolverAstLowering {
Expand Down Expand Up @@ -217,10 +215,6 @@ impl ResolverAstLoweringExt for ResolverAstLowering {
let lifetimes = self.extra_lifetime_params_map.remove(&from).unwrap_or_default();
self.extra_lifetime_params_map.insert(to, lifetimes);
}

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,
Expand Down Expand Up @@ -467,6 +461,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
parent: LocalDefId,
node_id: ast::NodeId,
data: DefPathData,
def_kind: DefKind,
span: Span,
) -> LocalDefId {
debug_assert_ne!(node_id, ast::DUMMY_NODE_ID);
Expand All @@ -478,7 +473,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.tcx.hir().def_key(self.local_def_id(node_id)),
);

let def_id = self.tcx.at(span).create_def(parent, data).def_id();
let def_id = self.tcx.at(span).create_def(parent, data, def_kind).def_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);
Expand Down Expand Up @@ -780,6 +775,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.current_hir_id_owner.def_id,
param,
DefPathData::LifetimeNs(kw::UnderscoreLifetime),
DefKind::LifetimeParam,
ident.span,
);
debug!(?_def_id);
Expand Down Expand Up @@ -1192,6 +1188,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
parent_def_id.def_id,
node_id,
DefPathData::AnonConst,
DefKind::AnonConst,
span,
);

Expand Down Expand Up @@ -1429,6 +1426,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.current_hir_id_owner.def_id,
*def_node_id,
DefPathData::TypeNs(ident.name),
DefKind::TyParam,
span,
);
let (param, bounds, path) = self.lower_universal_param_and_bounds(
Expand Down Expand Up @@ -1582,6 +1580,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.current_hir_id_owner.def_id,
opaque_ty_node_id,
DefPathData::ImplTrait,
DefKind::OpaqueTy,
opaque_ty_span,
);
debug!(?opaque_ty_def_id);
Expand Down Expand Up @@ -1636,6 +1635,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
opaque_ty_def_id,
duplicated_lifetime_node_id,
DefPathData::LifetimeNs(lifetime.ident.name),
DefKind::LifetimeParam,
lifetime.ident.span,
);
captured_to_synthesized_mapping.insert(old_def_id, duplicated_lifetime_def_id);
Expand Down Expand Up @@ -2505,8 +2505,13 @@ impl<'hir> GenericArgsCtor<'hir> {
});
lcx.attrs.insert(hir_id.local_id, std::slice::from_ref(attr));

let def_id =
lcx.create_def(lcx.current_hir_id_owner.def_id, id, DefPathData::AnonConst, span);
let def_id = lcx.create_def(
lcx.current_hir_id_owner.def_id,
id,
DefPathData::AnonConst,
DefKind::AnonConst,
span,
);
lcx.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
self.args.push(hir::GenericArg::Const(hir::ConstArg {
value: hir::AnonConst { def_id, hir_id, body },
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_interface/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use rustc_codegen_ssa::CodegenResults;
use rustc_data_structures::steal::Steal;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, OnceLock, WorkerLocal};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{StableCrateId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::Definitions;
use rustc_incremental::setup_dep_graph;
Expand Down Expand Up @@ -171,6 +172,9 @@ impl<'tcx> Queries<'tcx> {
)));
feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
feed.output_filenames(Arc::new(outputs));

let feed = tcx.feed_local_def_id(CRATE_DEF_ID);
feed.def_kind(DefKind::Mod);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a question regarding incremental builds: when referring to queries such as the results of tcx.def_kind(LocalDefId) or tcx.def_kind(DefId), does this mean the results are retrieved directly here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here the result is put directly into the query cache.
So when tcx.def_kind(def_id) is called it will look into the query cache first, and will always find the result there, and will never call the query implementation (which now would panic because providers.def_kind is not set).

});
Ok(qcx)
})
Expand Down
94 changes: 1 addition & 93 deletions compiler/rustc_middle/src/hir/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{par_for_each_in, try_par_for_each_in, DynSend, DynSync};
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::*;
use rustc_index::Idx;
Expand Down Expand Up @@ -168,98 +168,6 @@ impl<'hir> Map<'hir> {
self.tcx.definitions_untracked().def_path_hash(def_id)
}

/// Do not call this function directly. The query should be called.
pub(super) fn def_kind(self, local_def_id: LocalDefId) -> DefKind {
let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
let node = match self.find(hir_id) {
Some(node) => node,
None => match self.def_key(local_def_id).disambiguated_data.data {
// FIXME: Some anonymous constants produced by `#[rustc_legacy_const_generics]`
// do not have corresponding HIR nodes, but they are still anonymous constants.
DefPathData::AnonConst => return DefKind::AnonConst,
_ => bug!("no HIR node for def id {local_def_id:?}"),
},
};
match node {
Node::Item(item) => match item.kind {
ItemKind::Static(_, mt, _) => DefKind::Static(mt),
ItemKind::Const(..) => DefKind::Const,
ItemKind::Fn(..) => DefKind::Fn,
ItemKind::Macro(_, macro_kind) => DefKind::Macro(macro_kind),
ItemKind::Mod(..) => DefKind::Mod,
ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
ItemKind::TyAlias(..) => DefKind::TyAlias,
ItemKind::Enum(..) => DefKind::Enum,
ItemKind::Struct(..) => DefKind::Struct,
ItemKind::Union(..) => DefKind::Union,
ItemKind::Trait(..) => DefKind::Trait,
ItemKind::TraitAlias(..) => DefKind::TraitAlias,
ItemKind::ExternCrate(_) => DefKind::ExternCrate,
ItemKind::Use(..) => DefKind::Use,
ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
ItemKind::Impl(impl_) => DefKind::Impl { of_trait: impl_.of_trait.is_some() },
},
Node::ForeignItem(item) => match item.kind {
ForeignItemKind::Fn(..) => DefKind::Fn,
ForeignItemKind::Static(_, mt) => DefKind::Static(mt),
ForeignItemKind::Type => DefKind::ForeignTy,
},
Node::TraitItem(item) => match item.kind {
TraitItemKind::Const(..) => DefKind::AssocConst,
TraitItemKind::Fn(..) => DefKind::AssocFn,
TraitItemKind::Type(..) => DefKind::AssocTy,
},
Node::ImplItem(item) => match item.kind {
ImplItemKind::Const(..) => DefKind::AssocConst,
ImplItemKind::Fn(..) => DefKind::AssocFn,
ImplItemKind::Type(..) => DefKind::AssocTy,
},
Node::Variant(_) => DefKind::Variant,
Node::Ctor(variant_data) => {
let ctor_of = match self.find_parent(hir_id) {
Some(Node::Item(..)) => def::CtorOf::Struct,
Some(Node::Variant(..)) => def::CtorOf::Variant,
_ => unreachable!(),
};
match variant_data.ctor_kind() {
Some(kind) => DefKind::Ctor(ctor_of, kind),
None => bug!("constructor node without a constructor"),
}
}
Node::AnonConst(_) => DefKind::AnonConst,
Node::ConstBlock(_) => DefKind::InlineConst,
Node::Field(_) => DefKind::Field,
Node::Expr(expr) => match expr.kind {
ExprKind::Closure(_) => DefKind::Closure,
_ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
},
Node::GenericParam(param) => match param.kind {
GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
GenericParamKind::Type { .. } => DefKind::TyParam,
GenericParamKind::Const { .. } => DefKind::ConstParam,
},
Node::Crate(_) => DefKind::Mod,
Node::Stmt(_)
| Node::PathSegment(_)
| Node::Ty(_)
| Node::TypeBinding(_)
| Node::Infer(_)
| Node::TraitRef(_)
| Node::Pat(_)
| Node::PatField(_)
| Node::ExprField(_)
| Node::Local(_)
| Node::Param(_)
| Node::Arm(_)
| Node::Lifetime(_)
| Node::Block(_) => span_bug!(
self.span(hir_id),
"unexpected node with def id {local_def_id:?}: {node:?}"
),
}
}

/// Finds the id of the parent node to this one.
///
/// If calling repeatedly and iterating over parents, prefer [`Map::parent_iter`].
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/hir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ pub fn provide(providers: &mut Providers) {
span_bug!(hir.span(hir_id), "fn_arg_names: unexpected item {:?}", def_id);
}
};
providers.def_kind = |tcx, def_id| tcx.hir().def_kind(def_id);
providers.all_local_trait_impls = |tcx, ()| &tcx.resolutions(()).trait_impls;
providers.expn_that_defined =
|tcx, id| tcx.resolutions(()).expn_that_defined.get(&id).copied().unwrap_or(ExpnId::root());
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,9 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn feed_local_crate(self) -> TyCtxtFeed<'tcx, CrateNum> {
TyCtxtFeed { tcx: self, key: LOCAL_CRATE }
}
pub fn feed_local_def_id(self, key: LocalDefId) -> TyCtxtFeed<'tcx, LocalDefId> {
TyCtxtFeed { tcx: self, key }
}

/// In order to break cycles involving `AnonConst`, we need to set the expected type by side
/// effect. However, we do not want this as a general capability, so this interface restricts
Expand Down Expand Up @@ -973,6 +976,7 @@ impl<'tcx> TyCtxtAt<'tcx> {
self,
parent: LocalDefId,
data: hir::definitions::DefPathData,
def_kind: DefKind,
) -> TyCtxtFeed<'tcx, LocalDefId> {
// This function modifies `self.definitions` using a side-effect.
// We need to ensure that these side effects are re-run by the incr. comp. engine.
Expand All @@ -997,6 +1001,7 @@ impl<'tcx> TyCtxtAt<'tcx> {
let key = self.untracked.definitions.write().create_def(parent, data);

let feed = TyCtxtFeed { tcx: self.tcx, key };
feed.def_kind(def_kind);
feed.def_span(self.span);
feed
}
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,6 @@ pub struct ResolverAstLowering {
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>,
/// List functions and methods for which lifetime elision was successful.
pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,

Expand Down
Loading
Loading