1
Fork 0

Rollup merge of #137504 - nnethercote:remove-Map-4, r=Zalathar

Move methods from Map to TyCtxt, part 4.

A follow-up to https://github.com/rust-lang/rust/pull/137350.

r? ```@Zalathar```
This commit is contained in:
Manish Goregaokar 2025-03-12 10:19:26 -07:00 committed by GitHub
commit f88f27aff0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
124 changed files with 390 additions and 441 deletions

View file

@ -505,7 +505,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let var_id = let var_id =
self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable(); self.infcx.tcx.closure_captures(def_id)[field.index()].get_root_variable();
Some(self.infcx.tcx.hir().name(var_id).to_string()) Some(self.infcx.tcx.hir_name(var_id).to_string())
} }
_ => { _ => {
// Might need a revision when the fields in trait RFC is implemented // Might need a revision when the fields in trait RFC is implemented
@ -1124,7 +1124,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
def_id, target_place, places def_id, target_place, places
); );
let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id); let hir_id = self.infcx.tcx.local_def_id_to_hir_id(def_id);
let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind; let expr = &self.infcx.tcx.hir_expect_expr(hir_id).kind;
debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr); debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr { if let &hir::ExprKind::Closure(&hir::Closure { kind, fn_decl_span, .. }) = expr {
for (captured_place, place) in for (captured_place, place) in

View file

@ -698,7 +698,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if !matches!(k, hir::AssocItemKind::Fn { .. }) { if !matches!(k, hir::AssocItemKind::Fn { .. }) {
continue; continue;
} }
if self.infcx.tcx.hir().name(hi) != self.infcx.tcx.hir().name(my_hir) { if self.infcx.tcx.hir_name(hi) != self.infcx.tcx.hir_name(my_hir) {
continue; continue;
} }
f_in_trait_opt = Some(hi); f_in_trait_opt = Some(hi);

View file

@ -105,7 +105,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(opaque_def_id) = opaque_def_id.as_local() if let Some(opaque_def_id) = opaque_def_id.as_local()
&& let hir::OpaqueTyOrigin::FnReturn { parent, .. } = && let hir::OpaqueTyOrigin::FnReturn { parent, .. } =
tcx.hir().expect_opaque_ty(opaque_def_id).origin tcx.hir_expect_opaque_ty(opaque_def_id).origin
{ {
if let Some(sugg) = impl_trait_overcapture_suggestion( if let Some(sugg) = impl_trait_overcapture_suggestion(
tcx, tcx,

View file

@ -343,7 +343,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
} }
}; };
let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) = let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) =
tcx.hir().expect_expr(self.mir_hir_id()).kind tcx.hir_expect_expr(self.mir_hir_id()).kind
else { else {
bug!("Closure is not defined by a closure expr"); bug!("Closure is not defined by a closure expr");
}; };

View file

@ -69,7 +69,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
let upvar_hir_id = upvars[upvar_index].get_root_variable(); let upvar_hir_id = upvars[upvar_index].get_root_variable();
debug!("get_upvar_name_and_span_for_region: upvar_hir_id={upvar_hir_id:?}"); debug!("get_upvar_name_and_span_for_region: upvar_hir_id={upvar_hir_id:?}");
let upvar_name = tcx.hir().name(upvar_hir_id); let upvar_name = tcx.hir_name(upvar_hir_id);
let upvar_span = tcx.hir().span(upvar_hir_id); let upvar_span = tcx.hir().span(upvar_hir_id);
debug!( debug!(
"get_upvar_name_and_span_for_region: upvar_name={upvar_name:?} upvar_span={upvar_span:?}", "get_upvar_name_and_span_for_region: upvar_name={upvar_name:?} upvar_span={upvar_span:?}",

View file

@ -63,7 +63,7 @@ pub fn assert_module_sources(tcx: TyCtxt<'_>, set_reuse: &dyn Fn(&mut CguReuseTr
}, },
}; };
for attr in tcx.hir().attrs(rustc_hir::CRATE_HIR_ID) { for attr in tcx.hir_attrs(rustc_hir::CRATE_HIR_ID) {
ams.check_attr(attr); ams.check_attr(attr);
} }

View file

@ -475,7 +475,7 @@ pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
) -> OngoingCodegen<B> { ) -> OngoingCodegen<B> {
let (coordinator_send, coordinator_receive) = channel(); let (coordinator_send, coordinator_receive) = channel();
let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID); let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins); let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
let crate_info = CrateInfo::new(tcx, target_cpu); let crate_info = CrateInfo::new(tcx, target_cpu);

View file

@ -876,7 +876,7 @@ impl CrateInfo {
let linked_symbols = let linked_symbols =
crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect(); crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
let local_crate_name = tcx.crate_name(LOCAL_CRATE); let local_crate_name = tcx.crate_name(LOCAL_CRATE);
let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID); let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
let subsystem = let subsystem =
ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem); ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
let windows_subsystem = subsystem.map(|subsystem| { let windows_subsystem = subsystem.map(|subsystem| {

View file

@ -60,7 +60,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
); );
} }
let attrs = tcx.hir().attrs(tcx.local_def_id_to_hir_id(did)); let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
let mut codegen_fn_attrs = CodegenFnAttrs::new(); let mut codegen_fn_attrs = CodegenFnAttrs::new();
if tcx.should_inherit_track_caller(did) { if tcx.should_inherit_track_caller(did) {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER; codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
@ -75,7 +75,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// When `no_builtins` is applied at the crate level, we should add the // When `no_builtins` is applied at the crate level, we should add the
// `no-builtins` attribute to each function to ensure it takes effect in LTO. // `no-builtins` attribute to each function to ensure it takes effect in LTO.
let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID); let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins); let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
if no_builtins { if no_builtins {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;

View file

@ -81,7 +81,7 @@ pub fn rustc_allow_const_fn_unstable(
def_id: LocalDefId, def_id: LocalDefId,
feature_gate: Symbol, feature_gate: Symbol,
) -> bool { ) -> bool {
let attrs = tcx.hir().attrs(tcx.local_def_id_to_hir_id(def_id)); let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
find_attr!(attrs, AttributeKind::AllowConstFnUnstable(syms) if syms.contains(&feature_gate)) find_attr!(attrs, AttributeKind::AllowConstFnUnstable(syms) if syms.contains(&feature_gate))
} }

View file

@ -268,8 +268,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
let tcx = ex.tcx(); let tcx = ex.tcx();
let f = |annotation: &dyn pprust_hir::PpAnn| { let f = |annotation: &dyn pprust_hir::PpAnn| {
let sm = sess.source_map(); let sm = sess.source_map();
let hir_map = tcx.hir(); let attrs = |id| tcx.hir_attrs(id);
let attrs = |id| hir_map.attrs(id);
pprust_hir::print_crate( pprust_hir::print_crate(
sm, sm,
tcx.hir_root_module(), tcx.hir_root_module(),

View file

@ -185,7 +185,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo` /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
/// projections that would result in "inheriting lifetimes". /// projections that would result in "inheriting lifetimes".
fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) { fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let hir::OpaqueTy { origin, .. } = *tcx.hir().expect_opaque_ty(def_id); let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
// HACK(jynelson): trying to infer the type of `impl trait` breaks documenting // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
// `async-std` (and `pub async fn` in general). // `async-std` (and `pub async fn` in general).
@ -785,7 +785,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) {
check_type_alias_type_params_are_used(tcx, def_id); check_type_alias_type_params_are_used(tcx, def_id);
} }
DefKind::ForeignMod => { DefKind::ForeignMod => {
let it = tcx.hir().expect_item(def_id); let it = tcx.hir_expect_item(def_id);
let hir::ItemKind::ForeignMod { abi, items } = it.kind else { let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
return; return;
}; };

View file

@ -1031,7 +1031,7 @@ fn report_trait_method_mismatch<'tcx>(
// When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
// span points only at the type `Box<Self`>, but we want to cover the whole // span points only at the type `Box<Self`>, but we want to cover the whole
// argument pattern and type. // argument pattern and type.
let (sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); let (sig, body) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
let span = tcx let span = tcx
.hir_body_param_names(body) .hir_body_param_names(body)
.zip(sig.decl.inputs.iter()) .zip(sig.decl.inputs.iter())
@ -1051,7 +1051,7 @@ fn report_trait_method_mismatch<'tcx>(
// Suggestion to change output type. We do not suggest in `async` functions // Suggestion to change output type. We do not suggest in `async` functions
// to avoid complex logic or incorrect output. // to avoid complex logic or incorrect output.
if let ImplItemKind::Fn(sig, _) = if let ImplItemKind::Fn(sig, _) =
&tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).kind
&& !sig.header.asyncness.is_async() && !sig.header.asyncness.is_async()
{ {
let msg = "change the output type to match the trait"; let msg = "change the output type to match the trait";
@ -1190,12 +1190,12 @@ fn extract_spans_for_error_reporting<'tcx>(
) -> (Span, Option<Span>) { ) -> (Span, Option<Span>) {
let tcx = infcx.tcx; let tcx = infcx.tcx;
let mut impl_args = { let mut impl_args = {
let (sig, _) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); let (sig, _) = tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span())) sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
}; };
let trait_args = trait_m.def_id.as_local().map(|def_id| { let trait_args = trait_m.def_id.as_local().map(|def_id| {
let (sig, _) = tcx.hir().expect_trait_item(def_id).expect_fn(); let (sig, _) = tcx.hir_expect_trait_item(def_id).expect_fn();
sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span())) sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
}); });
@ -1371,7 +1371,7 @@ fn compare_number_of_generics<'tcx>(
spans spans
}; };
let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() { let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
let trait_item = tcx.hir().expect_trait_item(def_id); let trait_item = tcx.hir_expect_trait_item(def_id);
let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics); let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
let impl_trait_spans: Vec<Span> = trait_item let impl_trait_spans: Vec<Span> = trait_item
.generics .generics
@ -1388,7 +1388,7 @@ fn compare_number_of_generics<'tcx>(
(trait_span.map(|s| vec![s]), vec![]) (trait_span.map(|s| vec![s]), vec![])
}; };
let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local()); let impl_item = tcx.hir_expect_impl_item(impl_.def_id.expect_local());
let impl_item_impl_trait_spans: Vec<Span> = impl_item let impl_item_impl_trait_spans: Vec<Span> = impl_item
.generics .generics
.params .params
@ -1466,7 +1466,7 @@ fn compare_number_of_method_arguments<'tcx>(
.def_id .def_id
.as_local() .as_local()
.and_then(|def_id| { .and_then(|def_id| {
let (trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).expect_fn(); let (trait_m_sig, _) = &tcx.hir_expect_trait_item(def_id).expect_fn();
let pos = trait_number_args.saturating_sub(1); let pos = trait_number_args.saturating_sub(1);
trait_m_sig.decl.inputs.get(pos).map(|arg| { trait_m_sig.decl.inputs.get(pos).map(|arg| {
if pos == 0 { if pos == 0 {
@ -1478,7 +1478,7 @@ fn compare_number_of_method_arguments<'tcx>(
}) })
.or_else(|| tcx.hir().span_if_local(trait_m.def_id)); .or_else(|| tcx.hir().span_if_local(trait_m.def_id));
let (impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn(); let (impl_m_sig, _) = &tcx.hir_expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
let pos = impl_number_args.saturating_sub(1); let pos = impl_number_args.saturating_sub(1);
let impl_span = impl_m_sig let impl_span = impl_m_sig
.decl .decl
@ -1580,10 +1580,10 @@ fn compare_synthetic_generics<'tcx>(
// as another generic argument // as another generic argument
let new_name = tcx.opt_item_name(trait_def_id)?; let new_name = tcx.opt_item_name(trait_def_id)?;
let trait_m = trait_m.def_id.as_local()?; let trait_m = trait_m.def_id.as_local()?;
let trait_m = tcx.hir().expect_trait_item(trait_m); let trait_m = tcx.hir_expect_trait_item(trait_m);
let impl_m = impl_m.def_id.as_local()?; let impl_m = impl_m.def_id.as_local()?;
let impl_m = tcx.hir().expect_impl_item(impl_m); let impl_m = tcx.hir_expect_impl_item(impl_m);
// in case there are no generics, take the spot between the function name // in case there are no generics, take the spot between the function name
// and the opening paren of the argument list // and the opening paren of the argument list
@ -1613,7 +1613,7 @@ fn compare_synthetic_generics<'tcx>(
err.span_label(impl_span, "expected `impl Trait`, found generic parameter"); err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
let _: Option<_> = try { let _: Option<_> = try {
let impl_m = impl_m.def_id.as_local()?; let impl_m = impl_m.def_id.as_local()?;
let impl_m = tcx.hir().expect_impl_item(impl_m); let impl_m = tcx.hir_expect_impl_item(impl_m);
let (sig, _) = impl_m.expect_fn(); let (sig, _) = impl_m.expect_fn();
let input_tys = sig.decl.inputs; let input_tys = sig.decl.inputs;
@ -1855,7 +1855,7 @@ fn compare_const_predicate_entailment<'tcx>(
debug!(?impl_ty, ?trait_ty); debug!(?impl_ty, ?trait_ty);
// Locate the Span containing just the type of the offending impl // Locate the Span containing just the type of the offending impl
let (ty, _) = tcx.hir().expect_impl_item(impl_ct_def_id).expect_const(); let (ty, _) = tcx.hir_expect_impl_item(impl_ct_def_id).expect_const();
cause.span = ty.span; cause.span = ty.span;
let mut diag = struct_span_code_err!( let mut diag = struct_span_code_err!(
@ -1868,7 +1868,7 @@ fn compare_const_predicate_entailment<'tcx>(
let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| { let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
// Add a label to the Span containing just the type of the const // Add a label to the Span containing just the type of the const
let (ty, _) = tcx.hir().expect_trait_item(trait_ct_def_id).expect_const(); let (ty, _) = tcx.hir_expect_trait_item(trait_ct_def_id).expect_const();
ty.span ty.span
}); });

View file

@ -513,7 +513,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
continue; continue;
} }
let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id); let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
debug!(?required_bounds); debug!(?required_bounds);
let param_env = tcx.param_env(gat_def_id); let param_env = tcx.param_env(gat_def_id);

View file

@ -31,7 +31,7 @@ fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) {
if used_trait_imports.contains(&id) { if used_trait_imports.contains(&id) {
continue; continue;
} }
let item = tcx.hir().expect_item(id); let item = tcx.hir_expect_item(id);
if item.span.is_dummy() { if item.span.is_dummy() {
continue; continue;
} }

View file

@ -82,7 +82,7 @@ fn visit_implementation_of_drop(checker: &Checker<'_>) -> Result<(), ErrorGuaran
_ => {} _ => {}
} }
let impl_ = tcx.hir().expect_item(impl_did).expect_impl(); let impl_ = tcx.hir_expect_item(impl_did).expect_impl();
Err(tcx.dcx().emit_err(errors::DropImplOnWrongItem { span: impl_.self_ty.span })) Err(tcx.dcx().emit_err(errors::DropImplOnWrongItem { span: impl_.self_ty.span }))
} }
@ -109,7 +109,7 @@ fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaran
match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) { match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(CopyImplementationError::InfringingFields(fields)) => { Err(CopyImplementationError::InfringingFields(fields)) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(infringing_fields_error( Err(infringing_fields_error(
tcx, tcx,
fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)), fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
@ -119,15 +119,15 @@ fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaran
)) ))
} }
Err(CopyImplementationError::NotAnAdt) => { Err(CopyImplementationError::NotAnAdt) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(tcx.dcx().emit_err(errors::CopyImplOnNonAdt { span })) Err(tcx.dcx().emit_err(errors::CopyImplOnNonAdt { span }))
} }
Err(CopyImplementationError::HasDestructor) => { Err(CopyImplementationError::HasDestructor) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(tcx.dcx().emit_err(errors::CopyImplOnTypeWithDtor { span })) Err(tcx.dcx().emit_err(errors::CopyImplOnTypeWithDtor { span }))
} }
Err(CopyImplementationError::HasUnsafeFields) => { Err(CopyImplementationError::HasUnsafeFields) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(tcx Err(tcx
.dcx() .dcx()
.span_delayed_bug(span, format!("cannot implement `Copy` for `{}`", self_type))) .span_delayed_bug(span, format!("cannot implement `Copy` for `{}`", self_type)))
@ -157,7 +157,7 @@ fn visit_implementation_of_const_param_ty(
match type_allowed_to_implement_const_param_ty(tcx, param_env, self_type, kind, cause) { match type_allowed_to_implement_const_param_ty(tcx, param_env, self_type, kind, cause) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(ConstParamTyImplementationError::InfrigingFields(fields)) => { Err(ConstParamTyImplementationError::InfrigingFields(fields)) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(infringing_fields_error( Err(infringing_fields_error(
tcx, tcx,
fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)), fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
@ -167,11 +167,11 @@ fn visit_implementation_of_const_param_ty(
)) ))
} }
Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => { Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnNonAdt { span })) Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnNonAdt { span }))
} }
Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => { Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(infringing_fields_error( Err(infringing_fields_error(
tcx, tcx,
infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)), infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)),
@ -181,7 +181,7 @@ fn visit_implementation_of_const_param_ty(
)) ))
} }
Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => { Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span; let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnUnsized { span })) Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnUnsized { span }))
} }
} }
@ -526,7 +526,7 @@ pub(crate) fn coerce_unsized_info<'tcx>(
note: true, note: true,
})); }));
} else if diff_fields.len() > 1 { } else if diff_fields.len() > 1 {
let item = tcx.hir().expect_item(impl_did); let item = tcx.hir_expect_item(impl_did);
let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(t), .. }) = &item.kind { let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(t), .. }) = &item.kind {
t.path.span t.path.span
} else { } else {

View file

@ -376,7 +376,7 @@ fn emit_orphan_check_error<'tcx>(
) -> ErrorGuaranteed { ) -> ErrorGuaranteed {
match err { match err {
traits::OrphanCheckErr::NonLocalInputType(tys) => { traits::OrphanCheckErr::NonLocalInputType(tys) => {
let item = tcx.hir().expect_item(impl_def_id); let item = tcx.hir_expect_item(impl_def_id);
let impl_ = item.expect_impl(); let impl_ = item.expect_impl();
let hir_trait_ref = impl_.of_trait.as_ref().unwrap(); let hir_trait_ref = impl_.of_trait.as_ref().unwrap();

View file

@ -469,8 +469,7 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => { hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
let item = self let item = self
.tcx .tcx
.hir() .hir_expect_item(self.tcx.hir_get_parent_item(self.hir_id()).def_id);
.expect_item(self.tcx.hir_get_parent_item(self.hir_id()).def_id);
match &item.kind { match &item.kind {
hir::ItemKind::Enum(_, generics) hir::ItemKind::Enum(_, generics)
| hir::ItemKind::Struct(_, generics) | hir::ItemKind::Struct(_, generics)
@ -1143,7 +1142,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
} }
fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
let item = tcx.hir().expect_item(def_id); let item = tcx.hir_expect_item(def_id);
let (is_alias, is_auto, safety, items) = match item.kind { let (is_alias, is_auto, safety, items) = match item.kind {
hir::ItemKind::Trait(is_auto, safety, .., items) => { hir::ItemKind::Trait(is_auto, safety, .., items) => {
@ -1342,7 +1341,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFn
), ),
ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => { ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
let abi = tcx.hir().get_foreign_abi(hir_id); let abi = tcx.hir_get_foreign_abi(hir_id);
compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety()) compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety())
} }
@ -1597,7 +1596,7 @@ pub fn suggest_impl_trait<'tcx>(
fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTraitHeader<'_>> { fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTraitHeader<'_>> {
let icx = ItemCtxt::new(tcx, def_id); let icx = ItemCtxt::new(tcx, def_id);
let item = tcx.hir().expect_item(def_id); let item = tcx.hir_expect_item(def_id);
let impl_ = item.expect_impl(); let impl_ = item.expect_impl();
impl_.of_trait.as_ref().map(|ast_trait_ref| { impl_.of_trait.as_ref().map(|ast_trait_ref| {
let selfty = tcx.type_of(def_id).instantiate_identity(); let selfty = tcx.type_of(def_id).instantiate_identity();

View file

@ -13,7 +13,7 @@ pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) {
for id in tcx.hir_crate_items(()).opaques() { for id in tcx.hir_crate_items(()).opaques() {
if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. } if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
| hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } =
tcx.hir().expect_opaque_ty(id).origin tcx.hir_expect_opaque_ty(id).origin
&& let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id) && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
&& let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn() && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
{ {

View file

@ -480,5 +480,5 @@ pub(crate) fn type_alias_is_lazy<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) ->
} }
} }
} }
HasTait.visit_ty_unambig(tcx.hir().expect_item(def_id).expect_ty_alias().0).is_break() HasTait.visit_ty_unambig(tcx.hir_expect_item(def_id).expect_ty_alias().0).is_break()
} }

View file

@ -404,7 +404,7 @@ fn check_constraints<'tcx>(
}; };
if let Some(local_sig_id) = sig_id.as_local() if let Some(local_sig_id) = sig_id.as_local()
&& tcx.hir().opt_delegation_sig_id(local_sig_id).is_some() && tcx.hir_opt_delegation_sig_id(local_sig_id).is_some()
{ {
emit("recursive delegation is not supported yet"); emit("recursive delegation is not supported yet");
} }
@ -416,7 +416,7 @@ pub(crate) fn inherit_sig_for_delegation_item<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
def_id: LocalDefId, def_id: LocalDefId,
) -> &'tcx [Ty<'tcx>] { ) -> &'tcx [Ty<'tcx>] {
let sig_id = tcx.hir().opt_delegation_sig_id(def_id).unwrap(); let sig_id = tcx.hir_opt_delegation_sig_id(def_id).unwrap();
let caller_sig = tcx.fn_sig(sig_id); let caller_sig = tcx.fn_sig(sig_id);
if let Err(err) = check_constraints(tcx, def_id, sig_id) { if let Err(err) = check_constraints(tcx, def_id, sig_id) {
let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1; let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1;

View file

@ -370,7 +370,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
#[instrument(level = "debug", skip(self), ret)] #[instrument(level = "debug", skip(self), ret)]
pub fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> { pub fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
let tcx = self.tcx(); let tcx = self.tcx();
let lifetime_name = |def_id| tcx.hir().name(tcx.local_def_id_to_hir_id(def_id)); let lifetime_name = |def_id| tcx.hir_name(tcx.local_def_id_to_hir_id(def_id));
match resolved { match resolved {
rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static, rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,

View file

@ -799,7 +799,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Emit a different diagnostic for local variables, as they are not // Emit a different diagnostic for local variables, as they are not
// type definitions themselves, but rather variables *of* that type. // type definitions themselves, but rather variables *of* that type.
Res::Local(hir_id) => { Res::Local(hir_id) => {
err.arg("local_name", self.tcx.hir().name(hir_id)); err.arg("local_name", self.tcx.hir_name(hir_id));
Some(fluent_generated::hir_typeck_invalid_local) Some(fluent_generated::hir_typeck_invalid_local)
} }
Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => { Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => {

View file

@ -298,7 +298,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Combine the diverging and has_error flags. // Combine the diverging and has_error flags.
self.diverges.set(self.diverges.get() | old_diverges); self.diverges.set(self.diverges.get() | old_diverges);
debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id)); debug!("type of {} is...", self.tcx.hir_id_to_string(expr.hir_id));
debug!("... {:?}, expected is {:?}", ty, expected); debug!("... {:?}, expected is {:?}", ty, expected);
ty ty

View file

@ -1235,7 +1235,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx
self.cx.tainted_by_errors()?; self.cx.tainted_by_errors()?;
bug!( bug!(
"no type for node {} in mem_categorization", "no type for node {} in mem_categorization",
self.cx.tcx().hir().node_to_string(id) self.cx.tcx().hir_id_to_string(id)
); );
} }
} }

View file

@ -140,7 +140,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> { pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> {
self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| { self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid)) span_bug!(span, "no type for local variable {}", self.tcx.hir_id_to_string(nid))
}) })
} }
@ -559,11 +559,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Some(&t) => t, Some(&t) => t,
None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e), None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e),
None => { None => {
bug!( bug!("no type for node {} in fcx {}", self.tcx.hir_id_to_string(id), self.tag());
"no type for node {} in fcx {}",
self.tcx.hir().node_to_string(id),
self.tag()
);
} }
} }
} }

View file

@ -613,7 +613,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter() .iter()
.take(4) .take(4)
.map(|(var_hir_id, upvar)| { .map(|(var_hir_id, upvar)| {
let var_name = self.tcx.hir().name(*var_hir_id).to_string(); let var_name = self.tcx.hir_name(*var_hir_id).to_string();
let msg = format!("`{var_name}` captured here"); let msg = format!("`{var_name}` captured here");
(upvar.span, msg) (upvar.span, msg)
}) })

View file

@ -363,7 +363,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let import_items: Vec<_> = applicable_trait let import_items: Vec<_> = applicable_trait
.import_ids .import_ids
.iter() .iter()
.map(|&import_id| self.tcx.hir().expect_item(import_id)) .map(|&import_id| self.tcx.hir_expect_item(import_id))
.collect(); .collect();
// Find an identifier with which this trait was imported (note that `_` doesn't count). // Find an identifier with which this trait was imported (note that `_` doesn't count).

View file

@ -2344,7 +2344,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
return false; return false;
}; };
let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id); let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id);
let attrs = self.fcx.tcx.hir().attrs(hir_id); let attrs = self.fcx.tcx.hir_attrs(hir_id);
for attr in attrs { for attr in attrs {
if sym::doc == attr.name_or_empty() { if sym::doc == attr.name_or_empty() {
} else if sym::rustc_confusables == attr.name_or_empty() { } else if sym::rustc_confusables == attr.name_or_empty() {

View file

@ -791,7 +791,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& let Ok(pick) = self.lookup_probe_for_diagnostic( && let Ok(pick) = self.lookup_probe_for_diagnostic(
item_name, item_name,
Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl), Ty::new_ref(tcx, ty::Region::new_error_misc(tcx), ty, ptr_mutbl),
self.tcx.hir().expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)), self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id)),
ProbeScope::TraitsInScope, ProbeScope::TraitsInScope,
None, None,
) )
@ -834,8 +834,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let SelfSource::MethodCall(rcvr_expr) = source { if let SelfSource::MethodCall(rcvr_expr) = source {
self.suggest_fn_call(&mut err, rcvr_expr, rcvr_ty, |output_ty| { self.suggest_fn_call(&mut err, rcvr_expr, rcvr_ty, |output_ty| {
let call_expr = let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
self.tcx.hir().expect_expr(self.tcx.parent_hir_id(rcvr_expr.hir_id));
let probe = self.lookup_probe_for_diagnostic( let probe = self.lookup_probe_for_diagnostic(
item_name, item_name,
output_ty, output_ty,
@ -2373,7 +2372,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} else { } else {
let call_expr = tcx.hir().expect_expr(tcx.parent_hir_id(expr.hir_id)); let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
if let Some(span) = call_expr.span.trim_start(item_name.span) { if let Some(span) = call_expr.span.trim_start(item_name.span) {
err.span_suggestion( err.span_suggestion(
@ -2680,7 +2679,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
mod_id, mod_id,
expr.hir_id, expr.hir_id,
) { ) {
let call_expr = self.tcx.hir().expect_expr(self.tcx.parent_hir_id(expr.hir_id)); let call_expr = self.tcx.hir_expect_expr(self.tcx.parent_hir_id(expr.hir_id));
let lang_items = self.tcx.lang_items(); let lang_items = self.tcx.lang_items();
let never_mention_traits = [ let never_mention_traits = [
@ -2757,7 +2756,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let SelfSource::MethodCall(expr) = source else { let SelfSource::MethodCall(expr) = source else {
return; return;
}; };
let call_expr = tcx.hir().expect_expr(tcx.parent_hir_id(expr.hir_id)); let call_expr = tcx.hir_expect_expr(tcx.parent_hir_id(expr.hir_id));
let ty::Adt(kind, args) = actual.kind() else { let ty::Adt(kind, args) = actual.kind() else {
return; return;

View file

@ -781,7 +781,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id, PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
base => bug!("Expected upvar, found={:?}", base), base => bug!("Expected upvar, found={:?}", base),
}; };
let var_ident = self.tcx.hir().ident(var_hir_id); let var_ident = self.tcx.hir_ident(var_hir_id);
let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else { let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
let mutability = self.determine_capture_mutability(&typeck_results, &place); let mutability = self.determine_capture_mutability(&typeck_results, &place);
@ -988,13 +988,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => { UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
let cause_span = self.tcx.hir().span(*capture_expr_id); let cause_span = self.tcx.hir().span(*capture_expr_id);
lint.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`", lint.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
self.tcx.hir().name(*var_hir_id), self.tcx.hir_name(*var_hir_id),
captured_name, captured_name,
)); ));
} }
UpvarMigrationInfo::CapturingNothing { use_span } => { UpvarMigrationInfo::CapturingNothing { use_span } => {
lint.span_label(*use_span, format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect", lint.span_label(*use_span, format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
self.tcx.hir().name(*var_hir_id), self.tcx.hir_name(*var_hir_id),
)); ));
} }
@ -1009,13 +1009,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
match &lint_note.captures_info { match &lint_note.captures_info {
UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => { UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
lint.span_label(drop_location_span, format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure", lint.span_label(drop_location_span, format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure",
self.tcx.hir().name(*var_hir_id), self.tcx.hir_name(*var_hir_id),
captured_name, captured_name,
)); ));
} }
UpvarMigrationInfo::CapturingNothing { use_span: _ } => { UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
lint.span_label(drop_location_span, format!("in Rust 2018, `{v}` is dropped here along with the closure, but in Rust 2021 `{v}` is not part of the closure", lint.span_label(drop_location_span, format!("in Rust 2018, `{v}` is dropped here along with the closure, but in Rust 2021 `{v}` is not part of the closure",
v = self.tcx.hir().name(*var_hir_id), v = self.tcx.hir_name(*var_hir_id),
)); ));
} }
} }
@ -1026,7 +1026,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// not capturing something anymore cannot cause a trait to fail to be implemented: // not capturing something anymore cannot cause a trait to fail to be implemented:
match &lint_note.captures_info { match &lint_note.captures_info {
UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => { UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
let var_name = self.tcx.hir().name(*var_hir_id); let var_name = self.tcx.hir_name(*var_hir_id);
lint.span_label(closure_head_span, format!("\ lint.span_label(closure_head_span, format!("\
in Rust 2018, this closure implements {missing_trait} \ in Rust 2018, this closure implements {missing_trait} \
as `{var_name}` implements {missing_trait}, but in Rust 2021, \ as `{var_name}` implements {missing_trait}, but in Rust 2021, \
@ -2300,7 +2300,7 @@ fn construct_capture_info_string<'tcx>(
} }
fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol { fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
tcx.hir().name(var_hir_id) tcx.hir_name(var_hir_id)
} }
#[instrument(level = "debug", skip(tcx))] #[instrument(level = "debug", skip(tcx))]

View file

@ -123,7 +123,7 @@ impl<'tcx> IfThisChanged<'tcx> {
fn process_attrs(&mut self, def_id: LocalDefId) { fn process_attrs(&mut self, def_id: LocalDefId) {
let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id()); let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id());
let hir_id = self.tcx.local_def_id_to_hir_id(def_id); let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
let attrs = self.tcx.hir().attrs(hir_id); let attrs = self.tcx.hir_attrs(hir_id);
for attr in attrs { for attr in attrs {
if attr.has_name(sym::rustc_if_this_changed) { if attr.has_name(sym::rustc_if_this_changed) {
let dep_node_interned = self.argument(attr); let dep_node_interned = self.argument(attr);

View file

@ -8,7 +8,7 @@ fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option<LocalDefId> {
let mut decls = None; let mut decls = None;
for id in tcx.hir_free_items() { for id in tcx.hir_free_items() {
let attrs = tcx.hir().attrs(id.hir_id()); let attrs = tcx.hir_attrs(id.hir_id());
if attr::contains_name(attrs, sym::rustc_proc_macro_decls) { if attr::contains_name(attrs, sym::rustc_proc_macro_decls) {
decls = Some(id.owner_id.def_id); decls = Some(id.owner_id.def_id);
} }

View file

@ -419,7 +419,7 @@ impl MissingDoc {
return; return;
} }
let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id)); let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
let has_doc = attrs.iter().any(has_doc); let has_doc = attrs.iter().any(has_doc);
if !has_doc { if !has_doc {
cx.emit_span_lint( cx.emit_span_lint(
@ -997,7 +997,7 @@ declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GEN
impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
let attrs = cx.tcx.hir().attrs(it.hir_id()); let attrs = cx.tcx.hir_attrs(it.hir_id());
let check_no_mangle_on_generic_fn = |no_mangle_attr: &hir::Attribute, let check_no_mangle_on_generic_fn = |no_mangle_attr: &hir::Attribute,
impl_generics: Option<&hir::Generics<'_>>, impl_generics: Option<&hir::Generics<'_>>,
generics: &hir::Generics<'_>, generics: &hir::Generics<'_>,
@ -1050,7 +1050,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
for it in *items { for it in *items {
if let hir::AssocItemKind::Fn { .. } = it.kind { if let hir::AssocItemKind::Fn { .. } = it.kind {
if let Some(no_mangle_attr) = if let Some(no_mangle_attr) =
attr::find_by_name(cx.tcx.hir().attrs(it.id.hir_id()), sym::no_mangle) attr::find_by_name(cx.tcx.hir_attrs(it.id.hir_id()), sym::no_mangle)
{ {
check_no_mangle_on_generic_fn( check_no_mangle_on_generic_fn(
no_mangle_attr, no_mangle_attr,

View file

@ -38,7 +38,7 @@ fn check_expectations(tcx: TyCtxt<'_>, tool_filter: Option<Symbol>) {
} }
LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => { LintExpectationId::Stable { hir_id, attr_index, lint_index: Some(lint_index) } => {
// We are an `eval_always` query, so looking at the attribute's `AttrId` is ok. // We are an `eval_always` query, so looking at the attribute's `AttrId` is ok.
let attr_id = tcx.hir().attrs(hir_id)[attr_index as usize].id(); let attr_id = tcx.hir_attrs(hir_id)[attr_index as usize].id();
(attr_id, lint_index) (attr_id, lint_index)
} }

View file

@ -48,7 +48,7 @@ impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> {
where where
F: FnOnce(&mut Self), F: FnOnce(&mut Self),
{ {
let attrs = self.context.tcx.hir().attrs(id); let attrs = self.context.tcx.hir_attrs(id);
let prev = self.context.last_node_with_lint_attrs; let prev = self.context.last_node_with_lint_attrs;
self.context.last_node_with_lint_attrs = id; self.context.last_node_with_lint_attrs = id;
debug!("late context: enter_attrs({:?})", attrs); debug!("late context: enter_attrs({:?})", attrs);

View file

@ -152,7 +152,7 @@ fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LintId> {
#[instrument(level = "trace", skip(tcx), ret)] #[instrument(level = "trace", skip(tcx), ret)]
fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLevelMap { fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLevelMap {
let store = unerased_lint_store(tcx.sess); let store = unerased_lint_store(tcx.sess);
let attrs = tcx.hir_attrs(owner); let attrs = tcx.hir_attr_map(owner);
let mut levels = LintLevelsBuilder { let mut levels = LintLevelsBuilder {
sess: tcx.sess, sess: tcx.sess,

View file

@ -342,8 +342,8 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name { let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
Some(Ident::from_str(name)) Some(Ident::from_str(name))
} else { } else {
ast::attr::find_by_name(cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name) ast::attr::find_by_name(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), sym::crate_name).and_then(
.and_then(|attr| { |attr| {
if let Attribute::Unparsed(n) = attr if let Attribute::Unparsed(n) = attr
&& let AttrItem { args: AttrArgs::Eq { eq_span: _, expr: lit }, .. } = && let AttrItem { args: AttrArgs::Eq { eq_span: _, expr: lit }, .. } =
n.as_ref() n.as_ref()
@ -371,7 +371,8 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
} else { } else {
None None
} }
}) },
)
}; };
if let Some(ident) = &crate_ident { if let Some(ident) = &crate_ident {
@ -500,7 +501,7 @@ impl NonUpperCaseGlobals {
impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
let attrs = cx.tcx.hir().attrs(it.hir_id()); let attrs = cx.tcx.hir_attrs(it.hir_id());
match it.kind { match it.kind {
hir::ItemKind::Static(..) if !ast::attr::contains_name(attrs, sym::no_mangle) => { hir::ItemKind::Static(..) if !ast::attr::contains_name(attrs, sym::no_mangle) => {
NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident); NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);

View file

@ -1589,7 +1589,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations {
fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, it: &hir::ForeignItem<'tcx>) { fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, it: &hir::ForeignItem<'tcx>) {
let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Declaration }; let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Declaration };
let abi = cx.tcx.hir().get_foreign_abi(it.hir_id()); let abi = cx.tcx.hir_get_foreign_abi(it.hir_id());
match it.kind { match it.kind {
hir::ForeignItemKind::Fn(sig, _, _) => { hir::ForeignItemKind::Fn(sig, _, _) => {

View file

@ -1357,8 +1357,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
features: &tcx.features(), features: &tcx.features(),
}; };
let attr_iter = tcx let attr_iter = tcx
.hir() .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
.attrs(tcx.local_def_id_to_hir_id(def_id))
.iter() .iter()
.filter(|attr| analyze_attr(*attr, &mut state)); .filter(|attr| analyze_attr(*attr, &mut state));
@ -1839,7 +1838,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn encode_info_for_macro(&mut self, def_id: LocalDefId) { fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
let tcx = self.tcx; let tcx = self.tcx;
let hir::ItemKind::Macro(macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() }; let hir::ItemKind::Macro(macro_def, _) = tcx.hir_expect_item(def_id).kind else { bug!() };
self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules); self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body); record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
} }
@ -1918,11 +1917,11 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
for &proc_macro in &tcx.resolutions(()).proc_macros { for &proc_macro in &tcx.resolutions(()).proc_macros {
let id = proc_macro; let id = proc_macro;
let proc_macro = tcx.local_def_id_to_hir_id(proc_macro); let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
let mut name = hir.name(proc_macro); let mut name = tcx.hir_name(proc_macro);
let span = hir.span(proc_macro); let span = hir.span(proc_macro);
// Proc-macros may have attributes like `#[allow_internal_unstable]`, // Proc-macros may have attributes like `#[allow_internal_unstable]`,
// so downstream crates need access to them. // so downstream crates need access to them.
let attrs = hir.attrs(proc_macro); let attrs = tcx.hir_attrs(proc_macro);
let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) { let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) {
MacroKind::Bang MacroKind::Bang
} else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) { } else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) {

View file

@ -275,7 +275,7 @@ impl<'tcx> TyCtxt<'tcx> {
span_bug!( span_bug!(
self.hir().span(hir_id), self.hir().span(hir_id),
"body_owned_by: {} has no associated body", "body_owned_by: {} has no associated body",
self.hir().node_to_string(hir_id) self.hir_id_to_string(hir_id)
); );
}) })
} }
@ -374,7 +374,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// invoking `krate.attrs` because it registers a tighter /// invoking `krate.attrs` because it registers a tighter
/// dep-graph access. /// dep-graph access.
pub fn hir_krate_attrs(self) -> &'tcx [Attribute] { pub fn hir_krate_attrs(self) -> &'tcx [Attribute] {
self.hir().attrs(CRATE_HIR_ID) self.hir_attrs(CRATE_HIR_ID)
} }
pub fn hir_rustc_coherence_is_core(self) -> bool { pub fn hir_rustc_coherence_is_core(self) -> bool {
@ -674,104 +674,178 @@ impl<'tcx> TyCtxt<'tcx> {
} }
} }
} }
}
impl<'hir> Map<'hir> { /// Get a representation of this `id` for debugging purposes.
pub fn get_foreign_abi(self, hir_id: HirId) -> ExternAbi { /// NOTE: Do NOT use this in diagnostics!
let parent = self.tcx.hir_get_parent_item(hir_id); pub fn hir_id_to_string(self, id: HirId) -> String {
let path_str = |def_id: LocalDefId| self.def_path_str(def_id);
let span_str = || {
self.sess.source_map().span_to_snippet(Map { tcx: self }.span(id)).unwrap_or_default()
};
let node_str = |prefix| format!("{id} ({prefix} `{}`)", span_str());
match self.hir_node(id) {
Node::Item(item) => {
let item_str = match item.kind {
ItemKind::ExternCrate(..) => "extern crate",
ItemKind::Use(..) => "use",
ItemKind::Static(..) => "static",
ItemKind::Const(..) => "const",
ItemKind::Fn { .. } => "fn",
ItemKind::Macro(..) => "macro",
ItemKind::Mod(..) => "mod",
ItemKind::ForeignMod { .. } => "foreign mod",
ItemKind::GlobalAsm { .. } => "global asm",
ItemKind::TyAlias(..) => "ty",
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Union(..) => "union",
ItemKind::Trait(..) => "trait",
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Impl { .. } => "impl",
};
format!("{id} ({item_str} {})", path_str(item.owner_id.def_id))
}
Node::ForeignItem(item) => {
format!("{id} (foreign item {})", path_str(item.owner_id.def_id))
}
Node::ImplItem(ii) => {
let kind = match ii.kind {
ImplItemKind::Const(..) => "associated constant",
ImplItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
ImplicitSelfKind::None => "associated function",
_ => "method",
},
ImplItemKind::Type(_) => "associated type",
};
format!("{id} ({kind} `{}` in {})", ii.ident, path_str(ii.owner_id.def_id))
}
Node::TraitItem(ti) => {
let kind = match ti.kind {
TraitItemKind::Const(..) => "associated constant",
TraitItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
ImplicitSelfKind::None => "associated function",
_ => "trait method",
},
TraitItemKind::Type(..) => "associated type",
};
format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id))
}
Node::Variant(variant) => {
format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id))
}
Node::Field(field) => {
format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id))
}
Node::AnonConst(_) => node_str("const"),
Node::ConstBlock(_) => node_str("const"),
Node::ConstArg(_) => node_str("const"),
Node::Expr(_) => node_str("expr"),
Node::ExprField(_) => node_str("expr field"),
Node::Stmt(_) => node_str("stmt"),
Node::PathSegment(_) => node_str("path segment"),
Node::Ty(_) => node_str("type"),
Node::AssocItemConstraint(_) => node_str("assoc item constraint"),
Node::TraitRef(_) => node_str("trait ref"),
Node::OpaqueTy(_) => node_str("opaque type"),
Node::Pat(_) => node_str("pat"),
Node::TyPat(_) => node_str("pat ty"),
Node::PatField(_) => node_str("pattern field"),
Node::PatExpr(_) => node_str("pattern literal"),
Node::Param(_) => node_str("param"),
Node::Arm(_) => node_str("arm"),
Node::Block(_) => node_str("block"),
Node::Infer(_) => node_str("infer"),
Node::LetStmt(_) => node_str("local"),
Node::Ctor(ctor) => format!(
"{id} (ctor {})",
ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
),
Node::Lifetime(_) => node_str("lifetime"),
Node::GenericParam(param) => {
format!("{id} (generic_param {})", path_str(param.def_id))
}
Node::Crate(..) => String::from("(root_crate)"),
Node::WherePredicate(_) => node_str("where predicate"),
Node::Synthetic => unreachable!(),
Node::Err(_) => node_str("error"),
Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),
}
}
pub fn hir_get_foreign_abi(self, hir_id: HirId) -> ExternAbi {
let parent = self.hir_get_parent_item(hir_id);
if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) =
self.tcx.hir_owner_node(parent) self.hir_owner_node(parent)
{ {
return *abi; return *abi;
} }
bug!( bug!(
"expected foreign mod or inlined parent, found {}", "expected foreign mod or inlined parent, found {}",
self.node_to_string(HirId::make_owner(parent.def_id)) self.hir_id_to_string(HirId::make_owner(parent.def_id))
) )
} }
pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> { pub fn hir_expect_item(self, id: LocalDefId) -> &'tcx Item<'tcx> {
match self.tcx.expect_hir_owner_node(id) { match self.expect_hir_owner_node(id) {
OwnerNode::Item(item) => item, OwnerNode::Item(item) => item,
_ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))), _ => bug!("expected item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
} }
} }
pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> { pub fn hir_expect_impl_item(self, id: LocalDefId) -> &'tcx ImplItem<'tcx> {
match self.tcx.expect_hir_owner_node(id) { match self.expect_hir_owner_node(id) {
OwnerNode::ImplItem(item) => item, OwnerNode::ImplItem(item) => item,
_ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))), _ => bug!("expected impl item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
} }
} }
pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> { pub fn hir_expect_trait_item(self, id: LocalDefId) -> &'tcx TraitItem<'tcx> {
match self.tcx.expect_hir_owner_node(id) { match self.expect_hir_owner_node(id) {
OwnerNode::TraitItem(item) => item, OwnerNode::TraitItem(item) => item,
_ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))),
}
}
pub fn get_fn_output(self, def_id: LocalDefId) -> Option<&'hir FnRetTy<'hir>> {
Some(&self.tcx.opt_hir_owner_node(def_id)?.fn_decl()?.output)
}
pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> {
match self.tcx.hir_node(id) {
Node::Variant(variant) => variant,
_ => bug!("expected variant, found {}", self.node_to_string(id)),
}
}
pub fn expect_field(self, id: HirId) -> &'hir FieldDef<'hir> {
match self.tcx.hir_node(id) {
Node::Field(field) => field,
_ => bug!("expected field, found {}", self.node_to_string(id)),
}
}
pub fn expect_foreign_item(self, id: OwnerId) -> &'hir ForeignItem<'hir> {
match self.tcx.hir_owner_node(id) {
OwnerNode::ForeignItem(item) => item,
_ => { _ => {
bug!( bug!("expected trait item, found {}", self.hir_id_to_string(HirId::make_owner(id)))
"expected foreign item, found {}",
self.node_to_string(HirId::make_owner(id.def_id))
)
} }
} }
} }
pub fn hir_get_fn_output(self, def_id: LocalDefId) -> Option<&'tcx FnRetTy<'tcx>> {
Some(&self.opt_hir_owner_node(def_id)?.fn_decl()?.output)
}
#[track_caller] #[track_caller]
pub fn expect_opaque_ty(self, id: LocalDefId) -> &'hir OpaqueTy<'hir> { pub fn hir_expect_opaque_ty(self, id: LocalDefId) -> &'tcx OpaqueTy<'tcx> {
match self.tcx.hir_node_by_def_id(id) { match self.hir_node_by_def_id(id) {
Node::OpaqueTy(opaq) => opaq, Node::OpaqueTy(opaq) => opaq,
_ => { _ => {
bug!( bug!(
"expected opaque type definition, found {}", "expected opaque type definition, found {}",
self.node_to_string(self.tcx.local_def_id_to_hir_id(id)) self.hir_id_to_string(self.local_def_id_to_hir_id(id))
) )
} }
} }
} }
pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> { pub fn hir_expect_expr(self, id: HirId) -> &'tcx Expr<'tcx> {
match self.tcx.hir_node(id) { match self.hir_node(id) {
Node::Expr(expr) => expr, Node::Expr(expr) => expr,
_ => bug!("expected expr, found {}", self.node_to_string(id)), _ => bug!("expected expr, found {}", self.hir_id_to_string(id)),
} }
} }
pub fn opt_delegation_sig_id(self, def_id: LocalDefId) -> Option<DefId> { pub fn hir_opt_delegation_sig_id(self, def_id: LocalDefId) -> Option<DefId> {
self.tcx.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id() self.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id()
} }
#[inline] #[inline]
fn opt_ident(self, id: HirId) -> Option<Ident> { fn hir_opt_ident(self, id: HirId) -> Option<Ident> {
match self.tcx.hir_node(id) { match self.hir_node(id) {
Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident), Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
// A `Ctor` doesn't have an identifier itself, but its parent // A `Ctor` doesn't have an identifier itself, but its parent
// struct/variant does. Compare with `hir::Map::span`. // struct/variant does. Compare with `hir::Map::span`.
Node::Ctor(..) => match self.tcx.parent_hir_node(id) { Node::Ctor(..) => match self.parent_hir_node(id) {
Node::Item(item) => Some(item.ident), Node::Item(item) => Some(item.ident),
Node::Variant(variant) => Some(variant.ident), Node::Variant(variant) => Some(variant.ident),
_ => unreachable!(), _ => unreachable!(),
@ -781,30 +855,32 @@ impl<'hir> Map<'hir> {
} }
#[inline] #[inline]
pub(super) fn opt_ident_span(self, id: HirId) -> Option<Span> { pub(super) fn hir_opt_ident_span(self, id: HirId) -> Option<Span> {
self.opt_ident(id).map(|ident| ident.span) self.hir_opt_ident(id).map(|ident| ident.span)
} }
#[inline] #[inline]
pub fn ident(self, id: HirId) -> Ident { pub fn hir_ident(self, id: HirId) -> Ident {
self.opt_ident(id).unwrap() self.hir_opt_ident(id).unwrap()
} }
#[inline] #[inline]
pub fn opt_name(self, id: HirId) -> Option<Symbol> { pub fn hir_opt_name(self, id: HirId) -> Option<Symbol> {
self.opt_ident(id).map(|ident| ident.name) self.hir_opt_ident(id).map(|ident| ident.name)
} }
pub fn name(self, id: HirId) -> Symbol { pub fn hir_name(self, id: HirId) -> Symbol {
self.opt_name(id).unwrap_or_else(|| bug!("no name for {}", self.node_to_string(id))) self.hir_opt_name(id).unwrap_or_else(|| bug!("no name for {}", self.hir_id_to_string(id)))
} }
/// Given a node ID, gets a list of attributes associated with the AST /// Given a node ID, gets a list of attributes associated with the AST
/// corresponding to the node-ID. /// corresponding to the node-ID.
pub fn attrs(self, id: HirId) -> &'hir [Attribute] { pub fn hir_attrs(self, id: HirId) -> &'tcx [Attribute] {
self.tcx.hir_attrs(id.owner).get(id.local_id) self.hir_attr_map(id.owner).get(id.local_id)
} }
}
impl<'hir> Map<'hir> {
/// Gets the span of the definition of the specified HIR node. /// Gets the span of the definition of the specified HIR node.
/// This is used by `tcx.def_span`. /// This is used by `tcx.def_span`.
pub fn span(self, hir_id: HirId) -> Span { pub fn span(self, hir_id: HirId) -> Span {
@ -977,12 +1053,6 @@ impl<'hir> Map<'hir> {
} }
} }
/// Get a representation of this `id` for debugging purposes.
/// NOTE: Do NOT use this in diagnostics!
pub fn node_to_string(self, id: HirId) -> String {
hir_id_to_string(self, id)
}
/// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
/// called with the HirId for the `{ ... }` anon const /// called with the HirId for the `{ ... }` anon const
pub fn opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> { pub fn opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> {
@ -1147,102 +1217,6 @@ fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
upstream_crates upstream_crates
} }
fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
let path_str = |def_id: LocalDefId| map.tcx.def_path_str(def_id);
let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
let node_str = |prefix| format!("{id} ({prefix} `{}`)", span_str());
match map.tcx.hir_node(id) {
Node::Item(item) => {
let item_str = match item.kind {
ItemKind::ExternCrate(..) => "extern crate",
ItemKind::Use(..) => "use",
ItemKind::Static(..) => "static",
ItemKind::Const(..) => "const",
ItemKind::Fn { .. } => "fn",
ItemKind::Macro(..) => "macro",
ItemKind::Mod(..) => "mod",
ItemKind::ForeignMod { .. } => "foreign mod",
ItemKind::GlobalAsm { .. } => "global asm",
ItemKind::TyAlias(..) => "ty",
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Union(..) => "union",
ItemKind::Trait(..) => "trait",
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Impl { .. } => "impl",
};
format!("{id} ({item_str} {})", path_str(item.owner_id.def_id))
}
Node::ForeignItem(item) => {
format!("{id} (foreign item {})", path_str(item.owner_id.def_id))
}
Node::ImplItem(ii) => {
let kind = match ii.kind {
ImplItemKind::Const(..) => "associated constant",
ImplItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
ImplicitSelfKind::None => "associated function",
_ => "method",
},
ImplItemKind::Type(_) => "associated type",
};
format!("{id} ({kind} `{}` in {})", ii.ident, path_str(ii.owner_id.def_id))
}
Node::TraitItem(ti) => {
let kind = match ti.kind {
TraitItemKind::Const(..) => "associated constant",
TraitItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
ImplicitSelfKind::None => "associated function",
_ => "trait method",
},
TraitItemKind::Type(..) => "associated type",
};
format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id))
}
Node::Variant(variant) => {
format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id))
}
Node::Field(field) => {
format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id))
}
Node::AnonConst(_) => node_str("const"),
Node::ConstBlock(_) => node_str("const"),
Node::ConstArg(_) => node_str("const"),
Node::Expr(_) => node_str("expr"),
Node::ExprField(_) => node_str("expr field"),
Node::Stmt(_) => node_str("stmt"),
Node::PathSegment(_) => node_str("path segment"),
Node::Ty(_) => node_str("type"),
Node::AssocItemConstraint(_) => node_str("assoc item constraint"),
Node::TraitRef(_) => node_str("trait ref"),
Node::OpaqueTy(_) => node_str("opaque type"),
Node::Pat(_) => node_str("pat"),
Node::TyPat(_) => node_str("pat ty"),
Node::PatField(_) => node_str("pattern field"),
Node::PatExpr(_) => node_str("pattern literal"),
Node::Param(_) => node_str("param"),
Node::Arm(_) => node_str("arm"),
Node::Block(_) => node_str("block"),
Node::Infer(_) => node_str("infer"),
Node::LetStmt(_) => node_str("local"),
Node::Ctor(ctor) => format!(
"{id} (ctor {})",
ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
),
Node::Lifetime(_) => node_str("lifetime"),
Node::GenericParam(param) => {
format!("{id} (generic_param {})", path_str(param.def_id))
}
Node::Crate(..) => String::from("(root_crate)"),
Node::WherePredicate(_) => node_str("where predicate"),
Node::Synthetic => unreachable!(),
Node::Err(_) => node_str("error"),
Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),
}
}
pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> ModuleItems { pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> ModuleItems {
let mut collector = ItemCollector::new(tcx, false); let mut collector = ItemCollector::new(tcx, false);

View file

@ -202,13 +202,13 @@ pub fn provide(providers: &mut Providers) {
} }
}) })
}; };
providers.hir_attrs = |tcx, id| { providers.hir_attr_map = |tcx, id| {
tcx.hir_crate(()).owners[id.def_id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs) tcx.hir_crate(()).owners[id.def_id].as_owner().map_or(AttributeMap::EMPTY, |o| &o.attrs)
}; };
providers.def_span = |tcx, def_id| tcx.hir().span(tcx.local_def_id_to_hir_id(def_id)); providers.def_span = |tcx, def_id| tcx.hir().span(tcx.local_def_id_to_hir_id(def_id));
providers.def_ident_span = |tcx, def_id| { providers.def_ident_span = |tcx, def_id| {
let hir_id = tcx.local_def_id_to_hir_id(def_id); let hir_id = tcx.local_def_id_to_hir_id(def_id);
tcx.hir().opt_ident_span(hir_id) tcx.hir_opt_ident_span(hir_id)
}; };
providers.fn_arg_names = |tcx, def_id| { providers.fn_arg_names = |tcx, def_id| {
let hir = tcx.hir(); let hir = tcx.hir();

View file

@ -1200,7 +1200,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
&& let Some(upvars) = tcx.upvars_mentioned(def_id) && let Some(upvars) = tcx.upvars_mentioned(def_id)
{ {
for (&var_id, place) in iter::zip(upvars.keys(), places) { for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id); let var_name = tcx.hir_name(var_id);
struct_fmt.field(var_name.as_str(), place); struct_fmt.field(var_name.as_str(), place);
} }
} else { } else {
@ -1221,7 +1221,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
&& let Some(upvars) = tcx.upvars_mentioned(def_id) && let Some(upvars) = tcx.upvars_mentioned(def_id)
{ {
for (&var_id, place) in iter::zip(upvars.keys(), places) { for (&var_id, place) in iter::zip(upvars.keys(), places) {
let var_name = tcx.hir().name(var_id); let var_name = tcx.hir_name(var_id);
struct_fmt.field(var_name.as_str(), place); struct_fmt.field(var_name.as_str(), place);
} }
} else { } else {

View file

@ -198,7 +198,7 @@ rustc_queries! {
/// ///
/// This can be conveniently accessed by methods on `tcx.hir()`. /// This can be conveniently accessed by methods on `tcx.hir()`.
/// Avoid calling this query directly. /// Avoid calling this query directly.
query hir_attrs(key: hir::OwnerId) -> &'tcx hir::AttributeMap<'tcx> { query hir_attr_map(key: hir::OwnerId) -> &'tcx hir::AttributeMap<'tcx> {
desc { |tcx| "getting HIR owner attributes in `{}`", tcx.def_path_str(key) } desc { |tcx| "getting HIR owner attributes in `{}`", tcx.def_path_str(key) }
feedable feedable
} }

View file

@ -72,7 +72,7 @@ impl OverlapMode {
.as_local() .as_local()
.into_iter() .into_iter()
.flat_map(|local_def_id| { .flat_map(|local_def_id| {
tcx.hir().attrs(tcx.local_def_id_to_hir_id(local_def_id)) tcx.hir_attrs(tcx.local_def_id_to_hir_id(local_def_id))
}) })
.find(|attr| attr.has_name(sym::rustc_strict_coherence)) .find(|attr| attr.has_name(sym::rustc_strict_coherence))
.map(|attr| attr.span()); .map(|attr| attr.span());

View file

@ -296,7 +296,7 @@ pub struct CaptureInfo {
pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String { pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tcx>) -> String {
let mut curr_string: String = match place.base { let mut curr_string: String = match place.base {
HirPlaceBase::Upvar(upvar_id) => tcx.hir().name(upvar_id.var_path.hir_id).to_string(), HirPlaceBase::Upvar(upvar_id) => tcx.hir_name(upvar_id.var_path.hir_id).to_string(),
_ => bug!("Capture_information should only contain upvars"), _ => bug!("Capture_information should only contain upvars"),
}; };

View file

@ -1299,7 +1299,7 @@ impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> {
), ),
bodies, bodies,
}))); })));
self.feed_owner_id().hir_attrs(attrs); self.feed_owner_id().hir_attr_map(attrs);
} }
} }
@ -2214,7 +2214,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// Returns the origin of the opaque type `def_id`. /// Returns the origin of the opaque type `def_id`.
#[instrument(skip(self), level = "trace", ret)] #[instrument(skip(self), level = "trace", ret)]
pub fn local_opaque_ty_origin(self, def_id: LocalDefId) -> hir::OpaqueTyOrigin<LocalDefId> { pub fn local_opaque_ty_origin(self, def_id: LocalDefId) -> hir::OpaqueTyOrigin<LocalDefId> {
self.hir().expect_opaque_ty(def_id).origin self.hir_expect_opaque_ty(def_id).origin
} }
pub fn finish(self) { pub fn finish(self) {
@ -3118,9 +3118,11 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> { pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind> {
self.mk_bound_variable_kinds( self.mk_bound_variable_kinds(
&self.late_bound_vars_map(id.owner).get(&id.local_id).cloned().unwrap_or_else(|| { &self
bug!("No bound vars found for {}", self.hir().node_to_string(id)) .late_bound_vars_map(id.owner)
}), .get(&id.local_id)
.cloned()
.unwrap_or_else(|| bug!("No bound vars found for {}", self.hir_id_to_string(id))),
) )
} }

View file

@ -1696,7 +1696,7 @@ impl<'tcx> TyCtxt<'tcx> {
// FIXME(@lcnr): Remove this function. // FIXME(@lcnr): Remove this function.
pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] { pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] {
if let Some(did) = did.as_local() { if let Some(did) = did.as_local() {
self.hir().attrs(self.local_def_id_to_hir_id(did)) self.hir_attrs(self.local_def_id_to_hir_id(did))
} else { } else {
self.attrs_for_def(did) self.attrs_for_def(did)
} }
@ -1720,7 +1720,7 @@ impl<'tcx> TyCtxt<'tcx> {
) -> impl Iterator<Item = &'tcx hir::Attribute> { ) -> impl Iterator<Item = &'tcx hir::Attribute> {
let did: DefId = did.into(); let did: DefId = did.into();
if let Some(did) = did.as_local() { if let Some(did) = did.as_local() {
self.hir().attrs(self.local_def_id_to_hir_id(did)).iter() self.hir_attrs(self.local_def_id_to_hir_id(did)).iter()
} else { } else {
self.attrs_for_def(did).iter() self.attrs_for_def(did).iter()
} }
@ -1764,7 +1764,7 @@ impl<'tcx> TyCtxt<'tcx> {
) -> impl Iterator<Item = &'tcx hir::Attribute> { ) -> impl Iterator<Item = &'tcx hir::Attribute> {
let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr); let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
if let Some(did) = did.as_local() { if let Some(did) = did.as_local() {
self.hir().attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn) self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
} else { } else {
self.attrs_for_def(did).iter().filter(filter_fn) self.attrs_for_def(did).iter().filter(filter_fn)
} }

View file

@ -50,7 +50,7 @@ impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> {
impl fmt::Debug for ty::UpvarId { impl fmt::Debug for ty::UpvarId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = ty::tls::with(|tcx| tcx.hir().name(self.var_path.hir_id)); let name = ty::tls::with(|tcx| tcx.hir_name(self.var_path.hir_id));
write!(f, "UpvarId({:?};`{}`;{:?})", self.var_path.hir_id, name, self.closure_expr_id) write!(f, "UpvarId({:?};`{}`;{:?})", self.var_path.hir_id, name, self.closure_expr_id)
} }
} }

View file

@ -310,7 +310,7 @@ impl<'tcx> TypeckResults<'tcx> {
pub fn node_type(&self, id: HirId) -> Ty<'tcx> { pub fn node_type(&self, id: HirId) -> Ty<'tcx> {
self.node_type_opt(id).unwrap_or_else(|| { self.node_type_opt(id).unwrap_or_else(|| {
bug!("node_type: no type for node {}", tls::with(|tcx| tcx.hir().node_to_string(id))) bug!("node_type: no type for node {}", tls::with(|tcx| tcx.hir_id_to_string(id)))
}) })
} }
@ -554,7 +554,7 @@ fn invalid_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: HirId) {
ty::tls::with(|tcx| { ty::tls::with(|tcx| {
bug!( bug!(
"node {} cannot be placed in TypeckResults with hir_owner {:?}", "node {} cannot be placed in TypeckResults with hir_owner {:?}",
tcx.hir().node_to_string(hir_id), tcx.hir_id_to_string(hir_id),
hir_owner hir_owner
) )
}); });

View file

@ -485,7 +485,7 @@ fn construct_fn<'tcx>(
}; };
if let Some(custom_mir_attr) = if let Some(custom_mir_attr) =
tcx.hir().attrs(fn_id).iter().find(|attr| attr.name_or_empty() == sym::custom_mir) tcx.hir_attrs(fn_id).iter().find(|attr| attr.name_or_empty() == sym::custom_mir)
{ {
return custom::build_custom_mir( return custom::build_custom_mir(
tcx, tcx,
@ -741,7 +741,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
coroutine: Option<Box<CoroutineInfo<'tcx>>>, coroutine: Option<Box<CoroutineInfo<'tcx>>>,
) -> Builder<'a, 'tcx> { ) -> Builder<'a, 'tcx> {
let tcx = infcx.tcx; let tcx = infcx.tcx;
let attrs = tcx.hir().attrs(hir_id); let attrs = tcx.hir_attrs(hir_id);
// Some functions always have overflow checks enabled, // Some functions always have overflow checks enabled,
// however, they may not get codegen'd, depending on // however, they may not get codegen'd, depending on
// the settings for the crate they are codegened in. // the settings for the crate they are codegened in.

View file

@ -942,14 +942,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
assert_eq!(orig_id.owner, self.hir_id.owner); assert_eq!(orig_id.owner, self.hir_id.owner);
let mut id = orig_id; let mut id = orig_id;
let hir = self.tcx.hir();
loop { loop {
if id == self.hir_id { if id == self.hir_id {
// This is a moderately common case, mostly hit for previously unseen nodes. // This is a moderately common case, mostly hit for previously unseen nodes.
break; break;
} }
if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) { if self.tcx.hir_attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
// This is a rare case. It's for a node path that doesn't reach the root due to an // This is a rare case. It's for a node path that doesn't reach the root due to an
// intervening lint level attribute. This result doesn't get cached. // intervening lint level attribute. This result doesn't get cached.
return id; return id;

View file

@ -1041,7 +1041,7 @@ impl<'tcx> ThirBuildCx<'tcx> {
"Should have already errored about late bound consts: {def_id:?}" "Should have already errored about late bound consts: {def_id:?}"
); );
}; };
let name = self.tcx.hir().name(hir_id); let name = self.tcx.hir_name(hir_id);
let param = ty::ParamConst::new(index, name); let param = ty::ParamConst::new(index, name);
ExprKind::ConstParam { param, def_id } ExprKind::ConstParam { param, def_id }

View file

@ -73,7 +73,6 @@ struct ThirBuildCx<'tcx> {
impl<'tcx> ThirBuildCx<'tcx> { impl<'tcx> ThirBuildCx<'tcx> {
fn new(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Self { fn new(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Self {
let typeck_results = tcx.typeck(def); let typeck_results = tcx.typeck(def);
let hir = tcx.hir();
let hir_id = tcx.local_def_id_to_hir_id(def); let hir_id = tcx.local_def_id_to_hir_id(def);
let body_type = match tcx.hir_body_owner_kind(def) { let body_type = match tcx.hir_body_owner_kind(def) {
@ -111,8 +110,8 @@ impl<'tcx> ThirBuildCx<'tcx> {
typeck_results, typeck_results,
rvalue_scopes: &typeck_results.rvalue_scopes, rvalue_scopes: &typeck_results.rvalue_scopes,
body_owner: def.to_def_id(), body_owner: def.to_def_id(),
apply_adjustments: hir apply_adjustments: tcx
.attrs(hir_id) .hir_attrs(hir_id)
.iter() .iter()
.all(|attr| attr.name_or_empty() != rustc_span::sym::custom_mir), .all(|attr| attr.name_or_empty() != rustc_span::sym::custom_mir),
} }

View file

@ -1043,7 +1043,7 @@ fn find_fallback_pattern_typo<'tcx>(
for item in cx.tcx.hir_crate_items(()).free_items() { for item in cx.tcx.hir_crate_items(()).free_items() {
if let DefKind::Use = cx.tcx.def_kind(item.owner_id) { if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
// Look for consts being re-exported. // Look for consts being re-exported.
let item = cx.tcx.hir().expect_item(item.owner_id.def_id); let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
let use_name = item.ident.name; let use_name = item.ident.name;
let hir::ItemKind::Use(path, _) = item.kind else { let hir::ItemKind::Use(path, _) = item.kind else {
continue; continue;

View file

@ -52,7 +52,7 @@ fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>)
hir::ImplItemKind::Const(..) => Target::AssocConst, hir::ImplItemKind::Const(..) => Target::AssocConst,
hir::ImplItemKind::Fn(..) => { hir::ImplItemKind::Fn(..) => {
let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id; let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let containing_item = tcx.hir().expect_item(parent_def_id); let containing_item = tcx.hir_expect_item(parent_def_id);
let containing_impl_is_for_trait = match &containing_item.kind { let containing_impl_is_for_trait = match &containing_item.kind {
hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(), hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
_ => bug!("parent of an ImplItem must be an Impl"), _ => bug!("parent of an ImplItem must be an Impl"),
@ -114,7 +114,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
let mut doc_aliases = FxHashMap::default(); let mut doc_aliases = FxHashMap::default();
let mut specified_inline = None; let mut specified_inline = None;
let mut seen = FxHashMap::default(); let mut seen = FxHashMap::default();
let attrs = self.tcx.hir().attrs(hir_id); let attrs = self.tcx.hir_attrs(hir_id);
for attr in attrs { for attr in attrs {
match attr { match attr {
Attribute::Parsed(AttributeKind::Confusables { first_span, .. }) => { Attribute::Parsed(AttributeKind::Confusables { first_span, .. }) => {
@ -899,7 +899,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
if let Some(location) = match target { if let Some(location) = match target {
Target::AssocTy => { Target::AssocTy => {
let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id; let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
let containing_item = self.tcx.hir().expect_item(parent_def_id); let containing_item = self.tcx.hir_expect_item(parent_def_id);
if Target::from_item(containing_item) == Target::Impl { if Target::from_item(containing_item) == Target::Impl {
Some("type alias in implementation block") Some("type alias in implementation block")
} else { } else {
@ -908,7 +908,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
} }
Target::AssocConst => { Target::AssocConst => {
let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id; let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
let containing_item = self.tcx.hir().expect_item(parent_def_id); let containing_item = self.tcx.hir_expect_item(parent_def_id);
// We can't link to trait impl's consts. // We can't link to trait impl's consts.
let err = "associated constant in trait implementation block"; let err = "associated constant in trait implementation block";
match containing_item.kind { match containing_item.kind {
@ -952,7 +952,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
tcx.dcx().emit_err(errors::DocAliasBadLocation { span, attr_str, location }); tcx.dcx().emit_err(errors::DocAliasBadLocation { span, attr_str, location });
return; return;
} }
let item_name = self.tcx.hir().name(hir_id); let item_name = self.tcx.hir_name(hir_id);
if item_name == doc_alias { if item_name == doc_alias {
tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str }); tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str });
return; return;
@ -1481,7 +1481,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
// `#[must_use]` can be applied to a trait method definition with a default body // `#[must_use]` can be applied to a trait method definition with a default body
if let Target::Method(MethodKind::Trait { body: true }) = target if let Target::Method(MethodKind::Trait { body: true }) = target
&& let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id && let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id
&& let containing_item = self.tcx.hir().expect_item(parent_def_id) && let containing_item = self.tcx.hir_expect_item(parent_def_id)
&& let hir::ItemKind::Trait(..) = containing_item.kind && let hir::ItemKind::Trait(..) = containing_item.kind
{ {
return; return;
@ -2572,7 +2572,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
match (target, force_inline_attr) { match (target, force_inline_attr) {
(Target::Closure, None) => { (Target::Closure, None) => {
let is_coro = matches!( let is_coro = matches!(
self.tcx.hir().expect_expr(hir_id).kind, self.tcx.hir_expect_expr(hir_id).kind,
hir::ExprKind::Closure(hir::Closure { hir::ExprKind::Closure(hir::Closure {
kind: hir::ClosureKind::Coroutine(..) kind: hir::ClosureKind::Coroutine(..)
| hir::ClosureKind::CoroutineClosure(..), | hir::ClosureKind::CoroutineClosure(..),
@ -2644,8 +2644,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr]; const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr];
let spans = self let spans = self
.tcx .tcx
.hir() .hir_attrs(where_predicate.hir_id)
.attrs(where_predicate.hir_id)
.iter() .iter()
.filter(|attr| !ATTRS_ALLOWED.iter().any(|&sym| attr.has_name(sym))) .filter(|attr| !ATTRS_ALLOWED.iter().any(|&sym| attr.has_name(sym)))
.map(|attr| attr.span()) .map(|attr| attr.span())
@ -2814,7 +2813,7 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
} }
fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) { fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
let attrs = tcx.hir().attrs(item.hir_id()); let attrs = tcx.hir_attrs(item.hir_id());
for attr in attrs { for attr in attrs {
if attr.has_name(sym::inline) { if attr.has_name(sym::inline) {

View file

@ -361,7 +361,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
self.tcx.hir_fn_sig_by_hir_id(self.tcx.local_def_id_to_hir_id(local_def_id)) self.tcx.hir_fn_sig_by_hir_id(self.tcx.local_def_id_to_hir_id(local_def_id))
&& matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None) && matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None)
&& let TyKind::Path(hir::QPath::Resolved(_, path)) = && let TyKind::Path(hir::QPath::Resolved(_, path)) =
self.tcx.hir().expect_item(local_impl_of).expect_impl().self_ty.kind self.tcx.hir_expect_item(local_impl_of).expect_impl().self_ty.kind
&& let Res::Def(def_kind, did) = path.res && let Res::Def(def_kind, did) = path.res
{ {
match def_kind { match def_kind {
@ -424,7 +424,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
for impl_def_id in self.tcx.all_impls(item.owner_id.to_def_id()) { for impl_def_id in self.tcx.all_impls(item.owner_id.to_def_id()) {
if let Some(local_def_id) = impl_def_id.as_local() if let Some(local_def_id) = impl_def_id.as_local()
&& let ItemKind::Impl(impl_ref) = && let ItemKind::Impl(impl_ref) =
self.tcx.hir().expect_item(local_def_id).kind self.tcx.hir_expect_item(local_def_id).kind
{ {
// skip items // skip items
// mark dependent traits live // mark dependent traits live
@ -448,7 +448,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
for impl_id in self.tcx.all_impls(trait_id) { for impl_id in self.tcx.all_impls(trait_id) {
if let Some(local_impl_id) = impl_id.as_local() if let Some(local_impl_id) = impl_id.as_local()
&& let ItemKind::Impl(impl_ref) = && let ItemKind::Impl(impl_ref) =
self.tcx.hir().expect_item(local_impl_id).kind self.tcx.hir_expect_item(local_impl_id).kind
{ {
if !matches!(trait_item.kind, hir::TraitItemKind::Type(..)) if !matches!(trait_item.kind, hir::TraitItemKind::Type(..))
&& !ty_ref_to_pub_struct(self.tcx, impl_ref.self_ty) && !ty_ref_to_pub_struct(self.tcx, impl_ref.self_ty)

View file

@ -19,7 +19,7 @@ use rustc_span::{Symbol, sym};
use crate::errors::DuplicateDiagnosticItemInCrate; use crate::errors::DuplicateDiagnosticItemInCrate;
fn observe_item<'tcx>(tcx: TyCtxt<'tcx>, diagnostic_items: &mut DiagnosticItems, owner: OwnerId) { fn observe_item<'tcx>(tcx: TyCtxt<'tcx>, diagnostic_items: &mut DiagnosticItems, owner: OwnerId) {
let attrs = tcx.hir().attrs(owner.into()); let attrs = tcx.hir_attrs(owner.into());
if let Some(name) = extract(attrs) { if let Some(name) = extract(attrs) {
// insert into our table // insert into our table
collect_item(tcx, diagnostic_items, name, owner.to_def_id()); collect_item(tcx, diagnostic_items, name, owner.to_def_id());

View file

@ -31,7 +31,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
} }
// If the user wants no main function at all, then stop here. // If the user wants no main function at all, then stop here.
if attr::contains_name(tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) { if attr::contains_name(tcx.hir_attrs(CRATE_HIR_ID), sym::no_main) {
return None; return None;
} }
@ -45,7 +45,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
} }
fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Option<Span> { fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Option<Span> {
let attrs = ctxt.tcx.hir().attrs(id.hir_id()); let attrs = ctxt.tcx.hir_attrs(id.hir_id());
attr::find_by_name(attrs, sym).map(|attr| attr.span()) attr::find_by_name(attrs, sym).map(|attr| attr.span())
} }
@ -61,7 +61,7 @@ fn check_and_search_item(id: ItemId, ctxt: &mut EntryContext<'_>) {
let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID); let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID);
let attrs = ctxt.tcx.hir().attrs(id.hir_id()); let attrs = ctxt.tcx.hir_attrs(id.hir_id());
let entry_point_type = rustc_ast::entry::entry_point_type( let entry_point_type = rustc_ast::entry::entry_point_type(
attrs, attrs,
at_root, at_root,

View file

@ -60,19 +60,18 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
.expect("owning item has no entry"); .expect("owning item has no entry");
if max != self.hir_ids_seen.len() - 1 { if max != self.hir_ids_seen.len() - 1 {
let hir = self.tcx.hir();
let pretty_owner = self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose(); let pretty_owner = self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose();
let missing_items: Vec<_> = (0..=max as u32) let missing_items: Vec<_> = (0..=max as u32)
.map(|i| ItemLocalId::from_u32(i)) .map(|i| ItemLocalId::from_u32(i))
.filter(|&local_id| !self.hir_ids_seen.contains(local_id)) .filter(|&local_id| !self.hir_ids_seen.contains(local_id))
.map(|local_id| hir.node_to_string(HirId { owner, local_id })) .map(|local_id| self.tcx.hir_id_to_string(HirId { owner, local_id }))
.collect(); .collect();
let seen_items: Vec<_> = self let seen_items: Vec<_> = self
.hir_ids_seen .hir_ids_seen
.iter() .iter()
.map(|local_id| hir.node_to_string(HirId { owner, local_id })) .map(|local_id| self.tcx.hir_id_to_string(HirId { owner, local_id }))
.collect(); .collect();
self.error(|| { self.error(|| {
@ -137,7 +136,7 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
self.error(|| { self.error(|| {
format!( format!(
"HirIdValidator: The recorded owner of {} is {} instead of {}", "HirIdValidator: The recorded owner of {} is {} instead of {}",
self.tcx.hir().node_to_string(hir_id), self.tcx.hir_id_to_string(hir_id),
self.tcx.hir_def_path(hir_id.owner.def_id).to_string_no_crate_verbose(), self.tcx.hir_def_path(hir_id.owner.def_id).to_string_no_crate_verbose(),
self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose() self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose()
) )

View file

@ -157,7 +157,7 @@ fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) {
if let Some(upvars) = tcx.upvars_mentioned(def_id) { if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for &var_hir_id in upvars.keys() { for &var_hir_id in upvars.keys() {
let var_name = tcx.hir().name(var_hir_id); let var_name = tcx.hir_name(var_hir_id);
maps.add_variable(Upvar(var_hir_id, var_name)); maps.add_variable(Upvar(var_hir_id, var_name));
} }
} }

View file

@ -222,7 +222,7 @@ impl<'hir> Visitor<'hir> for CheckLoopVisitor<'hir> {
if let Some(break_expr) = opt_expr { if let Some(break_expr) = opt_expr {
let (head, loop_label, loop_kind) = if let Some(loop_id) = loop_id { let (head, loop_label, loop_kind) = if let Some(loop_id) = loop_id {
match self.tcx.hir().expect_expr(loop_id).kind { match self.tcx.hir_expect_expr(loop_id).kind {
hir::ExprKind::Loop(_, label, source, sp) => { hir::ExprKind::Loop(_, label, source, sp) => {
(Some(sp), label, Some(source)) (Some(sp), label, Some(source))
} }

View file

@ -291,7 +291,7 @@ impl<'tcx> ReachableContext<'tcx> {
_ => { _ => {
bug!( bug!(
"found unexpected node kind in worklist: {} ({:?})", "found unexpected node kind in worklist: {} ({:?})",
self.tcx.hir().node_to_string(self.tcx.local_def_id_to_hir_id(search_item)), self.tcx.hir_id_to_string(self.tcx.local_def_id_to_hir_id(search_item)),
node, node,
); );
} }

View file

@ -118,7 +118,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> {
) where ) where
F: FnOnce(&mut Self), F: FnOnce(&mut Self),
{ {
let attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id)); let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs); debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
let depr = attr::find_attr!(attrs, AttributeKind::Deprecation{deprecation, span} => (*deprecation, *span)); let depr = attr::find_attr!(attrs, AttributeKind::Deprecation{deprecation, span} => (*deprecation, *span));
@ -795,7 +795,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
}) => { }) => {
let features = self.tcx.features(); let features = self.tcx.features();
if features.staged_api() { if features.staged_api() {
let attrs = self.tcx.hir().attrs(item.hir_id()); let attrs = self.tcx.hir_attrs(item.hir_id());
let stab = attr::find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span)); let stab = attr::find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span));
// FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem
@ -1034,7 +1034,7 @@ fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
} }
// If this is a path that isn't a use, we don't need to do anything special // If this is a path that isn't a use, we don't need to do anything special
if !matches!(tcx.hir().expect_item(def_id).kind, ItemKind::Use(..)) { if !matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {
return false; return false;
} }

View file

@ -493,7 +493,7 @@ impl<'tcx> EmbargoVisitor<'tcx> {
) { ) {
// Non-opaque macros cannot make other items more accessible than they already are. // Non-opaque macros cannot make other items more accessible than they already are.
let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
let attrs = self.tcx.hir().attrs(hir_id); let attrs = self.tcx.hir_attrs(hir_id);
if attr::find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x) if attr::find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x)
.unwrap_or(Transparency::fallback(md.macro_rules)) .unwrap_or(Transparency::fallback(md.macro_rules))
@ -573,7 +573,7 @@ impl<'tcx> EmbargoVisitor<'tcx> {
// have normal hygiene, so we can treat them like other items without type // have normal hygiene, so we can treat them like other items without type
// privacy and mark them reachable. // privacy and mark them reachable.
DefKind::Macro(_) => { DefKind::Macro(_) => {
let item = self.tcx.hir().expect_item(def_id); let item = self.tcx.hir_expect_item(def_id);
if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind { if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind {
if vis.is_accessible_from(module, self.tcx) { if vis.is_accessible_from(module, self.tcx) {
self.update(def_id, macro_ev, Level::Reachable); self.update(def_id, macro_ev, Level::Reachable);
@ -597,7 +597,7 @@ impl<'tcx> EmbargoVisitor<'tcx> {
DefKind::Struct | DefKind::Union => { DefKind::Struct | DefKind::Union => {
// While structs and unions have type privacy, their fields do not. // While structs and unions have type privacy, their fields do not.
let item = self.tcx.hir().expect_item(def_id); let item = self.tcx.hir_expect_item(def_id);
if let hir::ItemKind::Struct(ref struct_def, _) if let hir::ItemKind::Struct(ref struct_def, _)
| hir::ItemKind::Union(ref struct_def, _) = item.kind | hir::ItemKind::Union(ref struct_def, _) = item.kind
{ {

View file

@ -272,7 +272,7 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
let tcx = tables.tcx; let tcx = tables.tcx;
let did = tables[def_id]; let did = tables[def_id];
let attrs_iter = if let Some(did) = did.as_local() { let attrs_iter = if let Some(did) = did.as_local() {
tcx.hir().attrs(tcx.local_def_id_to_hir_id(did)).iter() tcx.hir_attrs(tcx.local_def_id_to_hir_id(did)).iter()
} else { } else {
tcx.attrs_for_def(did).iter() tcx.attrs_for_def(did).iter()
}; };

View file

@ -509,7 +509,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
hir::MatchSource::TryDesugar(scrut_hir_id), hir::MatchSource::TryDesugar(scrut_hir_id),
) => { ) => {
if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found { if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id); let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind { let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
let arg_expr = args.first().expect("try desugaring call w/out arg"); let arg_expr = args.first().expect("try desugaring call w/out arg");
self.typeck_results self.typeck_results
@ -548,7 +548,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
}) => match source { }) => match source {
hir::MatchSource::TryDesugar(scrut_hir_id) => { hir::MatchSource::TryDesugar(scrut_hir_id) => {
if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found { if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id); let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind { let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
let arg_expr = args.first().expect("try desugaring call w/out arg"); let arg_expr = args.first().expect("try desugaring call w/out arg");
self.typeck_results self.typeck_results

View file

@ -1351,7 +1351,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> {
&& !has_impl_trait(def_id) && !has_impl_trait(def_id)
// FIXME(fn_delegation): In delegation item argument spans are equal to last path // FIXME(fn_delegation): In delegation item argument spans are equal to last path
// segment. This leads to ICE's when emitting `multipart_suggestion`. // segment. This leads to ICE's when emitting `multipart_suggestion`.
&& tcx.hir().opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none() && tcx.hir_opt_delegation_sig_id(expr.hir_id.owner.def_id).is_none()
{ {
let successor = let successor =
method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo())); method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo()));

View file

@ -743,7 +743,7 @@ fn foo(&self) -> Self::T { String::new() }
if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() { if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
let opaque_local_def_id = def_id.as_local(); let opaque_local_def_id = def_id.as_local();
let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id { let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
tcx.hir().expect_opaque_ty(opaque_local_def_id) tcx.hir_expect_opaque_ty(opaque_local_def_id)
} else { } else {
return false; return false;
}; };

View file

@ -1023,7 +1023,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
format!(" for lifetime parameter `{name}`") format!(" for lifetime parameter `{name}`")
} }
infer::UpvarRegion(ref upvar_id, _) => { infer::UpvarRegion(ref upvar_id, _) => {
let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id); let var_name = self.tcx.hir_name(upvar_id.var_path.hir_id);
format!(" for capture of `{var_name}` by closure") format!(" for capture of `{var_name}` by closure")
} }
infer::Nll(..) => bug!("NLL variable found in lexical phase"), infer::Nll(..) => bug!("NLL variable found in lexical phase"),

View file

@ -778,8 +778,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let exp_local_id = exp_def_id.as_local()?; let exp_local_id = exp_def_id.as_local()?;
match ( match (
&self.tcx.hir().expect_opaque_ty(last_local_id), &self.tcx.hir_expect_opaque_ty(last_local_id),
&self.tcx.hir().expect_opaque_ty(exp_local_id), &self.tcx.hir_expect_opaque_ty(exp_local_id),
) { ) {
( (
hir::OpaqueTy { bounds: last_bounds, .. }, hir::OpaqueTy { bounds: last_bounds, .. },

View file

@ -22,7 +22,6 @@ use rustc_hir::{
expr_needs_parens, is_range_literal, expr_needs_parens, is_range_literal,
}; };
use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
use rustc_middle::hir::map;
use rustc_middle::traits::IsConstable; use rustc_middle::traits::IsConstable;
use rustc_middle::ty::error::TypeError; use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::print::{ use rustc_middle::ty::print::{
@ -93,7 +92,7 @@ impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
fn get_from_await_ty<F>( fn get_from_await_ty<F>(
&self, &self,
visitor: AwaitsVisitor, visitor: AwaitsVisitor,
hir: map::Map<'tcx>, tcx: TyCtxt<'tcx>,
ty_matches: F, ty_matches: F,
) -> Option<Span> ) -> Option<Span>
where where
@ -102,7 +101,7 @@ impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
visitor visitor
.awaits .awaits
.into_iter() .into_iter()
.map(|id| hir.expect_expr(id)) .map(|id| tcx.hir_expect_expr(id))
.find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr)))) .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
.map(|expr| expr.span) .map(|expr| expr.span)
} }
@ -2180,8 +2179,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
err: &mut Diag<'_, G>, err: &mut Diag<'_, G>,
obligation: &PredicateObligation<'tcx>, obligation: &PredicateObligation<'tcx>,
) -> bool { ) -> bool {
let hir = self.tcx.hir();
// Attempt to detect an async-await error by looking at the obligation causes, looking // Attempt to detect an async-await error by looking at the obligation causes, looking
// for a coroutine to be present. // for a coroutine to be present.
// //
@ -2350,7 +2347,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
let mut interior_or_upvar_span = None; let mut interior_or_upvar_span = None;
let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, hir, ty_matches); let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
debug!(?from_awaited_ty); debug!(?from_awaited_ty);
// Avoid disclosing internal information to downstream crates. // Avoid disclosing internal information to downstream crates.
@ -2428,7 +2425,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
// Special case the primary error message when send or sync is the trait that was // Special case the primary error message when send or sync is the trait that was
// not implemented. // not implemented.
let hir = self.tcx.hir();
let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) = let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
self.tcx.get_diagnostic_name(trait_pred.def_id()) self.tcx.get_diagnostic_name(trait_pred.def_id())
{ {
@ -2455,7 +2451,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
.parent(coroutine_did) .parent(coroutine_did)
.as_local() .as_local()
.map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did)) .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
.and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
.map(|name| { .map(|name| {
format!("future returned by `{name}` is not {trait_name}") format!("future returned by `{name}` is not {trait_name}")
})?, })?,
@ -2479,7 +2475,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
.parent(coroutine_did) .parent(coroutine_did)
.as_local() .as_local()
.map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did)) .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
.and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
.map(|name| { .map(|name| {
format!("async iterator returned by `{name}` is not {trait_name}") format!("async iterator returned by `{name}` is not {trait_name}")
})?, })?,
@ -2502,7 +2498,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
.parent(coroutine_did) .parent(coroutine_did)
.as_local() .as_local()
.map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did)) .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
.and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
.map(|name| { .map(|name| {
format!("iterator returned by `{name}` is not {trait_name}") format!("iterator returned by `{name}` is not {trait_name}")
})? })?
@ -3569,7 +3565,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
ObligationCauseCode::OpaqueReturnType(expr_info) => { ObligationCauseCode::OpaqueReturnType(expr_info) => {
let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info { let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
let expr_ty = tcx.short_string(expr_ty, err.long_ty_path()); let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
let expr = tcx.hir().expect_expr(hir_id); let expr = tcx.hir_expect_expr(hir_id);
(expr_ty, expr) (expr_ty, expr)
} else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id() } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
&& let body = tcx.hir_body(body_id) && let body = tcx.hir_body(body_id)

View file

@ -21,7 +21,7 @@ pub(crate) fn provide(providers: &mut Providers) {
} }
fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] { fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
let item = tcx.hir().expect_item(def_id); let item = tcx.hir_expect_item(def_id);
match item.kind { match item.kind {
hir::ItemKind::Trait(.., trait_item_refs) => { hir::ItemKind::Trait(.., trait_item_refs) => {
// We collect RPITITs for each trait method's return type and create a // We collect RPITITs for each trait method's return type and create a
@ -96,7 +96,7 @@ fn impl_item_implementor_ids(tcx: TyCtxt<'_>, impl_id: DefId) -> DefIdMap<DefId>
fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem { fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem {
let id = tcx.local_def_id_to_hir_id(def_id); let id = tcx.local_def_id_to_hir_id(def_id);
let parent_def_id = tcx.hir_get_parent_item(id); let parent_def_id = tcx.hir_get_parent_item(id);
let parent_item = tcx.hir().expect_item(parent_def_id.def_id); let parent_item = tcx.hir_expect_item(parent_def_id.def_id);
match parent_item.kind { match parent_item.kind {
hir::ItemKind::Impl(impl_) => { hir::ItemKind::Impl(impl_) => {
if let Some(impl_item_ref) = impl_.items.iter().find(|i| i.id.owner_id.def_id == def_id) if let Some(impl_item_ref) = impl_.items.iter().find(|i| i.id.owner_id.def_id == def_id)
@ -201,7 +201,7 @@ fn associated_types_for_impl_traits_in_associated_fn(
let mut visitor = RPITVisitor { rpits: FxIndexSet::default() }; let mut visitor = RPITVisitor { rpits: FxIndexSet::default() };
if let Some(output) = tcx.hir().get_fn_output(fn_def_id) { if let Some(output) = tcx.hir_get_fn_output(fn_def_id) {
visitor.visit_fn_ret_ty(output); visitor.visit_fn_ret_ty(output);
tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|opaque_ty_def_id| { tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|opaque_ty_def_id| {

View file

@ -161,7 +161,7 @@ fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator<Item = Spa
} }
fn impl_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator<Item = Span> { fn impl_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator<Item = Span> {
let item = tcx.hir().expect_item(def_id); let item = tcx.hir_expect_item(def_id);
if let hir::ItemKind::Impl(impl_) = item.kind { if let hir::ItemKind::Impl(impl_) = item.kind {
let trait_args = impl_ let trait_args = impl_
.of_trait .of_trait

View file

@ -187,7 +187,7 @@ impl<'tcx> OpaqueTypeCollector<'tcx> {
if !hir_id.is_owner() { if !hir_id.is_owner() {
return; return;
} }
let Some(defines) = self.tcx.hir_attrs(hir_id.owner).define_opaque else { let Some(defines) = self.tcx.hir_attr_map(hir_id.owner).define_opaque else {
return; return;
}; };
for &(span, define) in defines { for &(span, define) in defines {

View file

@ -139,12 +139,12 @@ defined in the map. By matching on this, you can find out what sort of
node the `HirId` referred to and also get a pointer to the data node the `HirId` referred to and also get a pointer to the data
itself. Often, you know what sort of node `n` is e.g. if you know itself. Often, you know what sort of node `n` is e.g. if you know
that `n` must be some HIR expression, you can do that `n` must be some HIR expression, you can do
[`tcx.hir().expect_expr(n)`][expect_expr], which will extract and return the [`tcx.hir_expect_expr(n)`][expect_expr], which will extract and return the
[`&hir::Expr`][Expr], panicking if `n` is not in fact an expression. [`&hir::Expr`][Expr], panicking if `n` is not in fact an expression.
[find]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/hir/map/struct.Map.html#method.find [find]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/hir/map/struct.Map.html#method.find
[`Node`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.Node.html [`Node`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.Node.html
[expect_expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/hir/map/struct.Map.html#method.expect_expr [expect_expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.expect_expr
[Expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/struct.Expr.html [Expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/struct.Expr.html
Finally, you can use the HIR map to find the parents of nodes, via Finally, you can use the HIR map to find the parents of nodes, via

View file

@ -181,7 +181,7 @@ pub(crate) fn try_inline_glob(
.filter_map(|child| child.res.opt_def_id()) .filter_map(|child| child.res.opt_def_id())
.filter(|def_id| !cx.tcx.is_doc_hidden(def_id)) .filter(|def_id| !cx.tcx.is_doc_hidden(def_id))
.collect(); .collect();
let attrs = cx.tcx.hir().attrs(import.hir_id()); let attrs = cx.tcx.hir_attrs(import.hir_id());
let mut items = build_module_items( let mut items = build_module_items(
cx, cx,
did, did,
@ -455,7 +455,7 @@ pub(crate) fn build_impl(
} }
let impl_item = match did.as_local() { let impl_item = match did.as_local() {
Some(did) => match &tcx.hir().expect_item(did).kind { Some(did) => match &tcx.hir_expect_item(did).kind {
hir::ItemKind::Impl(impl_) => Some(impl_), hir::ItemKind::Impl(impl_) => Some(impl_),
_ => panic!("`DefID` passed to `build_impl` is not an `impl"), _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
}, },

View file

@ -112,7 +112,7 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<
items.extend(doc.inlined_foreigns.iter().flat_map(|((_, renamed), (res, local_import_id))| { items.extend(doc.inlined_foreigns.iter().flat_map(|((_, renamed), (res, local_import_id))| {
let Some(def_id) = res.opt_def_id() else { return Vec::new() }; let Some(def_id) = res.opt_def_id() else { return Vec::new() };
let name = renamed.unwrap_or_else(|| cx.tcx.item_name(def_id)); let name = renamed.unwrap_or_else(|| cx.tcx.item_name(def_id));
let import = cx.tcx.hir().expect_item(*local_import_id); let import = cx.tcx.hir_expect_item(*local_import_id);
match import.kind { match import.kind {
hir::ItemKind::Use(path, kind) => { hir::ItemKind::Use(path, kind) => {
let hir::UsePath { segments, span, .. } = *path; let hir::UsePath { segments, span, .. } = *path;
@ -125,7 +125,7 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<
items.extend(doc.items.values().flat_map(|(item, renamed, _)| { items.extend(doc.items.values().flat_map(|(item, renamed, _)| {
// Now we actually lower the imports, skipping everything else. // Now we actually lower the imports, skipping everything else.
if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind { if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
let name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id())); let name = renamed.unwrap_or_else(|| cx.tcx.hir_name(item.hir_id()));
clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted) clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted)
} else { } else {
// skip everything else // skip everything else
@ -986,7 +986,7 @@ fn clean_proc_macro<'tcx>(
kind: MacroKind, kind: MacroKind,
cx: &mut DocContext<'tcx>, cx: &mut DocContext<'tcx>,
) -> ItemKind { ) -> ItemKind {
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
if kind == MacroKind::Derive if kind == MacroKind::Derive
&& let Some(derive_name) = && let Some(derive_name) =
hir_attr_lists(attrs, sym::proc_macro_derive).find_map(|mi| mi.ident()) hir_attr_lists(attrs, sym::proc_macro_derive).find_map(|mi| mi.ident())
@ -1019,7 +1019,7 @@ fn clean_fn_or_proc_macro<'tcx>(
name: &mut Symbol, name: &mut Symbol,
cx: &mut DocContext<'tcx>, cx: &mut DocContext<'tcx>,
) -> ItemKind { ) -> ItemKind {
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
let macro_kind = attrs.iter().find_map(|a| { let macro_kind = attrs.iter().find_map(|a| {
if a.has_name(sym::proc_macro) { if a.has_name(sym::proc_macro) {
Some(MacroKind::Bang) Some(MacroKind::Bang)
@ -1756,7 +1756,7 @@ fn maybe_expand_private_type_alias<'tcx>(
let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id()) let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
&& !cx.current_type_aliases.contains_key(&def_id.to_def_id()) && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
{ {
&cx.tcx.hir().expect_item(def_id).kind &cx.tcx.hir_expect_item(def_id).kind
} else { } else {
return None; return None;
}; };
@ -2762,7 +2762,7 @@ fn clean_maybe_renamed_item<'tcx>(
use hir::ItemKind; use hir::ItemKind;
let def_id = item.owner_id.to_def_id(); let def_id = item.owner_id.to_def_id();
let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id())); let mut name = renamed.unwrap_or_else(|| cx.tcx.hir_name(item.hir_id()));
cx.with_param_env(def_id, |cx| { cx.with_param_env(def_id, |cx| {
let kind = match item.kind { let kind = match item.kind {
ItemKind::Static(ty, mutability, body_id) => StaticItem(Static { ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
@ -2937,7 +2937,7 @@ fn clean_extern_crate<'tcx>(
let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE); let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
// this is the ID of the crate itself // this is the ID of the crate itself
let crate_def_id = cnum.as_def_id(); let crate_def_id = cnum.as_def_id();
let attrs = cx.tcx.hir().attrs(krate.hir_id()); let attrs = cx.tcx.hir_attrs(krate.hir_id());
let ty_vis = cx.tcx.visibility(krate.owner_id); let ty_vis = cx.tcx.visibility(krate.owner_id);
let please_inline = ty_vis.is_public() let please_inline = ty_vis.is_public()
&& attrs.iter().any(|a| { && attrs.iter().any(|a| {
@ -3006,7 +3006,7 @@ fn clean_use_statement_inner<'tcx>(
} }
let visibility = cx.tcx.visibility(import.owner_id); let visibility = cx.tcx.visibility(import.owner_id);
let attrs = cx.tcx.hir().attrs(import.hir_id()); let attrs = cx.tcx.hir_attrs(import.hir_id());
let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline); let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline);
let pub_underscore = visibility.is_public() && name == kw::Underscore; let pub_underscore = visibility.is_public() && name == kw::Underscore;
let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id); let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);

View file

@ -216,7 +216,7 @@ pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions
let collector = rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| { let collector = rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
let crate_name = tcx.crate_name(LOCAL_CRATE).to_string(); let crate_name = tcx.crate_name(LOCAL_CRATE).to_string();
let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID); let crate_attrs = tcx.hir_attrs(CRATE_HIR_ID);
let opts = scrape_test_config(crate_name, crate_attrs, args_path); let opts = scrape_test_config(crate_name, crate_attrs, args_path);
let enable_per_target_ignores = options.enable_per_target_ignores; let enable_per_target_ignores = options.enable_per_target_ignores;

View file

@ -95,7 +95,7 @@ impl HirCollector<'_> {
sp: Span, sp: Span,
nested: F, nested: F,
) { ) {
let ast_attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id)); let ast_attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
if let Some(ref cfg) = if let Some(ref cfg) =
extract_cfg_from_attrs(ast_attrs.iter(), self.tcx, &FxHashSet::default()) extract_cfg_from_attrs(ast_attrs.iter(), self.tcx, &FxHashSet::default())
&& !cfg.matches(&self.tcx.sess.psess, Some(self.tcx.features())) && !cfg.matches(&self.tcx.sess.psess, Some(self.tcx.features()))

View file

@ -143,7 +143,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
&& self.cx.tcx.has_attr(def_id, sym::macro_export) && self.cx.tcx.has_attr(def_id, sym::macro_export)
&& inserted.insert(def_id) && inserted.insert(def_id)
{ {
let item = self.cx.tcx.hir().expect_item(local_def_id); let item = self.cx.tcx.hir_expect_item(local_def_id);
top_level_module top_level_module
.items .items
.insert((local_def_id, Some(item.ident.name)), (item, None, None)); .insert((local_def_id, Some(item.ident.name)), (item, None, None));
@ -153,8 +153,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
self.cx.cache.hidden_cfg = self self.cx.cache.hidden_cfg = self
.cx .cx
.tcx .tcx
.hir() .hir_attrs(CRATE_HIR_ID)
.attrs(CRATE_HIR_ID)
.iter() .iter()
.filter(|attr| attr.has_name(sym::doc)) .filter(|attr| attr.has_name(sym::doc))
.flat_map(|attr| attr.meta_item_list().into_iter().flatten()) .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
@ -245,7 +244,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
}; };
let document_hidden = self.cx.render_options.document_hidden; let document_hidden = self.cx.render_options.document_hidden;
let use_attrs = tcx.hir().attrs(tcx.local_def_id_to_hir_id(def_id)); let use_attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
// Don't inline `doc(hidden)` imports so they can be stripped at a later stage. // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
let is_no_inline = hir_attr_lists(use_attrs, sym::doc).has_word(sym::no_inline) let is_no_inline = hir_attr_lists(use_attrs, sym::doc).has_word(sym::no_inline)
|| (document_hidden && hir_attr_lists(use_attrs, sym::doc).has_word(sym::hidden)); || (document_hidden && hir_attr_lists(use_attrs, sym::doc).has_word(sym::hidden));
@ -449,7 +448,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
continue; continue;
} }
let attrs = tcx.hir().attrs(tcx.local_def_id_to_hir_id(item.owner_id.def_id)); let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(item.owner_id.def_id));
// If there was a private module in the current path then don't bother inlining // If there was a private module in the current path then don't bother inlining
// anything as it will probably be stripped anyway. // anything as it will probably be stripped anyway.

View file

@ -465,7 +465,7 @@ impl Attributes {
impl<'tcx> LateLintPass<'tcx> for Attributes { impl<'tcx> LateLintPass<'tcx> for Attributes {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
if is_relevant_item(cx, item) { if is_relevant_item(cx, item) {
inline_always::check(cx, item.span, item.ident.name, attrs); inline_always::check(cx, item.span, item.ident.name, attrs);
} }
@ -474,13 +474,13 @@ impl<'tcx> LateLintPass<'tcx> for Attributes {
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) { fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
if is_relevant_impl(cx, item) { if is_relevant_impl(cx, item) {
inline_always::check(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id())); inline_always::check(cx, item.span, item.ident.name, cx.tcx.hir_attrs(item.hir_id()));
} }
} }
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
if is_relevant_trait(cx, item) { if is_relevant_trait(cx, item) {
inline_always::check(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id())); inline_always::check(cx, item.span, item.ident.name, cx.tcx.hir_attrs(item.hir_id()));
} }
} }
} }

View file

@ -97,7 +97,7 @@ fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: ty::GenericArgsR
} }
fn has_c_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool { fn has_c_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
let attrs = cx.tcx.hir().attrs(hir_id); let attrs = cx.tcx.hir_attrs(hir_id);
find_attr!(attrs, AttributeKind::Repr(r) if r.iter().any(|(x, _)| *x == ReprAttr::ReprC)) find_attr!(attrs, AttributeKind::Repr(r) if r.iter().any(|(x, _)| *x == ReprAttr::ReprC))
} }

View file

@ -197,9 +197,9 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls {
&& let ImplItemKind::Fn(_, b) = &impl_item.kind && let ImplItemKind::Fn(_, b) = &impl_item.kind
&& let Body { value: func_expr, .. } = cx.tcx.hir_body(*b) && let Body { value: func_expr, .. } = cx.tcx.hir_body(*b)
&& let &ty::Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind() && let &ty::Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind()
&& let attrs = cx.tcx.hir().attrs(item.hir_id()) && let attrs = cx.tcx.hir_attrs(item.hir_id())
&& !attrs.iter().any(|attr| attr.doc_str().is_some()) && !attrs.iter().any(|attr| attr.doc_str().is_some())
&& cx.tcx.hir().attrs(impl_item_hir).is_empty() && cx.tcx.hir_attrs(impl_item_hir).is_empty()
{ {
if adt_def.is_struct() { if adt_def.is_struct() {
check_struct(cx, item, self_ty, func_expr, adt_def, args, cx.tcx.typeck_body(*b)); check_struct(cx, item, self_ty, func_expr, adt_def, args, cx.tcx.typeck_body(*b));

View file

@ -384,7 +384,7 @@ fn check_unsafe_derive_deserialize<'tcx>(
.tcx .tcx
.inherent_impls(def.did()) .inherent_impls(def.did())
.iter() .iter()
.map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local())) .map(|imp_did| cx.tcx.hir_expect_item(imp_did.expect_local()))
.any(|imp| has_unsafe(cx, imp)) .any(|imp| has_unsafe(cx, imp))
{ {
span_lint_hir_and_then( span_lint_hir_and_then(

View file

@ -25,7 +25,7 @@ pub fn check(
&& cx && cx
.tcx .tcx
.hir_parent_iter(owner_id.into()) .hir_parent_iter(owner_id.into())
.any(|(id, _node)| is_doc_hidden(cx.tcx.hir().attrs(id))) .any(|(id, _node)| is_doc_hidden(cx.tcx.hir_attrs(id)))
{ {
return; return;
} }

View file

@ -163,7 +163,6 @@ impl<'tcx> Delegate<'tcx> for EscapeDelegate<'_, 'tcx> {
fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) { fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
if cmt.place.projections.is_empty() { if cmt.place.projections.is_empty() {
let map = &self.cx.tcx.hir();
if is_argument(self.cx.tcx, cmt.hir_id) { if is_argument(self.cx.tcx, cmt.hir_id) {
// Skip closure arguments // Skip closure arguments
let parent_id = self.cx.tcx.parent_hir_id(cmt.hir_id); let parent_id = self.cx.tcx.parent_hir_id(cmt.hir_id);
@ -174,7 +173,7 @@ impl<'tcx> Delegate<'tcx> for EscapeDelegate<'_, 'tcx> {
// skip if there is a `self` parameter binding to a type // skip if there is a `self` parameter binding to a type
// that contains `Self` (i.e.: `self: Box<Self>`), see #4804 // that contains `Self` (i.e.: `self: Box<Self>`), see #4804
if let Some(trait_self_ty) = self.trait_self_ty { if let Some(trait_self_ty) = self.trait_self_ty {
if map.name(cmt.hir_id) == kw::SelfLower && cmt.place.ty().contains(trait_self_ty) { if self.cx.tcx.hir_name(cmt.hir_id) == kw::SelfLower && cmt.place.ty().contains(trait_self_ty) {
return; return;
} }
} }

View file

@ -84,7 +84,7 @@ impl LateLintPass<'_> for ExhaustiveItems {
_ => return, _ => return,
}; };
if cx.effective_visibilities.is_exported(item.owner_id.def_id) if cx.effective_visibilities.is_exported(item.owner_id.def_id)
&& let attrs = cx.tcx.hir().attrs(item.hir_id()) && let attrs = cx.tcx.hir_attrs(item.hir_id())
&& !attrs.iter().any(|a| a.has_name(sym::non_exhaustive)) && !attrs.iter().any(|a| a.has_name(sym::non_exhaustive))
&& fields.iter().all(|f| cx.tcx.visibility(f.def_id).is_public()) && fields.iter().all(|f| cx.tcx.visibility(f.def_id).is_public())
{ {

View file

@ -209,9 +209,8 @@ impl FormatImplExpr<'_, '_> {
// Handle dereference of &self -> self that is equivalent (i.e. via *self in fmt() impl) // Handle dereference of &self -> self that is equivalent (i.e. via *self in fmt() impl)
// Since the argument to fmt is itself a reference: &self // Since the argument to fmt is itself a reference: &self
let reference = peel_ref_operators(self.cx, arg); let reference = peel_ref_operators(self.cx, arg);
let map = self.cx.tcx.hir();
// Is the reference self? // Is the reference self?
if path_to_local(reference).map(|x| map.name(x)) == Some(kw::SelfLower) { if path_to_local(reference).map(|x| self.cx.tcx.hir_name(x)) == Some(kw::SelfLower) {
let FormatTraitNames { name, .. } = self.format_trait_impl; let FormatTraitNames { name, .. } = self.format_trait_impl;
span_lint( span_lint(
self.cx, self.cx,

View file

@ -43,8 +43,7 @@ impl<'tcx> LateLintPass<'tcx> for FourForwardSlashes {
let sm = cx.sess().source_map(); let sm = cx.sess().source_map();
let mut span = cx let mut span = cx
.tcx .tcx
.hir() .hir_attrs(item.hir_id())
.attrs(item.hir_id())
.iter() .iter()
.filter(|i| i.is_doc_comment()) .filter(|i| i.is_doc_comment())
.fold(item.span.shrink_to_lo(), |span, attr| span.to(attr.span())); .fold(item.span.shrink_to_lo(), |span, attr| span.to(attr.span()));

View file

@ -21,7 +21,7 @@ use core::ops::ControlFlow;
use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT}; use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT};
pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
let attr = cx.tcx.get_attr(item.owner_id, sym::must_use); let attr = cx.tcx.get_attr(item.owner_id, sym::must_use);
if let hir::ItemKind::Fn { if let hir::ItemKind::Fn {
ref sig, ref sig,
@ -51,7 +51,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Imp
if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind { if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id); let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id);
let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
let attr = cx.tcx.get_attr(item.owner_id, sym::must_use); let attr = cx.tcx.get_attr(item.owner_id, sym::must_use);
if let Some(attr) = attr { if let Some(attr) = attr {
check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr, attrs, sig); check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr, attrs, sig);
@ -74,7 +74,7 @@ pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Tr
let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id); let is_public = cx.effective_visibilities.is_exported(item.owner_id.def_id);
let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
let attrs = cx.tcx.hir().attrs(item.hir_id()); let attrs = cx.tcx.hir_attrs(item.hir_id());
let attr = cx.tcx.get_attr(item.owner_id, sym::must_use); let attr = cx.tcx.get_attr(item.owner_id, sym::must_use);
if let Some(attr) = attr { if let Some(attr) = attr {
check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr, attrs, sig); check_needless_must_use(cx, sig.decl, item.owner_id, item.span, fn_header_span, attr, attrs, sig);

View file

@ -182,7 +182,7 @@ fn suggestion<'tcx>(
} }
fn field_with_attrs_span(tcx: TyCtxt<'_>, field: &hir::ExprField<'_>) -> Span { fn field_with_attrs_span(tcx: TyCtxt<'_>, field: &hir::ExprField<'_>) -> Span {
if let Some(attr) = tcx.hir().attrs(field.hir_id).first() { if let Some(attr) = tcx.hir_attrs(field.hir_id).first() {
field.span.with_lo(attr.span().lo()) field.span.with_lo(attr.span().lo())
} else { } else {
field.span field.span

View file

@ -34,8 +34,7 @@ impl<'tcx> LateLintPass<'tcx> for InlineFnWithoutBody {
if let TraitItemKind::Fn(_, TraitFn::Required(_)) = item.kind if let TraitItemKind::Fn(_, TraitFn::Required(_)) = item.kind
&& let Some(attr) = cx && let Some(attr) = cx
.tcx .tcx
.hir() .hir_attrs(item.hir_id())
.attrs(item.hir_id())
.iter() .iter()
.find(|a| a.has_name(sym::inline)) .find(|a| a.has_name(sym::inline))
{ {

View file

@ -98,7 +98,7 @@ impl LateLintPass<'_> for MacroUseImports {
if cx.sess().opts.edition >= Edition::Edition2018 if cx.sess().opts.edition >= Edition::Edition2018
&& let hir::ItemKind::Use(path, _kind) = &item.kind && let hir::ItemKind::Use(path, _kind) = &item.kind
&& let hir_id = item.hir_id() && let hir_id = item.hir_id()
&& let attrs = cx.tcx.hir().attrs(hir_id) && let attrs = cx.tcx.hir_attrs(hir_id)
&& let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use)) && let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use))
&& let Some(id) = path.res.iter().find_map(|res| match res { && let Some(id) = path.res.iter().find_map(|res| match res {
Res::Def(DefKind::Mod, id) => Some(id), Res::Def(DefKind::Mod, id) => Some(id),

View file

@ -89,11 +89,11 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
match item.kind { match item.kind {
ItemKind::Enum(def, _) if def.variants.len() > 1 => { ItemKind::Enum(def, _) if def.variants.len() > 1 => {
let iter = def.variants.iter().filter_map(|v| { let iter = def.variants.iter().filter_map(|v| {
(matches!(v.data, VariantData::Unit(_, _)) && is_doc_hidden(cx.tcx.hir().attrs(v.hir_id))) (matches!(v.data, VariantData::Unit(_, _)) && is_doc_hidden(cx.tcx.hir_attrs(v.hir_id)))
.then_some((v.def_id, v.span)) .then_some((v.def_id, v.span))
}); });
if let Ok((id, span)) = iter.exactly_one() if let Ok((id, span)) = iter.exactly_one()
&& !attr::contains_name(cx.tcx.hir().attrs(item.hir_id()), sym::non_exhaustive) && !attr::contains_name(cx.tcx.hir_attrs(item.hir_id()), sym::non_exhaustive)
{ {
self.potential_enums.push((item.owner_id.def_id, id, item.span, span)); self.potential_enums.push((item.owner_id.def_id, id, item.span, span));
} }
@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
"this seems like a manual implementation of the non-exhaustive pattern", "this seems like a manual implementation of the non-exhaustive pattern",
|diag| { |diag| {
if let Some(non_exhaustive) = if let Some(non_exhaustive) =
attr::find_by_name(cx.tcx.hir().attrs(item.hir_id()), sym::non_exhaustive) attr::find_by_name(cx.tcx.hir_attrs(item.hir_id()), sym::non_exhaustive)
{ {
diag.span_note(non_exhaustive.span(), "the struct is already non-exhaustive"); diag.span_note(non_exhaustive.span(), "the struct is already non-exhaustive");
} else { } else {

View file

@ -42,7 +42,7 @@ pub(super) fn check_match<'tcx>(
cx, cx,
scrutinee, scrutinee,
arms.iter() arms.iter()
.map(|arm| (cx.tcx.hir().attrs(arm.hir_id), Some(arm.pat), arm.body, arm.guard)), .map(|arm| (cx.tcx.hir_attrs(arm.hir_id), Some(arm.pat), arm.body, arm.guard)),
e, e,
false, false,
) )

View file

@ -75,7 +75,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) {
HirIdMapEntry::Occupied(entry) => return *entry.get() == b_id, HirIdMapEntry::Occupied(entry) => return *entry.get() == b_id,
} }
// the names technically don't have to match; this makes the lint more conservative // the names technically don't have to match; this makes the lint more conservative
&& cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id) && cx.tcx.hir_name(a_id) == cx.tcx.hir_name(b_id)
&& cx.typeck_results().expr_ty(a) == cx.typeck_results().expr_ty(b) && cx.typeck_results().expr_ty(a) == cx.typeck_results().expr_ty(b)
&& pat_contains_local(lhs.pat, a_id) && pat_contains_local(lhs.pat, a_id)
&& pat_contains_local(rhs.pat, b_id) && pat_contains_local(rhs.pat, b_id)

View file

@ -41,7 +41,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_
fn is_under_cfg(cx: &LateContext<'_>, id: HirId) -> bool { fn is_under_cfg(cx: &LateContext<'_>, id: HirId) -> bool {
cx.tcx cx.tcx
.hir_parent_id_iter(id) .hir_parent_id_iter(id)
.any(|id| cx.tcx.hir().attrs(id).iter().any(|attr| attr.has_name(sym::cfg))) .any(|id| cx.tcx.hir_attrs(id).iter().any(|attr| attr.has_name(sym::cfg)))
} }
/// Similar to [`clippy_utils::expr_or_init`], but does not go up the chain if the initialization /// Similar to [`clippy_utils::expr_or_init`], but does not go up the chain if the initialization

View file

@ -4731,7 +4731,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
} }
let name = impl_item.ident.name.as_str(); let name = impl_item.ident.name.as_str();
let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id()).def_id; let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let item = cx.tcx.hir().expect_item(parent); let item = cx.tcx.hir_expect_item(parent);
let self_ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let self_ty = cx.tcx.type_of(item.owner_id).instantiate_identity();
let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })); let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));

View file

@ -182,7 +182,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
} }
fn check_crate(&mut self, cx: &LateContext<'tcx>) { fn check_crate(&mut self, cx: &LateContext<'tcx>) {
let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID); let attrs = cx.tcx.hir_attrs(hir::CRATE_HIR_ID);
self.check_missing_docs_attrs(cx, CRATE_DEF_ID, attrs, cx.tcx.def_span(CRATE_DEF_ID), "the", "crate"); self.check_missing_docs_attrs(cx, CRATE_DEF_ID, attrs, cx.tcx.def_span(CRATE_DEF_ID), "the", "crate");
} }
@ -224,7 +224,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id()); let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
let attrs = cx.tcx.hir().attrs(it.hir_id()); let attrs = cx.tcx.hir_attrs(it.hir_id());
if !is_from_proc_macro(cx, it) { if !is_from_proc_macro(cx, it) {
self.check_missing_docs_attrs(cx, it.owner_id.def_id, attrs, it.span, article, desc); self.check_missing_docs_attrs(cx, it.owner_id.def_id, attrs, it.span, article, desc);
} }
@ -234,7 +234,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx hir::TraitItem<'_>) { fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx hir::TraitItem<'_>) {
let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id()); let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
let attrs = cx.tcx.hir().attrs(trait_item.hir_id()); let attrs = cx.tcx.hir_attrs(trait_item.hir_id());
if !is_from_proc_macro(cx, trait_item) { if !is_from_proc_macro(cx, trait_item) {
self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, attrs, trait_item.span, article, desc); self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, attrs, trait_item.span, article, desc);
} }
@ -252,7 +252,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
} }
let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id()); let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
let attrs = cx.tcx.hir().attrs(impl_item.hir_id()); let attrs = cx.tcx.hir_attrs(impl_item.hir_id());
if !is_from_proc_macro(cx, impl_item) { if !is_from_proc_macro(cx, impl_item) {
self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, attrs, impl_item.span, article, desc); self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, attrs, impl_item.span, article, desc);
} }
@ -261,7 +261,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
fn check_field_def(&mut self, cx: &LateContext<'tcx>, sf: &'tcx hir::FieldDef<'_>) { fn check_field_def(&mut self, cx: &LateContext<'tcx>, sf: &'tcx hir::FieldDef<'_>) {
if !sf.is_positional() { if !sf.is_positional() {
let attrs = cx.tcx.hir().attrs(sf.hir_id); let attrs = cx.tcx.hir_attrs(sf.hir_id);
if !is_from_proc_macro(cx, sf) { if !is_from_proc_macro(cx, sf) {
self.check_missing_docs_attrs(cx, sf.def_id, attrs, sf.span, "a", "struct field"); self.check_missing_docs_attrs(cx, sf.def_id, attrs, sf.span, "a", "struct field");
} }
@ -270,7 +270,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
} }
fn check_variant(&mut self, cx: &LateContext<'tcx>, v: &'tcx hir::Variant<'_>) { fn check_variant(&mut self, cx: &LateContext<'tcx>, v: &'tcx hir::Variant<'_>) {
let attrs = cx.tcx.hir().attrs(v.hir_id); let attrs = cx.tcx.hir_attrs(v.hir_id);
if !is_from_proc_macro(cx, v) { if !is_from_proc_macro(cx, v) {
self.check_missing_docs_attrs(cx, v.def_id, attrs, v.span, "a", "variant"); self.check_missing_docs_attrs(cx, v.def_id, attrs, v.span, "a", "variant");
} }

Some files were not shown because too many files have changed in this diff Show more