Skip to content

Reduce uses of hir_crate. #142687

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

Merged
merged 3 commits into from
Jun 20, 2025
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
8 changes: 0 additions & 8 deletions compiler/rustc_const_eval/src/check_consts/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,12 +463,6 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
);
}

fn crate_inject_span(&self) -> Option<Span> {
self.tcx.hir_crate_items(()).definitions().next().and_then(|id| {
self.tcx.crate_level_attribute_injection_span(self.tcx.local_def_id_to_hir_id(id))
})
}

/// Check the const stability of the given item (fn or trait).
fn check_callee_stability(&mut self, def_id: DefId) {
match self.tcx.lookup_const_stability(def_id) {
Expand Down Expand Up @@ -543,7 +537,6 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
feature,
feature_enabled,
safe_to_expose_on_stable: callee_safe_to_expose_on_stable,
suggestion_span: self.crate_inject_span(),
is_function_call: self.tcx.def_kind(def_id) != DefKind::Trait,
});
}
Expand Down Expand Up @@ -919,7 +912,6 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
name: intrinsic.name,
feature,
const_stable_indirect: is_const_stable,
suggestion: self.crate_inject_span(),
});
}
Some(attrs::ConstStability {
Expand Down
22 changes: 3 additions & 19 deletions compiler/rustc_const_eval/src/check_consts/ops.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Concrete error types for all operations which may be invalid in a certain const context.

use hir::{ConstContext, LangItem};
use rustc_errors::Diag;
use rustc_errors::codes::*;
use rustc_errors::{Applicability, Diag};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_infer::infer::TyCtxtInferExt;
Expand Down Expand Up @@ -384,7 +384,6 @@ pub(crate) struct CallUnstable {
/// expose on stable.
pub feature_enabled: bool,
pub safe_to_expose_on_stable: bool,
pub suggestion_span: Option<Span>,
/// true if `def_id` is the function we are calling, false if `def_id` is an unstable trait.
pub is_function_call: bool,
}
Expand Down Expand Up @@ -412,20 +411,7 @@ impl<'tcx> NonConstOp<'tcx> for CallUnstable {
def_path: ccx.tcx.def_path_str(self.def_id),
})
};
// FIXME: make this translatable
let msg = format!("add `#![feature({})]` to the crate attributes to enable", self.feature);
#[allow(rustc::untranslatable_diagnostic)]
if let Some(span) = self.suggestion_span {
err.span_suggestion_verbose(
span,
msg,
format!("#![feature({})]\n", self.feature),
Applicability::MachineApplicable,
);
} else {
err.help(msg);
}

ccx.tcx.disabled_nightly_features(&mut err, [(String::new(), self.feature)]);
err
}
}
Expand All @@ -452,7 +438,6 @@ pub(crate) struct IntrinsicUnstable {
pub name: Symbol,
pub feature: Symbol,
pub const_stable_indirect: bool,
pub suggestion: Option<Span>,
}

impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable {
Expand All @@ -472,8 +457,7 @@ impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable {
span,
name: self.name,
feature: self.feature,
suggestion: self.suggestion,
help: self.suggestion.is_none(),
suggestion: ccx.tcx.crate_level_attribute_injection_span(),
})
}
}
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_const_eval/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,7 @@ pub(crate) struct UnstableIntrinsic {
code = "#![feature({feature})]\n",
applicability = "machine-applicable"
)]
pub suggestion: Option<Span>,
#[help(const_eval_unstable_intrinsic_suggestion)]
pub help: bool,
pub suggestion: Span,
}

#[derive(Diagnostic)]
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_driver_impl/src/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,11 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
}
HirTree => {
debug!("pretty printing HIR tree");
format!("{:#?}", ex.tcx().hir_crate(()))
ex.tcx()
.hir_crate_items(())
.owners()
.map(|owner| format!("{:#?} => {:#?}\n", owner, ex.tcx().hir_owner_nodes(owner)))
.collect()
}
Mir => {
let mut out = Vec::new();
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_hir_analysis/src/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,7 @@ fn default_body_is_unstable(
reason: reason_str,
});

let inject_span = item_did
.as_local()
.and_then(|id| tcx.crate_level_attribute_injection_span(tcx.local_def_id_to_hir_id(id)));
let inject_span = item_did.is_local().then(|| tcx.crate_level_attribute_injection_span());
rustc_session::parse::add_feature_diagnostics_for_issue(
&mut err,
&tcx.sess,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1064,7 +1064,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(),
Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
};
if let Some(features) = may_suggest_feature {
tcx.disabled_nightly_features(&mut diag, Some(param.hir_id), features);
tcx.disabled_nightly_features(&mut diag, features);
}

Err(diag.emit())
Expand Down
6 changes: 0 additions & 6 deletions compiler/rustc_hir_typeck/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ pub(crate) struct BaseExpressionDoubleDot {
)]
pub default_field_values_suggestion: Option<Span>,
#[subdiagnostic]
pub default_field_values_help: Option<BaseExpressionDoubleDotEnableDefaultFieldValues>,
#[subdiagnostic]
pub add_expr: Option<BaseExpressionDoubleDotAddExpr>,
#[subdiagnostic]
pub remove_dots: Option<BaseExpressionDoubleDotRemove>,
Expand Down Expand Up @@ -61,10 +59,6 @@ pub(crate) struct BaseExpressionDoubleDotAddExpr {
pub span: Span,
}

#[derive(Subdiagnostic)]
#[help(hir_typeck_base_expression_double_dot_enable_default_field_values)]
pub(crate) struct BaseExpressionDoubleDotEnableDefaultFieldValues;

#[derive(Diagnostic)]
#[diag(hir_typeck_field_multiply_specified_in_initializer, code = E0062)]
pub(crate) struct FieldMultiplySpecifiedInInitializer {
Expand Down
21 changes: 5 additions & 16 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectatio
use crate::coercion::{CoerceMany, DynamicCoerceMany};
use crate::errors::{
AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
BaseExpressionDoubleDotEnableDefaultFieldValues, BaseExpressionDoubleDotRemove,
CantDereference, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
HelpUseLatestEdition, NakedAsmOutsideNakedFn, NoFieldOnType, NoFieldOnVariant,
ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive,
BaseExpressionDoubleDotRemove, CantDereference, FieldMultiplySpecifiedInInitializer,
FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, NakedAsmOutsideNakedFn, NoFieldOnType,
NoFieldOnVariant, ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive,
TypeMismatchFruTypo, YieldExprOutsideOfCoroutine,
};
use crate::{
Expand Down Expand Up @@ -2133,26 +2132,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
if !self.tcx.features().default_field_values() {
let sugg = self.tcx.crate_level_attribute_injection_span(expr.hir_id);
let sugg = self.tcx.crate_level_attribute_injection_span();
self.dcx().emit_err(BaseExpressionDoubleDot {
span: span.shrink_to_hi(),
// We only mention enabling the feature if this is a nightly rustc *and* the
// expression would make sense with the feature enabled.
default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
&& missing_mandatory_fields.is_empty()
&& !missing_optional_fields.is_empty()
&& sugg.is_some()
{
sugg
} else {
None
},
default_field_values_help: if self.tcx.sess.is_nightly_build()
&& missing_mandatory_fields.is_empty()
&& !missing_optional_fields.is_empty()
&& sugg.is_none()
{
Some(BaseExpressionDoubleDotEnableDefaultFieldValues)
Some(sugg)
} else {
None
},
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_hir_typeck/src/method/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1727,7 +1727,6 @@ impl<'tcx> Pick<'tcx> {
}
tcx.disabled_nightly_features(
lint,
Some(scope_expr_id),
self.unstable_candidates.iter().map(|(candidate, feature)| {
(format!(" `{}`", tcx.def_path_str(candidate.item.def_id)), *feature)
}),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1010,8 +1010,8 @@ fn run_required_analyses(tcx: TyCtxt<'_>) {

// Prefetch this to prevent multiple threads from blocking on it later.
// This is needed since the `hir_id_validator::check_crate` call above is not guaranteed
// to use `hir_crate`.
tcx.ensure_done().hir_crate(());
// to use `hir_crate_items`.
tcx.ensure_done().hir_crate_items(());

let sess = tcx.sess;
sess.time("misc_checking_1", || {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_lint/src/expect.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use rustc_data_structures::fx::FxHashSet;
use rustc_hir::CRATE_OWNER_ID;
use rustc_middle::lint::LintExpectation;
use rustc_middle::query::Providers;
use rustc_middle::ty::TyCtxt;
Expand All @@ -18,7 +17,7 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp

let mut expectations = Vec::new();

for owner in std::iter::once(CRATE_OWNER_ID).chain(krate.owners()) {
for owner in krate.owners() {
let lints = tcx.shallow_lint_levels_on(owner);
expectations.extend_from_slice(&lints.expectations);
}
Expand Down
16 changes: 8 additions & 8 deletions compiler/rustc_middle/src/hir/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,7 @@ impl<'tcx> TyCtxt<'tcx> {
}

/// Returns an iterator of the `DefId`s for all body-owners in this
/// crate. If you would prefer to iterate over the bodies
/// themselves, you can do `self.hir_crate(()).body_ids.iter()`.
/// crate.
#[inline]
pub fn hir_body_owners(self) -> impl Iterator<Item = LocalDefId> {
self.hir_crate_items(()).body_owners.iter().copied()
Expand Down Expand Up @@ -396,12 +395,11 @@ impl<'tcx> TyCtxt<'tcx> {
where
V: Visitor<'tcx>,
{
let krate = self.hir_crate(());
for info in krate.owners.iter() {
if let MaybeOwner::Owner(info) = info {
for attrs in info.attrs.map.values() {
walk_list!(visitor, visit_attribute, *attrs);
}
let krate = self.hir_crate_items(());
for owner in krate.owners() {
let attrs = self.hir_attr_map(owner);
for attrs in attrs.map.values() {
walk_list!(visitor, visit_attribute, *attrs);
}
}
V::Result::output()
Expand Down Expand Up @@ -1225,6 +1223,7 @@ pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> Mod
..
} = collector;
ModuleItems {
add_root: false,
submodules: submodules.into_boxed_slice(),
free_items: items.into_boxed_slice(),
trait_items: trait_items.into_boxed_slice(),
Expand Down Expand Up @@ -1258,6 +1257,7 @@ pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
} = collector;

ModuleItems {
add_root: true,
submodules: submodules.into_boxed_slice(),
free_items: items.into_boxed_slice(),
trait_items: trait_items.into_boxed_slice(),
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_middle/src/hir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ use crate::ty::{EarlyBinder, ImplSubject, TyCtxt};
/// bodies. The Ids are in visitor order. This is used to partition a pass between modules.
#[derive(Debug, HashStable, Encodable, Decodable)]
pub struct ModuleItems {
/// Whether this represents the whole crate, in which case we need to add `CRATE_OWNER_ID` to
/// the iterators if we want to account for the crate root.
add_root: bool,
submodules: Box<[OwnerId]>,
free_items: Box<[ItemId]>,
trait_items: Box<[TraitItemId]>,
Expand Down Expand Up @@ -60,9 +63,10 @@ impl ModuleItems {
}

pub fn owners(&self) -> impl Iterator<Item = OwnerId> {
self.free_items
.iter()
.map(|id| id.owner_id)
self.add_root
.then_some(CRATE_OWNER_ID)
.into_iter()
.chain(self.free_items.iter().map(|id| id.owner_id))
.chain(self.trait_items.iter().map(|id| id.owner_id))
.chain(self.impl_items.iter().map(|id| id.owner_id))
.chain(self.foreign_items.iter().map(|id| id.owner_id))
Expand Down
35 changes: 13 additions & 22 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2118,7 +2118,7 @@ impl<'tcx> TyCtxt<'tcx> {
) -> &'tcx rustc_hir::def_path_hash_map::DefPathHashMap {
// Create a dependency to the crate to be sure we re-execute this when the amount of
// definitions change.
self.ensure_ok().hir_crate(());
self.ensure_ok().hir_crate_items(());
// Freeze definitions once we start iterating on them, to prevent adding new ones
// while iterating. If some query needs to add definitions, it should be `ensure`d above.
self.untracked.definitions.freeze().def_path_hash_to_def_index_map()
Expand Down Expand Up @@ -3165,42 +3165,33 @@ impl<'tcx> TyCtxt<'tcx> {
lint_level(self.sess, lint, level, Some(span.into()), decorate);
}

/// Find the crate root and the appropriate span where `use` and outer attributes can be
/// inserted at.
pub fn crate_level_attribute_injection_span(self, hir_id: HirId) -> Option<Span> {
for (_hir_id, node) in self.hir_parent_iter(hir_id) {
if let hir::Node::Crate(m) = node {
return Some(m.spans.inject_use_span.shrink_to_lo());
}
}
None
/// Find the appropriate span where `use` and outer attributes can be inserted at.
pub fn crate_level_attribute_injection_span(self) -> Span {
let node = self.hir_node(hir::CRATE_HIR_ID);
let hir::Node::Crate(m) = node else { bug!() };
m.spans.inject_use_span.shrink_to_lo()
}

pub fn disabled_nightly_features<E: rustc_errors::EmissionGuarantee>(
self,
diag: &mut Diag<'_, E>,
hir_id: Option<HirId>,
features: impl IntoIterator<Item = (String, Symbol)>,
) {
if !self.sess.is_nightly_build() {
return;
}

let span = hir_id.and_then(|id| self.crate_level_attribute_injection_span(id));
let span = self.crate_level_attribute_injection_span();
for (desc, feature) in features {
// FIXME: make this string translatable
let msg =
format!("add `#![feature({feature})]` to the crate attributes to enable{desc}");
if let Some(span) = span {
diag.span_suggestion_verbose(
span,
msg,
format!("#![feature({feature})]\n"),
Applicability::MaybeIncorrect,
);
} else {
diag.help(msg);
}
diag.span_suggestion_verbose(
span,
msg,
format!("#![feature({feature})]\n"),
Applicability::MaybeIncorrect,
);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3575,11 +3575,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
}
ObligationCauseCode::TrivialBound => {
err.help("see issue #48214");
tcx.disabled_nightly_features(
err,
Some(tcx.local_def_id_to_hir_id(body_id)),
[(String::new(), sym::trivial_bounds)],
);
tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
}
ObligationCauseCode::OpaqueReturnType(expr_info) => {
let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
Expand Down
2 changes: 0 additions & 2 deletions src/librustdoc/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,8 +387,6 @@ pub(crate) fn run_global_ctxt(
ctxt.external_traits.insert(sized_trait_did, sized_trait);
}

debug!("crate: {:?}", tcx.hir_crate(()));

let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));

if krate.module.doc_value().is_empty() {
Expand Down
Loading