diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index cccfb112ec2b7..f20b979588c57 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -264,11 +264,14 @@ impl<'hir> LoweringContext<'_, 'hir> { .flatten() }) .flatten(), - None => self - .tcx - .get_all_attrs(*def_id) - .iter() - .find(|base_attr| (addition_info.equals)(base_attr)), + None => + { + #[allow(deprecated)] + self.tcx + .get_all_attrs(*def_id) + .iter() + .find(|base_attr| (addition_info.equals)(base_attr)) + } }; if let Some(original_attr) = original_attr { diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index b034e250b58d0..5b31c421bf346 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -7,7 +7,6 @@ use rustc_ast_pretty::pprust::expr_to_string; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::msg; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::definitions::DefPathData; use rustc_hir::{HirId, Target, find_attr}; @@ -805,7 +804,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) { if self.tcx.features().async_fn_track_caller() && let Some(attrs) = self.attrs.get(&outer_hir_id.local_id) - && find_attr!(*attrs, AttributeKind::TrackCaller(_)) + && find_attr!(*attrs, TrackCaller(_)) { let unstable_span = self.mark_span_with_reason( DesugaringKind::Async, @@ -1072,8 +1071,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let (binder_clause, generic_params) = self.lower_closure_binder(binder); let (body_id, closure_kind) = self.with_new_scopes(fn_decl_span, move |this| { - - let mut coroutine_kind = find_attr!(attrs, AttributeKind::Coroutine(_) => hir::CoroutineKind::Coroutine(Movability::Movable)); + let mut coroutine_kind = find_attr!(attrs, Coroutine(_) => hir::CoroutineKind::Coroutine(Movability::Movable)); // FIXME(contracts): Support contracts on closures? let body_id = this.lower_fn_body(decl, None, |this| { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 8ae117f62786f..4f58fef2d24c3 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -243,7 +243,7 @@ impl<'hir> LoweringContext<'_, 'hir> { vis_span, span: self.lower_span(i.span), has_delayed_lints: !self.delayed_lints.is_empty(), - eii: find_attr!(attrs, AttributeKind::EiiImpls(..) | AttributeKind::EiiDeclaration(..)), + eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)), }; self.arena.alloc(item) } @@ -707,10 +707,7 @@ impl<'hir> LoweringContext<'_, 'hir> { vis_span, span: this.lower_span(use_tree.span), has_delayed_lints: !this.delayed_lints.is_empty(), - eii: find_attr!( - attrs, - AttributeKind::EiiImpls(..) | AttributeKind::EiiDeclaration(..) - ), + eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)), }; hir::OwnerNode::Item(this.arena.alloc(item)) }); @@ -1415,9 +1412,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // create a fake body so that the entire rest of the compiler doesn't have to deal with // this as a special case. return self.lower_fn_body(decl, contract, |this| { - if find_attr!(attrs, AttributeKind::RustcIntrinsic) - || this.tcx.is_sdylib_interface_build() - { + if find_attr!(attrs, RustcIntrinsic) || this.tcx.is_sdylib_interface_build() { let span = this.lower_span(span); let empty_block = hir::Block { hir_id: this.next_id(), @@ -1695,7 +1690,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let safety = self.lower_safety(h.safety, default_safety); // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so. - let safety = if find_attr!(attrs, AttributeKind::TargetFeature { was_forced: false, .. }) + let safety = if find_attr!(attrs, TargetFeature { was_forced: false, .. }) && safety.is_safe() && !self.tcx.sess.target.is_like_wasm { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index c5ec53af6e505..24a7215ddb385 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -47,7 +47,6 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::spawn; use rustc_data_structures::tagged_ptr::TaggedRef; use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::{DefPathData, DisambiguatorState}; @@ -255,10 +254,10 @@ impl ResolverAstLowering { return None; } + // we can use parsed attrs here since for other crates they're already available find_attr!( - // we can use parsed attrs here since for other crates they're already available - tcx.get_all_attrs(def_id), - AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes + tcx, def_id, + RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes ) .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect()) } diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 419d56d8059a2..2bd5b9a130d1c 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -854,7 +854,6 @@ impl CombineAttributeParser for RustcMirParser { .collect() } } - pub(crate) struct RustcNonConstTraitMethodParser; impl NoArgsAttributeParser for RustcNonConstTraitMethodParser { @@ -1252,24 +1251,6 @@ impl SingleAttributeParser for RustcDefPath { } } -pub(crate) struct RustcIntrinsicParser; - -impl NoArgsAttributeParser for RustcIntrinsicParser { - const PATH: &[Symbol] = &[sym::rustc_intrinsic]; - const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; - const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]); - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsic; -} - -pub(crate) struct RustcIntrinsicConstStableIndirectParser; - -impl NoArgsAttributeParser for RustcIntrinsicConstStableIndirectParser { - const PATH: &'static [Symbol] = &[sym::rustc_intrinsic_const_stable_indirect]; - const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; - const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]); - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsicConstStableIndirect; -} - pub(crate) struct RustcStrictCoherenceParser; impl NoArgsAttributeParser for RustcStrictCoherenceParser { @@ -1343,3 +1324,21 @@ impl SingleAttributeParser for RustcDocPrimitiveParser { Some(AttributeKind::RustcDocPrimitive(cx.attr_span, value_str)) } } + +pub(crate) struct RustcIntrinsicParser; + +impl NoArgsAttributeParser for RustcIntrinsicParser { + const PATH: &[Symbol] = &[sym::rustc_intrinsic]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsic; +} + +pub(crate) struct RustcIntrinsicConstStableIndirectParser; + +impl NoArgsAttributeParser for RustcIntrinsicConstStableIndirectParser { + const PATH: &'static [Symbol] = &[sym::rustc_intrinsic_const_stable_indirect]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsicConstStableIndirect; +} diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index acd01be470709..dd6eb17947577 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -7,7 +7,6 @@ use std::str::FromStr; use polonius_engine::{Algorithm, AllFacts, Output}; use rustc_data_structures::frozen::Frozen; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_index::IndexSlice; use rustc_middle::mir::pretty::PrettyPrintMirOptions; @@ -296,7 +295,7 @@ pub(super) fn dump_annotation<'tcx, 'infcx>( ) { let tcx = infcx.tcx; let base_def_id = tcx.typeck_root_def_id(body.source.def_id()); - if !find_attr!(tcx.get_all_attrs(base_def_id), AttributeKind::RustcRegions) { + if !find_attr!(tcx, base_def_id, RustcRegions) { return; } diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index b5ab26aea4922..546fa87ff5612 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -460,7 +460,8 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( { to_add.push(create_alloc_family_attr(cx.llcx)); if let Some(instance) = instance - && let Some(name) = find_attr!(tcx.get_all_attrs(instance.def_id()), rustc_hir::attrs::AttributeKind::RustcAllocatorZeroedVariant {name} => name) + && let Some(name) = + find_attr!(tcx, instance.def_id(), RustcAllocatorZeroedVariant {name} => name) { to_add.push(llvm::CreateAttrStringValue( cx.llcx, diff --git a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs index 081fe0aa91aa4..9858d9335dc6f 100644 --- a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs +++ b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs @@ -28,7 +28,7 @@ use std::fmt; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{DiagArgValue, IntoDiagArg}; -use rustc_hir::attrs::{AttributeKind, CguFields, CguKind}; +use rustc_hir::attrs::{CguFields, CguKind}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir::{self as hir, find_attr}; use rustc_middle::mir::mono::CodegenUnitNameBuilder; @@ -89,7 +89,7 @@ struct AssertModuleSource<'tcx> { impl<'tcx> AssertModuleSource<'tcx> { fn check_attrs(&mut self, attrs: &[hir::Attribute]) { for &(span, cgu_fields) in find_attr!(attrs, - AttributeKind::RustcCguTestAttr(e) => e) + RustcCguTestAttr(e) => e) .into_iter() .flatten() { diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 87a043fbdf245..8ffab7a4d8f73 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -18,7 +18,6 @@ use rustc_errors::{ Level, MultiSpan, Style, Suggestions, catch_fatal_errors, }; use rustc_fs_util::link_or_copy; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_incremental::{ copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess, @@ -454,8 +453,7 @@ pub(crate) fn start_async_codegen( ) -> OngoingCodegen { let (coordinator_send, coordinator_receive) = channel(); - let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID); - let no_builtins = find_attr!(crate_attrs, AttributeKind::NoBuiltins); + let no_builtins = find_attr!(tcx, crate, NoBuiltins); let crate_info = CrateInfo::new(tcx, target_cpu); diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 85c8890d661c5..0d3fc63a69bd8 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -13,8 +13,8 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; use rustc_data_structures::unord::UnordMap; -use rustc_hir::attrs::{AttributeKind, DebuggerVisualizerType, OptimizeAttr}; -use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE}; +use rustc_hir::attrs::{DebuggerVisualizerType, OptimizeAttr}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ItemId, Target, find_attr}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; @@ -894,7 +894,7 @@ impl CrateInfo { let linked_symbols = crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect(); let local_crate_name = tcx.crate_name(LOCAL_CRATE); - let windows_subsystem = find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::WindowsSubsystem(kind, _) => *kind); + let windows_subsystem = find_attr!(tcx, crate, WindowsSubsystem(kind, _) => *kind); // This list is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index edd73f418036b..6b0d46f5dc5d1 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -230,9 +230,7 @@ fn process_builtin_attrs( for i in impls { let foreign_item = match i.resolution { EiiImplResolution::Macro(def_id) => { - let Some(extern_item) = find_attr!( - tcx.get_all_attrs(def_id), - AttributeKind::EiiDeclaration(target) => target.foreign_item + let Some(extern_item) = find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item ) else { tcx.dcx().span_delayed_bug( i.span, @@ -352,8 +350,7 @@ fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut Code // 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. - let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID); - let no_builtins = find_attr!(crate_attrs, AttributeKind::NoBuiltins); + let no_builtins = find_attr!(tcx, crate, NoBuiltins); if no_builtins { codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; } @@ -483,9 +480,8 @@ fn check_result( .map(|features| (features.name.as_str(), true)) .collect(), ) { - let span = - find_attr!(tcx.get_all_attrs(did), AttributeKind::TargetFeature{attr_span: span, ..} => *span) - .unwrap_or_else(|| tcx.def_span(did)); + let span = find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span) + .unwrap_or_else(|| tcx.def_span(did)); tcx.dcx() .create_err(errors::TargetFeatureDisableOrEnable { @@ -504,7 +500,7 @@ fn handle_lang_items( attrs: &[Attribute], codegen_fn_attrs: &mut CodegenFnAttrs, ) { - let lang_item = find_attr!(attrs, AttributeKind::Lang(lang, _) => lang); + let lang_item = find_attr!(attrs, Lang(lang, _) => lang); // Weak lang items have the same semantics as "std internal" symbols in the // sense that they're preserved through all our LTO passes and only @@ -583,7 +579,8 @@ fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs }; // Check for a sanitize annotation directly on this def. - if let Some((on_set, off_set, rtsan)) = find_attr!(tcx.get_all_attrs(did), AttributeKind::Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan)) + if let Some((on_set, off_set, rtsan)) = + find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan)) { // the on set is the set of sanitizers explicitly enabled. // we mask those out since we want the set of disabled sanitizers here @@ -624,6 +621,7 @@ fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option { /// panic, unless we introduced a bug when parsing the autodiff macro. //FIXME(jdonszelmann): put in the main loop. No need to have two..... :/ Let's do that when we make autodiff parsed. pub fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option { + #[allow(deprecated)] let attrs = tcx.get_attrs(id, sym::rustc_autodiff); let attrs = attrs.filter(|attr| attr.has_name(sym::rustc_autodiff)).collect::>(); diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 9c9a921bd62d5..e4f99be339df5 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -7,7 +7,6 @@ use std::ops::Deref; use rustc_data_structures::assert_matches; use rustc_errors::{Diag, ErrorGuaranteed}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem, find_attr}; @@ -216,7 +215,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { return; } - if !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcDoNotConstCheck) { + if !find_attr!(tcx, def_id, RustcDoNotConstCheck) { self.visit_body(body); } diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index 1adba200caaf2..3f4527a8750b6 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -5,7 +5,6 @@ //! it finds operations that are invalid in a certain context. use rustc_errors::DiagCtxtHandle; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, find_attr}; use rustc_middle::ty::{self, PolyFnSig, TyCtxt}; @@ -81,9 +80,7 @@ pub fn rustc_allow_const_fn_unstable( def_id: LocalDefId, feature_gate: Symbol, ) -> bool { - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - - find_attr!(attrs, AttributeKind::RustcAllowConstFnUnstable(syms, _) if syms.contains(&feature_gate)) + find_attr!(tcx, def_id, RustcAllowConstFnUnstable(syms, _) if syms.contains(&feature_gate)) } /// Returns `true` if the given `def_id` (trait or function) is "safe to expose on stable". diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index 6189d9321dc09..34d4ce9f9f2c2 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; @@ -36,7 +35,7 @@ pub fn check_live_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) { return; } - if find_attr!(tcx.get_all_attrs(body.source.def_id()), AttributeKind::RustcDoNotConstCheck) { + if find_attr!(tcx, body.source.def_id(), RustcDoNotConstCheck) { return; } diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index 46cdca53ba8cf..ad4c9aa5ff9bd 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{ Constness, ExprKind, ForeignItemKind, ImplItem, ImplItemImplKind, ImplItemKind, Item, ItemKind, @@ -38,7 +37,7 @@ fn constness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Constness { } } Node::TraitItem(ti @ TraitItem { kind: TraitItemKind::Fn(..), .. }) => { - if find_attr!(tcx.hir_attrs(ti.hir_id()), AttributeKind::RustcNonConstTraitMethod) { + if find_attr!(tcx.hir_attrs(ti.hir_id()), RustcNonConstTraitMethod) { Constness::NotConst } else { tcx.trait_def(tcx.local_parent(def_id)).constness diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 3b4f7ed3261ab..025c59747eaf7 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -6,7 +6,6 @@ use rustc_abi::{Align, Size}; use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry}; use rustc_errors::msg; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem, find_attr}; use rustc_middle::mir::AssertMessage; @@ -441,9 +440,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // sensitive check here. But we can at least rule out functions that are not const at // all. That said, we have to allow calling functions inside a `const trait`. These // *are* const-checked! - if !ecx.tcx.is_const_fn(def) - || find_attr!(ecx.tcx.get_all_attrs(def), AttributeKind::RustcDoNotConstCheck) - { + if !ecx.tcx.is_const_fn(def) || find_attr!(ecx.tcx, def, RustcDoNotConstCheck) { // We certainly do *not* want to actually call the fn // though, so be sure we return here. throw_unsup_format!("calling non-const function `{}`", instance) diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 9220fde474e4e..b8205bda68525 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -7,7 +7,6 @@ use either::{Left, Right}; use rustc_abi::{self as abi, ExternAbi, FieldIdx, Integer, VariantIdx}; use rustc_data_structures::assert_matches; use rustc_errors::msg; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::DefId; use rustc_hir::find_attr; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; @@ -142,12 +141,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Check if the inner type is one of the NPO-guaranteed ones. // For that we first unpeel transparent *structs* (but not unions). - let is_npo = |def: AdtDef<'tcx>| { - find_attr!( - self.tcx.get_all_attrs(def.did()), - AttributeKind::RustcNonnullOptimizationGuaranteed - ) - }; + let is_npo = + |def: AdtDef<'tcx>| find_attr!(self.tcx, def.did(), RustcNonnullOptimizationGuaranteed); let inner = self.unfold_transparent(inner, /* may_unfold */ |def| { // Stop at NPO types so that we don't miss that attribute in the check below! def.is_struct() && !is_npo(def) diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 476be94efd9e4..ae3022b83e564 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -15,7 +15,7 @@ use rustc_data_structures::sync; use rustc_errors::{BufferedEarlyLint, DiagCtxtHandle, ErrorGuaranteed, PResult}; use rustc_feature::Features; use rustc_hir as hir; -use rustc_hir::attrs::{AttributeKind, CfgEntry, CollapseMacroDebuginfo, Deprecation}; +use rustc_hir::attrs::{CfgEntry, CollapseMacroDebuginfo, Deprecation}; use rustc_hir::def::MacroKinds; use rustc_hir::limit::Limit; use rustc_hir::{Stability, find_attr}; @@ -896,14 +896,13 @@ impl SyntaxExtension { /// | yes | yes | yes | yes | yes | fn get_collapse_debuginfo(sess: &Session, attrs: &[hir::Attribute], ext: bool) -> bool { let flag = sess.opts.cg.collapse_macro_debuginfo; - let attr = - if let Some(info) = find_attr!(attrs, AttributeKind::CollapseDebugInfo(info) => info) { - info.clone() - } else if find_attr!(attrs, AttributeKind::RustcBuiltinMacro { .. }) { - CollapseMacroDebuginfo::Yes - } else { - CollapseMacroDebuginfo::Unspecified - }; + let attr = if let Some(info) = find_attr!(attrs, CollapseDebugInfo(info) => info) { + info.clone() + } else if find_attr!(attrs, RustcBuiltinMacro { .. }) { + CollapseMacroDebuginfo::Yes + } else { + CollapseMacroDebuginfo::Unspecified + }; #[rustfmt::skip] let collapse_table = [ @@ -918,7 +917,7 @@ impl SyntaxExtension { fn get_hide_backtrace(attrs: &[hir::Attribute]) -> bool { // FIXME(estebank): instead of reusing `#[rustc_diagnostic_item]` as a proxy, introduce a // new attribute purely for this under the `#[diagnostic]` namespace. - find_attr!(attrs, AttributeKind::RustcDiagnosticItem(..)) + find_attr!(attrs, RustcDiagnosticItem(..)) } /// Constructs a syntax extension with the given properties @@ -933,19 +932,17 @@ impl SyntaxExtension { attrs: &[hir::Attribute], is_local: bool, ) -> SyntaxExtension { - let allow_internal_unstable = - find_attr!(attrs, AttributeKind::AllowInternalUnstable(i, _) => i) - .map(|i| i.as_slice()) - .unwrap_or_default(); - let allow_internal_unsafe = find_attr!(attrs, AttributeKind::AllowInternalUnsafe(_)); + let allow_internal_unstable = find_attr!(attrs, AllowInternalUnstable(i, _) => i) + .map(|i| i.as_slice()) + .unwrap_or_default(); + let allow_internal_unsafe = find_attr!(attrs, AllowInternalUnsafe(_)); let local_inner_macros = - *find_attr!(attrs, AttributeKind::MacroExport {local_inner_macros: l, ..} => l) - .unwrap_or(&false); + *find_attr!(attrs, MacroExport {local_inner_macros: l, ..} => l).unwrap_or(&false); let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, !is_local); tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe); - let (builtin_name, helper_attrs) = match find_attr!(attrs, AttributeKind::RustcBuiltinMacro { builtin_name, helper_attrs, .. } => (builtin_name, helper_attrs)) + let (builtin_name, helper_attrs) = match find_attr!(attrs, RustcBuiltinMacro { builtin_name, helper_attrs, .. } => (builtin_name, helper_attrs)) { // Override `helper_attrs` passed above if it's a built-in macro, // marking `proc_macro_derive` macros as built-in is not a realistic use case. @@ -959,10 +956,9 @@ impl SyntaxExtension { }; let hide_backtrace = builtin_name.is_some() || Self::get_hide_backtrace(attrs); - let stability = find_attr!(attrs, AttributeKind::Stability { stability, .. } => *stability); + let stability = find_attr!(attrs, Stability { stability, .. } => *stability); - if let Some(sp) = find_attr!(attrs, AttributeKind::RustcBodyStability{ span, .. } => *span) - { + if let Some(sp) = find_attr!(attrs, RustcBodyStability{ span, .. } => *span) { sess.dcx().emit_err(errors::MacroBodyStability { span: sp, head_span: sess.source_map().guess_head_span(span), @@ -978,7 +974,7 @@ impl SyntaxExtension { stability, deprecation: find_attr!( attrs, - AttributeKind::Deprecation { deprecation, .. } => *deprecation + Deprecation { deprecation, .. } => *deprecation ), helper_attrs, edition, diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 7cd96211de508..7ff49e040f6f3 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -14,7 +14,6 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan}; use rustc_feature::Features; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::MacroKinds; use rustc_hir::find_attr; use rustc_lint_defs::builtin::{ @@ -819,7 +818,7 @@ pub fn compile_declarative_macro( } assert!(!kinds.is_empty()); - let transparency = find_attr!(attrs, AttributeKind::RustcMacroTransparency(x) => *x) + let transparency = find_attr!(attrs, RustcMacroTransparency(x) => *x) .unwrap_or(Transparency::fallback(macro_rules)); if let Some(guar) = guar { diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 64a94887c2ab7..5d154cef66a65 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -847,7 +847,10 @@ pub enum AttributeKind { // tidy-alphabetical-start /// Represents `#[align(N)]`. // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity - Align { align: Align, span: Span }, + Align { + align: Align, + span: Span, + }, /// Represents `#[allow_internal_unsafe]`. AllowInternalUnsafe(Span), @@ -865,7 +868,9 @@ pub enum AttributeKind { CfgTrace(ThinVec<(CfgEntry, Span)>), /// Represents `#[cfi_encoding]` - CfiEncoding { encoding: Symbol }, + CfiEncoding { + encoding: Symbol, + }, /// Represents `#[cold]`. Cold(Span), @@ -886,7 +891,11 @@ pub enum AttributeKind { Coverage(Span, CoverageAttrKind), /// Represents `#[crate_name = ...]` - CrateName { name: Symbol, name_span: Span, attr_span: Span }, + CrateName { + name: Symbol, + name_span: Span, + attr_span: Span, + }, /// Represents `#![crate_type = ...]` CrateType(ThinVec), @@ -901,10 +910,15 @@ pub enum AttributeKind { DefaultLibAllocator, /// Represents [`#[deprecated]`](https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html#the-deprecated-attribute). - Deprecation { deprecation: Deprecation, span: Span }, + Deprecation { + deprecation: Deprecation, + span: Span, + }, /// Represents `#[diagnostic::do_not_recommend]`. - DoNotRecommend { attr_span: Span }, + DoNotRecommend { + attr_span: Span, + }, /// Represents [`#[doc]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html). /// Represents all other uses of the [`#[doc]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html) @@ -913,7 +927,12 @@ pub enum AttributeKind { /// Represents specifically [`#[doc = "..."]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html). /// i.e. doc comments. - DocComment { style: AttrStyle, kind: DocFragmentKind, span: Span, comment: Symbol }, + DocComment { + style: AttrStyle, + kind: DocFragmentKind, + span: Span, + comment: Symbol, + }, /// Implementation detail of `#[eii]` EiiDeclaration(EiiDecl), @@ -964,13 +983,22 @@ pub enum AttributeKind { Link(ThinVec, Span), /// Represents `#[link_name]`. - LinkName { name: Symbol, span: Span }, + LinkName { + name: Symbol, + span: Span, + }, /// Represents `#[link_ordinal]`. - LinkOrdinal { ordinal: u16, span: Span }, + LinkOrdinal { + ordinal: u16, + span: Span, + }, /// Represents [`#[link_section]`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute) - LinkSection { name: Symbol, span: Span }, + LinkSection { + name: Symbol, + span: Span, + }, /// Represents `#[linkage]`. Linkage(Linkage, Span), @@ -982,10 +1010,16 @@ pub enum AttributeKind { MacroEscape(Span), /// Represents [`#[macro_export]`](https://doc.rust-lang.org/reference/macros-by-example.html#r-macro.decl.scope.path). - MacroExport { span: Span, local_inner_macros: bool }, + MacroExport { + span: Span, + local_inner_macros: bool, + }, /// Represents `#[macro_use]`. - MacroUse { span: Span, arguments: MacroUseArgs }, + MacroUse { + span: Span, + arguments: MacroUseArgs, + }, /// Represents `#[marker]`. Marker(Span), @@ -994,10 +1028,16 @@ pub enum AttributeKind { MayDangle(Span), /// Represents `#[move_size_limit]` - MoveSizeLimit { attr_span: Span, limit_span: Span, limit: Limit }, + MoveSizeLimit { + attr_span: Span, + limit_span: Span, + limit: Limit, + }, /// Represents `#[must_not_suspend]` - MustNotSupend { reason: Option }, + MustNotSupend { + reason: Option, + }, /// Represents `#[must_use]`. MustUse { @@ -1046,13 +1086,20 @@ pub enum AttributeKind { PanicRuntime, /// Represents `#[patchable_function_entry]` - PatchableFunctionEntry { prefix: u8, entry: u8 }, + PatchableFunctionEntry { + prefix: u8, + entry: u8, + }, /// Represents `#[path]` Path(Symbol, Span), /// Represents `#[pattern_complexity_limit]` - PatternComplexityLimit { attr_span: Span, limit_span: Span, limit: Limit }, + PatternComplexityLimit { + attr_span: Span, + limit_span: Span, + limit: Limit, + }, /// Represents `#[pin_v2]` PinV2(Span), @@ -1070,22 +1117,36 @@ pub enum AttributeKind { ProcMacroAttribute(Span), /// Represents `#[proc_macro_derive]` - ProcMacroDerive { trait_name: Symbol, helper_attrs: ThinVec, span: Span }, + ProcMacroDerive { + trait_name: Symbol, + helper_attrs: ThinVec, + span: Span, + }, /// Represents `#[profiler_runtime]` ProfilerRuntime, /// Represents [`#[recursion_limit]`](https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute) - RecursionLimit { attr_span: Span, limit_span: Span, limit: Limit }, + RecursionLimit { + attr_span: Span, + limit_span: Span, + limit: Limit, + }, /// Represents `#[reexport_test_harness_main]` ReexportTestHarnessMain(Symbol), /// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations). - Repr { reprs: ThinVec<(ReprAttr, Span)>, first_span: Span }, + Repr { + reprs: ThinVec<(ReprAttr, Span)>, + first_span: Span, + }, /// Represents `#[rustc_abi(..)]` - RustcAbi { attr_span: Span, kind: RustcAbiAttrKind }, + RustcAbi { + attr_span: Span, + kind: RustcAbiAttrKind, + }, /// Represents `#[rustc_allocator]` RustcAllocator, @@ -1094,7 +1155,9 @@ pub enum AttributeKind { RustcAllocatorZeroed, /// Represents `#[rustc_allocator_zeroed_variant]` - RustcAllocatorZeroedVariant { name: Symbol }, + RustcAllocatorZeroedVariant { + name: Symbol, + }, /// Represents `#[rustc_allow_const_fn_unstable]`. RustcAllowConstFnUnstable(ThinVec, Span), @@ -1112,8 +1175,11 @@ pub enum AttributeKind { span: Span, }, /// Represents `#[rustc_builtin_macro]`. - RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, span: Span }, - + RustcBuiltinMacro { + builtin_name: Option, + helper_attrs: ThinVec, + span: Span, + }, /// Represents `#[rustc_capture_analysis]` RustcCaptureAnalysis, @@ -1161,8 +1227,9 @@ pub enum AttributeKind { RustcDenyExplicitImpl(Span), /// Represents `#[rustc_deprecated_safe_2024]` - RustcDeprecatedSafe2024 { suggestion: Symbol }, - + RustcDeprecatedSafe2024 { + suggestion: Symbol, + }, /// Represents `#[rustc_diagnostic_item]` RustcDiagnosticItem(Symbol), @@ -1199,7 +1266,6 @@ pub enum AttributeKind { /// Represents `#[rustc_evaluate_where_clauses]` RustcEvaluateWhereClauses, - /// Represents `#[rustc_has_incoherent_inherent_impls]` RustcHasIncoherentInherentImpls, /// Represents `#[rustc_hidden_type_of_opaques]` @@ -1227,10 +1293,15 @@ pub enum AttributeKind { RustcLayoutScalarValidRangeStart(Box, Span), /// Represents `#[rustc_legacy_const_generics]` - RustcLegacyConstGenerics { fn_indexes: ThinVec<(usize, Span)>, attr_span: Span }, + RustcLegacyConstGenerics { + fn_indexes: ThinVec<(usize, Span)>, + attr_span: Span, + }, /// Represents `#[rustc_lint_opt_deny_field_access]` - RustcLintOptDenyFieldAccess { lint_message: Symbol }, + RustcLintOptDenyFieldAccess { + lint_message: Symbol, + }, /// Represents `#[rustc_lint_opt_ty]` RustcLintOptTy, @@ -1251,7 +1322,10 @@ pub enum AttributeKind { RustcMir(ThinVec), /// Represents `#[rustc_must_implement_one_of]` - RustcMustImplementOneOf { attr_span: Span, fn_names: ThinVec }, + RustcMustImplementOneOf { + attr_span: Span, + fn_names: ThinVec, + }, /// Represents `#[rustc_never_returns_null_ptr]` RustcNeverReturnsNullPointer, @@ -1281,10 +1355,16 @@ pub enum AttributeKind { RustcNounwind, /// Represents `#[rustc_objc_class]` - RustcObjcClass { classname: Symbol, span: Span }, + RustcObjcClass { + classname: Symbol, + span: Span, + }, /// Represents `#[rustc_objc_selector]` - RustcObjcSelector { methname: Symbol, span: Span }, + RustcObjcSelector { + methname: Symbol, + span: Span, + }, /// Represents `#[rustc_object_lifetime_default]`. RustcObjectLifetimeDefault, @@ -1337,7 +1417,11 @@ pub enum AttributeKind { RustcSimdMonomorphizeLaneLimit(Limit), /// Represents `#[rustc_skip_during_method_dispatch]`. - RustcSkipDuringMethodDispatch { array: bool, boxed_slice: bool, span: Span }, + RustcSkipDuringMethodDispatch { + array: bool, + boxed_slice: bool, + span: Span, + }, /// Represents `#[rustc_specialization_trait]`. RustcSpecializationTrait(Span), @@ -1382,7 +1466,10 @@ pub enum AttributeKind { }, /// Represents `#[should_panic]` - ShouldPanic { reason: Option, span: Span }, + ShouldPanic { + reason: Option, + span: Span, + }, /// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`. Stability { @@ -1393,7 +1480,11 @@ pub enum AttributeKind { /// Represents `#[target_feature(enable = "...")]` and /// `#[unsafe(force_target_feature(enable = "...")]`. - TargetFeature { features: ThinVec<(Symbol, Span)>, attr_span: Span, was_forced: bool }, + TargetFeature { + features: ThinVec<(Symbol, Span)>, + attr_span: Span, + was_forced: bool, + }, /// Represents `#![test_runner(path)]` TestRunner(Path), @@ -1405,13 +1496,20 @@ pub enum AttributeKind { TrackCaller(Span), /// Represents `#[type_length_limit]` - TypeLengthLimit { attr_span: Span, limit_span: Span, limit: Limit }, + TypeLengthLimit { + attr_span: Span, + limit_span: Span, + limit: Limit, + }, /// Represents `#[unstable_feature_bound]`. UnstableFeatureBound(ThinVec<(Symbol, Span)>), /// Represents `#[used]` - Used { used_by: UsedBy, span: Span }, + Used { + used_by: UsedBy, + span: Span, + }, /// Represents `#[windows_subsystem]`. WindowsSubsystem(WindowsSubsystemKind, Span), diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index 482e6c90739f2..7e3ac666d0f50 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -29,9 +29,41 @@ mod pretty_printing; /// ``` /// /// Often this requires you to first end up with a list of attributes. -/// A common way to get those is through `tcx.get_all_attrs(did)` +/// Often these are available through the `tcx`. +/// +/// As a convenience, this macro can do that for you! +/// +/// Instead of providing an attribute list, provide the `tcx` and a `DefId`. +/// +/// ```rust,ignore (illustrative) +/// find_attr!(tcx, def_id, ) +/// ``` +/// +/// Another common case is finding attributes applied to the root of the current crate. +/// For that, use the shortcut: +/// +/// ```rust, ignore (illustrative) +/// find_attr!(tcx, crate, ) +/// ``` #[macro_export] macro_rules! find_attr { + ($tcx: expr, crate, $pattern: pat $(if $guard: expr)?) => { + $crate::find_attr!($tcx, crate, $pattern $(if $guard)? => ()).is_some() + }; + ($tcx: expr, crate, $pattern: pat $(if $guard: expr)? => $e: expr) => { + $crate::find_attr!($tcx.hir_krate_attrs(), $pattern $(if $guard)? => $e) + }; + + ($tcx: expr, $def_id: expr, $pattern: pat $(if $guard: expr)?) => { + $crate::find_attr!($tcx, $def_id, $pattern $(if $guard)? => ()).is_some() + }; + ($tcx: expr, $def_id: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{ + #[allow(deprecated)] { + $crate::find_attr!($tcx.get_all_attrs($def_id), $pattern $(if $guard)? => $e) + } + }}; + + ($attributes_list: expr, $pattern: pat $(if $guard: expr)?) => {{ $crate::find_attr!($attributes_list, $pattern $(if $guard)? => ()).is_some() }}; @@ -39,11 +71,19 @@ macro_rules! find_attr { ($attributes_list: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{ 'done: { for i in $attributes_list { + #[allow(unused_imports)] + use rustc_hir::attrs::AttributeKind::*; let i: &rustc_hir::Attribute = i; match i { rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { break 'done Some($e); } + rustc_hir::Attribute::Unparsed(..) => {} + // In lint emitting, there's a specific exception for this warning. + // It's not usually emitted from inside macros from other crates + // (see https://github.com/rust-lang/rust/issues/110613) + // But this one is! + #[deny(unreachable_patterns)] _ => {} } } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 5f22dce29dc62..04773ad3f8bc1 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -6,10 +6,9 @@ use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; use rustc_errors::{EmissionGuarantee, MultiSpan}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::attrs::ReprAttr::ReprPacked; use rustc_hir::def::{CtorKind, DefKind}; -use rustc_hir::{LangItem, Node, attrs, find_attr, intravisit}; +use rustc_hir::{LangItem, Node, find_attr, intravisit}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc}; use rustc_lint_defs::builtin::{REPR_TRANSPARENT_NON_ZST_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS}; @@ -79,7 +78,7 @@ pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi pub fn check_custom_abi(tcx: TyCtxt<'_>, def_id: LocalDefId, fn_sig: FnSig<'_>, fn_sig_span: Span) { if fn_sig.abi == ExternAbi::Custom { // Function definitions that use `extern "custom"` must be naked functions. - if !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Naked(_)) { + if !find_attr!(tcx, def_id, Naked(_)) { tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction { span: fn_sig_span, naked_span: tcx.def_span(def_id).shrink_to_lo(), @@ -981,12 +980,11 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), (0, _) => ("const", "consts", None), _ => ("type or const", "types or consts", None), }; - let name = - if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::EiiForeignItem) { - "externally implementable items" - } else { - "foreign items" - }; + let name = if find_attr!(tcx, def_id, EiiForeignItem) { + "externally implementable items" + } else { + "foreign items" + }; let span = tcx.def_span(def_id); struct_span_code_err!( @@ -1373,7 +1371,7 @@ fn check_impl_items_against_trait<'tcx>( } if let Some(missing_items) = must_implement_one_of { - let attr_span = find_attr!(tcx.get_all_attrs(trait_ref.def_id), AttributeKind::RustcMustImplementOneOf {attr_span, ..} => *attr_span); + let attr_span = find_attr!(tcx, trait_ref.def_id, RustcMustImplementOneOf {attr_span, ..} => *attr_span); missing_items_must_implement_one_of_err( tcx, @@ -1556,8 +1554,7 @@ fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalab pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { let repr = def.repr(); if repr.packed() { - if let Some(reprs) = find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs) - { + if let Some(reprs) = find_attr!(tcx, def.did(), Repr { reprs, .. } => reprs) { for (r, _) in reprs { if let ReprPacked(pack) = r && let Some(repr_pack) = repr.pack @@ -1724,12 +1721,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)), ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty), ty::Adt(def, args) => { - if !def.did().is_local() - && !find_attr!( - tcx.get_all_attrs(def.did()), - AttributeKind::RustcPubTransparent(_) - ) - { + if !def.did().is_local() && !find_attr!(tcx, def.did(), RustcPubTransparent(_)) { let non_exhaustive = def.is_variant_list_non_exhaustive() || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive); let has_priv = def.all_fields().any(|f| !f.vis.is_public()); @@ -1800,19 +1792,16 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) { def.destructor(tcx); // force the destructor to be evaluated if def.variants().is_empty() { - find_attr!( - tcx.get_all_attrs(def_id), - attrs::AttributeKind::Repr { reprs, first_span } => { - struct_span_code_err!( - tcx.dcx(), - reprs.first().map(|repr| repr.1).unwrap_or(*first_span), - E0084, - "unsupported representation for zero-variant enum" - ) - .with_span_label(tcx.def_span(def_id), "zero-variant enum") - .emit(); - } - ); + find_attr!(tcx, def_id, Repr { reprs, first_span } => { + struct_span_code_err!( + tcx.dcx(), + reprs.first().map(|repr| repr.1).unwrap_or(*first_span), + E0084, + "unsupported representation for zero-variant enum" + ) + .with_span_label(tcx.def_span(def_id), "zero-variant enum") + .emit(); + }); } for v in def.variants() { diff --git a/compiler/rustc_hir_analysis/src/check/compare_eii.rs b/compiler/rustc_hir_analysis/src/check/compare_eii.rs index 2beb7eb09c119..9443aaac2258f 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_eii.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_eii.rs @@ -8,7 +8,7 @@ use std::iter; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, E0806, struct_span_code_err}; -use rustc_hir::attrs::{AttributeKind, EiiImplResolution}; +use rustc_hir::attrs::EiiImplResolution; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, FnSig, HirId, ItemKind, find_attr}; use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; @@ -177,9 +177,7 @@ fn check_no_generics<'tcx>( // since in that case it looks like a duplicate error: the declaration of the EII already can't contain generics. // So, we check here if at least one of the eii impls has ImplResolution::Macro, which indicates it's // not generated as part of the declaration. - && find_attr!( - tcx.get_all_attrs(external_impl), - AttributeKind::EiiImpls(impls) if impls.iter().any(|i| matches!(i.resolution, EiiImplResolution::Macro(_))) + && find_attr!(tcx, external_impl, EiiImpls(impls) if impls.iter().any(|i| matches!(i.resolution, EiiImplResolution::Macro(_))) ) { tcx.dcx().emit_err(EiiWithGenerics { diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index 207cb83bcc8e4..a6dae521db884 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -2,7 +2,6 @@ use std::ops::Not; use rustc_abi::ExternAbi; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Node, find_attr}; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::span_bug; @@ -99,9 +98,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { error = true; } - if let Some(attr_span) = - find_attr!(tcx.get_all_attrs(main_def_id), AttributeKind::TrackCaller(span) => *span) - { + if let Some(attr_span) = find_attr!(tcx, main_def_id, TrackCaller(span) => *span) { tcx.dcx().emit_err(errors::TrackCallerOnMain { span: attr_span, annotated: main_span }); error = true; } diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index b1daf2f2be9cf..ed951015a4f19 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -6,7 +6,7 @@ use rustc_abi::{ExternAbi, ScalableElt}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err}; -use rustc_hir::attrs::{AttributeKind, EiiDecl, EiiImpl, EiiImplResolution}; +use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; @@ -1197,15 +1197,14 @@ fn check_eiis(tcx: TyCtxt<'_>, def_id: LocalDefId) { // does the function have an EiiImpl attribute? that contains the defid of a *macro* // that was used to mark the implementation. This is a two step process. for EiiImpl { resolution, span, .. } in - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::EiiImpls(impls) => impls) - .into_iter() - .flatten() + find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten() { let (foreign_item, name) = match resolution { EiiImplResolution::Macro(def_id) => { // we expect this macro to have the `EiiMacroFor` attribute, that points to a function // signature that we'd like to compare the function we're currently checking with - if let Some(foreign_item) = find_attr!(tcx.get_all_attrs(*def_id), AttributeKind::EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t) + if let Some(foreign_item) = + find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t) { (foreign_item, tcx.item_name(*def_id)) } else { diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 588747f46d17d..0050fea988f85 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -8,7 +8,6 @@ //! is computed by selecting an idea from this table. use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::find_attr; @@ -79,20 +78,14 @@ impl<'tcx> InherentCollect<'tcx> { } if self.tcx.features().rustc_attrs() { - if !find_attr!( - self.tcx.get_all_attrs(ty_def_id), - AttributeKind::RustcHasIncoherentInherentImpls - ) { + if !find_attr!(self.tcx, ty_def_id, RustcHasIncoherentInherentImpls) { let impl_span = self.tcx.def_span(impl_def_id); return Err(self.tcx.dcx().emit_err(errors::InherentTyOutside { span: impl_span })); } let items = self.tcx.associated_item_def_ids(impl_def_id); for &impl_item in items { - if !find_attr!( - self.tcx.get_all_attrs(impl_item), - AttributeKind::RustcAllowIncoherentImpl(_) - ) { + if !find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) { let impl_span = self.tcx.def_span(impl_def_id); return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsideRelevant { span: impl_span, @@ -138,10 +131,7 @@ impl<'tcx> InherentCollect<'tcx> { if !self.tcx.hir_rustc_coherence_is_core() { if self.tcx.features().rustc_attrs() { for &impl_item in items { - if !find_attr!( - self.tcx.get_all_attrs(impl_item), - AttributeKind::RustcAllowIncoherentImpl(_) - ) { + if !find_attr!(self.tcx, impl_item, RustcAllowIncoherentImpl(_)) { let span = self.tcx.def_span(impl_def_id); return Err(self.tcx.dcx().emit_err(errors::InherentTyOutsidePrimitive { span, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 2fc1f1ab01d27..276bc697eaa96 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -23,7 +23,6 @@ use rustc_ast::Recovered; use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::{Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, InferKind, Visitor, VisitorExt}; @@ -816,11 +815,9 @@ fn lower_variant<'tcx>( fields, parent_did.to_def_id(), recovered, - adt_kind == AdtKind::Struct - && find_attr!(tcx.get_all_attrs(parent_did), AttributeKind::NonExhaustive(..)) - || variant_did.is_some_and(|variant_did| { - find_attr!(tcx.get_all_attrs(variant_did), AttributeKind::NonExhaustive(..)) - }), + adt_kind == AdtKind::Struct && find_attr!(tcx, parent_did, NonExhaustive(..)) + || variant_did + .is_some_and(|variant_did| find_attr!(tcx, variant_did, NonExhaustive(..))), ) } @@ -895,46 +892,46 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"), }; + // we do a bunch of find_attr calls here, probably faster to get them from the tcx just once. + #[allow(deprecated)] let attrs = tcx.get_all_attrs(def_id); - let paren_sugar = find_attr!(attrs, AttributeKind::RustcParenSugar(_)); + let paren_sugar = find_attr!(attrs, RustcParenSugar(_)); if paren_sugar && !tcx.features().unboxed_closures() { tcx.dcx().emit_err(errors::ParenSugarAttribute { span: item.span }); } // Only regular traits can be marker. - let is_marker = !is_alias && find_attr!(attrs, AttributeKind::Marker(_)); + let is_marker = !is_alias && find_attr!(attrs, Marker(_)); - let rustc_coinductive = find_attr!(attrs, AttributeKind::RustcCoinductive(_)); - let is_fundamental = find_attr!(attrs, AttributeKind::Fundamental); + let rustc_coinductive = find_attr!(attrs, RustcCoinductive(_)); + let is_fundamental = find_attr!(attrs, Fundamental); let [skip_array_during_method_dispatch, skip_boxed_slice_during_method_dispatch] = find_attr!( attrs, - AttributeKind::RustcSkipDuringMethodDispatch { array, boxed_slice, span: _ } => [*array, *boxed_slice] + RustcSkipDuringMethodDispatch { array, boxed_slice, span: _ } => [*array, *boxed_slice] ) .unwrap_or([false; 2]); - let specialization_kind = - if find_attr!(attrs, AttributeKind::RustcUnsafeSpecializationMarker(_)) { - ty::trait_def::TraitSpecializationKind::Marker - } else if find_attr!(attrs, AttributeKind::RustcSpecializationTrait(_)) { - ty::trait_def::TraitSpecializationKind::AlwaysApplicable - } else { - ty::trait_def::TraitSpecializationKind::None - }; + let specialization_kind = if find_attr!(attrs, RustcUnsafeSpecializationMarker(_)) { + ty::trait_def::TraitSpecializationKind::Marker + } else if find_attr!(attrs, RustcSpecializationTrait(_)) { + ty::trait_def::TraitSpecializationKind::AlwaysApplicable + } else { + ty::trait_def::TraitSpecializationKind::None + }; let must_implement_one_of = find_attr!( attrs, - AttributeKind::RustcMustImplementOneOf { fn_names, .. } => + RustcMustImplementOneOf { fn_names, .. } => fn_names .iter() .cloned() .collect::>() ); - let deny_explicit_impl = find_attr!(attrs, AttributeKind::RustcDenyExplicitImpl(_)); - let force_dyn_incompatible = - find_attr!(attrs, AttributeKind::RustcDynIncompatibleTrait(span) => *span); + let deny_explicit_impl = find_attr!(attrs, RustcDenyExplicitImpl(_)); + let force_dyn_incompatible = find_attr!(attrs, RustcDynIncompatibleTrait(span) => *span); ty::TraitDef { def_id: def_id.to_def_id(), @@ -1355,8 +1352,7 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::ImplTraitHeader .of_trait .unwrap_or_else(|| panic!("expected impl trait, found inherent impl on {def_id:?}")); let selfty = tcx.type_of(def_id).instantiate_identity(); - let is_rustc_reservation = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcReservationImpl(..)); + let is_rustc_reservation = find_attr!(tcx, def_id, RustcReservationImpl(..)); check_impl_constness(tcx, impl_.constness, &of_trait.trait_ref); diff --git a/compiler/rustc_hir_analysis/src/collect/dump.rs b/compiler/rustc_hir_analysis/src/collect/dump.rs index bbf912cd4bde8..8534cc26fd944 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -1,13 +1,12 @@ use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; -use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; +use rustc_hir::def_id::LocalDefId; use rustc_hir::{find_attr, intravisit}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_span::sym; pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) { - if !find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::RustcHiddenTypeOfOpaques) { + if !find_attr!(tcx, crate, RustcHiddenTypeOfOpaques) { return; } for id in tcx.hir_crate_items(()).opaques() { @@ -28,7 +27,7 @@ pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) { pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) { for id in tcx.hir_crate_items(()).owners() { - if find_attr!(tcx.get_all_attrs(id), AttributeKind::RustcDumpPredicates) { + if find_attr!(tcx, id, RustcDumpPredicates) { let preds = tcx.predicates_of(id).instantiate_identity(tcx).predicates; let span = tcx.def_span(id); @@ -38,7 +37,7 @@ pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) { } diag.emit(); } - if find_attr!(tcx.get_all_attrs(id), AttributeKind::RustcDumpItemBounds) { + if find_attr!(tcx, id, RustcDumpItemBounds) { let bounds = tcx.item_bounds(id).instantiate_identity(); let span = tcx.def_span(id); @@ -54,7 +53,7 @@ pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) { pub(crate) fn def_parents(tcx: TyCtxt<'_>) { for iid in tcx.hir_free_items() { let did = iid.owner_id.def_id; - if find_attr!(tcx.get_all_attrs(did), AttributeKind::RustcDumpDefParents) { + if find_attr!(tcx, did, RustcDumpDefParents) { struct AnonConstFinder<'tcx> { tcx: TyCtxt<'tcx>, anon_consts: Vec, @@ -102,9 +101,7 @@ pub(crate) fn vtables<'tcx>(tcx: TyCtxt<'tcx>) { for id in tcx.hir_free_items() { let def_id = id.owner_id.def_id; - let Some(&attr_span) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcDumpVtable(span) => span) - else { + let Some(&attr_span) = find_attr!(tcx, def_id, RustcDumpVtable(span) => span) else { continue; }; diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index a2236b4263059..777610402893b 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -2,7 +2,6 @@ use hir::Node; use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::find_attr; @@ -331,9 +330,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // first we would need a way to let std/core use APIs with unstable feature bounds from // within stable APIs. let allow_unstable_feature_attr = - find_attr!(attrs, AttributeKind::UnstableFeatureBound(i) => i) - .map(|i| i.as_slice()) - .unwrap_or_default(); + find_attr!(attrs, UnstableFeatureBound(i) => i).map(|i| i.as_slice()).unwrap_or_default(); for (feat_name, span) in allow_unstable_feature_attr { predicates.insert((ty::ClauseKind::UnstableFeature(*feat_name).upcast(tcx), *span)); diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 670312ff1ba1b..ca399964fdd93 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -4,9 +4,8 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::struct_span_code_err; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; +use rustc_hir::def_id::DefId; use rustc_hir::{PolyTraitRef, find_attr}; use rustc_middle::bug; use rustc_middle::ty::{ @@ -171,7 +170,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let tcx = self.tcx(); // Skip adding any default bounds if `#![rustc_no_implicit_bounds]` - if find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::RustcNoImplicitBounds) { + if find_attr!(tcx, crate, RustcNoImplicitBounds) { return; } @@ -285,8 +284,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { context: ImpliedBoundsContext<'tcx>, ) -> bool { let collected = collect_bounds(hir_bounds, context, trait_def_id); - !find_attr!(self.tcx().get_all_attrs(CRATE_DEF_ID), AttributeKind::RustcNoImplicitBounds) - && !collected.any() + !find_attr!(self.tcx(), crate, RustcNoImplicitBounds) && !collected.any() } fn reject_duplicate_relaxed_bounds(&self, relaxed_bounds: SmallVec<[&PolyTraitRef<'_>; 1]>) { diff --git a/compiler/rustc_hir_analysis/src/outlives/dump.rs b/compiler/rustc_hir_analysis/src/outlives/dump.rs index cf770a2561db8..671846a35b266 100644 --- a/compiler/rustc_hir_analysis/src/outlives/dump.rs +++ b/compiler/rustc_hir_analysis/src/outlives/dump.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_middle::bug; use rustc_middle::ty::{self, TyCtxt}; @@ -6,7 +5,7 @@ use rustc_span::sym; pub(crate) fn inferred_outlives(tcx: TyCtxt<'_>) { for id in tcx.hir_free_items() { - if !find_attr!(tcx.get_all_attrs(id.owner_id), AttributeKind::RustcOutlives) { + if !find_attr!(tcx, id.owner_id, RustcOutlives) { continue; } diff --git a/compiler/rustc_hir_analysis/src/variance/dump.rs b/compiler/rustc_hir_analysis/src/variance/dump.rs index e625d9dfe3b5f..db17aaf8de1f3 100644 --- a/compiler/rustc_hir_analysis/src/variance/dump.rs +++ b/compiler/rustc_hir_analysis/src/variance/dump.rs @@ -1,7 +1,6 @@ use std::fmt::Write; -use rustc_hir::attrs::AttributeKind; -use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; +use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; use rustc_middle::ty::{GenericArgs, TyCtxt}; @@ -26,7 +25,7 @@ fn format_variances(tcx: TyCtxt<'_>, def_id: LocalDefId) -> String { pub(crate) fn variances(tcx: TyCtxt<'_>) { let crate_items = tcx.hir_crate_items(()); - if find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::RustcVarianceOfOpaques) { + if find_attr!(tcx, crate, RustcVarianceOfOpaques) { for id in crate_items.opaques() { tcx.dcx().emit_err(crate::errors::VariancesOf { span: tcx.def_span(id), @@ -36,7 +35,7 @@ pub(crate) fn variances(tcx: TyCtxt<'_>) { } for id in crate_items.free_items() { - if !find_attr!(tcx.get_all_attrs(id.owner_id), AttributeKind::RustcVariance) { + if !find_attr!(tcx, id.owner_id, RustcVariance) { continue; } diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 13960fd4d607c..471aa4384984a 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -3,7 +3,6 @@ use std::iter; use rustc_abi::{CanonAbi, ExternAbi}; use rustc_ast::util::parser::ExprPrecedence; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, msg}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId, LangItem, find_attr}; @@ -526,12 +525,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Unit testing: function items annotated with // `#[rustc_evaluate_where_clauses]` trigger special output // to let us test the trait evaluation system. - if self.has_rustc_attrs - && find_attr!( - self.tcx.get_all_attrs(def_id), - AttributeKind::RustcEvaluateWhereClauses - ) - { + if self.has_rustc_attrs && find_attr!(self.tcx, def_id, RustcEvaluateWhereClauses) { let predicates = self.tcx.predicates_of(def_id); let predicates = predicates.instantiate(self.tcx, args); for (predicate, predicate_span) in predicates { @@ -906,9 +900,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { callee_args: GenericArgsRef<'tcx>, ) { // If we have `rustc_do_not_const_check`, do not check `[const]` bounds. - if self.has_rustc_attrs - && find_attr!(self.tcx.get_all_attrs(self.body_id), AttributeKind::RustcDoNotConstCheck) - { + if self.has_rustc_attrs && find_attr!(self.tcx, self.body_id, RustcDoNotConstCheck) { return; } diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 2768023e49b94..d9604ceedb150 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1,5 +1,4 @@ use rustc_errors::{Applicability, Diag, MultiSpan, listify}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; use rustc_hir::intravisit::Visitor; use rustc_hir::{self as hir, find_attr}; @@ -1092,7 +1091,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // // FIXME? Other potential candidate methods: `as_ref` and // `as_mut`? - && find_attr!(self.tcx.get_all_attrs(m.def_id), AttributeKind::RustcConversionSuggestion) + && find_attr!(self.tcx, m.def_id, RustcConversionSuggestion) }, ); diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 5b40531f94627..8baa671972139 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -15,7 +15,6 @@ use rustc_errors::{ Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize, struct_span_code_err, }; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; @@ -3676,7 +3675,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> { if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro { - if !find_attr!(self.tcx.get_all_attrs(self.body_id), AttributeKind::Naked(..)) { + if !find_attr!(self.tcx, self.body_id, Naked(..)) { self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span }); } } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 412df9162e9f2..873e95f13bb97 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -8,9 +8,8 @@ mod suggestions; use std::cell::{Cell, RefCell}; use std::ops::Deref; -use hir::def_id::CRATE_DEF_ID; use rustc_errors::DiagCtxtHandle; -use rustc_hir::attrs::{AttributeKind, DivergingBlockBehavior, DivergingFallbackBehavior}; +use rustc_hir::attrs::{DivergingBlockBehavior, DivergingFallbackBehavior}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, HirId, ItemLocalMap, find_attr}; use rustc_hir_analysis::hir_ty_lowering::{ @@ -516,5 +515,5 @@ fn parse_never_type_options_attr( // Error handling is dubious here (unwraps), but that's probably fine for an internal attribute. // Just don't write incorrect attributes <3 - find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::RustcNeverTypeOptions {fallback, diverging_block_default} => (*fallback, *diverging_block_default)).unwrap_or_default() + find_attr!(tcx, crate, RustcNeverTypeOptions {fallback, diverging_block_default} => (*fallback, *diverging_block_default)).unwrap_or_default() } diff --git a/compiler/rustc_hir_typeck/src/loops.rs b/compiler/rustc_hir_typeck/src/loops.rs index 799e82ec13b80..e77c93641e1a6 100644 --- a/compiler/rustc_hir_typeck/src/loops.rs +++ b/compiler/rustc_hir_typeck/src/loops.rs @@ -3,7 +3,6 @@ use std::fmt; use Context::*; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; @@ -208,7 +207,7 @@ impl<'hir> Visitor<'hir> for CheckLoopVisitor<'hir> { }; // A `#[const_continue]` must break to a block in a `#[loop_match]`. - if find_attr!(self.tcx.hir_attrs(e.hir_id), AttributeKind::ConstContinue(_)) { + if find_attr!(self.tcx.hir_attrs(e.hir_id), ConstContinue(_)) { let Some(label) = break_destination.label else { let span = e.span; self.tcx.dcx().emit_fatal(ConstContinueBadLabel { span }); @@ -421,7 +420,7 @@ impl<'hir> CheckLoopVisitor<'hir> { e: &'hir hir::Expr<'hir>, body: &'hir hir::Block<'hir>, ) -> Option { - if !find_attr!(self.tcx.hir_attrs(e.hir_id), AttributeKind::LoopMatch(_)) { + if !find_attr!(self.tcx.hir_attrs(e.hir_id), LoopMatch(_)) { return None; } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 5c1bc20bdbece..b98c9de92ca9b 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -6,7 +6,6 @@ use rustc_data_structures::debug_assert_matches; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sso::SsoHashSet; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::{self as hir, ExprKind, HirId, Node, find_attr}; use rustc_hir_analysis::autoderef::{self, Autoderef}; @@ -2591,7 +2590,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let hir_id = self.fcx.tcx.local_def_id_to_hir_id(local_def_id); let attrs = self.fcx.tcx.hir_attrs(hir_id); - if let Some(d) = find_attr!(attrs, AttributeKind::Doc(d) => d) + if let Some(d) = find_attr!(attrs, Doc(d) => d) && d.aliases.contains_key(&method.name) { return true; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 737ba250957d2..c5e055e68aea1 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -16,7 +16,6 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, MultiSpan, StashKey, listify, pluralize, struct_span_code_err, }; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, Visitor}; @@ -2261,7 +2260,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for inherent_method in self.tcx.associated_items(inherent_impl_did).in_definition_order() { - if let Some(candidates) = find_attr!(self.tcx.get_all_attrs(inherent_method.def_id), AttributeKind::RustcConfusables{symbols, ..} => symbols) + if let Some(candidates) = find_attr!(self.tcx, inherent_method.def_id, RustcConfusables{symbols, ..} => symbols) && candidates.contains(&item_name.name) && inherent_method.is_fn() { diff --git a/compiler/rustc_hir_typeck/src/naked_functions.rs b/compiler/rustc_hir_typeck/src/naked_functions.rs index d3fd63d871aab..c118f49dca6df 100644 --- a/compiler/rustc_hir_typeck/src/naked_functions.rs +++ b/compiler/rustc_hir_typeck/src/naked_functions.rs @@ -1,7 +1,6 @@ //! Checks validity of naked functions. use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::Visitor; use rustc_hir::{ExprKind, HirIdSet, StmtKind, find_attr}; @@ -21,7 +20,7 @@ pub(crate) fn typeck_naked_fn<'tcx>( def_id: LocalDefId, body: &'tcx hir::Body<'tcx>, ) { - debug_assert!(find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Naked(..))); + debug_assert!(find_attr!(tcx, def_id, Naked(..))); check_no_patterns(tcx, body.params); check_no_parameters_use(tcx, body); check_asm(tcx, def_id, body); diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 767913ba5261a..8cc2be9c45e4f 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -36,7 +36,6 @@ use rustc_abi::FIRST_VARIANT; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::{ExtendUnord, UnordSet}; use rustc_errors::{Applicability, MultiSpan}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{self as hir, HirId, find_attr}; @@ -1743,11 +1742,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool { - self.has_rustc_attrs - && find_attr!( - self.tcx.get_all_attrs(closure_def_id), - AttributeKind::RustcCaptureAnalysis - ) + self.has_rustc_attrs && find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis) } fn log_capture_analysis_first_pass( diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 0078cd9d06833..afb20b3c7cd0a 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -14,7 +14,6 @@ use std::ops::ControlFlow; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{E0720, ErrorGuaranteed}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, InferKind, Visitor}; use rustc_hir::{self as hir, AmbigArg, HirId, find_attr}; @@ -46,8 +45,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // This attribute causes us to dump some writeback information // in the form of errors, which is used for unit tests. - let rustc_dump_user_args = self.has_rustc_attrs - && find_attr!(self.tcx.get_all_attrs(item_def_id), AttributeKind::RustcDumpUserArgs); + let rustc_dump_user_args = + self.has_rustc_attrs && find_attr!(self.tcx, item_def_id, RustcDumpUserArgs); let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args); for param in body.params { diff --git a/compiler/rustc_incremental/src/persist/clean.rs b/compiler/rustc_incremental/src/persist/clean.rs index 9e974e432c399..2969152848986 100644 --- a/compiler/rustc_incremental/src/persist/clean.rs +++ b/compiler/rustc_incremental/src/persist/clean.rs @@ -352,13 +352,11 @@ impl<'tcx> CleanVisitor<'tcx> { let item_span = self.tcx.def_span(item_id.to_def_id()); let def_path_hash = self.tcx.def_path_hash(item_id.to_def_id()); - let Some(attr) = - find_attr!(self.tcx.get_all_attrs(item_id), AttributeKind::RustcClean(attr) => attr) - else { + let Some(clean_attrs) = find_attr!(self.tcx, item_id, RustcClean(attr) => attr) else { return; }; - for attr in attr { + for attr in clean_attrs { let Some(assertion) = self.assertion_maybe(item_id, attr) else { continue; }; diff --git a/compiler/rustc_interface/src/limits.rs b/compiler/rustc_interface/src/limits.rs index 10e58f32256f1..e0fc91f3b723b 100644 --- a/compiler/rustc_interface/src/limits.rs +++ b/compiler/rustc_interface/src/limits.rs @@ -8,7 +8,6 @@ //! Users can override these limits via an attribute on the crate like //! `#![recursion_limit="22"]`. This pass just looks for those attributes. -use rustc_hir::attrs::AttributeKind; use rustc_hir::limit::Limit; use rustc_hir::{Attribute, find_attr}; use rustc_middle::query::Providers; @@ -19,14 +18,12 @@ pub(crate) fn provide(providers: &mut Providers) { let attrs = tcx.hir_krate_attrs(); Limits { recursion_limit: get_recursion_limit(tcx.hir_krate_attrs()), - move_size_limit: - find_attr!(attrs, AttributeKind::MoveSizeLimit { limit, .. } => *limit) - .unwrap_or(Limit::new(tcx.sess.opts.unstable_opts.move_size_limit.unwrap_or(0))), - type_length_limit: - find_attr!(attrs, AttributeKind::TypeLengthLimit { limit, .. } => *limit) - .unwrap_or(Limit::new(2usize.pow(24))), + move_size_limit: find_attr!(attrs, MoveSizeLimit { limit, .. } => *limit) + .unwrap_or(Limit::new(tcx.sess.opts.unstable_opts.move_size_limit.unwrap_or(0))), + type_length_limit: find_attr!(attrs, TypeLengthLimit { limit, .. } => *limit) + .unwrap_or(Limit::new(2usize.pow(24))), pattern_complexity_limit: - find_attr!(attrs, AttributeKind::PatternComplexityLimit { limit, .. } => *limit) + find_attr!(attrs, PatternComplexityLimit { limit, .. } => *limit) .unwrap_or(Limit::unlimited()), } } @@ -34,6 +31,5 @@ pub(crate) fn provide(providers: &mut Providers) { // This one is separate because it must be read prior to macro expansion. pub(crate) fn get_recursion_limit(attrs: &[Attribute]) -> Limit { - find_attr!(attrs, AttributeKind::RecursionLimit { limit, .. } => *limit) - .unwrap_or(Limit::new(128)) + find_attr!(attrs, RecursionLimit { limit, .. } => *limit).unwrap_or(Limit::new(128)) } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 6838a495fd0f2..15addd2407857 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1199,7 +1199,7 @@ pub(crate) fn start_codegen<'tcx>( // Hook for tests. if let Some((def_id, _)) = tcx.entry_fn(()) - && find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcDelayedBugFromInsideQuery) + && find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery) { tcx.ensure_ok().trigger_delayed_bug(def_id); } diff --git a/compiler/rustc_interface/src/proc_macro_decls.rs b/compiler/rustc_interface/src/proc_macro_decls.rs index bd08faa1ed3a4..63fed51b020a9 100644 --- a/compiler/rustc_interface/src/proc_macro_decls.rs +++ b/compiler/rustc_interface/src/proc_macro_decls.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; use rustc_middle::query::Providers; @@ -8,7 +7,7 @@ fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option { let mut decls = None; for id in tcx.hir_free_items() { - if find_attr!(tcx.hir_attrs(id.hir_id()), AttributeKind::RustcProcMacroDecls) { + if find_attr!(tcx.hir_attrs(id.hir_id()), RustcProcMacroDecls) { decls = Some(id.owner_id.def_id); } } diff --git a/compiler/rustc_lint/src/autorefs.rs b/compiler/rustc_lint/src/autorefs.rs index 5bb7df80ffb36..34049288ea809 100644 --- a/compiler/rustc_lint/src/autorefs.rs +++ b/compiler/rustc_lint/src/autorefs.rs @@ -1,5 +1,4 @@ use rustc_ast::{BorrowKind, UnOp}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Expr, ExprKind, Mutability, find_attr}; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AutoBorrow, DerefAdjustKind, OverloadedDeref, @@ -108,7 +107,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitAutorefs { ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id), _ => None, } - && method_did.map(|did| find_attr!(cx.tcx.get_all_attrs(did), AttributeKind::RustcNoImplicitAutorefs)).unwrap_or(true) + && method_did.map(|did| find_attr!(cx.tcx, did, RustcNoImplicitAutorefs)).unwrap_or(true) { cx.emit_span_lint( DANGEROUS_IMPLICIT_AUTOREFS, diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 42e7142300103..c83de3b38eb5b 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -980,15 +980,14 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { let attrs = cx.tcx.hir_attrs(it.hir_id()); match it.kind { hir::ItemKind::Fn { .. } => { - if let Some(attr_span) = - find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span) - .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span)) + if let Some(attr_span) = find_attr!(attrs, ExportName {span, ..} => *span) + .or_else(|| find_attr!(attrs, NoMangle(span) => *span)) { self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id); } } hir::ItemKind::Const(ident, generics, ..) => { - if find_attr!(attrs, AttributeKind::NoMangle(..)) { + if find_attr!(attrs, NoMangle(..)) { let suggestion = if generics.params.is_empty() && generics.where_clause_span.is_empty() { // account for "pub const" (#45562) @@ -1014,9 +1013,8 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { let attrs = cx.tcx.hir_attrs(it.hir_id()); match it.kind { hir::ImplItemKind::Fn { .. } => { - if let Some(attr_span) = - find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span) - .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span)) + if let Some(attr_span) = find_attr!(attrs, ExportName {span, ..} => *span) + .or_else(|| find_attr!(attrs, NoMangle(span) => *span)) { self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id); } @@ -1178,7 +1176,7 @@ impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller { if fn_kind.asyncness().is_async() && !cx.tcx.features().async_fn_track_caller() // Now, check if the function has the `#[track_caller]` attribute - && let Some(attr_span) = find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::TrackCaller(span) => *span) + && let Some(attr_span) = find_attr!(cx.tcx, def_id, TrackCaller(span) => *span) { cx.emit_span_lint( UNGATED_ASYNC_FN_TRACK_CALLER, diff --git a/compiler/rustc_lint/src/dangling.rs b/compiler/rustc_lint/src/dangling.rs index 71ea801a408ed..448c0ded637c6 100644 --- a/compiler/rustc_lint/src/dangling.rs +++ b/compiler/rustc_lint/src/dangling.rs @@ -1,5 +1,4 @@ use rustc_ast::visit::{visit_opt, walk_list}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{FnKind, Visitor, walk_expr}; @@ -268,7 +267,7 @@ fn lint_expr(cx: &LateContext<'_>, expr: &Expr<'_>) { && let ty = cx.typeck_results().expr_ty(receiver) && owns_allocation(cx.tcx, ty) && let Some(fn_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) - && find_attr!(cx.tcx.get_all_attrs(fn_id), AttributeKind::RustcAsPtr(_)) + && find_attr!(cx.tcx, fn_id, RustcAsPtr(_)) { // FIXME: use `emit_node_lint` when `#[primary_span]` is added. cx.tcx.emit_node_span_lint( diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index ad73e15e31f37..d234c68631030 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -2,7 +2,6 @@ use rustc_abi::FIRST_VARIANT; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::find_attr; use rustc_middle::query::Providers; @@ -183,11 +182,7 @@ fn name_of_extern_decl(tcx: TyCtxt<'_>, fi: hir::OwnerId) -> SymbolName { // information, we could have codegen_fn_attrs also give span information back for // where the attribute was defined. However, until this is found to be a // bottleneck, this does just fine. - ( - overridden_link_name, - find_attr!(tcx.get_all_attrs(fi), AttributeKind::LinkName {span, ..} => *span) - .unwrap(), - ) + (overridden_link_name, find_attr!(tcx, fi, LinkName {span, ..} => *span).unwrap()) }) { SymbolName::Link(overridden_link_name, overridden_link_name_span) diff --git a/compiler/rustc_lint/src/gpukernel_abi.rs b/compiler/rustc_lint/src/gpukernel_abi.rs index dbdf5b6e7955f..4fb26739cd28a 100644 --- a/compiler/rustc_lint/src/gpukernel_abi.rs +++ b/compiler/rustc_lint/src/gpukernel_abi.rs @@ -1,7 +1,6 @@ use std::iter; use rustc_abi::ExternAbi; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{self as hir, find_attr}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_session::{declare_lint, declare_lint_pass}; @@ -184,10 +183,7 @@ impl<'tcx> LateLintPass<'tcx> for ImproperGpuKernelLint { } // Check for no_mangle/export_name, so the kernel can be found when querying the compiled object for the kernel function by name - if !find_attr!( - cx.tcx.get_all_attrs(id), - AttributeKind::NoMangle(..) | AttributeKind::ExportName { .. } - ) { + if !find_attr!(cx.tcx, id, NoMangle(..) | ExportName { .. }) { cx.emit_span_lint(MISSING_GPU_KERNEL_EXPORT_NAME, span, MissingGpuKernelExportName); } } diff --git a/compiler/rustc_lint/src/interior_mutable_consts.rs b/compiler/rustc_lint/src/interior_mutable_consts.rs index 4c7d2c6af93b1..807a121abd9e6 100644 --- a/compiler/rustc_lint/src/interior_mutable_consts.rs +++ b/compiler/rustc_lint/src/interior_mutable_consts.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{Expr, ExprKind, ItemKind, Node, find_attr}; use rustc_middle::ty::adjustment::Adjust; @@ -87,8 +86,8 @@ impl<'tcx> LateLintPass<'tcx> for InteriorMutableConsts { .any(|adj| matches!(adj.kind, Adjust::Deref(_))) // Let's do the attribute check after the other checks for perf reasons && find_attr!( - cx.tcx.get_all_attrs(method_did), - AttributeKind::RustcShouldNotBeCalledOnConstItems(_) + cx.tcx, method_did, + RustcShouldNotBeCalledOnConstItems(_) ) && let Some(method_name) = cx.tcx.opt_item_ident(method_did) && let Some(const_name) = cx.tcx.opt_item_ident(const_did) diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 37eb375c7a6c2..87c36f41afab1 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -1,7 +1,7 @@ //! Some lints that are only useful in the compiler or crates that use compiler internals, such as //! Clippy. -use rustc_hir::attrs::AttributeKind; +use rustc_ast::{Pat, PatKind, Path}; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, HirId, find_attr}; @@ -12,10 +12,10 @@ use rustc_span::{Span, sym}; use {rustc_ast as ast, rustc_hir as hir}; use crate::lints::{ - BadOptAccessDiag, DefaultHashTypesDiag, ImplicitSysrootCrateImportDiag, LintPassByHand, - NonGlobImportTypeIrInherent, QueryInstability, QueryUntracked, SpanUseEqCtxtDiag, - SymbolInternStringLiteralDiag, TyQualified, TykindDiag, TykindKind, TypeIrDirectUse, - TypeIrInherentUsage, TypeIrTraitUsage, + AttributeKindInFindAttr, BadOptAccessDiag, DefaultHashTypesDiag, + ImplicitSysrootCrateImportDiag, LintPassByHand, NonGlobImportTypeIrInherent, QueryInstability, + QueryUntracked, SpanUseEqCtxtDiag, SymbolInternStringLiteralDiag, TyQualified, TykindDiag, + TykindKind, TypeIrDirectUse, TypeIrInherentUsage, TypeIrTraitUsage, }; use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; @@ -90,7 +90,7 @@ impl<'tcx> LateLintPass<'tcx> for QueryStability { ty::Instance::try_resolve(cx.tcx, cx.typing_env(), callee_def_id, generic_args) { let def_id = instance.def_id(); - if find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::RustcLintQueryInstability) { + if find_attr!(cx.tcx, def_id, RustcLintQueryInstability) { cx.emit_span_lint( POTENTIAL_QUERY_INSTABILITY, span, @@ -105,10 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for QueryStability { ); } - if find_attr!( - cx.tcx.get_all_attrs(def_id), - AttributeKind::RustcLintUntrackedQueryInformation - ) { + if find_attr!(cx.tcx, def_id, RustcLintUntrackedQueryInformation) { cx.emit_span_lint( UNTRACKED_QUERY_INFORMATION, span, @@ -153,10 +150,7 @@ fn has_unstable_into_iter_predicate<'tcx>( }; // Does the input type's `IntoIterator` implementation have the // `rustc_lint_query_instability` attribute on its `into_iter` method? - if find_attr!( - cx.tcx.get_all_attrs(instance.def_id()), - AttributeKind::RustcLintQueryInstability - ) { + if find_attr!(cx.tcx, instance.def_id(), RustcLintQueryInstability) { return true; } } @@ -508,13 +502,13 @@ impl LateLintPass<'_> for BadOptAccess { let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return }; // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be // avoided. - if !find_attr!(cx.tcx.get_all_attrs(adt_def.did()), AttributeKind::RustcLintOptTy) { + if !find_attr!(cx.tcx, adt_def.did(), RustcLintOptTy) { return; } for field in adt_def.all_fields() { if field.name == target.name - && let Some(lint_message) = find_attr!(cx.tcx.get_all_attrs(field.did), AttributeKind::RustcLintOptDenyFieldAccess { lint_message, } => lint_message) + && let Some(lint_message) = find_attr!(cx.tcx, field.did, RustcLintOptDenyFieldAccess { lint_message, } => lint_message) { cx.emit_span_lint( BAD_OPT_ACCESS, @@ -627,3 +621,94 @@ impl EarlyLintPass for ImplicitSysrootCrateImport { } } } + +declare_tool_lint! { + pub rustc::BAD_USE_OF_FIND_ATTR, + Allow, + "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.", + report_in_external_macro: true +} +declare_lint_pass!(BadUseOfFindAttr => [BAD_USE_OF_FIND_ATTR]); + +impl EarlyLintPass for BadUseOfFindAttr { + fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &rustc_ast::Arm) { + fn path_contains_attribute_kind(cx: &EarlyContext<'_>, path: &Path) { + for segment in &path.segments { + if segment.ident.as_str() == "AttributeKind" { + cx.emit_span_lint( + BAD_USE_OF_FIND_ATTR, + segment.span(), + AttributeKindInFindAttr {}, + ); + } + } + } + + fn find_attr_kind_in_pat(cx: &EarlyContext<'_>, pat: &Pat) { + match &pat.kind { + PatKind::Struct(_, path, fields, _) => { + path_contains_attribute_kind(cx, path); + for field in fields { + find_attr_kind_in_pat(cx, &field.pat); + } + } + PatKind::TupleStruct(_, path, fields) => { + path_contains_attribute_kind(cx, path); + for field in fields { + find_attr_kind_in_pat(cx, &field); + } + } + PatKind::Or(options) => { + for pat in options { + find_attr_kind_in_pat(cx, pat); + } + } + PatKind::Path(_, path) => { + path_contains_attribute_kind(cx, path); + } + PatKind::Tuple(elems) => { + for pat in elems { + find_attr_kind_in_pat(cx, pat); + } + } + PatKind::Box(pat) => { + find_attr_kind_in_pat(cx, pat); + } + PatKind::Deref(pat) => { + find_attr_kind_in_pat(cx, pat); + } + PatKind::Ref(..) => { + find_attr_kind_in_pat(cx, pat); + } + PatKind::Slice(elems) => { + for pat in elems { + find_attr_kind_in_pat(cx, pat); + } + } + + PatKind::Guard(pat, ..) => { + find_attr_kind_in_pat(cx, pat); + } + PatKind::Paren(pat) => { + find_attr_kind_in_pat(cx, pat); + } + PatKind::Expr(..) + | PatKind::Range(..) + | PatKind::MacCall(..) + | PatKind::Rest + | PatKind::Missing + | PatKind::Err(..) + | PatKind::Ident(..) + | PatKind::Never + | PatKind::Wild => {} + } + } + + if let Some(expn_data) = arm.span.source_callee() + && let ExpnKind::Macro(_, name) = expn_data.kind + && name.as_str() == "find_attr" + { + find_attr_kind_in_pat(cx, &arm.pat); + } + } +} diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 58fa6562f2a6b..a5c3a889826c7 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -665,6 +665,8 @@ fn register_internals(store: &mut LintStore) { store.register_late_mod_pass(|_| Box::new(SymbolInternStringLiteral)); store.register_lints(&ImplicitSysrootCrateImport::lint_vec()); store.register_early_pass(|| Box::new(ImplicitSysrootCrateImport)); + store.register_lints(&BadUseOfFindAttr::lint_vec()); + store.register_early_pass(|| Box::new(BadUseOfFindAttr)); store.register_group( false, "rustc::internal", @@ -684,6 +686,7 @@ fn register_internals(store: &mut LintStore) { LintId::of(SPAN_USE_EQ_CTXT), LintId::of(DIRECT_USE_OF_RUSTC_TYPE_IR), LintId::of(IMPLICIT_SYSROOT_CRATE_IMPORT), + LintId::of(BAD_USE_OF_FIND_ATTR), ], ); } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 3b34a217edfd9..5627f34f82e97 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -1143,6 +1143,12 @@ pub(crate) struct ImplicitSysrootCrateImportDiag<'a> { pub name: &'a str, } +#[derive(LintDiagnostic)] +#[diag("use of `AttributeKind` in `find_attr!(...)` invocation")] +#[note("`find_attr!(...)` already imports `AttributeKind::*`")] +#[help("remove `AttributeKind`")] +pub(crate) struct AttributeKindInFindAttr {} + // let_underscore.rs #[derive(LintDiagnostic)] pub(crate) enum NonBindingLet { diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 8fb6532e68c4c..2b9a65f84a026 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -1,5 +1,4 @@ use rustc_errors::{MultiSpan, msg}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{self, Visitor, VisitorExt}; use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, TyKind, find_attr}; @@ -243,10 +242,7 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { ) } ItemKind::Macro(_, _macro, _kinds) - if find_attr!( - cx.tcx.get_all_attrs(item.owner_id.def_id), - AttributeKind::MacroExport { .. } - ) => + if find_attr!(cx.tcx, item.owner_id.def_id, MacroExport { .. }) => { cx.emit_span_lint( NON_LOCAL_DEFINITIONS, diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index b90abe0a24f15..1496e3974bd75 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -322,7 +322,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name { Some(Ident::from_str(name)) } else { - find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::CrateName{name, name_span,..} => (name, name_span)).map( + find_attr!(cx.tcx, crate, CrateName{name, name_span,..} => (name, name_span)).map( |(&name, &span)| { // Discard the double quotes surrounding the literal. let sp = cx @@ -335,8 +335,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?; Some( - span - .with_lo(span.lo() + BytePos(left as u32 + 1)) + span.with_lo(span.lo() + BytePos(left as u32 + 1)) .with_hi(span.hi() - BytePos(right as u32)), ) }) @@ -370,9 +369,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { match &fk { FnKind::Method(ident, sig, ..) => match cx.tcx.associated_item(id).container { AssocContainer::InherentImpl => { - if sig.header.abi != ExternAbi::Rust - && find_attr!(cx.tcx.get_all_attrs(id), AttributeKind::NoMangle(..)) - { + if sig.header.abi != ExternAbi::Rust && find_attr!(cx.tcx, id, NoMangle(..)) { return; } self.check_snake_case(cx, "method", ident); @@ -384,9 +381,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { }, FnKind::ItemFn(ident, _, header) => { // Skip foreign-ABI #[no_mangle] functions (Issue #31924) - if header.abi != ExternAbi::Rust - && find_attr!(cx.tcx.get_all_attrs(id), AttributeKind::NoMangle(..)) - { + if header.abi != ExternAbi::Rust && find_attr!(cx.tcx, id, NoMangle(..)) { return; } self.check_snake_case(cx, "function", ident); @@ -551,9 +546,7 @@ impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals { fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { let attrs = cx.tcx.hir_attrs(it.hir_id()); match it.kind { - hir::ItemKind::Static(_, ident, ..) - if !find_attr!(attrs, AttributeKind::NoMangle(..)) => - { + hir::ItemKind::Static(_, ident, ..) if !find_attr!(attrs, NoMangle(..)) => { NonUpperCaseGlobals::check_upper_case( cx, "static variable", diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index 3823c9aa1861e..5a4eb29433815 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -1,4 +1,3 @@ -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; use rustc_hir::{self as hir, AmbigArg, GenericArg, PathSegment, QPath, TyKind, find_attr}; use rustc_middle::ty; @@ -43,19 +42,14 @@ impl<'tcx> LateLintPass<'tcx> for PassByValue { fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option { if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind { match path.res { - Res::Def(_, def_id) - if find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::RustcPassByValue(_)) => - { + Res::Def(_, def_id) if find_attr!(cx.tcx, def_id, RustcPassByValue(_)) => { let name = cx.tcx.item_ident(def_id); let path_segment = path.segments.last().unwrap(); return Some(format!("{}{}", name, gen_args(cx, path_segment))); } Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => { if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().kind() { - if find_attr!( - cx.tcx.get_all_attrs(adt.did()), - AttributeKind::RustcPassByValue(_) - ) { + if find_attr!(cx.tcx, adt.did(), RustcPassByValue(_)) { return Some(cx.tcx.def_path_str_with_args(adt.did(), args)); } } diff --git a/compiler/rustc_lint/src/ptr_nulls.rs b/compiler/rustc_lint/src/ptr_nulls.rs index b89e00dcbaae3..18a80684fa44e 100644 --- a/compiler/rustc_lint/src/ptr_nulls.rs +++ b/compiler/rustc_lint/src/ptr_nulls.rs @@ -1,5 +1,4 @@ use rustc_ast::LitKind; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{BinOpKind, Expr, ExprKind, TyKind, find_attr}; use rustc_middle::ty::RawPtr; use rustc_session::{declare_lint, declare_lint_pass}; @@ -73,14 +72,14 @@ fn useless_check<'a, 'tcx: 'a>( e = e.peel_blocks(); if let ExprKind::MethodCall(_, _expr, [], _) = e.kind && let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) - && find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::RustcNeverReturnsNullPointer) + && find_attr!(cx.tcx, def_id, RustcNeverReturnsNullPointer) && let Some(fn_name) = cx.tcx.opt_item_ident(def_id) { return Some(UselessPtrNullChecksDiag::FnRet { fn_name }); } else if let ExprKind::Call(path, _args) = e.kind && let ExprKind::Path(ref qpath) = path.kind && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id() - && find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::RustcNeverReturnsNullPointer) + && find_attr!(cx.tcx, def_id, RustcNeverReturnsNullPointer) && let Some(fn_name) = cx.tcx.opt_item_ident(def_id) { return Some(UselessPtrNullChecksDiag::FnRet { fn_name }); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index b5126fffc1c5d..a2427d9ca5889 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1,7 +1,6 @@ use std::iter; use rustc_abi::{BackendRepr, TagEncoding, Variants, WrappingRange}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Expr, ExprKind, HirId, LangItem, find_attr}; use rustc_middle::bug; use rustc_middle::ty::layout::{LayoutOf, SizeSkeleton}; @@ -687,7 +686,7 @@ pub(crate) fn nonnull_optimization_guaranteed<'tcx>( tcx: TyCtxt<'tcx>, def: ty::AdtDef<'tcx>, ) -> bool { - find_attr!(tcx.get_all_attrs(def.did()), AttributeKind::RustcNonnullOptimizationGuaranteed) + find_attr!(tcx, def.did(), RustcNonnullOptimizationGuaranteed) } /// `repr(transparent)` structs can have a single non-1-ZST field, this function returns that diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 8b2a6d1d2ab53..4b3a49af08369 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -4,7 +4,6 @@ use rustc_ast::util::{classify, parser}; use rustc_ast::{self as ast, ExprKind, FnRetTy, HasAttrs as _, StmtKind}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{MultiSpan, pluralize}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem, find_attr}; @@ -401,8 +400,8 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option { if let Some(reason) = find_attr!( - cx.tcx.get_all_attrs(def_id), - AttributeKind::MustUse { reason, .. } => reason + cx.tcx, def_id, + MustUse { reason, .. } => reason ) { // check for #[must_use = "..."] Some(MustUsePath::Def(span, def_id, *reason)) diff --git a/compiler/rustc_metadata/src/eii.rs b/compiler/rustc_metadata/src/eii.rs index 42497a82ef8c0..f3ce07aa75a11 100644 --- a/compiler/rustc_metadata/src/eii.rs +++ b/compiler/rustc_metadata/src/eii.rs @@ -1,5 +1,5 @@ use rustc_data_structures::fx::FxIndexMap; -use rustc_hir::attrs::{AttributeKind, EiiDecl, EiiImpl, EiiImplResolution}; +use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution}; use rustc_hir::def_id::DefId; use rustc_hir::find_attr; use rustc_middle::query::LocalCrate; @@ -25,14 +25,11 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, LocalCrate: LocalCrate) -> EiiMap // iterate over all items in the current crate for id in tcx.hir_crate_items(()).eiis() { - for i in - find_attr!(tcx.get_all_attrs(id), AttributeKind::EiiImpls(e) => e).into_iter().flatten() - { + for i in find_attr!(tcx, id, EiiImpls(e) => e).into_iter().flatten() { let decl = match i.resolution { EiiImplResolution::Macro(macro_defid) => { // find the decl for this one if it wasn't in yet (maybe it's from the local crate? not very useful but not illegal) - let Some(decl) = find_attr!(tcx.get_all_attrs(macro_defid), AttributeKind::EiiDeclaration(d) => *d) - else { + let Some(decl) = find_attr!(tcx, macro_defid, EiiDeclaration(d) => *d) else { // skip if it doesn't have eii_declaration (if we resolved to another macro that's not an EII) tcx.dcx() .span_delayed_bug(i.span, "resolved to something that's not an EII"); @@ -52,9 +49,7 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, LocalCrate: LocalCrate) -> EiiMap } // if we find a new declaration, add it to the list without a known implementation - if let Some(decl) = - find_attr!(tcx.get_all_attrs(id), AttributeKind::EiiDeclaration(d) => *d) - { + if let Some(decl) = find_attr!(tcx, id, EiiDeclaration(d) => *d) { eiis.entry(decl.foreign_item).or_insert((decl, Default::default())); } } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index f969bb734d6d6..52b11615c76f0 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use rustc_abi::ExternAbi; use rustc_attr_parsing::eval_config_entry; use rustc_data_structures::fx::FxHashSet; -use rustc_hir::attrs::{AttributeKind, NativeLibKind, PeImportNameType}; +use rustc_hir::attrs::{NativeLibKind, PeImportNameType}; use rustc_hir::find_attr; use rustc_middle::query::LocalCrate; use rustc_middle::ty::{self, List, Ty, TyCtxt}; @@ -214,10 +214,7 @@ impl<'tcx> Collector<'tcx> { } for attr in - find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::Link(links, _) => links) - .iter() - .map(|v| v.iter()) - .flatten() + find_attr!(self.tcx, def_id, Link(links, _) => links).iter().map(|v| v.iter()).flatten() { let dll_imports = match attr.kind { NativeLibKind::RawDylib { .. } => foreign_items @@ -232,7 +229,8 @@ impl<'tcx> Collector<'tcx> { .collect(), _ => { for &child_item in foreign_items { - if let Some(span) = find_attr!(self.tcx.get_all_attrs(child_item), AttributeKind::LinkOrdinal {span, ..} => *span) + if let Some(span) = + find_attr!(self.tcx, child_item, LinkOrdinal {span, ..} => *span) { sess.dcx().emit_err(errors::LinkOrdinalRawDylib { span }); } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index a3d8b07fb1d9a..e9ae43b78d542 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -734,16 +734,16 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE), has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), - has_default_lib_allocator: find_attr!(attrs, AttributeKind::DefaultLibAllocator), + has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator), externally_implementable_items, proc_macro_data, debugger_visualizers, - compiler_builtins: find_attr!(attrs, AttributeKind::CompilerBuiltins), - needs_allocator: find_attr!(attrs, AttributeKind::NeedsAllocator), - needs_panic_runtime: find_attr!(attrs, AttributeKind::NeedsPanicRuntime), - no_builtins: find_attr!(attrs, AttributeKind::NoBuiltins), - panic_runtime: find_attr!(attrs, AttributeKind::PanicRuntime), - profiler_runtime: find_attr!(attrs, AttributeKind::ProfilerRuntime), + compiler_builtins: find_attr!(attrs, CompilerBuiltins), + needs_allocator: find_attr!(attrs, NeedsAllocator), + needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime), + no_builtins: find_attr!(attrs, NoBuiltins), + panic_runtime: find_attr!(attrs, PanicRuntime), + profiler_runtime: find_attr!(attrs, ProfilerRuntime), symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), crate_deps, @@ -2012,11 +2012,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // Proc-macros may have attributes like `#[allow_internal_unstable]`, // so downstream crates need access to them. let attrs = tcx.hir_attrs(proc_macro); - let macro_kind = if find_attr!(attrs, AttributeKind::ProcMacro(..)) { + let macro_kind = if find_attr!(attrs, ProcMacro(..)) { MacroKind::Bang - } else if find_attr!(attrs, AttributeKind::ProcMacroAttribute(..)) { + } else if find_attr!(attrs, ProcMacroAttribute(..)) { MacroKind::Attr - } else if let Some(trait_name) = find_attr!(attrs, AttributeKind::ProcMacroDerive { trait_name, ..} => trait_name) + } else if let Some(trait_name) = + find_attr!(attrs, ProcMacroDerive { trait_name, ..} => trait_name) { name = *trait_name; MacroKind::Derive diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index ca783311586f1..67dd26c8a7d31 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -8,7 +8,6 @@ use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; @@ -369,7 +368,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn hir_rustc_coherence_is_core(self) -> bool { - find_attr!(self.hir_krate_attrs(), AttributeKind::RustcCoherenceIsCore(..)) + find_attr!(self.hir_krate_attrs(), RustcCoherenceIsCore(..)) } pub fn hir_get_module(self, module: LocalModDefId) -> (&'tcx Mod<'tcx>, Span, HirId) { diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index e4715f6e2c10b..f039799c3b7b6 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -9,7 +9,7 @@ use rustc_macros::{Decodable, Encodable, HashStable}; use rustc_session::Session; use rustc_session::lint::builtin::{self, FORBIDDEN_LINT_GROUPS}; use rustc_session::lint::{FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId}; -use rustc_span::{DUMMY_SP, Span, Symbol, kw}; +use rustc_span::{DUMMY_SP, ExpnKind, Span, Symbol, kw}; use tracing::instrument; use crate::ty::TyCtxt; @@ -380,7 +380,17 @@ pub fn lint_level( // allow individual lints to opt-out from being reported. let incompatible = future_incompatible.is_some_and(|f| f.reason.edition().is_none()); - if !incompatible && !lint.report_in_external_macro { + // In rustc, for the find_attr macro, we want to always emit this. + // This completely circumvents normal lint checking, which usually doesn't happen for macros from other crates. + // However, we kind of want that when using find_attr from another rustc crate. So we cheat a little. + let is_in_find_attr = sess.enable_internal_lints() + && err.span.primary_spans().iter().any(|s| { + s.source_callee().is_some_and( + |i| matches!(i.kind, ExpnKind::Macro(_, name) if name.as_str() == "find_attr") + ) + }); + + if !incompatible && !lint.report_in_external_macro && !is_in_find_attr { err.cancel(); // Don't continue further, since we don't want to have diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 84415a592a2ec..6367c87b1aa95 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -1,6 +1,5 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_hir::find_attr; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; @@ -62,7 +61,7 @@ pub enum OverlapMode { impl OverlapMode { pub fn get(tcx: TyCtxt<'_>, trait_id: DefId) -> OverlapMode { let with_negative_coherence = tcx.features().with_negative_coherence(); - let strict_coherence = find_attr!(tcx.get_all_attrs(trait_id), AttributeKind::RustcStrictCoherence(span) => *span); + let strict_coherence = find_attr!(tcx, trait_id, RustcStrictCoherence(span) => *span); if with_negative_coherence { if strict_coherence.is_some() { OverlapMode::Strict } else { OverlapMode::WithNegative } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 242d3742abad0..020669588ac5c 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -9,7 +9,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher}; use rustc_errors::ErrorGuaranteed; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem, find_attr}; @@ -282,13 +281,11 @@ impl AdtDefData { debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr); let mut flags = AdtFlags::NO_ADT_FLAGS; - if kind == AdtKind::Enum - && find_attr!(tcx.get_all_attrs(did), AttributeKind::NonExhaustive(..)) - { + if kind == AdtKind::Enum && find_attr!(tcx, did, NonExhaustive(..)) { debug!("found non-exhaustive variant list for {:?}", did); flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE; } - if find_attr!(tcx.get_all_attrs(did), AttributeKind::PinV2(..)) { + if find_attr!(tcx, did, PinV2(..)) { debug!("found pin-project type {:?}", did); flags |= AdtFlags::IS_PIN_PROJECT; } @@ -303,7 +300,7 @@ impl AdtDefData { flags |= AdtFlags::HAS_CTOR; } - if find_attr!(tcx.get_all_attrs(did), AttributeKind::Fundamental) { + if find_attr!(tcx, did, Fundamental) { flags |= AdtFlags::IS_FUNDAMENTAL; } if tcx.is_lang_item(did, LangItem::PhantomData) { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 94a77ce13c14a..47843a260440e 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -30,7 +30,6 @@ use rustc_data_structures::sync::{ self, DynSend, DynSync, FreezeReadGuard, Lock, RwLock, WorkerLocal, }; use rustc_errors::{Applicability, Diag, DiagCtxtHandle, LintDiagnostic, MultiSpan}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::{DefPathData, Definitions, DisambiguatorState}; @@ -994,8 +993,10 @@ impl<'tcx> TyCtxt<'tcx> { /// `rustc_layout_scalar_valid_range` attribute. // FIXME(eddyb) this is an awkward spot for this method, maybe move it? pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { - let start = find_attr!(self.get_all_attrs(def_id), AttributeKind::RustcLayoutScalarValidRangeStart(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); - let end = find_attr!(self.get_all_attrs(def_id), AttributeKind::RustcLayoutScalarValidRangeEnd(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); + let start = find_attr!(self, def_id, RustcLayoutScalarValidRangeStart(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); + let end = + find_attr!(self, def_id, RustcLayoutScalarValidRangeEnd(n, _) => Bound::Included(**n)) + .unwrap_or(Bound::Unbounded); (start, end) } @@ -2768,7 +2769,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Whether this is a trait implementation that has `#[diagnostic::do_not_recommend]` pub fn do_not_recommend_impl(self, def_id: DefId) -> bool { - find_attr!(self.get_all_attrs(def_id), AttributeKind::DoNotRecommend { .. }) + find_attr!(self, def_id, DoNotRecommend { .. }) } pub fn is_trivial_const

(self, def_id: P) -> bool @@ -2794,10 +2795,8 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn provide(providers: &mut Providers) { - providers.is_panic_runtime = - |tcx, LocalCrate| find_attr!(tcx.hir_krate_attrs(), AttributeKind::PanicRuntime); - providers.is_compiler_builtins = - |tcx, LocalCrate| find_attr!(tcx.hir_krate_attrs(), AttributeKind::CompilerBuiltins); + providers.is_panic_runtime = |tcx, LocalCrate| find_attr!(tcx, crate, PanicRuntime); + providers.is_compiler_builtins = |tcx, LocalCrate| find_attr!(tcx, crate, CompilerBuiltins); providers.has_panic_handler = |tcx, LocalCrate| { // We want to check if the panic handler was defined in this crate tcx.lang_items().panic_impl().is_some_and(|did| did.is_local()) diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 0e9dd7dd169cf..2444046c604b8 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -10,7 +10,7 @@ use rustc_hir::lang_items::LangItem; use rustc_index::bit_set::FiniteBitSet; use rustc_macros::{Decodable, Encodable, HashStable, Lift, TyDecodable, TyEncodable}; use rustc_span::def_id::LOCAL_CRATE; -use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use crate::error; @@ -286,15 +286,6 @@ impl<'tcx> InstanceKind<'tcx> { } } - #[inline] - pub fn get_attrs( - &self, - tcx: TyCtxt<'tcx>, - attr: Symbol, - ) -> impl Iterator { - tcx.get_attrs(self.def_id(), attr) - } - /// Returns `true` if the LLVM version of this instance is unconditionally /// marked with `inline`. This implies that a copy of this instance is /// generated in every codegen unit. diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2c7244187f4fd..8511f227c6699 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -37,7 +37,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer}; -use rustc_hir::attrs::{AttributeKind, StrippedCfgItem}; +use rustc_hir::attrs::StrippedCfgItem; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; use rustc_hir::{LangItem, attrs as attr, find_attr}; @@ -1442,10 +1442,7 @@ impl<'tcx> TyCtxt<'tcx> { field_shuffle_seed ^= user_seed; } - let attributes = self.get_all_attrs(did); - let elt = find_attr!( - attributes, - AttributeKind::RustcScalableVector { element_count, .. } => element_count + let elt = find_attr!(self, did, RustcScalableVector { element_count, .. } => element_count ) .map(|elt| match elt { Some(n) => ScalableElt::ElementCount(*n), @@ -1454,7 +1451,7 @@ impl<'tcx> TyCtxt<'tcx> { if elt.is_some() { flags.insert(ReprFlags::IS_SCALABLE); } - if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) { + if let Some(reprs) = find_attr!(self, did, Repr { reprs, .. } => reprs) { for (r, _) in reprs { flags.insert(match *r { attr::ReprRust => ReprFlags::empty(), @@ -1514,7 +1511,7 @@ impl<'tcx> TyCtxt<'tcx> { } // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details. - if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) { + if find_attr!(self, did, RustcPassIndirectlyInNonRusticAbis(..)) { flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS); } @@ -1711,11 +1708,13 @@ impl<'tcx> TyCtxt<'tcx> { } /// Gets all attributes with the given name. + #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."] pub fn get_attrs( self, did: impl Into, attr: Symbol, ) -> impl Iterator { + #[allow(deprecated)] self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr)) } @@ -1723,6 +1722,7 @@ impl<'tcx> TyCtxt<'tcx> { /// /// To see if an item has a specific attribute, you should use /// [`rustc_hir::find_attr!`] so you can use matching. + #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."] pub fn get_all_attrs(self, did: impl Into) -> &'tcx [hir::Attribute] { let did: DefId = did.into(); if let Some(did) = did.as_local() { @@ -1745,17 +1745,21 @@ impl<'tcx> TyCtxt<'tcx> { } } + #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."] pub fn get_attr(self, did: impl Into, attr: Symbol) -> Option<&'tcx hir::Attribute> { if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) { let did: DefId = did.into(); bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr); } else { + #[allow(deprecated)] self.get_attrs(did, attr).next() } } /// Determines whether an item is annotated with an attribute. + #[deprecated = "Though there are valid usecases for this method, especially when your attribute is not a parsed attribute, usually you want to call rustc_hir::find_attr! instead."] pub fn has_attr(self, did: impl Into, attr: Symbol) -> bool { + #[allow(deprecated)] self.get_attrs(did, attr).next().is_some() } @@ -1987,10 +1991,7 @@ impl<'tcx> TyCtxt<'tcx> { && let Some(def_id) = def_id.as_local() && let outer = self.def_span(def_id).ctxt().outer_expn_data() && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _)) - && find_attr!( - self.get_all_attrs(outer.macro_def_id.unwrap()), - AttributeKind::RustcBuiltinMacro { .. } - ) + && find_attr!(self, outer.macro_def_id.unwrap(), RustcBuiltinMacro { .. }) { true } else { @@ -2000,7 +2001,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Check if the given `DefId` is `#\[automatically_derived\]`. pub fn is_automatically_derived(self, def_id: DefId) -> bool { - find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..)) + find_attr!(self, def_id, AutomaticallyDerived(..)) } /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err` diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 0553561fac2cb..3e69eda11ca63 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -2,7 +2,6 @@ use std::iter; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::{self as hir, find_attr}; @@ -241,7 +240,7 @@ pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> Trait /// Query provider for `incoherent_impls`. pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] { if let Some(def_id) = simp.def() - && !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcHasIncoherentInherentImpls) + && !find_attr!(tcx, def_id, RustcHasIncoherentInherentImpls) { return &[]; } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index d534c273ff65f..c3be0b630d6ed 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -4,13 +4,11 @@ use std::{fmt, iter}; use rustc_abi::{Float, Integer, IntegerType, Size}; use rustc_apfloat::Float as _; -use rustc_ast::attr::AttributeExt; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::ErrorGuaranteed; use rustc_hashes::Hash128; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::limit::Limit; @@ -1672,14 +1670,12 @@ pub fn reveal_opaque_types_in_bounds<'tcx>( /// Determines whether an item is directly annotated with `doc(hidden)`. fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - attrs.iter().any(|attr| attr.is_doc_hidden()) + find_attr!(tcx, def_id, Doc(doc) if doc.hidden.is_some()) } /// Determines whether an item is annotated with `doc(notable_trait)`. pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - let attrs = tcx.get_all_attrs(def_id); - attrs.iter().any(|attr| matches!(attr, hir::Attribute::Parsed(AttributeKind::Doc(doc)) if doc.notable_trait.is_some())) + find_attr!(tcx, def_id, Doc(doc) if doc.notable_trait.is_some()) } /// Determines whether an item is an intrinsic (which may be via Abi or via the `rustc_intrinsic` attribute). @@ -1688,9 +1684,7 @@ pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool { /// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may /// cause an ICE that we otherwise may want to prevent. pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - if tcx.features().intrinsics() - && find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcIntrinsic) - { + if tcx.features().intrinsics() && find_attr!(tcx, def_id, RustcIntrinsic) { let must_be_overridden = match tcx.hir_node_by_def_id(def_id) { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => { !has_body @@ -1700,10 +1694,7 @@ pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option( ty => span_bug!(span_with_body, "unexpected type of body: {ty:?}"), }; - if let Some((dialect, phase)) = find_attr!(tcx.hir_attrs(fn_id), AttributeKind::CustomMir(dialect, phase, _) => (dialect, phase)) + if let Some((dialect, phase)) = + find_attr!(tcx.hir_attrs(fn_id), CustomMir(dialect, phase, _) => (dialect, phase)) { return custom::build_custom_mir( tcx, diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 48c512339ce17..001c4338ad0e1 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -5,7 +5,6 @@ use std::ops::Bound; use rustc_ast::AsmMacro; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::DiagArgValue; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability, find_attr}; use rustc_middle::middle::codegen_fn_attrs::{TargetFeature, TargetFeatureKind}; @@ -98,7 +97,7 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> { // from an edition before 2024. &UnsafeOpKind::CallToUnsafeFunction(Some(id)) if !span.at_least_rust_2024() - && let Some(suggestion) = find_attr!(self.tcx.get_all_attrs(id), AttributeKind::RustcDeprecatedSafe2024{suggestion} => suggestion) => + && let Some(suggestion) = find_attr!(self.tcx, id, RustcDeprecatedSafe2024{suggestion} => suggestion) => { let sm = self.tcx.sess.source_map(); let guarantee = format!("that {}", suggestion); @@ -1146,7 +1145,7 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { // Closures and inline consts are handled by their owner, if it has a body assert!(!tcx.is_typeck_child(def.to_def_id())); // Also, don't safety check custom MIR - if find_attr!(tcx.get_all_attrs(def), AttributeKind::CustomMir(..) => ()).is_some() { + if find_attr!(tcx, def, CustomMir(..) => ()).is_some() { return; } diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index fa3f89dfc4fcf..3d94ee701f564 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -3,7 +3,6 @@ use rustc_abi::{FIRST_VARIANT, FieldIdx, Size, VariantIdx}; use rustc_ast::UnsafeBinderCastKind; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::{LangItem, find_attr}; use rustc_index::Idx; @@ -865,7 +864,7 @@ impl<'tcx> ThirBuildCx<'tcx> { hir::ExprKind::Ret(v) => ExprKind::Return { value: v.map(|v| self.mirror_expr(v)) }, hir::ExprKind::Become(call) => ExprKind::Become { value: self.mirror_expr(call) }, hir::ExprKind::Break(dest, ref value) => { - if find_attr!(self.tcx.hir_attrs(expr.hir_id), AttributeKind::ConstContinue(_)) { + if find_attr!(self.tcx.hir_attrs(expr.hir_id), ConstContinue(_)) { match dest.target_id { Ok(target_id) => { let (Some(value), Some(_)) = (value, dest.label) else { @@ -930,7 +929,7 @@ impl<'tcx> ThirBuildCx<'tcx> { match_source, }, hir::ExprKind::Loop(body, ..) => { - if find_attr!(self.tcx.hir_attrs(expr.hir_id), AttributeKind::LoopMatch(_)) { + if find_attr!(self.tcx.hir_attrs(expr.hir_id), LoopMatch(_)) { let dcx = self.tcx.dcx(); // Accept either `state = expr` or `state = expr;`. diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index b08d1d4bcf27d..60cb509ee9dd2 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -4,7 +4,6 @@ use rustc_data_structures::steal::Steal; use rustc_errors::ErrorGuaranteed; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; @@ -105,8 +104,7 @@ impl<'tcx> ThirBuildCx<'tcx> { typing_env: ty::TypingEnv::non_body_analysis(tcx, def), typeck_results, body_owner: def.to_def_id(), - apply_adjustments: - !find_attr!(tcx.hir_attrs(hir_id), AttributeKind::CustomMir(..) => ()).is_some(), + apply_adjustments: !find_attr!(tcx.hir_attrs(hir_id), CustomMir(..) => ()).is_some(), } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index cce5776293e23..ae24605c39b43 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -5,7 +5,6 @@ use rustc_apfloat::Float; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{Diag, msg}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_index::Idx; use rustc_infer::infer::TyCtxtInferExt; @@ -488,8 +487,7 @@ fn type_has_partial_eq_impl<'tcx>( let mut structural_peq = false; let mut impl_def_id = None; for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) { - automatically_derived = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..)); + automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived(..)); impl_def_id = Some(def_id); } for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) { diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index c4b9b4ce64161..6c0f2e8d73058 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -8,7 +8,7 @@ use std::{io, ops, str}; use regex::Regex; use rustc_graphviz as dot; -use rustc_hir::attrs::{AttributeKind, BorrowckGraphvizFormatKind, RustcMirKind}; +use rustc_hir::attrs::{BorrowckGraphvizFormatKind, RustcMirKind}; use rustc_hir::find_attr; use rustc_index::bit_set::DenseBitSet; use rustc_middle::mir::{ @@ -97,8 +97,7 @@ impl RustcMirAttrs { fn parse(tcx: TyCtxt<'_>, def_id: DefId) -> Self { let mut ret = RustcMirAttrs::default(); - let attrs = tcx.get_all_attrs(def_id); - if let Some(rustc_mir_attrs) = find_attr!(attrs, AttributeKind::RustcMir(kind) => kind) { + if let Some(rustc_mir_attrs) = find_attr!(tcx, def_id, RustcMir(kind) => kind) { for attr in rustc_mir_attrs { match attr { RustcMirKind::BorrowckGraphvizPostflow { path } => { diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 1c5b383616690..5b5afd7ecc7db 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -1,4 +1,4 @@ -use rustc_hir::attrs::{AttributeKind, RustcMirKind}; +use rustc_hir::attrs::RustcMirKind; use rustc_hir::find_attr; use rustc_middle::mir::{self, Body, Local, Location}; use rustc_middle::ty::{self, Ty, TyCtxt}; @@ -16,8 +16,7 @@ use crate::{Analysis, JoinSemiLattice, ResultsCursor}; pub fn sanity_check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { let def_id = body.source.def_id(); - let attrs = tcx.get_all_attrs(def_id); - if let Some(kind) = find_attr!(attrs, AttributeKind::RustcMir(kind) => kind) { + if let Some(kind) = find_attr!(tcx, def_id, RustcMir(kind) => kind) { let move_data = MoveData::gather_moves(body, tcx, |_| true); debug!("running rustc_peek::SanityCheck on {}", tcx.def_path_str(def_id)); if kind.contains(&RustcMirKind::PeekMaybeInit) { diff --git a/compiler/rustc_mir_transform/src/check_inline.rs b/compiler/rustc_mir_transform/src/check_inline.rs index 1f65bd1ba69bc..aa945266413d0 100644 --- a/compiler/rustc_mir_transform/src/check_inline.rs +++ b/compiler/rustc_mir_transform/src/check_inline.rs @@ -1,7 +1,7 @@ //! Check that a body annotated with `#[rustc_force_inline]` will not fail to inline based on its //! definition alone (irrespective of any specific caller). -use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def_id::DefId; use rustc_hir::find_attr; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; @@ -42,7 +42,7 @@ pub(super) fn is_inline_valid_on_fn<'tcx>( ) -> Result<(), &'static str> { let codegen_attrs = tcx.codegen_fn_attrs(def_id); - if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcNoMirInline) { + if find_attr!(tcx, def_id, RustcNoMirInline) { return Err("#[rustc_no_mir_inline]"); } @@ -63,7 +63,7 @@ pub(super) fn is_inline_valid_on_fn<'tcx>( // but at this stage we don't know whether codegen knows the intrinsic, // so just conservatively don't inline it. This also ensures that we do not // accidentally inline the body of an intrinsic that *must* be overridden. - if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcIntrinsic) { + if find_attr!(tcx, def_id, RustcIntrinsic) { return Err("callee is an intrinsic"); } diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 705551c58f320..c83b10a5e583a 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -64,7 +64,6 @@ use itertools::izip; use rustc_abi::{FieldIdx, VariantIdx}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; -use rustc_hir::attrs::AttributeKind; use rustc_hir::lang_items::LangItem; use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind, find_attr}; use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet}; @@ -1988,9 +1987,7 @@ fn check_must_not_suspend_def( hir_id: hir::HirId, data: SuspendCheckData<'_>, ) -> bool { - if let Some(reason_str) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::MustNotSupend {reason} => reason) - { + if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSupend {reason} => reason) { let reason = reason_str.map(|s| errors::MustNotSuspendReason { span: data.source_span, reason: s }); tcx.emit_node_span_lint( diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 63c550c27fe4e..85870be912b56 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -1,4 +1,4 @@ -use rustc_hir::attrs::{AttributeKind, CoverageAttrKind}; +use rustc_hir::attrs::CoverageAttrKind; use rustc_hir::find_attr; use rustc_index::bit_set::DenseBitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; @@ -49,9 +49,7 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { /// Query implementation for `coverage_attr_on`. fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { // Check for a `#[coverage(..)]` attribute on this def. - if let Some(kind) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Coverage(_sp, kind) => kind) - { + if let Some(kind) = find_attr!(tcx, def_id, Coverage(_sp, kind) => kind) { match kind { CoverageAttrKind::On => return true, CoverageAttrKind::Off => return false, diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index da133861617f1..7435fbe8d38a5 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -1,4 +1,4 @@ -use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::attrs::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; @@ -37,6 +37,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { } // FIXME(autodiff): replace this as per discussion in https://github.com/rust-lang/rust/pull/149033#discussion_r2535465880 + #[allow(deprecated)] if tcx.has_attr(def_id, sym::autodiff_forward) || tcx.has_attr(def_id, sym::autodiff_reverse) || tcx.has_attr(def_id, sym::rustc_autodiff) @@ -44,7 +45,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return true; } - if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcIntrinsic) { + if find_attr!(tcx, def_id, RustcIntrinsic) { // Intrinsic fallback bodies are always cross-crate inlineable. // To ensure that the MIR inliner doesn't cluelessly try to inline fallback // bodies even when the backend would implement something better, we stop @@ -158,7 +159,7 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { // But intrinsics don't have a body that gets assigned to a CGU, so they are // ignored. if let Some((fn_def_id, _)) = func.const_fn_def() - && find_attr!(tcx.get_all_attrs(fn_def_id), AttributeKind::RustcIntrinsic) + && find_attr!(tcx, fn_def_id, RustcIntrinsic) { return; } diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index b92938c7094eb..b97901f075bc6 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -1,7 +1,6 @@ //! Performs various peephole optimizations. use rustc_abi::ExternAbi; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{LangItem, find_attr}; use rustc_middle::bug; use rustc_middle::mir::visit::MutVisitor; @@ -30,8 +29,7 @@ impl<'tcx> crate::MirPass<'tcx> for InstSimplify { } fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - let preserve_ub_checks = - find_attr!(tcx.hir_krate_attrs(), AttributeKind::RustcPreserveUbChecks); + let preserve_ub_checks = find_attr!(tcx.hir_krate_attrs(), RustcPreserveUbChecks); if !preserve_ub_checks { SimplifyUbCheck { tcx }.visit_body(body); } diff --git a/compiler/rustc_mir_transform/src/liveness.rs b/compiler/rustc_mir_transform/src/liveness.rs index 9d951f0874376..3fbe1e398a181 100644 --- a/compiler/rustc_mir_transform/src/liveness.rs +++ b/compiler/rustc_mir_transform/src/liveness.rs @@ -1,6 +1,5 @@ use rustc_abi::FieldIdx; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, IndexEntry}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::find_attr; @@ -63,14 +62,14 @@ pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Den } // Don't run unused pass for #[naked] - if find_attr!(tcx.get_all_attrs(def_id.to_def_id()), AttributeKind::Naked(..)) { + if find_attr!(tcx, def_id.to_def_id(), Naked(..)) { return DenseBitSet::new_empty(0); } // Don't run unused pass for #[derive] let parent = tcx.parent(tcx.typeck_root_def_id(def_id.to_def_id())); if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent) - && find_attr!(tcx.get_all_attrs(parent), AttributeKind::AutomaticallyDerived(..)) + && find_attr!(tcx, parent, AutomaticallyDerived(..)) { return DenseBitSet::new_empty(0); } diff --git a/compiler/rustc_passes/src/abi_test.rs b/compiler/rustc_passes/src/abi_test.rs index c3e80208e2d5f..3da0978e5ff86 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -1,4 +1,4 @@ -use rustc_hir::attrs::{AttributeKind, RustcAbiAttrKind}; +use rustc_hir::attrs::RustcAbiAttrKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; @@ -18,7 +18,8 @@ pub fn test_abi(tcx: TyCtxt<'_>) { return; } for id in tcx.hir_crate_items(()).definitions() { - let Some((attr_span, attr_kind)) = find_attr!(tcx.get_all_attrs(id), AttributeKind::RustcAbi{ attr_span, kind } => (*attr_span, *kind)) + let Some((attr_span, attr_kind)) = + find_attr!(tcx, id, RustcAbi{ attr_span, kind } => (*attr_span, *kind)) else { continue; }; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index d5051aea0cd4b..9af9398d78b96 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -401,15 +401,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::deny | sym::forbid // internal - | sym::rustc_inherit_overflow_checks | sym::rustc_on_unimplemented | sym::rustc_layout | sym::rustc_autodiff - | sym::rustc_capture_analysis - | sym::rustc_mir + | sym::rustc_inherit_overflow_checks // crate-level attrs, are checked below | sym::feature - | sym::register_tool, .. + | sym::register_tool, + .. ] => {} [name, rest@..] => { match BUILTIN_ATTRIBUTE_MAP.get(name) { @@ -568,7 +567,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } if let EiiImplResolution::Macro(eii_macro) = resolution - && find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe) + && find_attr!(self.tcx, *eii_macro, EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe) && !impl_marked_unsafe { self.dcx().emit_err(errors::EiiImplRequiresUnsafe { @@ -783,7 +782,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Target::Fn => { // `#[track_caller]` is not valid on weak lang items because they are called via // `extern` declarations and `#[track_caller]` would alter their ABI. - if let Some(item) = find_attr!(attrs, AttributeKind::Lang(item, _) => item) + if let Some(item) = find_attr!(attrs, Lang(item, _) => item) && item.is_weak() { let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap(); @@ -795,7 +794,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { }); } - if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) { + if let Some(impls) = find_attr!(attrs, EiiImpls(impls) => impls) { let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap(); for i in impls { let name = match i.resolution { @@ -854,7 +853,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) | Target::Fn => { // `#[target_feature]` is not allowed in lang items. - if let Some(lang_item) = find_attr!(attrs, AttributeKind::Lang(lang, _) => lang) + if let Some(lang_item) = find_attr!(attrs, Lang(lang, _) => lang) // Calling functions with `#[target_feature]` is // not unsafe on WASM, see #84988 && !self.tcx.sess.target.is_like_wasm @@ -1162,7 +1161,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) { - if find_attr!(attrs, AttributeKind::FfiConst(_)) { + if find_attr!(attrs, FfiConst(_)) { // `#[ffi_const]` functions cannot be `#[ffi_pure]` self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span }); } @@ -1269,7 +1268,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { // #[repr(foo)] // #[repr(bar, align(8))] // ``` - let (reprs, first_attr_span) = find_attr!(attrs, AttributeKind::Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))).unwrap_or((&[], None)); + let (reprs, first_attr_span) = + find_attr!(attrs, Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))) + .unwrap_or((&[], None)); let mut int_reprs = 0; let mut is_explicit_rust = false; @@ -1414,7 +1415,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { // `#[rustc_pass_indirectly_in_non_rustic_abis]` if is_transparent && let Some(&pass_indirectly_span) = - find_attr!(attrs, AttributeKind::RustcPassIndirectlyInNonRusticAbis(span) => span) + find_attr!(attrs, RustcPassIndirectlyInNonRusticAbis(span) => span) { self.dcx().emit_err(errors::TransparentIncompatible { hint_spans: vec![span, pass_indirectly_span], @@ -1752,7 +1753,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) { - if !find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent)) + if !find_attr!(attrs, Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent)) .unwrap_or(false) { self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span }); @@ -1762,7 +1763,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) { if let (Target::Closure, None) = ( target, - find_attr!(attrs, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span), + find_attr!(attrs, Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span), ) { let is_coro = matches!( self.tcx.hir_expect_expr(hir_id).kind, @@ -1775,8 +1776,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { let parent_span = self.tcx.def_span(parent_did); if let Some(attr_span) = find_attr!( - self.tcx.get_all_attrs(parent_did), - AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span + self.tcx, parent_did, + Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span ) && is_coro { self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span }); @@ -1785,9 +1786,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) { - if let Some(export_name_span) = find_attr!(attrs, AttributeKind::ExportName { span: export_name_span, .. } => *export_name_span) + if let Some(export_name_span) = + find_attr!(attrs, ExportName { span: export_name_span, .. } => *export_name_span) && let Some(no_mangle_span) = - find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span) + find_attr!(attrs, NoMangle(no_mangle_span) => *no_mangle_span) { let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 { "#[unsafe(no_mangle)]" @@ -1906,9 +1908,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { // In the long run, the checks should be harmonized. if let ItemKind::Macro(_, macro_def, _) = item.kind { let def_id = item.owner_id.to_def_id(); - if macro_def.macro_rules - && !find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }) - { + if macro_def.macro_rules && !find_attr!(self.tcx, def_id, MacroExport { .. }) { check_non_exported_macro_for_invalid_attrs(self.tcx, item); } } @@ -2098,7 +2098,8 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) { let attrs = tcx.hir_attrs(item.hir_id()); - if let Some(attr_span) = find_attr!(attrs, AttributeKind::Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span) + if let Some(attr_span) = + find_attr!(attrs, Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span) { tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span }); } diff --git a/compiler/rustc_passes/src/check_export.rs b/compiler/rustc_passes/src/check_export.rs index fee920221e1d1..f1c89face6a0f 100644 --- a/compiler/rustc_passes/src/check_export.rs +++ b/compiler/rustc_passes/src/check_export.rs @@ -4,7 +4,6 @@ use std::ops::ControlFlow; use rustc_abi::ExternAbi; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::find_attr; @@ -46,7 +45,7 @@ impl<'tcx> ExportableItemCollector<'tcx> { } fn item_is_exportable(&self, def_id: LocalDefId) -> bool { - let has_attr = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::ExportStable); + let has_attr = find_attr!(self.tcx, def_id, ExportStable); if !self.in_exportable_mod && !has_attr { return false; } @@ -82,7 +81,7 @@ impl<'tcx> ExportableItemCollector<'tcx> { fn walk_item_with_mod(&mut self, item: &'tcx hir::Item<'tcx>) { let def_id = item.hir_id().owner.def_id; let old_exportable_mod = self.in_exportable_mod; - if find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::ExportStable) { + if find_attr!(self.tcx, def_id, ExportStable) { self.in_exportable_mod = true; } let old_seen_exportable_in_mod = std::mem::replace(&mut self.seen_exportable_in_mod, false); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index e56d27721bddd..f6d00f5342f27 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -10,7 +10,6 @@ use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use rustc_abi::FieldIdx; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{ErrorGuaranteed, MultiSpan}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; @@ -381,10 +380,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { && let impl_of = self.tcx.parent(impl_item.owner_id.to_def_id()) && self.tcx.is_automatically_derived(impl_of) && let trait_ref = self.tcx.impl_trait_ref(impl_of).instantiate_identity() - && find_attr!( - self.tcx.get_all_attrs(trait_ref.def_id), - AttributeKind::RustcTrivialFieldReads - ) + && find_attr!(self.tcx, trait_ref.def_id, RustcTrivialFieldReads) { if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() && let Some(adt_def_id) = adt_def.did().as_local() @@ -726,9 +722,7 @@ fn has_allow_dead_code_or_lang_attr( if has_allow_expect_dead_code(tcx, def_id) { Some(ComesFromAllowExpect::Yes) - } else if has_used_like_attr(tcx, def_id) - || find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Lang(..)) - { + } else if has_used_like_attr(tcx, def_id) || find_attr!(tcx, def_id, Lang(..)) { Some(ComesFromAllowExpect::No) } else { None diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index c7b1dcb95e336..be7ae5b97f55c 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -9,7 +9,6 @@ //! //! * Compiler internal types like `Ty` and `TyCtxt` -use rustc_hir::attrs::AttributeKind; use rustc_hir::diagnostic_items::DiagnosticItems; use rustc_hir::{CRATE_OWNER_ID, OwnerId, find_attr}; use rustc_middle::query::{LocalCrate, Providers}; @@ -21,7 +20,7 @@ use crate::errors::DuplicateDiagnosticItemInCrate; fn observe_item<'tcx>(tcx: TyCtxt<'tcx>, diagnostic_items: &mut DiagnosticItems, owner: OwnerId) { let attrs = tcx.hir_attrs(owner.into()); - if let Some(name) = find_attr!(attrs, AttributeKind::RustcDiagnosticItem(name) => name) { + if let Some(name) = find_attr!(attrs, RustcDiagnosticItem(name) => name) { // insert into our table collect_item(tcx, diagnostic_items, *name, owner.to_def_id()); } diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index bd737518ed479..9fc9df7604c51 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -1,8 +1,7 @@ use rustc_ast::entry::EntryPointType; use rustc_errors::codes::*; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId}; -use rustc_hir::{CRATE_HIR_ID, ItemId, Node, find_attr}; +use rustc_hir::{ItemId, Node, find_attr}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::config::{CrateType, EntryFnType, sigpipe}; @@ -29,7 +28,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> { } // If the user wants no main function at all, then stop here. - if find_attr!(tcx.hir_attrs(CRATE_HIR_ID), AttributeKind::NoMain) { + if find_attr!(tcx, crate, NoMain) { return None; } @@ -47,7 +46,7 @@ fn check_and_search_item(id: ItemId, ctxt: &mut EntryContext<'_>) { let attrs = ctxt.tcx.hir_attrs(id.hir_id()); let entry_point_type = rustc_ast::entry::entry_point_type( - find_attr!(attrs, AttributeKind::RustcMain), + find_attr!(attrs, RustcMain), at_root, ctxt.tcx.opt_item_name(id.owner_id.to_def_id()), ); diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 354a98d6d0dc7..68834cf7d55af 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -1,5 +1,5 @@ use rustc_abi::{HasDataLayout, TargetDataLayout}; -use rustc_hir::attrs::{AttributeKind, RustcLayoutType}; +use rustc_hir::attrs::RustcLayoutType; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; @@ -20,8 +20,7 @@ pub fn test_layout(tcx: TyCtxt<'_>) { return; } for id in tcx.hir_crate_items(()).definitions() { - let attrs = tcx.get_all_attrs(id); - if let Some(attrs) = find_attr!(attrs, AttributeKind::RustcLayout(attrs) => attrs) { + if let Some(attrs) = find_attr!(tcx, id, RustcLayout(attrs) => attrs) { // Attribute parsing handles error reporting if matches!( tcx.def_kind(id), diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 657b362d5ca14..6fd28c78740cd 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -96,9 +96,8 @@ fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind { } fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - let depr = find_attr!(attrs, - AttributeKind::Deprecation { deprecation, span: _ } => *deprecation + let depr = find_attr!(tcx, def_id, + Deprecation { deprecation, span: _ } => *deprecation ); let Some(depr) = depr else { @@ -161,8 +160,7 @@ fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { } // # Regular stability - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); - let stab = find_attr!(attrs, AttributeKind::Stability { stability, span: _ } => *stability); + let stab = find_attr!(tcx, def_id, Stability { stability, span: _ } => *stability); if let Some(stab) = stab { return Some(stab); @@ -195,9 +193,8 @@ fn lookup_default_body_stability( return None; } - let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); // FIXME: check that this item can have body stability - find_attr!(attrs, AttributeKind::RustcBodyStability { stability, .. } => *stability) + find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability) } #[instrument(level = "debug", skip(tcx))] @@ -212,9 +209,7 @@ fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option, def_id: LocalDefId) -> Option *stability); + find_attr!(tcx, def_id, RustcConstStability { stability, span: _ } => *stability); // After checking the immediate attributes, get rid of the span and compute implied // const stability: inherit feature gate from regular stability. @@ -599,15 +593,15 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { let features = self.tcx.features(); if features.staged_api() { let attrs = self.tcx.hir_attrs(item.hir_id()); - let stab = find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span)); + let stab = find_attr!(attrs, Stability{stability, span} => (*stability, *span)); // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem - let const_stab = find_attr!(attrs, AttributeKind::RustcConstStability{stability, ..} => *stability); + let const_stab = + find_attr!(attrs, RustcConstStability{stability, ..} => *stability); - let unstable_feature_stab = - find_attr!(attrs, AttributeKind::UnstableFeatureBound(i) => i) - .map(|i| i.as_slice()) - .unwrap_or_default(); + let unstable_feature_stab = find_attr!(attrs, UnstableFeatureBound(i) => i) + .map(|i| i.as_slice()) + .unwrap_or_default(); // If this impl block has an #[unstable] attribute, give an // error if all involved types and traits are stable, because diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 9a952bb721951..59fd908756b02 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -21,7 +21,6 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; use rustc_errors::{MultiSpan, listify}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, InferKind, Visitor}; @@ -508,7 +507,7 @@ impl<'tcx> EmbargoVisitor<'tcx> { let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); let attrs = self.tcx.hir_attrs(hir_id); - if find_attr!(attrs, AttributeKind::RustcMacroTransparency(x) => *x) + if find_attr!(attrs, RustcMacroTransparency(x) => *x) .unwrap_or(Transparency::fallback(md.macro_rules)) != Transparency::Opaque { @@ -876,7 +875,7 @@ pub struct TestReachabilityVisitor<'a, 'tcx> { impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> { fn effective_visibility_diagnostic(&self, def_id: LocalDefId) { - if find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::RustcEffectiveVisibility) { + if find_attr!(self.tcx, def_id, RustcEffectiveVisibility) { let mut error_msg = String::new(); let span = self.tcx.def_span(def_id.to_def_id()); if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) { diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 179aa58ec10a3..78fd9c1e21a00 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -14,7 +14,7 @@ use rustc_errors::{ struct_span_code_err, }; use rustc_feature::BUILTIN_ATTRIBUTES; -use rustc_hir::attrs::{AttributeKind, CfgEntry, StrippedCfgItem}; +use rustc_hir::attrs::{CfgEntry, StrippedCfgItem}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; @@ -1430,8 +1430,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let note = if let Some(did) = did { let requires_note = !did.is_local() && find_attr!( - this.tcx.get_all_attrs(did), - AttributeKind::RustcDiagnosticItem( + this.tcx, + did, + RustcDiagnosticItem( sym::TryInto | sym::TryFrom | sym::FromIterator ) ); @@ -2170,7 +2171,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // Otherwise, point out if the struct has any private fields. if let Some(def_id) = res.opt_def_id() && !def_id.is_local() - && let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span) + && let Some(attr_span) = find_attr!(self.tcx, def_id, NonExhaustive(span) => *span) { non_exhaustive = Some(attr_span); } else if let Some(span) = ctor_fields_span { diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 5874b192216cc..b1d6e3526d9cd 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -17,7 +17,6 @@ use rustc_errors::{ struct_span_code_err, }; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; @@ -1115,8 +1114,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // confused by them. continue; } - if let Some(d) = - hir::find_attr!(r.tcx.get_all_attrs(did), AttributeKind::Doc(d) => d) + if let Some(d) = hir::find_attr!(r.tcx, did, Doc(d) => d) && d.aliases.contains_key(&item_name) { return Some(did); @@ -2665,12 +2663,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { ) .iter() .filter_map(|candidate| candidate.did) - .find(|did| { - find_attr!( - self.r.tcx.get_all_attrs(*did), - AttributeKind::RustcDiagnosticItem(sym::Default) - ) - }); + .find(|did| find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default))); let Some(default_trait) = default_trait else { return; }; diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 66f1d6b4ad55b..74e313bb4269b 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -53,7 +53,7 @@ use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer}; use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; use rustc_feature::BUILTIN_ATTRIBUTES; -use rustc_hir::attrs::{AttributeKind, StrippedCfgItem}; +use rustc_hir::attrs::StrippedCfgItem; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{ self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes, @@ -2475,8 +2475,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { find_attr!( // we can use parsed attrs here since for other crates they're already available - self.tcx.get_all_attrs(def_id), - AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes + self.tcx, def_id, + RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes ) .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect()) } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index 5505fe82cea65..26979c24bdb68 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -11,7 +11,6 @@ use rustc_abi::{ExternAbi, Integer}; use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, CASE_INSENSITIVE, ToBaseN}; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_middle::bug; use rustc_middle::ty::layout::IntegerExt; @@ -447,8 +446,7 @@ pub(crate) fn encode_ty<'tcx>( ty::Adt(adt_def, args) => { let mut s = String::new(); let def_id = adt_def.did(); - if let Some(encoding) = find_attr!(tcx.get_all_attrs(def_id), AttributeKind::CfiEncoding { encoding } => encoding) - { + if let Some(encoding) = find_attr!(tcx, def_id, CfiEncoding { encoding } => encoding) { let encoding = encoding.as_str().trim(); // Use user-defined CFI encoding for type s.push_str(&encoding); @@ -494,8 +492,7 @@ pub(crate) fn encode_ty<'tcx>( // , where is let mut s = String::new(); - if let Some(encoding) = find_attr!(tcx.get_all_attrs(*def_id), AttributeKind::CfiEncoding {encoding} => encoding) - { + if let Some(encoding) = find_attr!(tcx, *def_id, CfiEncoding {encoding} => encoding) { // Use user-defined CFI encoding for type s.push_str(encoding.as_str().trim()); } else { diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index 971ac9348fc4c..90b489258360f 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -6,7 +6,6 @@ use std::iter; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{self as hir, LangItem, find_attr}; use rustc_middle::bug; use rustc_middle::ty::{ @@ -138,10 +137,7 @@ impl<'tcx> TypeFolder> for TransformTy<'tcx> { { // Don't transform repr(transparent) types with an user-defined CFI encoding to // preserve the user-defined CFI encoding. - if find_attr!( - self.tcx.get_all_attrs(adt_def.did()), - AttributeKind::CfiEncoding { .. } - ) { + if find_attr!(self.tcx, adt_def.did(), CfiEncoding { .. }) { return t; } let variant = adt_def.non_enum_variant(); diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index 8f842e0300113..b4d9031469dd5 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -4,7 +4,6 @@ //! def-path. This is used for unit testing the code that generates //! paths etc in all kinds of annoying scenarios. -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::find_attr; use rustc_middle::ty::print::with_no_trimmed_paths; @@ -53,10 +52,7 @@ impl SymbolNamesTest<'_> { // to test the entirety of the string, if they choose, or else just // some subset. - if let Some(attr_span) = find_attr!( - tcx.get_all_attrs(def_id), - AttributeKind::RustcSymbolName(span) => span - ) { + if let Some(attr_span) = find_attr!(tcx, def_id, RustcSymbolName(span) => span) { let def_id = def_id.to_def_id(); let instance = Instance::new_raw( def_id, @@ -83,8 +79,8 @@ impl SymbolNamesTest<'_> { } if let Some(attr_span) = find_attr!( - tcx.get_all_attrs(def_id), - AttributeKind::RustcDefPath(span) => span + tcx, def_id, + RustcDefPath(span) => span ) { tcx.dcx().emit_err(TestOutput { span: *attr_span, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index b0b858aa270c1..ab19df5620cdb 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -1,7 +1,6 @@ use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; use rustc_errors::{Diag, MultiSpan, pluralize}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::find_attr; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; @@ -533,7 +532,7 @@ impl Trait for X { } } TypeError::TargetFeatureCast(def_id) => { - let target_spans = find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TargetFeature{attr_span: span, was_forced: false, ..} => *span); + let target_spans = find_attr!(tcx, def_id, TargetFeature{attr_span: span, was_forced: false, ..} => *span); diag.note( "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers" ); diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index a98f952d55a38..9c146d7326135 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -71,6 +71,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return None; }; + #[allow(deprecated)] tcx.has_attr(impl_def_id_and_args.0, sym::rustc_on_unimplemented) .then_some(impl_def_id_and_args) }) @@ -589,7 +590,10 @@ impl<'tcx> OnUnimplementedDirective { // We don't support those. return Ok(None); }; - if let Some(attr) = tcx.get_attr(item_def_id, sym::rustc_on_unimplemented) { + if let Some(attr) = { + #[allow(deprecated)] + tcx.get_attr(item_def_id, sym::rustc_on_unimplemented) + } { return Self::parse_attribute(attr, false, tcx, item_def_id); } else { tcx.get_attrs_by_path(item_def_id, &[sym::diagnostic, attr]) diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index fc628e78a3e23..4e37871d28a25 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -8,7 +8,6 @@ use std::fmt::Debug; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_errors::{Diag, EmissionGuarantee}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_hir::find_attr; @@ -760,8 +759,9 @@ impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> { } = cand.kind() && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) { - let message = find_attr!(infcx.tcx.get_all_attrs(def_id), AttributeKind::RustcReservationImpl(_, message) => *message); - if let Some(message) = message { + if let Some(message) = + find_attr!(infcx.tcx, def_id, RustcReservationImpl(_, message) => *message) + { self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message }); } } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 3c3160bc533e2..d6657ea392dc0 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -12,7 +12,6 @@ use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Diag, EmissionGuarantee}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem, find_attr}; use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType}; @@ -1445,7 +1444,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { && let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) { if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { - let message = find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcReservationImpl(_, message) => *message); + let message = find_attr!(tcx, def_id, RustcReservationImpl(_, message) => *message); if let Some(message) = message { debug!( "filter_reservation_impls: \ diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 5a41e46f3a6bd..a095ee7cbbbaf 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -7,7 +7,6 @@ use rustc_abi::{ TagEncoding, VariantIdx, Variants, WrappingRange, }; use rustc_hashes::Hash64; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_index::{Idx as _, IndexVec}; use rustc_middle::bug; @@ -624,8 +623,8 @@ fn layout_of_uncached<'tcx>( // Check for the rustc_simd_monomorphize_lane_limit attribute and check the lane limit if let Some(limit) = find_attr!( - tcx.get_all_attrs(def.did()), - AttributeKind::RustcSimdMonomorphizeLaneLimit(limit) => limit + tcx, def.did(), + RustcSimdMonomorphizeLaneLimit(limit) => limit ) { if !limit.value_within_limit(e_len as usize) { return Err(map_error( diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 06eef7e95145e..2cff60de9d1cf 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -1,7 +1,6 @@ //! Check whether a type has (potentially) non-trivial drop glue. use rustc_data_structures::fx::FxHashSet; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::DefId; use rustc_hir::find_attr; use rustc_hir::limit::Limit; @@ -397,7 +396,7 @@ fn adt_consider_insignificant_dtor<'tcx>( tcx: TyCtxt<'tcx>, ) -> impl Fn(ty::AdtDef<'tcx>) -> Option { move |adt_def: ty::AdtDef<'tcx>| { - if find_attr!(tcx.get_all_attrs(adt_def.did()), AttributeKind::RustcInsignificantDtor) { + if find_attr!(tcx, adt_def.did(), RustcInsignificantDtor) { // In some cases like `std::collections::HashMap` where the struct is a wrapper around // a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies // outside stdlib, we might choose to still annotate the wrapper (std HashMap) with diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 22737cda97e5e..9c7685ca30bc9 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -5,10 +5,9 @@ use std::sync::Arc; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::thin_vec::{ThinVec, thin_vec}; -use rustc_hir as hir; -use rustc_hir::Mutability; use rustc_hir::def::{DefKind, MacroKinds, Res}; use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalModDefId}; +use rustc_hir::{self as hir, Mutability, find_attr}; use rustc_metadata::creader::{CStore, LoadedMacro}; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{self, TyCtxt}; @@ -220,6 +219,8 @@ pub(crate) fn try_inline_glob( } pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> &'hir [hir::Attribute] { + // FIXME: all uses should use `find_attr`! + #[allow(deprecated)] cx.tcx.get_all_attrs(did) } @@ -403,7 +404,7 @@ pub(crate) fn build_impls( // * https://github.com/rust-lang/rust/issues/103170 — where it didn't used to get documented // * https://github.com/rust-lang/rust/pull/99917 — where the feature got used // * https://github.com/rust-lang/rust/issues/53487 — overall tracking issue for Error - if tcx.has_attr(did, sym::rustc_has_incoherent_inherent_impls) { + if find_attr!(tcx, did, RustcHasIncoherentInherentImpls) { let type_ = if tcx.is_trait(did) { SimplifiedType::Trait(did) } else { SimplifiedType::Adt(did) }; for &did in tcx.incoherent_impls(type_).iter() { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 18f991ad43aa6..880d2f7f37ccd 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -197,7 +197,7 @@ fn generate_item_with_correct_attrs( // itself matter), for non-inlined re-exports see #85043. let import_is_inline = find_attr!( inline::load_attrs(cx, import_id.to_def_id()), - AttributeKind::Doc(d) + Doc(d) if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::Inline) ) || (is_glob_import(cx.tcx, import_id) && (cx.document_hidden() || !cx.tcx.is_doc_hidden(def_id))); @@ -1007,7 +1007,7 @@ fn clean_proc_macro<'tcx>( return ProcMacroItem(ProcMacro { kind, helpers: vec![] }); } let attrs = cx.tcx.hir_attrs(item.hir_id()); - let Some((trait_name, helper_attrs)) = find_attr!(attrs, AttributeKind::ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs)) + let Some((trait_name, helper_attrs)) = find_attr!(attrs, ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs)) else { return ProcMacroItem(ProcMacro { kind, helpers: vec![] }); }; @@ -1026,11 +1026,11 @@ fn clean_fn_or_proc_macro<'tcx>( cx: &mut DocContext<'tcx>, ) -> ItemKind { let attrs = cx.tcx.hir_attrs(item.hir_id()); - let macro_kind = if find_attr!(attrs, AttributeKind::ProcMacro(..)) { + let macro_kind = if find_attr!(attrs, ProcMacro(..)) { Some(MacroKind::Bang) - } else if find_attr!(attrs, AttributeKind::ProcMacroDerive { .. }) { + } else if find_attr!(attrs, ProcMacroDerive { .. }) { Some(MacroKind::Derive) - } else if find_attr!(attrs, AttributeKind::ProcMacroAttribute(..)) { + } else if find_attr!(attrs, ProcMacroAttribute(..)) { Some(MacroKind::Attr) } else { None @@ -1050,8 +1050,7 @@ fn clean_fn_or_proc_macro<'tcx>( /// `rustc_legacy_const_generics`. More information in /// . fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) { - let Some(indexes) = - find_attr!(attrs, AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes) + let Some(indexes) = find_attr!(attrs, RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes) else { return; }; @@ -3022,7 +3021,7 @@ fn clean_use_statement_inner<'tcx>( let attrs = cx.tcx.hir_attrs(import.hir_id()); let inline_attr = find_attr!( attrs, - AttributeKind::Doc(d) if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline) => d + Doc(d) if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline) => d ) .and_then(|d| d.inline.first()); let pub_underscore = visibility.is_public() && name == Some(kw::Underscore); diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index bdd3a691e95f7..82cb56cabdc24 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -221,12 +221,8 @@ impl ExternalCrate { // Failing that, see if there's an attribute specifying where to find this // external crate let did = self.crate_num.as_def_id(); - tcx.get_all_attrs(did) - .iter() - .find_map(|a| match a { - Attribute::Parsed(AttributeKind::Doc(d)) => d.html_root_url.map(|(url, _)| url), - _ => None, - }) + find_attr!(tcx, did, Doc(d) =>d.html_root_url.map(|(url, _)| url)) + .flatten() .map(to_remote) .or_else(|| extern_url.map(to_remote)) // NOTE: only matters if `extern_url_takes_precedence` is false .unwrap_or(Unknown) // Well, at least we tried. @@ -275,13 +271,7 @@ impl ExternalCrate { callback: F, ) -> impl Iterator { let as_target = move |did: DefId, tcx: TyCtxt<'_>| -> Option<(DefId, Symbol)> { - tcx.get_all_attrs(did) - .iter() - .find_map(|attr| match attr { - Attribute::Parsed(AttributeKind::Doc(d)) => callback(d), - _ => None, - }) - .map(|value| (did, value)) + find_attr!(tcx, did, Doc(d) => callback(d)).flatten().map(|value| (did, value)) }; self.mapped_root_modules(tcx, as_target) } @@ -308,12 +298,10 @@ impl ExternalCrate { // duplicately for the same primitive. This is handled later on when // rendering by delegating everything to a hash map. fn as_primitive(def_id: DefId, tcx: TyCtxt<'_>) -> Option<(DefId, PrimitiveType)> { - let Some((attr_span, prim_sym)) = find_attr!( - tcx.get_all_attrs(def_id), - AttributeKind::RustcDocPrimitive(span, prim) => (*span, *prim) - ) else { - return None; - }; + let (attr_span, prim_sym) = find_attr!( + tcx, def_id, + RustcDocPrimitive(span, prim) => (*span, *prim) + )?; let Some(prim) = PrimitiveType::from_symbol(prim_sym) else { span_bug!(attr_span, "primitive `{prim_sym}` is not a member of `PrimitiveType`"); }; @@ -458,7 +446,15 @@ impl Item { } pub(crate) fn inner_docs(&self, tcx: TyCtxt<'_>) -> bool { - self.item_id.as_def_id().map(|did| inner_docs(tcx.get_all_attrs(did))).unwrap_or(false) + self.item_id + .as_def_id() + .map(|did| { + inner_docs( + #[allow(deprecated)] + tcx.get_all_attrs(did), + ) + }) + .unwrap_or(false) } pub(crate) fn span(&self, tcx: TyCtxt<'_>) -> Option { @@ -512,6 +508,7 @@ impl Item { kind: ItemKind, cx: &mut DocContext<'_>, ) -> Item { + #[allow(deprecated)] let hir_attrs = cx.tcx.get_all_attrs(def_id); Self::from_def_id_and_attrs_and_parts( @@ -721,7 +718,7 @@ impl Item { } pub(crate) fn is_non_exhaustive(&self) -> bool { - find_attr!(&self.attrs.other_attrs, AttributeKind::NonExhaustive(..)) + find_attr!(&self.attrs.other_attrs, NonExhaustive(..)) } /// Returns a documentation-level item type from the item. @@ -1013,13 +1010,11 @@ pub(crate) struct Attributes { impl Attributes { pub(crate) fn has_doc_flag bool>(&self, callback: F) -> bool { - self.other_attrs - .iter() - .any(|a| matches!(a, Attribute::Parsed(AttributeKind::Doc(d)) if callback(d))) + find_attr!(&self.other_attrs, Doc(d) if callback(d)) } pub(crate) fn is_doc_hidden(&self) -> bool { - find_attr!(&self.other_attrs, AttributeKind::Doc(d) if d.hidden.is_some()) + find_attr!(&self.other_attrs, Doc(d) if d.hidden.is_some()) } pub(crate) fn from_hir(attrs: &[hir::Attribute]) -> Attributes { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index bd83c6ea6b839..05272c083e692 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -9,10 +9,10 @@ use std::{ascii, mem}; use rustc_ast::join_path_idents; use rustc_ast::tokenstream::TokenTree; use rustc_data_structures::thin_vec::{ThinVec, thin_vec}; -use rustc_hir::Attribute; -use rustc_hir::attrs::{AttributeKind, DocAttribute}; +use rustc_hir::attrs::DocAttribute; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; +use rustc_hir::find_attr; use rustc_metadata::rendered_const; use rustc_middle::mir; use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt}; @@ -574,10 +574,7 @@ pub(crate) fn has_doc_flag bool>( did: DefId, callback: F, ) -> bool { - tcx.get_all_attrs(did).iter().any(|attr| match attr { - Attribute::Parsed(AttributeKind::Doc(d)) => callback(d), - _ => false, - }) + find_attr!(tcx, did, Doc(d) if callback(d)) } /// A link to `doc.rust-lang.org` that includes the channel name. Use this instead of manual links diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index cc27770c8aae8..a3c6525936eea 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -13,7 +13,6 @@ use ::serde::{Deserialize, Serialize}; use rustc_ast::join_path_syms; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::thin_vec::ThinVec; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; @@ -1464,7 +1463,7 @@ pub(crate) fn build_index( return None; } let path = if item.ty == ItemType::Macro - && find_attr!(tcx.get_all_attrs(defid), AttributeKind::MacroExport { .. }) + && find_attr!(tcx, defid, MacroExport { .. }) { // `#[macro_export]` always exports to the crate root. vec![tcx.crate_name(defid.krate)] diff --git a/src/librustdoc/json/ids.rs b/src/librustdoc/json/ids.rs index a3d86b25dadac..31043b8028f02 100644 --- a/src/librustdoc/json/ids.rs +++ b/src/librustdoc/json/ids.rs @@ -6,7 +6,6 @@ //! other phases think of as an "item". use rustc_data_structures::fx::FxHashMap; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::DefId; use rustc_hir::find_attr; use rustc_span::Symbol; @@ -89,14 +88,11 @@ impl JsonRenderer<'_> { // We need this workaround because primitive types' DefId actually refers to // their parent module, which isn't present in the output JSON items. So // instead, we directly get the primitive symbol - if let Some(prim) = find_attr!( - self.tcx.get_all_attrs(def_id), - AttributeKind::RustcDocPrimitive(_, prim) => *prim - ) { - Some(prim) - } else { - self.tcx.opt_item_name(def_id) - } + find_attr!( + self.tcx, def_id, + RustcDocPrimitive(_, prim) => *prim + ) + .or_else(|| self.tcx.opt_item_name(def_id)) } }; diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index a68e9dc87ae52..1da191c903871 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -15,7 +15,7 @@ use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Namespace::*; use rustc_hir::def::{DefKind, MacroKinds, Namespace, PerNS}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE}; -use rustc_hir::{Attribute, Mutability, Safety}; +use rustc_hir::{Attribute, Mutability, Safety, find_attr}; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_middle::{bug, span_bug, ty}; use rustc_resolve::rustdoc::pulldown_cmark::LinkType; @@ -1127,14 +1127,8 @@ impl LinkCollector<'_, '_> { // inlined item. // let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id - && tcx.get_all_attrs(inline_stmt_id).iter().any(|attr| { - matches!( - attr, - Attribute::Parsed(AttributeKind::Deprecation { - span: attr_span, .. - }) if attr_span == depr_span, - ) - }) { + && find_attr!(tcx, inline_stmt_id, Deprecation {span, ..} if span == depr_span) + { inline_stmt_id.to_def_id() } else { item.item_id.expect_def_id() diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index c2a69baf2989b..927a7e0f07159 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -3,9 +3,9 @@ //! struct implements that trait. use rustc_data_structures::fx::FxHashSet; -use rustc_hir::Attribute; use rustc_hir::attrs::{AttributeKind, DocAttribute}; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE}; +use rustc_hir::{Attribute, find_attr}; use rustc_middle::ty; use tracing::debug; @@ -66,16 +66,10 @@ pub(crate) fn collect_trait_impls(mut krate: Crate, cx: &mut DocContext<'_>) -> for &impl_def_id in tcx.trait_impls_in_crate(LOCAL_CRATE) { let mut parent = Some(tcx.parent(impl_def_id)); while let Some(did) = parent { - attr_buf.extend(tcx.get_all_attrs(did).iter().filter_map(|attr| match attr { - Attribute::Parsed(AttributeKind::Doc(d)) if !d.cfg.is_empty() => { - // The only doc attributes we're interested into for trait impls are the - // `cfg`s for the `doc_cfg` feature. So we create a new empty `DocAttribute` - // and then only clone the actual `DocAttribute::cfg` field. - let mut new_attr = DocAttribute::default(); - new_attr.cfg = d.cfg.clone(); - Some(Attribute::Parsed(AttributeKind::Doc(Box::new(new_attr)))) - } - _ => None, + attr_buf.extend(find_attr!(tcx, did, Doc(d) if !d.cfg.is_empty() => { + let mut new_attr = DocAttribute::default(); + new_attr.cfg = d.cfg.clone(); + Attribute::Parsed(AttributeKind::Doc(Box::new(new_attr))) })); parent = tcx.opt_parent(did); } diff --git a/src/librustdoc/passes/strip_hidden.rs b/src/librustdoc/passes/strip_hidden.rs index 27065d7675bb7..e1feccb13df88 100644 --- a/src/librustdoc/passes/strip_hidden.rs +++ b/src/librustdoc/passes/strip_hidden.rs @@ -2,7 +2,6 @@ use std::mem; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_hir::find_attr; use rustc_middle::ty::TyCtxt; @@ -115,7 +114,7 @@ impl DocFolder for Stripper<'_, '_> { // If the macro has the `#[macro_export]` attribute, it means it's accessible at the // crate level so it should be handled differently. clean::MacroItem(..) => { - find_attr!(&i.attrs.other_attrs, AttributeKind::MacroExport { .. }) + find_attr!(&i.attrs.other_attrs, MacroExport { .. }) } _ => false, }; diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 0f4460bed35a7..fd6ea21847c19 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -6,7 +6,7 @@ use std::mem; use rustc_ast::attr::AttributeExt; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_hir as hir; -use rustc_hir::attrs::{AttributeKind, DocInline}; +use rustc_hir::attrs::DocInline; use rustc_hir::def::{DefKind, MacroKinds, Res}; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet}; use rustc_hir::intravisit::{Visitor, walk_body, walk_item}; @@ -167,7 +167,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { if !child.reexport_chain.is_empty() && let Res::Def(DefKind::Macro(_), def_id) = child.res && let Some(local_def_id) = def_id.as_local() - && find_attr!(self.cx.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }) + && find_attr!(self.cx.tcx, def_id, MacroExport { .. }) && inserted.insert(def_id) { let item = self.cx.tcx.hir_expect_item(local_def_id); @@ -249,7 +249,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = find_attr!( use_attrs, - AttributeKind::Doc(d) + Doc(d) if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::NoInline) ) || (document_hidden && use_attrs.iter().any(|attr| attr.is_doc_hidden())); @@ -385,7 +385,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { || match item.kind { hir::ItemKind::Impl(..) => true, hir::ItemKind::Macro(_, _, _) => { - find_attr!(self.cx.tcx.get_all_attrs(item.owner_id.def_id), AttributeKind::MacroExport{..}) + find_attr!(self.cx.tcx, item.owner_id.def_id, MacroExport{..}) } _ => false, } @@ -471,7 +471,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { if is_pub && self.inside_public_path { let please_inline = find_attr!( attrs, - AttributeKind::Doc(d) + Doc(d) if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::Inline) ); let ident = match kind { @@ -502,8 +502,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { let def_id = item.owner_id.to_def_id(); let is_macro_2_0 = !macro_def.macro_rules; - let nonexported = - !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. }); + let nonexported = !find_attr!(tcx, def_id, MacroExport { .. }); if is_macro_2_0 || nonexported || self.inlining { self.add_to_current_mod(item, renamed, import_id); diff --git a/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs b/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs index fb86ae8da9d66..c0b14c2a4b66e 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/inline_always.rs @@ -1,6 +1,6 @@ use super::INLINE_ALWAYS; use clippy_utils::diagnostics::span_lint; -use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::attrs::InlineAttr; use rustc_hir::{Attribute, find_attr}; use rustc_lint::LateContext; use rustc_span::Span; @@ -11,7 +11,7 @@ pub(super) fn check(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Att return; } - if let Some(span) = find_attr!(attrs, AttributeKind::Inline(InlineAttr::Always, span) => *span) { + if let Some(span) = find_attr!(attrs, Inline(InlineAttr::Always, span) => *span) { span_lint( cx, INLINE_ALWAYS, diff --git a/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs index 8a530e8cff2e9..2a3e4b96b1cd9 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/repr_attributes.rs @@ -1,4 +1,4 @@ -use rustc_hir::attrs::{AttributeKind, ReprAttr}; +use rustc_hir::attrs::ReprAttr; use rustc_hir::{Attribute, find_attr}; use rustc_lint::LateContext; use rustc_span::Span; @@ -9,7 +9,7 @@ use clippy_utils::msrvs::{self, Msrv}; use super::REPR_PACKED_WITHOUT_ABI; pub(super) fn check(cx: &LateContext<'_>, item_span: Span, attrs: &[Attribute], msrv: Msrv) { - if let Some(reprs) = find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs) { + if let Some(reprs) = find_attr!(attrs, Repr { reprs, .. } => reprs) { let packed_span = reprs .iter() .find(|(r, _)| matches!(r, ReprAttr::ReprPacked(..))) diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index 595625c08bef9..dfc1ca107feb2 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -146,6 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for CognitiveComplexity { span: Span, def_id: LocalDefId, ) { + #[allow(deprecated)] if !cx.tcx.has_attr(def_id, sym::test) { let expr = if kind.asyncness().is_async() { match get_async_fn_body(cx.tcx, body) { diff --git a/src/tools/clippy/clippy_lints/src/default_union_representation.rs b/src/tools/clippy/clippy_lints/src/default_union_representation.rs index df6525ce040e0..c1005688a9215 100644 --- a/src/tools/clippy/clippy_lints/src/default_union_representation.rs +++ b/src/tools/clippy/clippy_lints/src/default_union_representation.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_then; -use rustc_hir::attrs::{AttributeKind, ReprAttr}; +use rustc_hir::attrs::ReprAttr; use rustc_hir::{HirId, Item, ItemKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf; @@ -99,5 +99,5 @@ fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: ty::GenericArgsR fn has_c_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool { let attrs = cx.tcx.hir_attrs(hir_id); - find_attr!(attrs, AttributeKind::Repr { reprs, .. } if reprs.iter().any(|(x, _)| *x == ReprAttr::ReprC)) + find_attr!(attrs, Repr { reprs, .. } if reprs.iter().any(|(x, _)| *x == ReprAttr::ReprC)) } diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 3e46c370fb704..bb94a111f7a14 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -6,7 +6,6 @@ use clippy_utils::usage::{local_used_after_expr, local_used_in}; use clippy_utils::{get_path_from_caller_to_method_type, is_adjusted, is_no_std_crate}; use rustc_abi::ExternAbi; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, GenericArgs, Param, PatKind, QPath, Safety, TyKind, find_attr}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; @@ -154,7 +153,7 @@ fn check_closure<'tcx>(cx: &LateContext<'tcx>, outer_receiver: Option<&Expr<'tcx let sig = match callee_ty_adjusted.kind() { ty::FnDef(def, _) => { // Rewriting `x(|| f())` to `x(f)` where f is marked `#[track_caller]` moves the `Location` - if find_attr!(cx.tcx.get_all_attrs(*def), AttributeKind::TrackCaller(..)) { + if find_attr!(cx.tcx, *def, TrackCaller(..)) { return; } @@ -262,7 +261,7 @@ fn check_closure<'tcx>(cx: &LateContext<'tcx>, outer_receiver: Option<&Expr<'tcx }, ExprKind::MethodCall(path, self_, args, _) if check_inputs(typeck, body.params, Some(self_), args) => { if let Some(method_def_id) = typeck.type_dependent_def_id(body.value.hir_id) - && !find_attr!(cx.tcx.get_all_attrs(method_def_id), AttributeKind::TrackCaller(..)) + && !find_attr!(cx.tcx, method_def_id, TrackCaller(..)) && check_sig(closure_sig, cx.tcx.fn_sig(method_def_id).skip_binder().skip_binder()) { let mut app = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs index ac61ce705eb7c..13c8f2d2059a6 100644 --- a/src/tools/clippy/clippy_lints/src/exhaustive_items.rs +++ b/src/tools/clippy/clippy_lints/src/exhaustive_items.rs @@ -1,7 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::indent_of; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Item, ItemKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; @@ -85,7 +84,7 @@ impl LateLintPass<'_> for ExhaustiveItems { }; if cx.effective_visibilities.is_exported(item.owner_id.def_id) && let attrs = cx.tcx.hir_attrs(item.hir_id()) - && !find_attr!(attrs, AttributeKind::NonExhaustive(..)) + && !find_attr!(attrs, NonExhaustive(..)) && fields.iter().all(|f| cx.tcx.visibility(f.def_id).is_public()) { span_lint_and_then(cx, lint, item.span, msg, |diag| { diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 5fb1a0b80f1a4..774c88233af69 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -21,7 +21,6 @@ use rustc_ast::{ use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_errors::SuggestionStyle::{CompletelyHidden, ShowCode}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Expr, ExprKind, LangItem, RustcVersion, find_attr}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; @@ -662,10 +661,7 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> { }; let selection = SelectionContext::new(&infcx).select(&obligation); let derived = if let Ok(Some(Selection::UserDefined(data))) = selection { - find_attr!( - tcx.get_all_attrs(data.impl_def_id), - AttributeKind::AutomaticallyDerived(..) - ) + find_attr!(tcx, data.impl_def_id, AutomaticallyDerived(..)) } else { false }; diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index 9ad36f7789041..b9f16f2a371a1 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -2,7 +2,7 @@ use hir::FnSig; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::def_id::DefIdSet; -use rustc_hir::{self as hir, Attribute, QPath}; +use rustc_hir::{self as hir, Attribute, QPath, find_attr}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LintContext}; use rustc_middle::ty::{self, Ty}; @@ -14,8 +14,6 @@ use clippy_utils::source::snippet_indent; use clippy_utils::ty::is_must_use_ty; use clippy_utils::visitors::for_each_expr_without_closures; use clippy_utils::{is_entrypoint_fn, return_ty, trait_ref_of_method}; -use rustc_hir::attrs::AttributeKind; -use rustc_hir::find_attr; use rustc_span::Symbol; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; @@ -25,7 +23,7 @@ use super::{DOUBLE_MUST_USE, MUST_USE_CANDIDATE, MUST_USE_UNIT}; pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { let attrs = cx.tcx.hir_attrs(item.hir_id()); - let attr = find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::MustUse { span, reason } => (span, reason)); + let attr = find_attr!(cx.tcx.hir_attrs(item.hir_id()), MustUse { span, reason } => (span, reason)); if let hir::ItemKind::Fn { ref sig, body: ref body_id, @@ -47,7 +45,7 @@ pub(super) fn check_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_> attrs, sig, ); - } else if is_public && !is_proc_macro(attrs) && !find_attr!(attrs, AttributeKind::NoMangle(..)) { + } else if is_public && !is_proc_macro(attrs) && !find_attr!(attrs, NoMangle(..)) { check_must_use_candidate( cx, sig.decl, @@ -66,8 +64,7 @@ pub(super) fn check_impl_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Imp 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 attrs = cx.tcx.hir_attrs(item.hir_id()); - let attr = - find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::MustUse { span, reason } => (span, reason)); + let attr = find_attr!(cx.tcx.hir_attrs(item.hir_id()), MustUse { span, reason } => (span, reason)); if let Some((attr_span, reason)) = attr { check_needless_must_use( cx, @@ -100,8 +97,7 @@ pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::Tr let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); let attrs = cx.tcx.hir_attrs(item.hir_id()); - let attr = - find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::MustUse { span, reason } => (span, reason)); + let attr = find_attr!(cx.tcx.hir_attrs(item.hir_id()), MustUse { span, reason } => (span, reason)); if let Some((attr_span, reason)) = attr { check_needless_must_use( cx, diff --git a/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs b/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs index 8d538ff1acba6..6ef3459f222c8 100644 --- a/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs +++ b/src/tools/clippy/clippy_lints/src/incompatible_msrv.rs @@ -3,7 +3,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::Msrv; use clippy_utils::{is_in_const_context, is_in_test, sym}; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{self as hir, AmbigArg, Expr, ExprKind, HirId, RustcVersion, StabilityLevel, StableSince, find_attr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, TyCtxt}; @@ -268,10 +267,7 @@ impl<'tcx> LateLintPass<'tcx> for IncompatibleMsrv { /// Heuristic checking if the node `hir_id` is under a `#[cfg()]` or `#[cfg_attr()]` /// attribute. fn is_under_cfg_attribute(cx: &LateContext<'_>, hir_id: HirId) -> bool { - cx.tcx.hir_parent_id_iter(hir_id).any(|id| { - find_attr!( - cx.tcx.hir_attrs(id), - AttributeKind::CfgTrace(..) | AttributeKind::CfgAttrTrace - ) - }) + cx.tcx + .hir_parent_id_iter(hir_id) + .any(|id| find_attr!(cx.tcx.hir_attrs(id), CfgTrace(..) | CfgAttrTrace)) } diff --git a/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs b/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs index e416ac079d6f7..2da13b57aec44 100644 --- a/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs +++ b/src/tools/clippy/clippy_lints/src/inline_fn_without_body.rs @@ -1,7 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::sugg::DiagExt; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{TraitFn, TraitItem, TraitItemKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; @@ -35,7 +34,7 @@ impl<'tcx> LateLintPass<'tcx> for InlineFnWithoutBody { && let Some(attr_span) = find_attr!(cx .tcx .hir_attrs(item.hir_id()), - AttributeKind::Inline(_, span) => *span + Inline(_, span) => *span ) { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs index 0a5b26bfa6898..f2b2b77c34967 100644 --- a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs @@ -2,7 +2,6 @@ use super::EMPTY_LOOP; use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{is_in_panic_handler, is_no_std_crate}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Block, Expr, ItemKind, Node, find_attr}; use rustc_lint::LateContext; @@ -11,7 +10,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, loop_block: &Block<'_ if let Node::Item(parent_node) = cx.tcx.hir_node(parent_hir_id) && matches!(parent_node.kind, ItemKind::Fn { .. }) && let attrs = cx.tcx.hir_attrs(parent_hir_id) - && find_attr!(attrs, AttributeKind::RustcIntrinsic) + && find_attr!(attrs, RustcIntrinsic) { // Intrinsic functions are expanded into an empty loop when lowering the AST // to simplify the job of later passes which might expect any function to have a body. diff --git a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs index a323c7cf8307c..db1ed269bb0ee 100644 --- a/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs +++ b/src/tools/clippy/clippy_lints/src/macro_metavars_in_unsafe.rs @@ -2,7 +2,6 @@ use clippy_config::Conf; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::is_lint_allowed; use itertools::Itertools; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{Visitor, walk_block, walk_expr, walk_stmt}; use rustc_hir::{BlockCheckMode, Expr, ExprKind, HirId, Stmt, UnsafeSource, find_attr}; @@ -147,8 +146,7 @@ struct BodyVisitor<'a, 'tcx> { } fn is_public_macro(cx: &LateContext<'_>, def_id: LocalDefId) -> bool { - (cx.effective_visibilities.is_exported(def_id) - || find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. })) + (cx.effective_visibilities.is_exported(def_id) || find_attr!(cx.tcx, def_id, MacroExport { .. })) && !cx.tcx.is_doc_hidden(def_id) } diff --git a/src/tools/clippy/clippy_lints/src/macro_use.rs b/src/tools/clippy/clippy_lints/src/macro_use.rs index 8989793625aaa..005a04002cf31 100644 --- a/src/tools/clippy/clippy_lints/src/macro_use.rs +++ b/src/tools/clippy/clippy_lints/src/macro_use.rs @@ -1,9 +1,8 @@ use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; -use hir::def::{DefKind, Res}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; +use rustc_hir::def::{DefKind, Res}; use rustc_hir::{self as hir, AmbigArg, find_attr}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; @@ -100,7 +99,7 @@ impl LateLintPass<'_> for MacroUseImports { && let hir::ItemKind::Use(path, _kind) = &item.kind && let hir_id = item.hir_id() && let attrs = cx.tcx.hir_attrs(hir_id) - && let Some(mac_attr_span) = find_attr!(attrs, AttributeKind::MacroUse {span, ..} => *span) + && let Some(mac_attr_span) = find_attr!(attrs, MacroUse {span, ..} => *span) && let Some(Res::Def(DefKind::Mod, id)) = path.res.type_ns && !id.is_local() { diff --git a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs index 0d783fde33131..8e09d88232f61 100644 --- a/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs +++ b/src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs @@ -6,7 +6,6 @@ use clippy_utils::source::snippet_indent; use itertools::Itertools; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::{Expr, ExprKind, Item, ItemKind, QPath, TyKind, VariantData, find_attr}; use rustc_lint::{LateContext, LateLintPass}; @@ -93,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive { .then_some((v.def_id, v.span)) }); if let Ok((id, span)) = iter.exactly_one() - && !find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::NonExhaustive(..)) + && !find_attr!(cx.tcx.hir_attrs(item.hir_id()), NonExhaustive(..)) { self.potential_enums.push((item.owner_id.def_id, id, item.span, span)); } @@ -114,7 +113,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive { "this seems like a manual implementation of the non-exhaustive pattern", |diag| { if let Some(non_exhaustive_span) = - find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::NonExhaustive(span) => *span) + find_attr!(cx.tcx.hir_attrs(item.hir_id()), NonExhaustive(span) => *span) { diag.span_note(non_exhaustive_span, "the struct is already non-exhaustive"); } else { diff --git a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs index 00bd1c2ca6981..768d0e8e268cc 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_wild_enum.rs @@ -208,5 +208,5 @@ impl<'a> CommonPrefixSearcher<'a> { } fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool { - cx.tcx.is_doc_hidden(variant_def.def_id) || cx.tcx.has_attr(variant_def.def_id, sym::unstable) + cx.tcx.is_doc_hidden(variant_def.def_id) } diff --git a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index 14d265bfdad87..4267cd1185523 100644 --- a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs @@ -185,6 +185,7 @@ impl<'a, 'tcx> SigDropChecker<'a, 'tcx> { if let Some(adt) = ty.ty_adt_def() && get_builtin_attr( self.cx.sess(), + #[allow(deprecated)] self.cx.tcx.get_all_attrs(adt.did()), sym::has_significant_drop, ) diff --git a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs index 8135c67d0d784..4577be34d4a77 100644 --- a/src/tools/clippy/clippy_lints/src/methods/is_empty.rs +++ b/src/tools/clippy/clippy_lints/src/methods/is_empty.rs @@ -3,7 +3,6 @@ use clippy_utils::diagnostics::span_lint; use clippy_utils::macros::{is_assert_macro, root_macro_call}; use clippy_utils::res::MaybeResPath; use clippy_utils::{find_binding_init, get_parent_expr, is_inside_always_const_context}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::{Expr, HirId, find_attr}; use rustc_lint::{LateContext, LintContext}; @@ -40,7 +39,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &'_ Expr<'_>, receiver: &Expr<'_ fn is_under_cfg(cx: &LateContext<'_>, id: HirId) -> bool { cx.tcx .hir_parent_id_iter(id) - .any(|id| find_attr!(cx.tcx.hir_attrs(id), AttributeKind::CfgTrace(..))) + .any(|id| find_attr!(cx.tcx.hir_attrs(id), CfgTrace(..))) } /// Similar to [`clippy_utils::expr_or_init`], but does not go up the chain if the initialization diff --git a/src/tools/clippy/clippy_lints/src/missing_inline.rs b/src/tools/clippy/clippy_lints/src/missing_inline.rs index c308f2a345852..0dd531d367428 100644 --- a/src/tools/clippy/clippy_lints/src/missing_inline.rs +++ b/src/tools/clippy/clippy_lints/src/missing_inline.rs @@ -1,5 +1,4 @@ use clippy_utils::diagnostics::{span_lint, span_lint_hir}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, Attribute, find_attr}; use rustc_lint::{LateContext, LateLintPass, LintContext}; @@ -72,7 +71,7 @@ fn check_missing_inline_attrs( desc: &'static str, hir_id: Option, ) { - if !find_attr!(attrs, AttributeKind::Inline(..)) { + if !find_attr!(attrs, Inline(..)) { let msg = format!("missing `#[inline]` for {desc}"); if let Some(hir_id) = hir_id { span_lint_hir(cx, MISSING_INLINE_IN_PUBLIC_ITEMS, hir_id, sp, msg); diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 6e9142b22e0ef..666476cb4bacd 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -8,7 +8,7 @@ use rustc_abi::ExternAbi; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_hir::attrs::{AttributeKind, InlineAttr}; +use rustc_hir::attrs::InlineAttr; use rustc_hir::intravisit::FnKind; use rustc_hir::{BindingMode, Body, FnDecl, Impl, ItemKind, MutTy, Mutability, Node, PatKind, find_attr}; use rustc_lint::{LateContext, LateLintPass}; @@ -270,7 +270,7 @@ impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue { return; } let attrs = cx.tcx.hir_attrs(hir_id); - if find_attr!(attrs, AttributeKind::Inline(InlineAttr::Always, _)) { + if find_attr!(attrs, Inline(InlineAttr::Always, _)) { return; } diff --git a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs index 83a226b29e75f..78f5167fa5436 100644 --- a/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs +++ b/src/tools/clippy/clippy_lints/src/return_self_not_must_use.rs @@ -1,7 +1,6 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::is_must_use_ty; use clippy_utils::{nth_arg, return_ty}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, OwnerId, TraitItem, TraitItemKind, find_attr}; @@ -77,7 +76,7 @@ fn check_method(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_def: LocalDefId, spa // We don't want to emit this lint if the `#[must_use]` attribute is already there. && !find_attr!( cx.tcx.hir_attrs(owner_id.into()), - AttributeKind::MustUse { .. } + MustUse { .. } ) && cx.tcx.visibility(fn_def.to_def_id()).is_public() && let ret_ty = return_ty(cx, owner_id) diff --git a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs index c2c1778882d3a..3e77c98b88456 100644 --- a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs +++ b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs @@ -171,6 +171,7 @@ impl<'cx, 'others, 'tcx> AttrChecker<'cx, 'others, 'tcx> { if let Some(adt) = ty.ty_adt_def() { let mut iter = get_builtin_attr( self.cx.sess(), + #[allow(deprecated)] self.cx.tcx.get_all_attrs(adt.did()), sym::has_significant_drop, ); diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index 56490cfc8b655..6e74347713695 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -4,7 +4,6 @@ use crate::source::SpanRangeExt; use crate::{sym, tokenize_with_text}; use rustc_ast::attr::AttributeExt; use rustc_errors::Applicability; -use rustc_hir::attrs::AttributeKind; use rustc_hir::find_attr; use rustc_lexer::TokenKind; use rustc_lint::LateContext; @@ -95,14 +94,13 @@ pub fn is_doc_hidden(attrs: &[impl AttributeExt]) -> bool { /// Checks whether the given ADT, or any of its fields/variants, are marked as `#[non_exhaustive]` pub fn has_non_exhaustive_attr(tcx: TyCtxt<'_>, adt: AdtDef<'_>) -> bool { adt.is_variant_list_non_exhaustive() - || find_attr!(tcx.get_all_attrs(adt.did()), AttributeKind::NonExhaustive(..)) + || find_attr!(tcx, adt.did(), NonExhaustive(..)) || adt.variants().iter().any(|variant_def| { - variant_def.is_field_list_non_exhaustive() - || find_attr!(tcx.get_all_attrs(variant_def.def_id), AttributeKind::NonExhaustive(..)) + variant_def.is_field_list_non_exhaustive() || find_attr!(tcx, variant_def.def_id, NonExhaustive(..)) }) || adt .all_fields() - .any(|field_def| find_attr!(tcx.get_all_attrs(field_def.did), AttributeKind::NonExhaustive(..))) + .any(|field_def| find_attr!(tcx, field_def.did, NonExhaustive(..))) } /// Checks whether the given span contains a `#[cfg(..)]` attribute diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index d8b2b22dd09dd..9a49845d9d46b 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -89,7 +89,7 @@ use rustc_data_structures::indexmap; use rustc_data_structures::packed::Pu128; use rustc_data_structures::unhash::UnindexMap; use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk}; -use rustc_hir::attrs::{AttributeKind, CfgEntry}; +use rustc_hir::attrs::CfgEntry; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::definitions::{DefPath, DefPathData}; @@ -1691,7 +1691,7 @@ pub fn has_attr(attrs: &[hir::Attribute], symbol: Symbol) -> bool { } pub fn has_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool { - find_attr!(cx.tcx.hir_attrs(hir_id), AttributeKind::Repr { .. }) + find_attr!(cx.tcx.hir_attrs(hir_id), Repr { .. }) } pub fn any_parent_has_attr(tcx: TyCtxt<'_>, node: HirId, symbol: Symbol) -> bool { @@ -1716,7 +1716,7 @@ pub fn in_automatically_derived(tcx: TyCtxt<'_>, id: HirId) -> bool { .any(|(id, _)| { find_attr!( tcx.hir_attrs(tcx.local_def_id_to_hir_id(id.def_id)), - AttributeKind::AutomaticallyDerived(..) + AutomaticallyDerived(..) ) }) } @@ -1807,7 +1807,7 @@ pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { _ => None, }; - did.is_some_and(|did| find_attr!(cx.tcx.get_all_attrs(did), AttributeKind::MustUse { .. })) + did.is_some_and(|did| find_attr!(cx.tcx, did, MustUse { .. })) } /// Checks if a function's body represents the identity function. Looks for bodies of the form: @@ -2034,11 +2034,11 @@ pub fn std_or_core(cx: &LateContext<'_>) -> Option<&'static str> { } pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool { - find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::NoStd(..)) + find_attr!(cx.tcx, crate, NoStd(..)) } pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool { - find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::NoCore(..)) + find_attr!(cx.tcx, crate, NoCore(..)) } /// Check if parent of a hir node is a trait implementation block. @@ -2318,6 +2318,7 @@ pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool { if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind && let Res::Def(_, def_id) = path.res { + #[allow(deprecated)] return cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr); } false @@ -2343,7 +2344,7 @@ fn with_test_item_names(tcx: TyCtxt<'_>, module: LocalModDefId, f: impl FnOnce(& // We could also check for the type name `test::TestDescAndFn` && let Res::Def(DefKind::Struct, _) = path.res { - if find_attr!(tcx.hir_attrs(item.hir_id()), AttributeKind::RustcTestMarker(..)) { + if find_attr!(tcx.hir_attrs(item.hir_id()), RustcTestMarker(..)) { names.push(ident.name); } } @@ -2401,7 +2402,7 @@ pub fn is_test_function(tcx: TyCtxt<'_>, fn_def_id: LocalDefId) -> bool { /// This only checks directly applied attributes, to see if a node is inside a `#[cfg(test)]` parent /// use [`is_in_cfg_test`] pub fn is_cfg_test(tcx: TyCtxt<'_>, id: HirId) -> bool { - if let Some(cfgs) = find_attr!(tcx.hir_attrs(id), AttributeKind::CfgTrace(cfgs) => cfgs) + if let Some(cfgs) = find_attr!(tcx.hir_attrs(id), CfgTrace(cfgs) => cfgs) && cfgs .iter() .any(|(cfg, _)| matches!(cfg, CfgEntry::NameValue { name: sym::test, .. })) @@ -2424,11 +2425,11 @@ pub fn is_in_test(tcx: TyCtxt<'_>, hir_id: HirId) -> bool { /// Checks if the item of any of its parents has `#[cfg(...)]` attribute applied. pub fn inherits_cfg(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::CfgTrace(..)) + find_attr!(tcx, def_id, CfgTrace(..)) || find_attr!( tcx.hir_parent_iter(tcx.local_def_id_to_hir_id(def_id)) .flat_map(|(parent_id, _)| tcx.hir_attrs(parent_id)), - AttributeKind::CfgTrace(..) + CfgTrace(..) ) } diff --git a/src/tools/clippy/clippy_utils/src/macros.rs b/src/tools/clippy/clippy_utils/src/macros.rs index 4e06f010bd591..3cfe648fdf322 100644 --- a/src/tools/clippy/clippy_utils/src/macros.rs +++ b/src/tools/clippy/clippy_utils/src/macros.rs @@ -42,7 +42,13 @@ pub fn is_format_macro(cx: &LateContext<'_>, macro_def_id: DefId) -> bool { } else { // Allow users to tag any macro as being format!-like // TODO: consider deleting FORMAT_MACRO_DIAG_ITEMS and using just this method - get_unique_builtin_attr(cx.sess(), cx.tcx.get_all_attrs(macro_def_id), sym::format_args).is_some() + get_unique_builtin_attr( + cx.sess(), + #[allow(deprecated)] + cx.tcx.get_all_attrs(macro_def_id), + sym::format_args, + ) + .is_some() } } diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index 639492b75747a..66b044e485f50 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -7,7 +7,6 @@ use rustc_abi::VariantIdx; use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, FnDecl, LangItem, find_attr}; @@ -311,8 +310,8 @@ pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // Returns whether the type has #[must_use] attribute pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { match ty.kind() { - ty::Adt(adt, _) => find_attr!(cx.tcx.get_all_attrs(adt.did()), AttributeKind::MustUse { .. }), - ty::Foreign(did) => find_attr!(cx.tcx.get_all_attrs(*did), AttributeKind::MustUse { .. }), + ty::Adt(adt, _) => find_attr!(cx.tcx, adt.did(), MustUse { .. }), + ty::Foreign(did) => find_attr!(cx.tcx, *did, MustUse { .. }), ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => { // for the Array case we don't need to care for the len == 0 case // because we don't want to lint functions returning empty arrays @@ -322,10 +321,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Alias(ty::Opaque, AliasTy { def_id, .. }) => { for (predicate, _) in cx.tcx.explicit_item_self_bounds(def_id).skip_binder() { if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() - && find_attr!( - cx.tcx.get_all_attrs(trait_predicate.trait_ref.def_id), - AttributeKind::MustUse { .. } - ) + && find_attr!(cx.tcx, trait_predicate.trait_ref.def_id, MustUse { .. }) { return true; } @@ -335,7 +331,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Dynamic(binder, _) => { for predicate in *binder { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() - && find_attr!(cx.tcx.get_all_attrs(trait_ref.def_id), AttributeKind::MustUse { .. }) + && find_attr!(cx.tcx, trait_ref.def_id, MustUse { .. }) { return true; } diff --git a/tests/ui-fulldeps/internal-lints/find_attr.rs b/tests/ui-fulldeps/internal-lints/find_attr.rs new file mode 100644 index 0000000000000..bb0c8c486bcdb --- /dev/null +++ b/tests/ui-fulldeps/internal-lints/find_attr.rs @@ -0,0 +1,27 @@ +//@ compile-flags: -Z unstable-options +//@ ignore-stage1 + +#![feature(rustc_private)] +#![deny(rustc::bad_use_of_find_attr)] + +extern crate rustc_hir; + +use rustc_hir::{attrs::AttributeKind, find_attr}; + +fn main() { + let attrs = &[]; + + find_attr!(attrs, AttributeKind::Inline(..)); + //~^ ERROR use of `AttributeKind` in `find_attr!(...)` invocation + find_attr!(attrs, AttributeKind::Inline{..} | AttributeKind::Deprecation {..}); + //~^ ERROR use of `AttributeKind` in `find_attr!(...)` invocation + //~| ERROR use of `AttributeKind` in `find_attr!(...)` invocation + + find_attr!(attrs, AttributeKind::Inline(..) => todo!()); + //~^ ERROR use of `AttributeKind` in `find_attr!(...)` invocation + find_attr!(attrs, AttributeKind::Inline(..) if true => todo!()); + //~^ ERROR use of `AttributeKind` in `find_attr!(...)` invocation + + find_attr!(attrs, wildcard); + //~^ ERROR unreachable pattern +} diff --git a/tests/ui-fulldeps/internal-lints/find_attr.stderr b/tests/ui-fulldeps/internal-lints/find_attr.stderr new file mode 100644 index 0000000000000..b7291ecbb84d9 --- /dev/null +++ b/tests/ui-fulldeps/internal-lints/find_attr.stderr @@ -0,0 +1,74 @@ +error: use of `AttributeKind` in `find_attr!(...)` invocation + --> $DIR/find_attr.rs:14:23 + | +LL | find_attr!(attrs, AttributeKind::Inline(..)); + | ^^^^^^^^^^^^^ + | + = note: `find_attr!(...)` already imports `AttributeKind::*` + = help: remove `AttributeKind` +note: the lint level is defined here + --> $DIR/find_attr.rs:5:9 + | +LL | #![deny(rustc::bad_use_of_find_attr)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: use of `AttributeKind` in `find_attr!(...)` invocation + --> $DIR/find_attr.rs:16:23 + | +LL | find_attr!(attrs, AttributeKind::Inline{..} | AttributeKind::Deprecation {..}); + | ^^^^^^^^^^^^^ + | + = note: `find_attr!(...)` already imports `AttributeKind::*` + = help: remove `AttributeKind` + +error: use of `AttributeKind` in `find_attr!(...)` invocation + --> $DIR/find_attr.rs:16:51 + | +LL | find_attr!(attrs, AttributeKind::Inline{..} | AttributeKind::Deprecation {..}); + | ^^^^^^^^^^^^^ + | + = note: `find_attr!(...)` already imports `AttributeKind::*` + = help: remove `AttributeKind` + +error: use of `AttributeKind` in `find_attr!(...)` invocation + --> $DIR/find_attr.rs:20:23 + | +LL | find_attr!(attrs, AttributeKind::Inline(..) => todo!()); + | ^^^^^^^^^^^^^ + | + = note: `find_attr!(...)` already imports `AttributeKind::*` + = help: remove `AttributeKind` + +error: use of `AttributeKind` in `find_attr!(...)` invocation + --> $DIR/find_attr.rs:22:23 + | +LL | find_attr!(attrs, AttributeKind::Inline(..) if true => todo!()); + | ^^^^^^^^^^^^^ + | + = note: `find_attr!(...)` already imports `AttributeKind::*` + = help: remove `AttributeKind` + +error: unreachable pattern + --> $DIR/find_attr.rs:25:5 + | +LL | find_attr!(attrs, wildcard); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ no value can reach this + | +note: multiple earlier patterns match some of the same values + --> $DIR/find_attr.rs:25:5 + | +LL | find_attr!(attrs, wildcard); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | matches some of the same values + | matches some of the same values + | collectively making this unreachable +note: the lint level is defined here + --> $DIR/find_attr.rs:25:5 + | +LL | find_attr!(attrs, wildcard); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `$crate::find_attr` which comes from the expansion of the macro `find_attr` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors +