From 20cb59be6449224b1418200a245a63bd2fd1302c Mon Sep 17 00:00:00 2001 From: Harmen Stoppels Date: Tue, 3 Feb 2026 16:30:22 +0100 Subject: [PATCH 01/23] bootstrap: respect modern jobserver When bootstrapping Rust, the `-j N` flag was passed to CMake, which was then forwarded to Ninja. This prevents the jobserver from being used, and as a result leads to oversubscription when Rust is just one of the many packages built as part of a larger software stack. Since Cargo and the Rust compiler have long supported the jobserver, it would be good if also bootstrapping Rust itself would participate in the protocol, leading to composable parallelism. This change allows bootstrapping to respect an existing FIFO based jobserver. Old pipe based jobservers are not supported, because they are brittle: currently the Python scripts in bootstrap do not inherit the file descriptors, but do pass on `MAKEFLAGS`. Because Ninja only supports FIFO based jobservers, it's better to focus on new jobservers only. In summary: * Bootstrap Cargo passes `MAKEFLAGS` verbatim to subprocesses if it advertises a FIFO style jobserver, otherwise it unsets it. * `llvm.rs` does not pass `-j` to `cmake` when a FIFO style jobserver is set in `MAKEFLAGS. * Bootstrap Cargo no longer unsets `MKFLAGS`: from git blame, GNU Make considered it a historical artifact back in 1992, and it is never read by GNU Make, it's only set for backwards compatibility. Signed-off-by: Harmen Stoppels --- src/bootstrap/src/core/build_steps/llvm.rs | 10 +++++++++- src/bootstrap/src/core/builder/cargo.rs | 14 +++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index dbd4f1c814055..ae86874cc99ae 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -773,7 +773,15 @@ fn configure_cmake( .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx)) .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc)); - cfg.build_arg("-j").build_arg(builder.jobs().to_string()); + // If we are running under a FIFO jobserver, we should not pass -j to CMake; otherwise it + // overrides the jobserver settings and can lead to oversubscription. + let has_modern_jobserver = env::var("MAKEFLAGS") + .map(|flags| flags.contains("--jobserver-auth=fifo:")) + .unwrap_or(false); + + if !has_modern_jobserver { + cfg.build_arg("-j").build_arg(builder.jobs().to_string()); + } let mut cflags = ccflags.cflags.clone(); // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing // our flags via `.cflag`/`.cxxflag` instead. diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index 7150b2b0d59f2..f08632d979051 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -547,9 +547,17 @@ impl Builder<'_> { assert_eq!(target, compiler.host); } - // Remove make-related flags to ensure Cargo can correctly set things up - cargo.env_remove("MAKEFLAGS"); - cargo.env_remove("MFLAGS"); + // Bootstrap only supports modern FIFO jobservers. Older pipe-based jobservers can run into + // "invalid file descriptor" errors, as the jobserver file descriptors are not inherited by + // scripts like bootstrap.py, while the environment variable is propagated. So, we pass + // MAKEFLAGS only if we detect a FIFO jobserver, otherwise we clear it. + let has_modern_jobserver = env::var("MAKEFLAGS") + .map(|flags| flags.contains("--jobserver-auth=fifo:")) + .unwrap_or(false); + + if !has_modern_jobserver { + cargo.env_remove("MAKEFLAGS"); + } cargo } From 5c64b89e86bdce77e1936ca4467fe998815f4c1b Mon Sep 17 00:00:00 2001 From: Matthias Geier Date: Wed, 18 Feb 2026 19:50:58 +0100 Subject: [PATCH 02/23] DOC: do not link to "nightly" in Iterator::by_ref() docstring --- library/core/src/iter/traits/iterator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index d919230d094d8..9e081e65f9ad6 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -1908,7 +1908,7 @@ pub const trait Iterator { /// without giving up ownership of the original iterator, /// so you can use the original iterator afterwards. /// - /// Uses [`impl Iterator for &mut I { type Item = I::Item; ...}`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#impl-Iterator-for-%26mut+I). + /// Uses [`impl Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I). /// /// # Examples /// From a9e6a89b067dc8c7f9eb2a8390343e5584fead62 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Thu, 19 Feb 2026 18:13:12 +0800 Subject: [PATCH 03/23] bootstrap: add snapshot tests for {`install`, `install src`} And `install src` with `build.docs = false`. --- src/bootstrap/src/core/builder/tests.rs | 155 +++++++++++++++++++++++- src/bootstrap/src/utils/tests/mod.rs | 5 + 2 files changed, 157 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 002fb32dcf0c6..9c7b66a4d373c 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -2854,6 +2854,151 @@ mod snapshot { .render_steps(), @"[clippy] rustc 0 -> bootstrap 1 "); } + #[test] + fn install_plain() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("install") + .args(&[ + // Using backslashes fails with `--set` + "--set", &format!("install.prefix={}", ctx.normalized_dir()), + "--set", &format!("install.bindir={}", ctx.normalized_dir()), + "--set", &format!("install.libdir={}", ctx.normalized_dir()), + "--set", &format!("install.datadir={}", ctx.normalized_dir()), + "--set", &format!("install.mandir={}", ctx.normalized_dir()), + "--set", &format!("install.sysconfdir={}", ctx.normalized_dir()), + "--build", "x86_64-unknown-linux-gnu", + "--host", "x86_64-unknown-linux-gnu", + "--target", "x86_64-unknown-linux-gnu", + ]) + .get_steps() + .render_with(RenderConfig { + normalize_host: false + }), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 0 -> UnstableBookGen 1 + [build] rustc 0 -> Rustbook 1 + [doc] unstable-book (book) + [build] rustc 1 -> std 1 + [doc] book (book) + [doc] book/first-edition (book) + [doc] book/second-edition (book) + [doc] book/2018-edition (book) + [build] rustdoc 1 + [doc] rustc 1 -> standalone 2 + [doc] rustc 1 -> std 1 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] + [build] rustc 1 -> rustc 2 + [build] rustc 1 -> error-index 2 + [doc] rustc 1 -> error-index 2 + [doc] nomicon (book) + [doc] rustc 1 -> reference (book) 2 + [doc] rustdoc (book) + [doc] rust-by-example (book) + [build] rustc 0 -> LintDocs 1 + [doc] rustc (book) + [doc] cargo (book) + [doc] clippy (book) + [doc] embedded-book (book) + [doc] edition-guide (book) + [doc] style-guide (book) + [doc] rustc 1 -> releases 2 + [build] rustc 0 -> RustInstaller 1 + [dist] docs + [dist] rustc 1 -> std 1 + [build] rustdoc 2 + [build] rustc 0 -> GenerateCopyright 1 + [dist] rustc + "); + } + + #[test] + fn install_src() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("install") + .path("src") + .args(&[ + // Using backslashes fails with `--set` + "--set", &format!("install.prefix={}", ctx.normalized_dir()), + "--set", &format!("install.bindir={}", ctx.normalized_dir()), + "--set", &format!("install.libdir={}", ctx.normalized_dir()), + "--set", &format!("install.datadir={}", ctx.normalized_dir()), + "--set", &format!("install.mandir={}", ctx.normalized_dir()), + "--set", &format!("install.sysconfdir={}", ctx.normalized_dir()), + "--build", "x86_64-unknown-linux-gnu", + "--host", "x86_64-unknown-linux-gnu", + "--target", "x86_64-unknown-linux-gnu", + ]) + .get_steps() + .render_with(RenderConfig { + normalize_host: false + }), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 0 -> UnstableBookGen 1 + [build] rustc 0 -> Rustbook 1 + [doc] unstable-book (book) + [build] rustc 1 -> std 1 + [doc] book (book) + [doc] book/first-edition (book) + [doc] book/second-edition (book) + [doc] book/2018-edition (book) + [build] rustdoc 1 + [doc] rustc 1 -> standalone 2 + [doc] rustc 1 -> std 1 crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,rustc-std-workspace-core,std,std_detect,sysroot,test,unwind] + [build] rustc 1 -> rustc 2 + [build] rustc 1 -> error-index 2 + [doc] rustc 1 -> error-index 2 + [doc] nomicon (book) + [doc] rustc 1 -> reference (book) 2 + [doc] rustdoc (book) + [doc] rust-by-example (book) + [build] rustc 0 -> LintDocs 1 + [doc] rustc (book) + [doc] cargo (book) + [doc] clippy (book) + [doc] embedded-book (book) + [doc] edition-guide (book) + [doc] style-guide (book) + [doc] rustc 1 -> releases 2 + [build] rustc 0 -> RustInstaller 1 + [dist] docs + [dist] src <> + "); + } + + #[test] + fn install_src_no_docs() { + let ctx = TestCtx::new(); + insta::assert_snapshot!( + ctx.config("install") + .path("src") + .args(&[ + // Using backslashes fails with `--set` + "--set", &format!("install.prefix={}", ctx.normalized_dir()), + "--set", &format!("install.bindir={}", ctx.normalized_dir()), + "--set", &format!("install.libdir={}", ctx.normalized_dir()), + "--set", &format!("install.datadir={}", ctx.normalized_dir()), + "--set", &format!("install.mandir={}", ctx.normalized_dir()), + "--set", &format!("install.sysconfdir={}", ctx.normalized_dir()), + "--set", "build.docs=false", + "--build", "x86_64-unknown-linux-gnu", + "--host", "x86_64-unknown-linux-gnu", + "--target", "x86_64-unknown-linux-gnu", + ]) + .get_steps() + .render_with(RenderConfig { + normalize_host: false + }), @r" + [build] llvm + [build] rustc 0 -> rustc 1 + [build] rustc 0 -> RustInstaller 1 + [dist] docs + [dist] src <> + "); + } + #[test] fn install_extended() { let ctx = TestCtx::new(); @@ -2861,12 +3006,16 @@ mod snapshot { ctx.config("install") .args(&[ // Using backslashes fails with `--set` - "--set", &format!("install.prefix={}", ctx.dir().display()).replace("\\", "/"), - "--set", &format!("install.sysconfdir={}", ctx.dir().display()).replace("\\", "/"), + "--set", &format!("install.prefix={}", ctx.normalized_dir()), + "--set", &format!("install.bindir={}", ctx.normalized_dir()), + "--set", &format!("install.libdir={}", ctx.normalized_dir()), + "--set", &format!("install.datadir={}", ctx.normalized_dir()), + "--set", &format!("install.mandir={}", ctx.normalized_dir()), + "--set", &format!("install.sysconfdir={}", ctx.normalized_dir()), "--set", "build.extended=true", // For Cranelift to be disted "--build", "x86_64-unknown-linux-gnu", - "--host", "x86_64-unknown-linux-gnu" + "--host", "x86_64-unknown-linux-gnu", ]) .get_steps() .render_with(RenderConfig { diff --git a/src/bootstrap/src/utils/tests/mod.rs b/src/bootstrap/src/utils/tests/mod.rs index 764b89086cf2f..e2a689c0f0ccf 100644 --- a/src/bootstrap/src/utils/tests/mod.rs +++ b/src/bootstrap/src/utils/tests/mod.rs @@ -35,6 +35,11 @@ impl TestCtx { self.directory.path() } + /// Using backslashes fails with `--set` + pub fn normalized_dir(&self) -> String { + self.dir().to_string_lossy().replace("\\", "/") + } + /// Starts a new invocation of bootstrap that executes `kind` as its top level command /// (i.e. `x `). Returns a builder that configures the created config through CLI flags. pub fn config(&self, kind: &str) -> ConfigBuilder { From ede72796ba79d2dda3a8668a813c307196dd65d8 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Wed, 18 Feb 2026 22:27:24 +1100 Subject: [PATCH 04/23] Clarify some variable names in the query proc-macro --- compiler/rustc_macros/src/query.rs | 85 +++++++++++++++++++----------- 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index 5b869dc3409a7..d81bac4930a63 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -30,14 +30,28 @@ fn check_attributes(attrs: Vec) -> Result> { attrs.into_iter().map(inner).collect() } -/// A compiler query. `query ... { ... }` +/// Declaration of a compiler query. +/// +/// ```ignore (illustrative) +/// /// Doc comment for `my_query`. +/// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ doc_comments +/// query my_query(key: DefId) -> Value { anon } +/// // ^^^^^^^^ name +/// // ^^^ key_pat +/// // ^^^^^ key_ty +/// // ^^^^^^^^ return_ty +/// // ^^^^ modifiers +/// ``` struct Query { doc_comments: Vec, - modifiers: QueryModifiers, name: Ident, - key: Pat, - arg: Type, - result: ReturnType, + + /// Parameter name for the key, or an arbitrary irrefutable pattern (e.g. `_`). + key_pat: Pat, + key_ty: Type, + return_ty: ReturnType, + + modifiers: QueryModifiers, } impl Parse for Query { @@ -47,18 +61,22 @@ impl Parse for Query { // Parse the query declaration. Like `query type_of(key: DefId) -> Ty<'tcx>` input.parse::()?; let name: Ident = input.parse()?; - let arg_content; - parenthesized!(arg_content in input); - let key = Pat::parse_single(&arg_content)?; - arg_content.parse::()?; - let arg = arg_content.parse()?; - let _ = arg_content.parse::>()?; - let result = input.parse()?; + + // `(key: DefId)` + let parens_content; + parenthesized!(parens_content in input); + let key_pat = Pat::parse_single(&parens_content)?; + parens_content.parse::()?; + let key_ty = parens_content.parse::()?; + let _trailing_comma = parens_content.parse::>()?; + + // `-> Value` + let return_ty = input.parse::()?; // Parse the query modifiers - let content; - braced!(content in input); - let modifiers = parse_query_modifiers(&content)?; + let braces_content; + braced!(braces_content in input); + let modifiers = parse_query_modifiers(&braces_content)?; // If there are no doc-comments, give at least some idea of what // it does by showing the query description. @@ -66,7 +84,7 @@ impl Parse for Query { doc_comments.push(doc_comment_from_desc(&modifiers.desc.expr_list)?); } - Ok(Query { doc_comments, modifiers, name, key, arg, result }) + Ok(Query { doc_comments, modifiers, name, key_pat, key_ty, return_ty }) } } @@ -288,7 +306,7 @@ struct HelperTokenStreams { } fn make_helpers_for_query(query: &Query, streams: &mut HelperTokenStreams) { - let Query { name, key, modifiers, arg, .. } = &query; + let Query { name, key_pat, key_ty, modifiers, .. } = &query; // Replace span for `name` to make rust-analyzer ignore it. let mut erased_name = name.clone(); @@ -301,7 +319,7 @@ fn make_helpers_for_query(query: &Query, streams: &mut HelperTokenStreams) { streams.cache_on_disk_if_fns_stream.extend(quote! { #[allow(unused_variables, rustc::pass_by_value)] #[inline] - pub fn #erased_name<'tcx>(#tcx: TyCtxt<'tcx>, #key: &crate::queries::#name::Key<'tcx>) -> bool + pub fn #erased_name<'tcx>(#tcx: TyCtxt<'tcx>, #key_pat: &crate::queries::#name::Key<'tcx>) -> bool #block }); } @@ -311,8 +329,8 @@ fn make_helpers_for_query(query: &Query, streams: &mut HelperTokenStreams) { let desc = quote! { #[allow(unused_variables)] - pub fn #erased_name<'tcx>(tcx: TyCtxt<'tcx>, key: #arg) -> String { - let (#tcx, #key) = (tcx, key); + pub fn #erased_name<'tcx>(tcx: TyCtxt<'tcx>, key: #key_ty) -> String { + let (#tcx, #key_pat) = (tcx, key); format!(#expr_list) } }; @@ -373,7 +391,7 @@ fn add_to_analyzer_stream(query: &Query, analyzer_stream: &mut proc_macro2::Toke let mut erased_name = name.clone(); erased_name.set_span(Span::call_site()); - let result = &query.result; + let result = &query.return_ty; // This dead code exists to instruct rust-analyzer about the link between the `rustc_queries` // query names and the corresponding produced provider. The issue is that by nature of this @@ -417,19 +435,20 @@ pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { } for query in queries.0 { - let Query { name, arg, modifiers, .. } = &query; - let result_full = &query.result; - let result = match query.result { + let Query { doc_comments, name, key_ty, return_ty, modifiers, .. } = &query; + + // Normalize an absent return type into `-> ()` to make macro-rules parsing easier. + let return_ty = match return_ty { ReturnType::Default => quote! { -> () }, - _ => quote! { #result_full }, + ReturnType::Type(..) => quote! { #return_ty }, }; - let mut attributes = Vec::new(); + let mut modifiers_out = vec![]; macro_rules! passthrough { ( $( $modifier:ident ),+ $(,)? ) => { $( if let Some($modifier) = &modifiers.$modifier { - attributes.push(quote! { (#$modifier) }); + modifiers_out.push(quote! { (#$modifier) }); }; )+ } } @@ -452,7 +471,7 @@ pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { // on a synthetic `(cache_on_disk)` modifier that can be inspected by // macro-rules macros. if modifiers.cache_on_disk_if.is_some() { - attributes.push(quote! { (cache_on_disk) }); + modifiers_out.push(quote! { (cache_on_disk) }); } // This uses the span of the query definition for the commas, @@ -462,12 +481,13 @@ pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { // at the entire `rustc_queries!` invocation, which wouldn't // be very useful. let span = name.span(); - let attribute_stream = quote_spanned! {span=> #(#attributes),*}; - let doc_comments = &query.doc_comments; + let modifiers_stream = quote_spanned! { span => #(#modifiers_out),* }; + // Add the query to the group query_stream.extend(quote! { #(#doc_comments)* - [#attribute_stream] fn #name(#arg) #result, + [#modifiers_stream] + fn #name(#key_ty) #return_ty, }); if let Some(feedable) = &modifiers.feedable { @@ -482,7 +502,8 @@ pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { "Query {name} cannot be both `feedable` and `eval_always`." ); feedable_queries.extend(quote! { - [#attribute_stream] fn #name(#arg) #result, + [#modifiers_stream] + fn #name(#key_ty) #return_ty, }); } From 27c04763e1b74b3ed241002bfb26061f2b3d66be Mon Sep 17 00:00:00 2001 From: Andrew Paseltiner Date: Thu, 19 Feb 2026 10:27:22 -0500 Subject: [PATCH 05/23] Fix typo in doc for core::mem::type_info::Struct --- library/core/src/mem/type_info.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 18612565aeef2..740055563d2d8 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -153,7 +153,7 @@ pub struct Trait { pub is_auto: bool, } -/// Compile-time type information about arrays. +/// Compile-time type information about structs. #[derive(Debug)] #[non_exhaustive] #[unstable(feature = "type_info", issue = "146922")] From aebafba4bba5d0034edba046821b83ff65ef2a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ozan=20Kenan=20G=C3=BCng=C3=B6r?= Date: Thu, 19 Feb 2026 21:22:06 +0300 Subject: [PATCH 06/23] resolve: do not suggest `_` for unresolved imports `use _` is never valid, so it should not be suggested as a similar name. --- compiler/rustc_resolve/src/imports.rs | 3 +++ .../underscore-bindings-disambiguators.stderr | 12 ------------ 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index d9f9d1ff5a479..704c316bce650 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1282,6 +1282,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { if i.name == ident.name { return None; } // Never suggest the same name + if i.name == kw::Underscore { + return None; + } // `use _` is never valid let resolution = resolution.borrow(); if let Some(name_binding) = resolution.best_decl() { diff --git a/tests/ui/resolve/underscore-bindings-disambiguators.stderr b/tests/ui/resolve/underscore-bindings-disambiguators.stderr index 69ac95158f8cb..ec1dec8fe8e28 100644 --- a/tests/ui/resolve/underscore-bindings-disambiguators.stderr +++ b/tests/ui/resolve/underscore-bindings-disambiguators.stderr @@ -3,24 +3,12 @@ error[E0432]: unresolved import `X` | LL | use X as Y; | ^^^^^^ no `X` in the root - | -help: a similar name exists in the module - | -LL - use X as Y; -LL + use _ as Y; - | error[E0432]: unresolved import `Z` --> $DIR/underscore-bindings-disambiguators.rs:26:5 | LL | use Z as W; | ^^^^^^ no `Z` in the root - | -help: a similar name exists in the module - | -LL - use Z as W; -LL + use _ as W; - | error[E0080]: evaluation panicked: not yet implemented --> $DIR/underscore-bindings-disambiguators.rs:19:19 From 4ab6d1f4ccd3d4d4cfa267f839363c787894b0d0 Mon Sep 17 00:00:00 2001 From: Daniel Scherzer Date: Thu, 19 Feb 2026 15:04:36 -0800 Subject: [PATCH 07/23] std::ops::ControlFlow - use "a" before `Result` Rather than "an" --- library/core/src/ops/control_flow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 84fc98cf73f1e..190401967264e 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -197,7 +197,7 @@ impl ControlFlow { } } - /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// Converts the `ControlFlow` into a `Result` which is `Ok` if the /// `ControlFlow` was `Break` and `Err` if otherwise. /// /// # Examples @@ -311,7 +311,7 @@ impl ControlFlow { } } - /// Converts the `ControlFlow` into an `Result` which is `Ok` if the + /// Converts the `ControlFlow` into a `Result` which is `Ok` if the /// `ControlFlow` was `Continue` and `Err` if otherwise. /// /// # Examples From be83f555958405712547738b4b298a7c70206410 Mon Sep 17 00:00:00 2001 From: Daniel Scherzer Date: Thu, 19 Feb 2026 16:44:09 -0800 Subject: [PATCH 08/23] std::ops::ControlFlow - use normal comment for internal methods Rather than a doc comment, which causes rustdoc to output the impl documentation even though the impl block only has non-public methods. --- library/core/src/ops/control_flow.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 84fc98cf73f1e..0ad459e9ce699 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -422,9 +422,9 @@ impl ControlFlow { } } -/// These are used only as part of implementing the iterator adapters. -/// They have mediocre names and non-obvious semantics, so aren't -/// currently on a path to potential stabilization. +// These are used only as part of implementing the iterator adapters. +// They have mediocre names and non-obvious semantics, so aren't +// currently on a path to potential stabilization. impl ControlFlow { /// Creates a `ControlFlow` from any type implementing `Try`. #[inline] From 59781157a7d45720399076311095732ecfd79606 Mon Sep 17 00:00:00 2001 From: mu001999 Date: Fri, 20 Feb 2026 12:12:21 +0800 Subject: [PATCH 09/23] Deny final not followed by item --- compiler/rustc_parse/src/errors.rs | 9 ++++++++ compiler/rustc_parse/src/parser/item.rs | 2 ++ tests/ui/traits/final/bad-positions.rs | 7 ++++++ tests/ui/traits/final/bad-positions.stderr | 26 ++++++++++++++++++++++ 4 files changed, 44 insertions(+) create mode 100644 tests/ui/traits/final/bad-positions.rs create mode 100644 tests/ui/traits/final/bad-positions.stderr diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 136963a2594ed..2a084a888e330 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -2203,6 +2203,15 @@ pub(crate) struct DefaultNotFollowedByItem { pub span: Span, } +#[derive(Diagnostic)] +#[diag("`final` is not followed by an item")] +#[note("only associated functions in traits may be prefixed by `final`")] +pub(crate) struct FinalNotFollowedByItem { + #[primary_span] + #[label("the `final` qualifier")] + pub span: Span, +} + #[derive(Diagnostic)] pub(crate) enum MissingKeywordForItemDefinition { #[diag("missing `enum` for enum definition")] diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index c03a237239e07..69610d062919d 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -197,6 +197,8 @@ impl<'a> Parser<'a> { if let Defaultness::Default(span) = def { this.dcx().emit_err(errors::DefaultNotFollowedByItem { span }); + } else if let Defaultness::Final(span) = def { + this.dcx().emit_err(errors::FinalNotFollowedByItem { span }); } if !attrs_allowed { diff --git a/tests/ui/traits/final/bad-positions.rs b/tests/ui/traits/final/bad-positions.rs new file mode 100644 index 0000000000000..3ee62985a13b1 --- /dev/null +++ b/tests/ui/traits/final/bad-positions.rs @@ -0,0 +1,7 @@ +#![feature(final_associated_functions)] + +fn main() { + final; //~ ERROR `final` is not followed by an item + final 1 + 1; //~ ERROR `final` is not followed by an item + final { println!("text"); }; //~ ERROR `final` is not followed by an item +} diff --git a/tests/ui/traits/final/bad-positions.stderr b/tests/ui/traits/final/bad-positions.stderr new file mode 100644 index 0000000000000..00dded85d0b79 --- /dev/null +++ b/tests/ui/traits/final/bad-positions.stderr @@ -0,0 +1,26 @@ +error: `final` is not followed by an item + --> $DIR/bad-positions.rs:4:5 + | +LL | final; + | ^^^^^ the `final` qualifier + | + = note: only associated functions in traits may be prefixed by `final` + +error: `final` is not followed by an item + --> $DIR/bad-positions.rs:5:5 + | +LL | final 1 + 1; + | ^^^^^ the `final` qualifier + | + = note: only associated functions in traits may be prefixed by `final` + +error: `final` is not followed by an item + --> $DIR/bad-positions.rs:6:5 + | +LL | final { println!("text"); }; + | ^^^^^ the `final` qualifier + | + = note: only associated functions in traits may be prefixed by `final` + +error: aborting due to 3 previous errors + From c3fe049a25060f4780c3ca0c414e639476991066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 12:26:03 +0100 Subject: [PATCH 10/23] change find_attr macro to search tcx.get_all_attrs automatically --- .../src/attributes/rustc_internal.rs | 37 ++-- .../rustc_hir/src/attrs/data_structures.rs | 168 ++++++++++++++---- compiler/rustc_hir/src/attrs/mod.rs | 8 + compiler/rustc_passes/src/check_attr.rs | 7 +- 4 files changed, 162 insertions(+), 58 deletions(-) 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_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..366c48168205c 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -32,6 +32,14 @@ mod pretty_printing; /// A common way to get those is through `tcx.get_all_attrs(did)` #[macro_export] macro_rules! find_attr { + ($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) => { + $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() }}; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index d5051aea0cd4b..9cf3f641fd9ef 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) { From 63edc913faca5feb772479c88f2686c023eab017 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 12:34:07 +0100 Subject: [PATCH 11/23] change all uses --- compiler/rustc_ast_lowering/src/expr.rs | 1 - compiler/rustc_ast_lowering/src/lib.rs | 2 +- compiler/rustc_borrowck/src/nll.rs | 2 +- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 3 +- .../rustc_codegen_ssa/src/codegen_attrs.rs | 11 ++--- .../src/check_consts/check.rs | 2 +- .../rustc_const_eval/src/check_consts/mod.rs | 4 +- .../src/check_consts/post_drop_elaboration.rs | 2 +- .../src/const_eval/machine.rs | 2 +- .../rustc_const_eval/src/interpret/call.rs | 5 +-- .../rustc_hir_analysis/src/check/check.rs | 45 ++++++++----------- .../src/check/compare_eii.rs | 4 +- .../rustc_hir_analysis/src/check/entry.rs | 3 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 6 +-- .../src/coherence/inherent_impls.rs | 16 ++----- compiler/rustc_hir_analysis/src/collect.rs | 7 ++- .../rustc_hir_analysis/src/collect/dump.rs | 10 ++--- .../rustc_hir_analysis/src/outlives/dump.rs | 2 +- .../rustc_hir_analysis/src/variance/dump.rs | 4 +- compiler/rustc_hir_typeck/src/callee.rs | 7 +-- compiler/rustc_hir_typeck/src/demand.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- .../rustc_hir_typeck/src/method/suggest.rs | 2 +- .../rustc_hir_typeck/src/naked_functions.rs | 2 +- compiler/rustc_hir_typeck/src/upvar.rs | 5 +-- compiler/rustc_hir_typeck/src/writeback.rs | 2 +- .../rustc_incremental/src/persist/clean.rs | 6 +-- compiler/rustc_interface/src/passes.rs | 2 +- compiler/rustc_lint/src/autorefs.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 2 +- compiler/rustc_lint/src/dangling.rs | 2 +- compiler/rustc_lint/src/foreign_modules.rs | 3 +- compiler/rustc_lint/src/gpukernel_abi.rs | 5 +-- .../rustc_lint/src/interior_mutable_consts.rs | 2 +- compiler/rustc_lint/src/internal.rs | 16 +++---- compiler/rustc_lint/src/non_local_def.rs | 5 +-- compiler/rustc_lint/src/nonstandard_style.rs | 8 ++-- compiler/rustc_lint/src/pass_by_value.rs | 7 +-- compiler/rustc_lint/src/ptr_nulls.rs | 4 +- compiler/rustc_lint/src/types.rs | 2 +- compiler/rustc_lint/src/unused.rs | 2 +- compiler/rustc_metadata/src/eii.rs | 11 ++--- compiler/rustc_metadata/src/native_libs.rs | 11 +++-- .../src/traits/specialization_graph.rs | 3 +- compiler/rustc_middle/src/ty/adt.rs | 8 ++-- compiler/rustc_middle/src/ty/context.rs | 6 +-- compiler/rustc_middle/src/ty/mod.rs | 14 +++--- compiler/rustc_middle/src/ty/trait_def.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 15 ++----- .../rustc_mir_build/src/check_unsafety.rs | 4 +- .../src/thir/pattern/const_to_pat.rs | 3 +- .../src/framework/graphviz.rs | 5 ++- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 3 +- .../rustc_mir_transform/src/check_inline.rs | 4 +- compiler/rustc_mir_transform/src/coroutine.rs | 2 +- .../rustc_mir_transform/src/coverage/query.rs | 4 +- .../src/cross_crate_inline.rs | 4 +- compiler/rustc_mir_transform/src/liveness.rs | 4 +- compiler/rustc_passes/src/abi_test.rs | 3 +- compiler/rustc_passes/src/check_attr.rs | 6 +-- compiler/rustc_passes/src/check_export.rs | 4 +- compiler/rustc_passes/src/dead.rs | 5 +-- compiler/rustc_passes/src/layout_test.rs | 3 +- compiler/rustc_passes/src/stability.rs | 20 ++++----- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_resolve/src/diagnostics.rs | 3 +- .../rustc_resolve/src/late/diagnostics.rs | 3 +- compiler/rustc_resolve/src/lib.rs | 2 +- .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 6 ++- .../cfi/typeid/itanium_cxx_abi/transform.rs | 5 +-- compiler/rustc_symbol_mangling/src/test.rs | 9 ++-- .../error_reporting/infer/note_and_explain.rs | 2 +- .../src/traits/coherence.rs | 4 +- .../src/traits/select/mod.rs | 2 +- compiler/rustc_ty_utils/src/layout.rs | 2 +- compiler/rustc_ty_utils/src/needs_drop.rs | 2 +- 77 files changed, 166 insertions(+), 243 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index b034e250b58d0..218126e64de92 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1072,7 +1072,6 @@ 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)); // FIXME(contracts): Support contracts on closures? diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index c5ec53af6e505..db9f27e4603a3 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -257,7 +257,7 @@ impl ResolverAstLowering { find_attr!( // we can use parsed attrs here since for other crates they're already available - tcx.get_all_attrs(def_id), + tcx, def_id, AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes ) .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect()) diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index acd01be470709..0d1925f138c70 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -296,7 +296,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, AttributeKind::RustcRegions) { return; } diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index b5ab26aea4922..e66df36913772 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -460,7 +460,7 @@ 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(), rustc_hir::attrs::AttributeKind::RustcAllocatorZeroedVariant {name} => name) { to_add.push(llvm::CreateAttrStringValue( cx.llcx, diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 85c8890d661c5..44c246769c9b2 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -894,7 +894,8 @@ 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_DEF_ID, AttributeKind::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..188e9afed083e 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, AttributeKind::EiiDeclaration(target) => target.foreign_item ) else { tcx.dcx().span_delayed_bug( i.span, @@ -483,9 +481,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, AttributeKind::TargetFeature{attr_span: span, ..} => *span) + .unwrap_or_else(|| tcx.def_span(did)); tcx.dcx() .create_err(errors::TargetFeatureDisableOrEnable { @@ -583,7 +580,7 @@ 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, AttributeKind::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 diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 9c9a921bd62d5..b1a93acdfc6b6 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -216,7 +216,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, AttributeKind::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..ed4bbe467f941 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -81,9 +81,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, AttributeKind::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..d27d66a9de281 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 @@ -36,7 +36,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(), AttributeKind::RustcDoNotConstCheck) { return; } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 3b4f7ed3261ab..4a215f277cf72 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -442,7 +442,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // 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) + || find_attr!(ecx.tcx, def, AttributeKind::RustcDoNotConstCheck) { // We certainly do *not* want to actually call the fn // though, so be sure we return here. diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 9220fde474e4e..ff9b177ac1e27 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -143,10 +143,7 @@ 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 - ) + find_attr!(self.tcx, def.did(), AttributeKind::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! diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 5f22dce29dc62..d057630bac338 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -79,7 +79,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, AttributeKind::Naked(_)) { tcx.dcx().emit_err(crate::errors::AbiCustomClothedFunction { span: fn_sig_span, naked_span: tcx.def_span(def_id).shrink_to_lo(), @@ -981,12 +981,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, AttributeKind::EiiForeignItem) { + "externally implementable items" + } else { + "foreign items" + }; let span = tcx.def_span(def_id); struct_span_code_err!( @@ -1373,7 +1372,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, AttributeKind::RustcMustImplementOneOf {attr_span, ..} => *attr_span); missing_items_must_implement_one_of_err( tcx, @@ -1556,7 +1555,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(), AttributeKind::Repr { reprs, .. } => reprs) { for (r, _) in reprs { if let ReprPacked(pack) = r @@ -1725,10 +1724,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) 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(_) - ) + && !find_attr!(tcx, def.did(), AttributeKind::RustcPubTransparent(_)) { let non_exhaustive = def.is_variant_list_non_exhaustive() || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive); @@ -1800,19 +1796,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, 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(); + }); } 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..43fbcb492160f 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_eii.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_eii.rs @@ -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, AttributeKind::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..25eef5e9bde37 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -99,8 +99,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, AttributeKind::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..1e6bdddf11d6b 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1197,15 +1197,13 @@ 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, AttributeKind::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, AttributeKind::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..1c37d06d55416 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -79,20 +79,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, AttributeKind::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, AttributeKind::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 +132,8 @@ 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, AttributeKind::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..2b5bc8e86c618 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -817,9 +817,9 @@ fn lower_variant<'tcx>( parent_did.to_def_id(), recovered, adt_kind == AdtKind::Struct - && find_attr!(tcx.get_all_attrs(parent_did), AttributeKind::NonExhaustive(..)) + && find_attr!(tcx, parent_did, AttributeKind::NonExhaustive(..)) || variant_did.is_some_and(|variant_did| { - find_attr!(tcx.get_all_attrs(variant_did), AttributeKind::NonExhaustive(..)) + find_attr!(tcx, variant_did, AttributeKind::NonExhaustive(..)) }), ) } @@ -1355,8 +1355,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, AttributeKind::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..2f5fdd386ec52 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -7,7 +7,7 @@ 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_DEF_ID, AttributeKind::RustcHiddenTypeOfOpaques) { return; } for id in tcx.hir_crate_items(()).opaques() { @@ -28,7 +28,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, AttributeKind::RustcDumpPredicates) { let preds = tcx.predicates_of(id).instantiate_identity(tcx).predicates; let span = tcx.def_span(id); @@ -38,7 +38,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, AttributeKind::RustcDumpItemBounds) { let bounds = tcx.item_bounds(id).instantiate_identity(); let span = tcx.def_span(id); @@ -54,7 +54,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, AttributeKind::RustcDumpDefParents) { struct AnonConstFinder<'tcx> { tcx: TyCtxt<'tcx>, anon_consts: Vec, @@ -103,7 +103,7 @@ pub(crate) fn vtables<'tcx>(tcx: TyCtxt<'tcx>) { let def_id = id.owner_id.def_id; let Some(&attr_span) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcDumpVtable(span) => span) + find_attr!(tcx, def_id, AttributeKind::RustcDumpVtable(span) => span) else { continue; }; diff --git a/compiler/rustc_hir_analysis/src/outlives/dump.rs b/compiler/rustc_hir_analysis/src/outlives/dump.rs index cf770a2561db8..52a0543e27bfe 100644 --- a/compiler/rustc_hir_analysis/src/outlives/dump.rs +++ b/compiler/rustc_hir_analysis/src/outlives/dump.rs @@ -6,7 +6,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, AttributeKind::RustcOutlives) { continue; } diff --git a/compiler/rustc_hir_analysis/src/variance/dump.rs b/compiler/rustc_hir_analysis/src/variance/dump.rs index e625d9dfe3b5f..e5f264d48feaf 100644 --- a/compiler/rustc_hir_analysis/src/variance/dump.rs +++ b/compiler/rustc_hir_analysis/src/variance/dump.rs @@ -26,7 +26,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_DEF_ID, AttributeKind::RustcVarianceOfOpaques) { for id in crate_items.opaques() { tcx.dcx().emit_err(crate::errors::VariancesOf { span: tcx.def_span(id), @@ -36,7 +36,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, AttributeKind::RustcVariance) { continue; } diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 13960fd4d607c..a363cee5a1f1e 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -527,10 +527,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `#[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 - ) + && find_attr!(self.tcx, def_id, AttributeKind::RustcEvaluateWhereClauses) { let predicates = self.tcx.predicates_of(def_id); let predicates = predicates.instantiate(self.tcx, args); @@ -907,7 +904,7 @@ impl<'a, 'tcx> FnCtxt<'a, '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) + && find_attr!(self.tcx, self.body_id, AttributeKind::RustcDoNotConstCheck) { return; } diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 2768023e49b94..6d6de0d3d90d5 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1092,7 +1092,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, AttributeKind::RustcConversionSuggestion) }, ); diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 5b40531f94627..b0b56c869449e 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -3676,7 +3676,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, AttributeKind::Naked(..)) { self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span }); } } diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 737ba250957d2..c0e83f9222930 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -2261,7 +2261,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, AttributeKind::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..49e4b1feb4d69 100644 --- a/compiler/rustc_hir_typeck/src/naked_functions.rs +++ b/compiler/rustc_hir_typeck/src/naked_functions.rs @@ -21,7 +21,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, AttributeKind::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..49a8dd29dce68 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -1744,10 +1744,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 - ) + && find_attr!(self.tcx, closure_def_id, AttributeKind::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..3962b748714e1 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -47,7 +47,7 @@ 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); + && find_attr!(self.tcx, item_def_id, AttributeKind::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..47cef5ac2d11f 100644 --- a/compiler/rustc_incremental/src/persist/clean.rs +++ b/compiler/rustc_incremental/src/persist/clean.rs @@ -352,13 +352,13 @@ 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) + let Some(clean_attrs) = + find_attr!(self.tcx, item_id, AttributeKind::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/passes.rs b/compiler/rustc_interface/src/passes.rs index 6838a495fd0f2..f33084afe2572 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, AttributeKind::RustcDelayedBugFromInsideQuery) { tcx.ensure_ok().trigger_delayed_bug(def_id); } diff --git a/compiler/rustc_lint/src/autorefs.rs b/compiler/rustc_lint/src/autorefs.rs index 5bb7df80ffb36..ecaadad9dfc30 100644 --- a/compiler/rustc_lint/src/autorefs.rs +++ b/compiler/rustc_lint/src/autorefs.rs @@ -108,7 +108,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, AttributeKind::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..c389fd26dbb2e 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1178,7 +1178,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, AttributeKind::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..16533722d8c0a 100644 --- a/compiler/rustc_lint/src/dangling.rs +++ b/compiler/rustc_lint/src/dangling.rs @@ -268,7 +268,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, AttributeKind::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..f775a7eb163b8 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -185,8 +185,7 @@ fn name_of_extern_decl(tcx: TyCtxt<'_>, fi: hir::OwnerId) -> SymbolName { // bottleneck, this does just fine. ( overridden_link_name, - find_attr!(tcx.get_all_attrs(fi), AttributeKind::LinkName {span, ..} => *span) - .unwrap(), + find_attr!(tcx, fi, AttributeKind::LinkName {span, ..} => *span).unwrap(), ) }) { diff --git a/compiler/rustc_lint/src/gpukernel_abi.rs b/compiler/rustc_lint/src/gpukernel_abi.rs index dbdf5b6e7955f..b3a061afd9d02 100644 --- a/compiler/rustc_lint/src/gpukernel_abi.rs +++ b/compiler/rustc_lint/src/gpukernel_abi.rs @@ -184,10 +184,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, AttributeKind::NoMangle(..) | AttributeKind::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..2ad1dc43bae7e 100644 --- a/compiler/rustc_lint/src/interior_mutable_consts.rs +++ b/compiler/rustc_lint/src/interior_mutable_consts.rs @@ -87,7 +87,7 @@ 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), + cx.tcx, method_did, AttributeKind::RustcShouldNotBeCalledOnConstItems(_) ) && let Some(method_name) = cx.tcx.opt_item_ident(method_did) diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 37eb375c7a6c2..4c2b3cb97f760 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -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, AttributeKind::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, AttributeKind::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(), AttributeKind::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(), AttributeKind::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, AttributeKind::RustcLintOptDenyFieldAccess { lint_message, } => lint_message) { cx.emit_span_lint( BAD_OPT_ACCESS, diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 8fb6532e68c4c..8da452861163e 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -243,10 +243,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, AttributeKind::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..6734cec6d87fc 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -3,7 +3,7 @@ use rustc_attr_parsing::AttributeParser; use rustc_errors::Applicability; use rustc_hir::attrs::{AttributeKind, ReprAttr}; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::DefId; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_hir::intravisit::{FnKind, Visitor}; use rustc_hir::{Attribute, GenericParamKind, PatExprKind, PatKind, find_attr}; use rustc_middle::hir::nested_filter::All; @@ -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_DEF_ID, AttributeKind::CrateName{name, name_span,..} => (name, name_span)).map( |(&name, &span)| { // Discard the double quotes surrounding the literal. let sp = cx @@ -371,7 +371,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { 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(..)) + && find_attr!(cx.tcx, id, AttributeKind::NoMangle(..)) { return; } @@ -385,7 +385,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(..)) + && find_attr!(cx.tcx, id, AttributeKind::NoMangle(..)) { return; } diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index 3823c9aa1861e..69c49519144c6 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -44,7 +44,7 @@ fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option + if find_attr!(cx.tcx, def_id, AttributeKind::RustcPassByValue(_)) => { let name = cx.tcx.item_ident(def_id); let path_segment = path.segments.last().unwrap(); @@ -52,10 +52,7 @@ fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option { 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(), AttributeKind::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..cfc36436a50df 100644 --- a/compiler/rustc_lint/src/ptr_nulls.rs +++ b/compiler/rustc_lint/src/ptr_nulls.rs @@ -73,14 +73,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, AttributeKind::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, AttributeKind::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..ca9a74f822c8c 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -687,7 +687,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(), AttributeKind::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..ef78fa05e89eb 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -401,7 +401,7 @@ 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), + cx.tcx, def_id, AttributeKind::MustUse { reason, .. } => reason ) { // check for #[must_use = "..."] diff --git a/compiler/rustc_metadata/src/eii.rs b/compiler/rustc_metadata/src/eii.rs index 42497a82ef8c0..7bc63b157814e 100644 --- a/compiler/rustc_metadata/src/eii.rs +++ b/compiler/rustc_metadata/src/eii.rs @@ -25,13 +25,12 @@ 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, AttributeKind::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) + let Some(decl) = + find_attr!(tcx, macro_defid, AttributeKind::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() @@ -52,9 +51,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, AttributeKind::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..e61ef3de9ccbf 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -213,11 +213,10 @@ impl<'tcx> Collector<'tcx> { return; } - for attr in - find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::Link(links, _) => links) - .iter() - .map(|v| v.iter()) - .flatten() + for attr in find_attr!(self.tcx, def_id, AttributeKind::Link(links, _) => links) + .iter() + .map(|v| v.iter()) + .flatten() { let dll_imports = match attr.kind { NativeLibKind::RawDylib { .. } => foreign_items @@ -232,7 +231,7 @@ 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, AttributeKind::LinkOrdinal {span, ..} => *span) { sess.dcx().emit_err(errors::LinkOrdinalRawDylib { span }); } diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 84415a592a2ec..3dc8a1d07609a 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -62,7 +62,8 @@ 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, AttributeKind::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..448be791c9eb5 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -282,13 +282,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, AttributeKind::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, AttributeKind::PinV2(..)) { debug!("found pin-project type {:?}", did); flags |= AdtFlags::IS_PIN_PROJECT; } @@ -303,7 +301,7 @@ impl AdtDefData { flags |= AdtFlags::HAS_CTOR; } - if find_attr!(tcx.get_all_attrs(did), AttributeKind::Fundamental) { + if find_attr!(tcx, did, AttributeKind::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..c1c4beaa30970 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -994,8 +994,8 @@ 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, AttributeKind::RustcLayoutScalarValidRangeStart(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); + let end = find_attr!(self, def_id, AttributeKind::RustcLayoutScalarValidRangeEnd(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); (start, end) } @@ -2768,7 +2768,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, AttributeKind::DoNotRecommend { .. }) } pub fn is_trivial_const

(self, def_id: P) -> bool diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2c7244187f4fd..8454eaa9e4307 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -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, AttributeKind::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, AttributeKind::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, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) { flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS); } @@ -1988,7 +1985,8 @@ impl<'tcx> TyCtxt<'tcx> { && 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()), + self, + outer.macro_def_id.unwrap(), AttributeKind::RustcBuiltinMacro { .. } ) { @@ -2000,7 +1998,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, AttributeKind::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..22fd22f2bba74 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -241,7 +241,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, AttributeKind::RustcHasIncoherentInherentImpls) { return &[]; } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index d534c273ff65f..1b1dc0739bc4d 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1672,14 +1672,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, AttributeKind::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, AttributeKind::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 +1686,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, AttributeKind::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 +1696,7 @@ pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option 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, AttributeKind::RustcDeprecatedSafe2024{suggestion} => suggestion) => { let sm = self.tcx.sess.source_map(); let guarantee = format!("that {}", suggestion); @@ -1146,7 +1146,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, AttributeKind::CustomMir(..) => ()).is_some() { return; } 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..424ac99a4b31f 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 @@ -488,8 +488,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, AttributeKind::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..9a8aea8244295 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -97,8 +97,9 @@ 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, AttributeKind::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..6cdf8b39df21d 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -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, AttributeKind::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..d084460ab84d6 100644 --- a/compiler/rustc_mir_transform/src/check_inline.rs +++ b/compiler/rustc_mir_transform/src/check_inline.rs @@ -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, AttributeKind::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, AttributeKind::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..bc65499a96a26 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -1989,7 +1989,7 @@ fn check_must_not_suspend_def( data: SuspendCheckData<'_>, ) -> bool { if let Some(reason_str) = - find_attr!(tcx.get_all_attrs(def_id), AttributeKind::MustNotSupend {reason} => reason) + find_attr!(tcx, def_id, AttributeKind::MustNotSupend {reason} => reason) { let reason = reason_str.map(|s| errors::MustNotSuspendReason { span: data.source_span, reason: s }); diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 63c550c27fe4e..74f4131258e48 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -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, AttributeKind::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..35b7d6c2047a0 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -44,7 +44,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, AttributeKind::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 +158,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, AttributeKind::RustcIntrinsic) { return; } diff --git a/compiler/rustc_mir_transform/src/liveness.rs b/compiler/rustc_mir_transform/src/liveness.rs index 9d951f0874376..bb746e490c8af 100644 --- a/compiler/rustc_mir_transform/src/liveness.rs +++ b/compiler/rustc_mir_transform/src/liveness.rs @@ -63,14 +63,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(), AttributeKind::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, AttributeKind::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..dac5684dc0ecb 100644 --- a/compiler/rustc_passes/src/abi_test.rs +++ b/compiler/rustc_passes/src/abi_test.rs @@ -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, AttributeKind::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 9cf3f641fd9ef..d6a171857ece8 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -567,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, AttributeKind::EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe) && !impl_marked_unsafe { self.dcx().emit_err(errors::EiiImplRequiresUnsafe { @@ -1774,7 +1774,7 @@ 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), + self.tcx, parent_did, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span ) && is_coro { @@ -1906,7 +1906,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { 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 { .. }) + && !find_attr!(self.tcx, def_id, AttributeKind::MacroExport { .. }) { check_non_exported_macro_for_invalid_attrs(self.tcx, item); } diff --git a/compiler/rustc_passes/src/check_export.rs b/compiler/rustc_passes/src/check_export.rs index fee920221e1d1..1e6f6d4598136 100644 --- a/compiler/rustc_passes/src/check_export.rs +++ b/compiler/rustc_passes/src/check_export.rs @@ -46,7 +46,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, AttributeKind::ExportStable); if !self.in_exportable_mod && !has_attr { return false; } @@ -82,7 +82,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, AttributeKind::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..d7795ab0fb8c9 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -381,10 +381,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, AttributeKind::RustcTrivialFieldReads) { if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() && let Some(adt_def_id) = adt_def.did().as_local() diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 354a98d6d0dc7..89766d84377c6 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -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, AttributeKind::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..ec38a334be286 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -96,8 +96,7 @@ 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, + let depr = find_attr!(tcx, def_id, AttributeKind::Deprecation { deprecation, span: _ } => *deprecation ); @@ -161,8 +160,8 @@ 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, AttributeKind::Stability { stability, span: _ } => *stability); if let Some(stab) = stab { return Some(stab); @@ -195,9 +194,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, AttributeKind::RustcBodyStability { stability, .. } => *stability) } #[instrument(level = "debug", skip(tcx))] @@ -212,9 +210,8 @@ fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option, def_id: LocalDefId) -> Option *stability); + let const_stability_indirect = + find_attr!(tcx, def_id, AttributeKind::RustcConstStabilityIndirect); + let const_stab = find_attr!(tcx, def_id, AttributeKind::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. diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 9a952bb721951..d84797f2fab6b 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -876,7 +876,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, AttributeKind::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..4882bd43316e9 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -2170,7 +2170,8 @@ 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, AttributeKind::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..cbfb0a51987fc 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1115,8 +1115,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, AttributeKind::Doc(d) => d) && d.aliases.contains_key(&item_name) { return Some(did); diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 66f1d6b4ad55b..476bd146e46a9 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -2475,7 +2475,7 @@ 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), + self.tcx, def_id, AttributeKind::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..3c50a993465b5 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 @@ -447,7 +447,8 @@ 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, AttributeKind::CfiEncoding { encoding } => encoding) { let encoding = encoding.as_str().trim(); // Use user-defined CFI encoding for type @@ -494,7 +495,8 @@ 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, AttributeKind::CfiEncoding {encoding} => encoding) { // Use user-defined CFI encoding for type s.push_str(encoding.as_str().trim()); 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..b4f8e8201f44a 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 @@ -138,10 +138,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(), AttributeKind::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..6a550c1328766 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -53,10 +53,9 @@ 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,AttributeKind::RustcSymbolName(span) => span) + { let def_id = def_id.to_def_id(); let instance = Instance::new_raw( def_id, @@ -83,7 +82,7 @@ impl SymbolNamesTest<'_> { } if let Some(attr_span) = find_attr!( - tcx.get_all_attrs(def_id), + tcx, def_id, AttributeKind::RustcDefPath(span) => span ) { tcx.dcx().emit_err(TestOutput { 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..df88b26d811c4 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 @@ -533,7 +533,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, AttributeKind::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/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index fc628e78a3e23..eaa767f1496e3 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -760,8 +760,8 @@ 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, AttributeKind::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..4620fe9b475db 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1445,7 +1445,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, AttributeKind::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..5b5fa82517ed9 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -624,7 +624,7 @@ 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()), + tcx, def.did(), AttributeKind::RustcSimdMonomorphizeLaneLimit(limit) => limit ) { if !limit.value_within_limit(e_len as usize) { diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 06eef7e95145e..c5dedd51af854 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -397,7 +397,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(), AttributeKind::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 From 07f46cec49ef73efdcbe92a065c23c2775d975d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 13:12:09 +0100 Subject: [PATCH 12/23] Convenience matcher in find_attrs for crate attrs --- compiler/rustc_hir/src/attrs/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index 366c48168205c..090517486d6f1 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -32,6 +32,13 @@ mod pretty_printing; /// A common way to get those is through `tcx.get_all_attrs(did)` #[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() }; From 9a9443950d8beca2b972e220c7964a741a0d1242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 13:12:09 +0100 Subject: [PATCH 13/23] change all uses --- compiler/rustc_codegen_ssa/src/back/write.rs | 3 +-- compiler/rustc_codegen_ssa/src/base.rs | 4 ++-- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 3 +-- compiler/rustc_hir_analysis/src/collect/dump.rs | 4 ++-- compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs | 7 +++---- compiler/rustc_hir_analysis/src/variance/dump.rs | 4 ++-- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 3 +-- compiler/rustc_lint/src/nonstandard_style.rs | 4 ++-- compiler/rustc_middle/src/ty/context.rs | 4 ++-- compiler/rustc_passes/src/entry.rs | 4 ++-- 10 files changed, 18 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 87a043fbdf245..1448ae674a90f 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -454,8 +454,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, AttributeKind::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 44c246769c9b2..b8bc585d16a3a 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -14,7 +14,7 @@ use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_ 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::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; @@ -895,7 +895,7 @@ impl CrateInfo { 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, CRATE_DEF_ID, AttributeKind::WindowsSubsystem(kind, _) => *kind); + find_attr!(tcx, crate, AttributeKind::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 188e9afed083e..744f672f25113 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -350,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, AttributeKind::NoBuiltins); if no_builtins { codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; } diff --git a/compiler/rustc_hir_analysis/src/collect/dump.rs b/compiler/rustc_hir_analysis/src/collect/dump.rs index 2f5fdd386ec52..ad73ea50323d2 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -1,13 +1,13 @@ 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, CRATE_DEF_ID, AttributeKind::RustcHiddenTypeOfOpaques) { + if !find_attr!(tcx, crate, AttributeKind::RustcHiddenTypeOfOpaques) { return; } for id in tcx.hir_crate_items(()).opaques() { 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..a73009838b0f7 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -6,7 +6,7 @@ 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 +171,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, AttributeKind::RustcNoImplicitBounds) { return; } @@ -285,8 +285,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, AttributeKind::RustcNoImplicitBounds) && !collected.any() } fn reject_duplicate_relaxed_bounds(&self, relaxed_bounds: SmallVec<[&PolyTraitRef<'_>; 1]>) { diff --git a/compiler/rustc_hir_analysis/src/variance/dump.rs b/compiler/rustc_hir_analysis/src/variance/dump.rs index e5f264d48feaf..1771f6295fbab 100644 --- a/compiler/rustc_hir_analysis/src/variance/dump.rs +++ b/compiler/rustc_hir_analysis/src/variance/dump.rs @@ -1,7 +1,7 @@ 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 +26,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, CRATE_DEF_ID, AttributeKind::RustcVarianceOfOpaques) { + if find_attr!(tcx, crate, AttributeKind::RustcVarianceOfOpaques) { for id in crate_items.opaques() { tcx.dcx().emit_err(crate::errors::VariancesOf { span: tcx.def_span(id), diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 412df9162e9f2..2724e2302009e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -8,7 +8,6 @@ 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::def_id::{DefId, LocalDefId}; @@ -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, AttributeKind::RustcNeverTypeOptions {fallback, diverging_block_default} => (*fallback, *diverging_block_default)).unwrap_or_default() } diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 6734cec6d87fc..85d08acb4cf54 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -3,7 +3,7 @@ use rustc_attr_parsing::AttributeParser; use rustc_errors::Applicability; use rustc_hir::attrs::{AttributeKind, ReprAttr}; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; +use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{FnKind, Visitor}; use rustc_hir::{Attribute, GenericParamKind, PatExprKind, PatKind, find_attr}; use rustc_middle::hir::nested_filter::All; @@ -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, CRATE_DEF_ID, AttributeKind::CrateName{name, name_span,..} => (name, name_span)).map( + find_attr!(cx.tcx, crate, AttributeKind::CrateName{name, name_span,..} => (name, name_span)).map( |(&name, &span)| { // Discard the double quotes surrounding the literal. let sp = cx diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index c1c4beaa30970..363e429df4e3f 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2795,9 +2795,9 @@ impl<'tcx> TyCtxt<'tcx> { pub fn provide(providers: &mut Providers) { providers.is_panic_runtime = - |tcx, LocalCrate| find_attr!(tcx.hir_krate_attrs(), AttributeKind::PanicRuntime); + |tcx, LocalCrate| find_attr!(tcx, crate, AttributeKind::PanicRuntime); providers.is_compiler_builtins = - |tcx, LocalCrate| find_attr!(tcx.hir_krate_attrs(), AttributeKind::CompilerBuiltins); + |tcx, LocalCrate| find_attr!(tcx, crate, AttributeKind::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_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index bd737518ed479..a5ebf7e5fee99 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -2,7 +2,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 +29,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, AttributeKind::NoMain) { return None; } From 7477a5b48e53d9a1c7cede3d89317f3b70daf817 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 13:19:57 +0100 Subject: [PATCH 14/23] update docs --- compiler/rustc_hir/src/attrs/mod.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index 090517486d6f1..660e7e0aa8be2 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -29,7 +29,22 @@ 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)?) => { From 54d673dd693d29773122e10fa3cfd4770763bddb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 13:24:24 +0100 Subject: [PATCH 15/23] deprecate functions --- compiler/rustc_hir/src/attrs/mod.rs | 8 +++++--- compiler/rustc_hir_analysis/src/collect.rs | 2 ++ compiler/rustc_middle/src/ty/instance.rs | 11 +---------- compiler/rustc_middle/src/ty/mod.rs | 7 +++++++ 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index 660e7e0aa8be2..e89feeb6129b2 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -57,9 +57,11 @@ macro_rules! find_attr { ($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) => { - $crate::find_attr!($tcx.get_all_attrs($def_id), $pattern $(if $guard)? => $e) - }; + ($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)?) => {{ diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 2b5bc8e86c618..9fa936d87ffdd 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -895,6 +895,8 @@ 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(_)); 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 8454eaa9e4307..7cdd48b9bf35d 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1708,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)) } @@ -1720,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() { @@ -1742,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() } From 04f762d8426487fa260829f22a2c59b0a1885259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Thu, 5 Feb 2026 13:46:44 +0100 Subject: [PATCH 16/23] allow deprecated for some valid uses --- compiler/rustc_ast_lowering/src/delegation.rs | 13 ++++++++----- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 1 + compiler/rustc_middle/src/ty/util.rs | 1 - .../rustc_mir_transform/src/cross_crate_inline.rs | 1 + compiler/rustc_passes/src/dead.rs | 4 +--- compiler/rustc_resolve/src/diagnostics.rs | 3 ++- compiler/rustc_resolve/src/late/diagnostics.rs | 5 +---- .../src/error_reporting/traits/on_unimplemented.rs | 6 +++++- 8 files changed, 19 insertions(+), 15 deletions(-) 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_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 744f672f25113..fbed5c96e1c42 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -620,6 +620,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_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 1b1dc0739bc4d..60ac1e13e849f 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -4,7 +4,6 @@ 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; diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index 35b7d6c2047a0..30ad713d201e8 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -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) diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index d7795ab0fb8c9..a2cbdd23e379c 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -723,9 +723,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, AttributeKind::Lang(..)) { Some(ComesFromAllowExpect::No) } else { None diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 4882bd43316e9..5eb1f73eb750e 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1430,7 +1430,8 @@ 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), + this.tcx, + did, AttributeKind::RustcDiagnosticItem( sym::TryInto | sym::TryFrom | sym::FromIterator ) diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index cbfb0a51987fc..7c20b006c00bb 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -2665,10 +2665,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_attr!(self.r.tcx, *did, AttributeKind::RustcDiagnosticItem(sym::Default)) }); let Some(default_trait) = default_trait else { return; 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]) From a2367eca478cca556e7a2708e77485d2191a63ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Fri, 13 Feb 2026 13:29:51 +0100 Subject: [PATCH 17/23] star-import AttributeKind --- compiler/rustc_hir/src/attrs/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index e89feeb6129b2..efd9c3853ee93 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -71,6 +71,7 @@ macro_rules! find_attr { ($attributes_list: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{ 'done: { for i in $attributes_list { + use rustc_hir::attrs::AttributeKind::*; let i: &rustc_hir::Attribute = i; match i { rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { From 2bed5847421cd83866dc444c524ac07235e97a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Fri, 13 Feb 2026 15:22:48 +0100 Subject: [PATCH 18/23] add lint for using AttributeKind in find_attr --- compiler/rustc_hir/src/attrs/mod.rs | 3 + compiler/rustc_lint/src/internal.rs | 100 +++++++++++++++++- compiler/rustc_lint/src/lib.rs | 3 + compiler/rustc_lint/src/lints.rs | 6 ++ tests/ui-fulldeps/internal-lints/find_attr.rs | 24 +++++ .../internal-lints/find_attr.stderr | 52 +++++++++ 6 files changed, 184 insertions(+), 4 deletions(-) create mode 100644 tests/ui-fulldeps/internal-lints/find_attr.rs create mode 100644 tests/ui-fulldeps/internal-lints/find_attr.stderr diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index efd9c3853ee93..92dd77e80a512 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -77,6 +77,9 @@ macro_rules! find_attr { rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { break 'done Some($e); } + // FIXME: doesn't actually trigger in other crates :/ + // https://github.com/rust-lang/rust/issues/110613 + #[deny(unreachable_patterns)] _ => {} } } diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 4c2b3cb97f760..7b97ff92e008b 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -1,6 +1,7 @@ //! Some lints that are only useful in the compiler or crates that use compiler internals, such as //! Clippy. +use rustc_ast::{Pat, PatKind, Path}; use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; @@ -12,10 +13,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}; @@ -621,3 +622,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..262a4121cc77a 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("remote `AttributeKind`")] +pub(crate) struct AttributeKindInFindAttr {} + // let_underscore.rs #[derive(LintDiagnostic)] pub(crate) enum NonBindingLet { 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..00838132226f6 --- /dev/null +++ b/tests/ui-fulldeps/internal-lints/find_attr.rs @@ -0,0 +1,24 @@ +//@ 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 +} 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..22c61563af70b --- /dev/null +++ b/tests/ui-fulldeps/internal-lints/find_attr.stderr @@ -0,0 +1,52 @@ +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: remote `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: remote `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: remote `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: remote `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: remote `AttributeKind` + +error: aborting due to 5 previous errors + From decec173ecfe2f5000c66b8bff90b4ff9edb95da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Fri, 13 Feb 2026 15:32:06 +0100 Subject: [PATCH 19/23] remove AttributeKind everywhere --- compiler/rustc_ast_lowering/src/expr.rs | 5 +-- compiler/rustc_ast_lowering/src/item.rs | 13 ++---- compiler/rustc_ast_lowering/src/lib.rs | 5 +-- compiler/rustc_borrowck/src/nll.rs | 3 +- compiler/rustc_codegen_llvm/src/attributes.rs | 3 +- .../src/assert_module_sources.rs | 4 +- compiler/rustc_codegen_ssa/src/back/write.rs | 3 +- compiler/rustc_codegen_ssa/src/base.rs | 5 +-- .../rustc_codegen_ssa/src/codegen_attrs.rs | 11 ++--- .../src/check_consts/check.rs | 3 +- .../rustc_const_eval/src/check_consts/mod.rs | 3 +- .../src/check_consts/post_drop_elaboration.rs | 3 +- .../src/const_eval/fn_queries.rs | 3 +- .../src/const_eval/machine.rs | 5 +-- .../rustc_const_eval/src/interpret/call.rs | 6 +-- compiler/rustc_expand/src/base.rs | 40 ++++++++--------- compiler/rustc_expand/src/mbe/macro_rules.rs | 3 +- .../rustc_hir_analysis/src/check/check.rs | 18 +++----- .../src/check/compare_eii.rs | 4 +- .../rustc_hir_analysis/src/check/entry.rs | 4 +- .../rustc_hir_analysis/src/check/wfcheck.rs | 7 +-- .../src/coherence/inherent_impls.rs | 8 ++-- compiler/rustc_hir_analysis/src/collect.rs | 43 ++++++++----------- .../rustc_hir_analysis/src/collect/dump.rs | 13 +++--- .../src/collect/predicates_of.rs | 5 +-- .../src/hir_ty_lowering/bounds.rs | 5 +-- .../rustc_hir_analysis/src/outlives/dump.rs | 3 +- .../rustc_hir_analysis/src/variance/dump.rs | 5 +-- compiler/rustc_hir_typeck/src/callee.rs | 9 +--- compiler/rustc_hir_typeck/src/demand.rs | 3 +- compiler/rustc_hir_typeck/src/expr.rs | 3 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 4 +- compiler/rustc_hir_typeck/src/loops.rs | 5 +-- compiler/rustc_hir_typeck/src/method/probe.rs | 3 +- .../rustc_hir_typeck/src/method/suggest.rs | 3 +- .../rustc_hir_typeck/src/naked_functions.rs | 3 +- compiler/rustc_hir_typeck/src/upvar.rs | 4 +- compiler/rustc_hir_typeck/src/writeback.rs | 5 +-- .../rustc_incremental/src/persist/clean.rs | 4 +- compiler/rustc_interface/src/limits.rs | 16 +++---- compiler/rustc_interface/src/passes.rs | 2 +- .../rustc_interface/src/proc_macro_decls.rs | 3 +- compiler/rustc_lint/src/autorefs.rs | 3 +- compiler/rustc_lint/src/builtin.rs | 14 +++--- compiler/rustc_lint/src/dangling.rs | 3 +- compiler/rustc_lint/src/foreign_modules.rs | 6 +-- compiler/rustc_lint/src/gpukernel_abi.rs | 3 +- .../rustc_lint/src/interior_mutable_consts.rs | 3 +- compiler/rustc_lint/src/internal.rs | 11 +++-- compiler/rustc_lint/src/non_local_def.rs | 3 +- compiler/rustc_lint/src/nonstandard_style.rs | 17 +++----- compiler/rustc_lint/src/pass_by_value.rs | 7 +-- compiler/rustc_lint/src/ptr_nulls.rs | 5 +-- compiler/rustc_lint/src/types.rs | 3 +- compiler/rustc_lint/src/unused.rs | 3 +- compiler/rustc_metadata/src/eii.rs | 10 ++--- compiler/rustc_metadata/src/native_libs.rs | 11 +++-- compiler/rustc_metadata/src/rmeta/encoder.rs | 21 ++++----- compiler/rustc_middle/src/hir/map.rs | 3 +- .../src/traits/specialization_graph.rs | 4 +- compiler/rustc_middle/src/ty/adt.rs | 7 ++- compiler/rustc_middle/src/ty/context.rs | 15 +++---- compiler/rustc_middle/src/ty/mod.rs | 16 +++---- compiler/rustc_middle/src/ty/trait_def.rs | 3 +- compiler/rustc_middle/src/ty/util.rs | 9 ++-- compiler/rustc_mir_build/src/builder/mod.rs | 4 +- .../rustc_mir_build/src/check_unsafety.rs | 5 +-- compiler/rustc_mir_build/src/thir/cx/expr.rs | 5 +-- compiler/rustc_mir_build/src/thir/cx/mod.rs | 4 +- .../src/thir/pattern/const_to_pat.rs | 3 +- .../src/framework/graphviz.rs | 6 +-- compiler/rustc_mir_dataflow/src/rustc_peek.rs | 4 +- .../rustc_mir_transform/src/check_inline.rs | 6 +-- compiler/rustc_mir_transform/src/coroutine.rs | 5 +-- .../rustc_mir_transform/src/coverage/query.rs | 4 +- .../src/cross_crate_inline.rs | 6 +-- .../rustc_mir_transform/src/instsimplify.rs | 4 +- compiler/rustc_mir_transform/src/liveness.rs | 5 +-- compiler/rustc_passes/src/abi_test.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 34 ++++++++------- compiler/rustc_passes/src/check_export.rs | 5 +-- compiler/rustc_passes/src/dead.rs | 5 +-- compiler/rustc_passes/src/diagnostic_items.rs | 3 +- compiler/rustc_passes/src/entry.rs | 5 +-- compiler/rustc_passes/src/layout_test.rs | 4 +- compiler/rustc_passes/src/stability.rs | 28 ++++++------ compiler/rustc_privacy/src/lib.rs | 5 +-- compiler/rustc_resolve/src/diagnostics.rs | 7 ++- .../rustc_resolve/src/late/diagnostics.rs | 7 +-- compiler/rustc_resolve/src/lib.rs | 4 +- .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 9 +--- .../cfi/typeid/itanium_cxx_abi/transform.rs | 3 +- compiler/rustc_symbol_mangling/src/test.rs | 7 +-- .../error_reporting/infer/note_and_explain.rs | 3 +- .../src/traits/coherence.rs | 4 +- .../src/traits/select/mod.rs | 3 +- compiler/rustc_ty_utils/src/layout.rs | 3 +- compiler/rustc_ty_utils/src/needs_drop.rs | 3 +- 98 files changed, 275 insertions(+), 412 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 218126e64de92..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,7 +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 db9f27e4603a3..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, def_id, - AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes + RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes ) .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect()) } diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 0d1925f138c70..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, 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 e66df36913772..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, 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 1448ae674a90f..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,7 +453,7 @@ pub(crate) fn start_async_codegen( ) -> OngoingCodegen { let (coordinator_send, coordinator_receive) = channel(); - let no_builtins = find_attr!(tcx, crate, 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 b8bc585d16a3a..0d3fc63a69bd8 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -13,7 +13,7 @@ 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::attrs::{DebuggerVisualizerType, OptimizeAttr}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ItemId, Target, find_attr}; @@ -894,8 +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, crate, 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 fbed5c96e1c42..6b0d46f5dc5d1 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -230,7 +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, 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, @@ -350,7 +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 no_builtins = find_attr!(tcx, crate, AttributeKind::NoBuiltins); + let no_builtins = find_attr!(tcx, crate, NoBuiltins); if no_builtins { codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS; } @@ -480,7 +480,7 @@ fn check_result( .map(|features| (features.name.as_str(), true)) .collect(), ) { - let span = find_attr!(tcx, did, AttributeKind::TargetFeature{attr_span: span, ..} => *span) + let span = find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span) .unwrap_or_else(|| tcx.def_span(did)); tcx.dcx() @@ -500,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 @@ -579,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, 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 diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index b1a93acdfc6b6..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, 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 ed4bbe467f941..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,7 +80,7 @@ pub fn rustc_allow_const_fn_unstable( def_id: LocalDefId, feature_gate: Symbol, ) -> bool { - find_attr!(tcx, def_id, 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 d27d66a9de281..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, 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 4a215f277cf72..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, 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 ff9b177ac1e27..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,9 +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, 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_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index d057630bac338..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, 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,7 +980,7 @@ 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, def_id, AttributeKind::EiiForeignItem) { + let name = if find_attr!(tcx, def_id, EiiForeignItem) { "externally implementable items" } else { "foreign items" @@ -1372,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, 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, @@ -1555,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, def.did(), 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 @@ -1723,9 +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, 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()); @@ -1796,7 +1792,7 @@ 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, def_id, attrs::AttributeKind::Repr { reprs, first_span } => { + 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), diff --git a/compiler/rustc_hir_analysis/src/check/compare_eii.rs b/compiler/rustc_hir_analysis/src/check/compare_eii.rs index 43fbcb492160f..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,7 +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, 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 25eef5e9bde37..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,8 +98,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { error = true; } - if let Some(attr_span) = find_attr!(tcx, 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 1e6bdddf11d6b..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,13 +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, 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, *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 1c37d06d55416..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,14 +78,14 @@ impl<'tcx> InherentCollect<'tcx> { } if self.tcx.features().rustc_attrs() { - if !find_attr!(self.tcx, 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, 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, @@ -132,8 +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, 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 9fa936d87ffdd..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, parent_did, AttributeKind::NonExhaustive(..)) - || variant_did.is_some_and(|variant_did| { - find_attr!(tcx, 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(..))), ) } @@ -899,44 +896,42 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { #[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(), @@ -1357,7 +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, 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 ad73ea50323d2..8534cc26fd944 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -1,5 +1,4 @@ use rustc_hir as hir; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::{find_attr, intravisit}; use rustc_middle::hir::nested_filter; @@ -7,7 +6,7 @@ use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_span::sym; pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) { - if !find_attr!(tcx, crate, 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, 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, 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, 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, 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 a73009838b0f7..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,7 +4,6 @@ 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::DefId; use rustc_hir::{PolyTraitRef, find_attr}; @@ -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, crate, AttributeKind::RustcNoImplicitBounds) { + if find_attr!(tcx, crate, RustcNoImplicitBounds) { return; } @@ -285,7 +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(), crate, 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 52a0543e27bfe..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, 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 1771f6295fbab..db17aaf8de1f3 100644 --- a/compiler/rustc_hir_analysis/src/variance/dump.rs +++ b/compiler/rustc_hir_analysis/src/variance/dump.rs @@ -1,6 +1,5 @@ use std::fmt::Write; -use rustc_hir::attrs::AttributeKind; 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, crate, 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, 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 a363cee5a1f1e..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,9 +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, 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 { @@ -903,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, 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 6d6de0d3d90d5..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, 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 b0b56c869449e..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, 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 2724e2302009e..873e95f13bb97 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -9,7 +9,7 @@ use std::cell::{Cell, RefCell}; use std::ops::Deref; 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::{ @@ -515,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, crate, 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 c0e83f9222930..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, 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 49e4b1feb4d69..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, 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 49a8dd29dce68..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,8 +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, 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 3962b748714e1..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, 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 47cef5ac2d11f..2969152848986 100644 --- a/compiler/rustc_incremental/src/persist/clean.rs +++ b/compiler/rustc_incremental/src/persist/clean.rs @@ -352,9 +352,7 @@ 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(clean_attrs) = - find_attr!(self.tcx, item_id, AttributeKind::RustcClean(attr) => attr) - else { + let Some(clean_attrs) = find_attr!(self.tcx, item_id, RustcClean(attr) => attr) else { return; }; 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 f33084afe2572..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, 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 ecaadad9dfc30..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, 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 c389fd26dbb2e..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, 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 16533722d8c0a..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, 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 f775a7eb163b8..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,10 +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, 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 b3a061afd9d02..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,7 +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, 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 2ad1dc43bae7e..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; @@ -88,7 +87,7 @@ impl<'tcx> LateLintPass<'tcx> for InteriorMutableConsts { // Let's do the attribute check after the other checks for perf reasons && find_attr!( cx.tcx, method_did, - AttributeKind::RustcShouldNotBeCalledOnConstItems(_) + 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 7b97ff92e008b..87c36f41afab1 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -2,7 +2,6 @@ //! Clippy. use rustc_ast::{Pat, PatKind, Path}; -use rustc_hir::attrs::AttributeKind; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, HirId, find_attr}; @@ -91,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, def_id, AttributeKind::RustcLintQueryInstability) { + if find_attr!(cx.tcx, def_id, RustcLintQueryInstability) { cx.emit_span_lint( POTENTIAL_QUERY_INSTABILITY, span, @@ -106,7 +105,7 @@ impl<'tcx> LateLintPass<'tcx> for QueryStability { ); } - if find_attr!(cx.tcx, def_id, AttributeKind::RustcLintUntrackedQueryInformation) { + if find_attr!(cx.tcx, def_id, RustcLintUntrackedQueryInformation) { cx.emit_span_lint( UNTRACKED_QUERY_INFORMATION, span, @@ -151,7 +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, instance.def_id(), AttributeKind::RustcLintQueryInstability) { + if find_attr!(cx.tcx, instance.def_id(), RustcLintQueryInstability) { return true; } } @@ -503,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, 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, 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, diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 8da452861163e..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,7 +242,7 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { ) } ItemKind::Macro(_, _macro, _kinds) - if find_attr!(cx.tcx, 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 85d08acb4cf54..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, crate, 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, 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, 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 69c49519144c6..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,16 +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, 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, 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 cfc36436a50df..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, 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, 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 ca9a74f822c8c..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, 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 ef78fa05e89eb..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}; @@ -402,7 +401,7 @@ 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, def_id, - AttributeKind::MustUse { reason, .. } => reason + 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 7bc63b157814e..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,13 +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, 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, 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"); @@ -51,7 +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, 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 e61ef3de9ccbf..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}; @@ -213,10 +213,8 @@ impl<'tcx> Collector<'tcx> { return; } - for attr in find_attr!(self.tcx, def_id, AttributeKind::Link(links, _) => links) - .iter() - .map(|v| v.iter()) - .flatten() + for attr in + 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 @@ -231,7 +229,8 @@ impl<'tcx> Collector<'tcx> { .collect(), _ => { for &child_item in foreign_items { - if let Some(span) = find_attr!(self.tcx, 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/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 3dc8a1d07609a..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,8 +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, 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 448be791c9eb5..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,11 +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, 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, did, AttributeKind::PinV2(..)) { + if find_attr!(tcx, did, PinV2(..)) { debug!("found pin-project type {:?}", did); flags |= AdtFlags::IS_PIN_PROJECT; } @@ -301,7 +300,7 @@ impl AdtDefData { flags |= AdtFlags::HAS_CTOR; } - if find_attr!(tcx, 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 363e429df4e3f..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, def_id, AttributeKind::RustcLayoutScalarValidRangeStart(n, _) => Bound::Included(**n)).unwrap_or(Bound::Unbounded); - let end = find_attr!(self, 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, 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, crate, AttributeKind::PanicRuntime); - providers.is_compiler_builtins = - |tcx, LocalCrate| find_attr!(tcx, crate, 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/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 7cdd48b9bf35d..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,7 +1442,7 @@ impl<'tcx> TyCtxt<'tcx> { field_shuffle_seed ^= user_seed; } - let elt = find_attr!(self, did, 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), @@ -1451,7 +1451,7 @@ impl<'tcx> TyCtxt<'tcx> { if elt.is_some() { flags.insert(ReprFlags::IS_SCALABLE); } - if let Some(reprs) = find_attr!(self, did, 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(), @@ -1511,7 +1511,7 @@ impl<'tcx> TyCtxt<'tcx> { } // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details. - if find_attr!(self, did, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) { + if find_attr!(self, did, RustcPassIndirectlyInNonRusticAbis(..)) { flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS); } @@ -1991,11 +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, - outer.macro_def_id.unwrap(), - AttributeKind::RustcBuiltinMacro { .. } - ) + && find_attr!(self, outer.macro_def_id.unwrap(), RustcBuiltinMacro { .. }) { true } else { @@ -2005,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, 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 22fd22f2bba74..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, 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 60ac1e13e849f..c3be0b630d6ed 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -9,7 +9,6 @@ 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; @@ -1671,12 +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 { - find_attr!(tcx, def_id, AttributeKind::Doc(doc) if doc.hidden.is_some()) + 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 { - find_attr!(tcx, def_id, 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). @@ -1685,7 +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, 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 @@ -1695,7 +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 64bec3ae3818f..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, 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, 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 424ac99a4b31f..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,7 +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, 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 9a8aea8244295..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,9 +97,7 @@ impl RustcMirAttrs { fn parse(tcx: TyCtxt<'_>, def_id: DefId) -> Self { let mut ret = RustcMirAttrs::default(); - if let Some(rustc_mir_attrs) = - find_attr!(tcx, def_id, 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 6cdf8b39df21d..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,7 +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(); - if let Some(kind) = find_attr!(tcx, def_id, 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 d084460ab84d6..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, 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, 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 bc65499a96a26..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, 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 74f4131258e48..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,7 +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, 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 30ad713d201e8..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; @@ -45,7 +45,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return true; } - if find_attr!(tcx, 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 @@ -159,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, 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 bb746e490c8af..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, 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, 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 dac5684dc0ecb..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; @@ -19,7 +19,7 @@ pub fn test_abi(tcx: TyCtxt<'_>) { } for id in tcx.hir_crate_items(()).definitions() { let Some((attr_span, attr_kind)) = - find_attr!(tcx, id, AttributeKind::RustcAbi{ attr_span, kind } => (*attr_span, *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 d6a171857ece8..9af9398d78b96 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -567,7 +567,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } if let EiiImplResolution::Macro(eii_macro) = resolution - && find_attr!(self.tcx, *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 { @@ -782,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(); @@ -794,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 { @@ -853,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 @@ -1161,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 }); } @@ -1268,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; @@ -1413,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], @@ -1751,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 }); @@ -1761,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,7 +1777,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { if let Some(attr_span) = find_attr!( self.tcx, parent_did, - AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span + Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span ) && is_coro { self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span }); @@ -1784,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)]" @@ -1905,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, 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); } } @@ -2097,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 1e6f6d4598136..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, 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, 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 a2cbdd23e379c..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,7 +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, 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() @@ -723,7 +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, 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 a5ebf7e5fee99..9fc9df7604c51 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -1,6 +1,5 @@ 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::{ItemId, Node, find_attr}; use rustc_middle::query::Providers; @@ -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, crate, 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 89766d84377c6..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,7 +20,7 @@ pub fn test_layout(tcx: TyCtxt<'_>) { return; } for id in tcx.hir_crate_items(()).definitions() { - if let Some(attrs) = find_attr!(tcx, id, 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 ec38a334be286..6fd28c78740cd 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -97,7 +97,7 @@ fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind { fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { let depr = find_attr!(tcx, def_id, - AttributeKind::Deprecation { deprecation, span: _ } => *deprecation + Deprecation { deprecation, span: _ } => *deprecation ); let Some(depr) = depr else { @@ -160,8 +160,7 @@ fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { } // # Regular stability - let stab = - find_attr!(tcx, def_id, 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,7 +194,7 @@ fn lookup_default_body_stability( } // FIXME: check that this item can have body stability - find_attr!(tcx, def_id, AttributeKind::RustcBodyStability { stability, .. } => *stability) + find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability) } #[instrument(level = "debug", skip(tcx))] @@ -210,8 +209,7 @@ fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option, def_id: LocalDefId) -> Option *stability); + let const_stability_indirect = find_attr!(tcx, def_id, RustcConstStabilityIndirect); + let const_stab = + 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. @@ -595,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 d84797f2fab6b..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, 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 5eb1f73eb750e..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}; @@ -1432,7 +1432,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { && find_attr!( this.tcx, did, - AttributeKind::RustcDiagnosticItem( + RustcDiagnosticItem( sym::TryInto | sym::TryFrom | sym::FromIterator ) ); @@ -2171,8 +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, 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 7c20b006c00bb..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,7 +1114,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // confused by them. continue; } - if let Some(d) = hir::find_attr!(r.tcx, 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); @@ -2664,9 +2663,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { ) .iter() .filter_map(|candidate| candidate.did) - .find(|did| { - find_attr!(self.r.tcx, *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 476bd146e46a9..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, @@ -2476,7 +2476,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { find_attr!( // we can use parsed attrs here since for other crates they're already available self.tcx, def_id, - AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes + 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 3c50a993465b5..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,9 +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, 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); @@ -495,9 +492,7 @@ pub(crate) fn encode_ty<'tcx>( // , where is let mut s = String::new(); - if let Some(encoding) = - find_attr!(tcx, *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 b4f8e8201f44a..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,7 +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, 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 6a550c1328766..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,9 +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, 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,7 +80,7 @@ impl SymbolNamesTest<'_> { if let Some(attr_span) = find_attr!( tcx, def_id, - AttributeKind::RustcDefPath(span) => span + 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 df88b26d811c4..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, 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/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index eaa767f1496e3..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,7 +759,8 @@ impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> { } = cand.kind() && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) { - if let Some(message) = find_attr!(infcx.tcx, def_id, AttributeKind::RustcReservationImpl(_, 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 4620fe9b475db..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, 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 5b5fa82517ed9..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; @@ -625,7 +624,7 @@ 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, def.did(), - AttributeKind::RustcSimdMonomorphizeLaneLimit(limit) => limit + 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 c5dedd51af854..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, 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 From be4f92fc458c501964fb390535988174851e661a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Fri, 13 Feb 2026 15:59:57 +0100 Subject: [PATCH 20/23] emit unreachable pattern lint --- compiler/rustc_hir/src/attrs/mod.rs | 7 ++++-- compiler/rustc_middle/src/lint.rs | 14 +++++++++-- tests/ui-fulldeps/internal-lints/find_attr.rs | 3 +++ .../internal-lints/find_attr.stderr | 24 ++++++++++++++++++- 4 files changed, 43 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index 92dd77e80a512..fc064fa65af95 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -77,8 +77,11 @@ macro_rules! find_attr { rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => { break 'done Some($e); } - // FIXME: doesn't actually trigger in other crates :/ - // https://github.com/rust-lang/rust/issues/110613 + 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_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/tests/ui-fulldeps/internal-lints/find_attr.rs b/tests/ui-fulldeps/internal-lints/find_attr.rs index 00838132226f6..bb0c8c486bcdb 100644 --- a/tests/ui-fulldeps/internal-lints/find_attr.rs +++ b/tests/ui-fulldeps/internal-lints/find_attr.rs @@ -21,4 +21,7 @@ fn main() { //~^ 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 index 22c61563af70b..ea8accaddb605 100644 --- a/tests/ui-fulldeps/internal-lints/find_attr.stderr +++ b/tests/ui-fulldeps/internal-lints/find_attr.stderr @@ -48,5 +48,27 @@ LL | find_attr!(attrs, AttributeKind::Inline(..) if true => todo!()); = note: `find_attr!(...)` already imports `AttributeKind::*` = help: remote `AttributeKind` -error: aborting due to 5 previous errors +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 From df23df54a6c4ad486b0231fd3dc2ea7a65f20989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Tue, 17 Feb 2026 23:52:19 +0100 Subject: [PATCH 21/23] tidy --- compiler/rustc_hir/src/attrs/data_structures.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 5d154cef66a65..2968083c7d727 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -1233,6 +1233,9 @@ pub enum AttributeKind { /// Represents `#[rustc_diagnostic_item]` RustcDiagnosticItem(Symbol), + /// Represents `#[rustc_diagnostic_item]` + RustcDiagnosticItem(Symbol), + /// Represents `#[rustc_do_not_const_check]` RustcDoNotConstCheck, From 8e7bc3c7d1689e17319b2d6fdc1220c373de7596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Wed, 18 Feb 2026 14:28:07 +0100 Subject: [PATCH 22/23] fix src/tools --- .../rustc_hir/src/attrs/data_structures.rs | 3 -- compiler/rustc_hir/src/attrs/mod.rs | 1 + compiler/rustc_lint/src/lints.rs | 2 +- src/librustdoc/clean/inline.rs | 7 +-- src/librustdoc/clean/mod.rs | 15 +++---- src/librustdoc/clean/types.rs | 45 +++++++++---------- src/librustdoc/clean/utils.rs | 9 ++-- src/librustdoc/html/render/search_index.rs | 3 +- src/librustdoc/json/ids.rs | 14 +++--- .../passes/collect_intra_doc_links.rs | 12 ++--- src/librustdoc/passes/collect_trait_impls.rs | 16 +++---- src/librustdoc/passes/strip_hidden.rs | 3 +- src/librustdoc/visit_ast.rs | 13 +++--- .../clippy_lints/src/attrs/inline_always.rs | 4 +- .../clippy_lints/src/attrs/repr_attributes.rs | 4 +- .../clippy_lints/src/cognitive_complexity.rs | 1 + .../src/default_union_representation.rs | 4 +- .../clippy/clippy_lints/src/eta_reduction.rs | 5 +-- .../clippy_lints/src/exhaustive_items.rs | 3 +- .../clippy/clippy_lints/src/format_args.rs | 6 +-- .../clippy_lints/src/functions/must_use.rs | 14 +++--- .../clippy_lints/src/incompatible_msrv.rs | 10 ++--- .../src/inline_fn_without_body.rs | 3 +- .../clippy_lints/src/loops/empty_loop.rs | 3 +- .../src/macro_metavars_in_unsafe.rs | 4 +- .../clippy/clippy_lints/src/macro_use.rs | 5 +-- .../clippy_lints/src/manual_non_exhaustive.rs | 5 +-- .../src/matches/match_wild_enum.rs | 2 +- .../matches/significant_drop_in_scrutinee.rs | 1 + .../clippy_lints/src/methods/is_empty.rs | 3 +- .../clippy/clippy_lints/src/missing_inline.rs | 3 +- .../clippy_lints/src/pass_by_ref_or_value.rs | 4 +- .../src/return_self_not_must_use.rs | 3 +- .../src/significant_drop_tightening.rs | 1 + src/tools/clippy/clippy_utils/src/attrs.rs | 8 ++-- src/tools/clippy/clippy_utils/src/lib.rs | 21 ++++----- src/tools/clippy/clippy_utils/src/macros.rs | 8 +++- src/tools/clippy/clippy_utils/src/ty/mod.rs | 12 ++--- .../internal-lints/find_attr.stderr | 10 ++--- 39 files changed, 121 insertions(+), 169 deletions(-) diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 2968083c7d727..5d154cef66a65 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -1233,9 +1233,6 @@ pub enum AttributeKind { /// Represents `#[rustc_diagnostic_item]` RustcDiagnosticItem(Symbol), - /// Represents `#[rustc_diagnostic_item]` - RustcDiagnosticItem(Symbol), - /// Represents `#[rustc_do_not_const_check]` RustcDoNotConstCheck, diff --git a/compiler/rustc_hir/src/attrs/mod.rs b/compiler/rustc_hir/src/attrs/mod.rs index fc064fa65af95..7e3ac666d0f50 100644 --- a/compiler/rustc_hir/src/attrs/mod.rs +++ b/compiler/rustc_hir/src/attrs/mod.rs @@ -71,6 +71,7 @@ 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 { diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 262a4121cc77a..5627f34f82e97 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -1146,7 +1146,7 @@ pub(crate) struct ImplicitSysrootCrateImportDiag<'a> { #[derive(LintDiagnostic)] #[diag("use of `AttributeKind` in `find_attr!(...)` invocation")] #[note("`find_attr!(...)` already imports `AttributeKind::*`")] -#[help("remote `AttributeKind`")] +#[help("remove `AttributeKind`")] pub(crate) struct AttributeKindInFindAttr {} // let_underscore.rs 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.stderr b/tests/ui-fulldeps/internal-lints/find_attr.stderr index ea8accaddb605..b7291ecbb84d9 100644 --- a/tests/ui-fulldeps/internal-lints/find_attr.stderr +++ b/tests/ui-fulldeps/internal-lints/find_attr.stderr @@ -5,7 +5,7 @@ LL | find_attr!(attrs, AttributeKind::Inline(..)); | ^^^^^^^^^^^^^ | = note: `find_attr!(...)` already imports `AttributeKind::*` - = help: remote `AttributeKind` + = help: remove `AttributeKind` note: the lint level is defined here --> $DIR/find_attr.rs:5:9 | @@ -19,7 +19,7 @@ LL | find_attr!(attrs, AttributeKind::Inline{..} | AttributeKind::Deprecatio | ^^^^^^^^^^^^^ | = note: `find_attr!(...)` already imports `AttributeKind::*` - = help: remote `AttributeKind` + = help: remove `AttributeKind` error: use of `AttributeKind` in `find_attr!(...)` invocation --> $DIR/find_attr.rs:16:51 @@ -28,7 +28,7 @@ LL | find_attr!(attrs, AttributeKind::Inline{..} | AttributeKind::Deprecatio | ^^^^^^^^^^^^^ | = note: `find_attr!(...)` already imports `AttributeKind::*` - = help: remote `AttributeKind` + = help: remove `AttributeKind` error: use of `AttributeKind` in `find_attr!(...)` invocation --> $DIR/find_attr.rs:20:23 @@ -37,7 +37,7 @@ LL | find_attr!(attrs, AttributeKind::Inline(..) => todo!()); | ^^^^^^^^^^^^^ | = note: `find_attr!(...)` already imports `AttributeKind::*` - = help: remote `AttributeKind` + = help: remove `AttributeKind` error: use of `AttributeKind` in `find_attr!(...)` invocation --> $DIR/find_attr.rs:22:23 @@ -46,7 +46,7 @@ LL | find_attr!(attrs, AttributeKind::Inline(..) if true => todo!()); | ^^^^^^^^^^^^^ | = note: `find_attr!(...)` already imports `AttributeKind::*` - = help: remote `AttributeKind` + = help: remove `AttributeKind` error: unreachable pattern --> $DIR/find_attr.rs:25:5 From 19e0c62e10ae62acf79a1cfde6c2fbd73c0d6c84 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 19 Feb 2026 22:33:51 +1100 Subject: [PATCH 23/23] Rename `DepGraphQuery` to `RetainedDepGraph` --- .../rustc_incremental/src/assert_dep_graph.rs | 84 +++++++++---------- compiler/rustc_middle/src/dep_graph/graph.rs | 6 +- compiler/rustc_middle/src/dep_graph/mod.rs | 4 +- .../src/dep_graph/{query.rs => retained.rs} | 30 ++++--- .../rustc_middle/src/dep_graph/serialized.rs | 39 ++++----- 5 files changed, 85 insertions(+), 78 deletions(-) rename compiler/rustc_middle/src/dep_graph/{query.rs => retained.rs} (62%) diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 945f1ab797e76..93e6c084a1914 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -44,7 +44,7 @@ use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::bug; -use rustc_middle::dep_graph::{DepGraphQuery, DepKind, DepNode, DepNodeFilter, EdgeFilter}; +use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeFilter, EdgeFilter, RetainedDepGraph}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::{Span, Symbol, sym}; @@ -57,7 +57,7 @@ use crate::errors; pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) { tcx.dep_graph.with_ignore(|| { if tcx.sess.opts.unstable_opts.dump_dep_graph { - tcx.dep_graph.with_query(dump_graph); + tcx.dep_graph.with_retained_dep_graph(dump_graph); } if !tcx.sess.opts.unstable_opts.query_dep_graph { @@ -184,7 +184,7 @@ fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_wou } return; } - tcx.dep_graph.with_query(|query| { + tcx.dep_graph.with_retained_dep_graph(|query| { for &(_, source_def_id, ref source_dep_node) in if_this_changed { let dependents = query.transitive_predecessors(source_dep_node); for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need { @@ -202,7 +202,7 @@ fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_wou }); } -fn dump_graph(query: &DepGraphQuery) { +fn dump_graph(graph: &RetainedDepGraph) { let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string()); let nodes = match env::var("RUST_DEP_GRAPH_FILTER") { @@ -210,13 +210,13 @@ fn dump_graph(query: &DepGraphQuery) { // Expect one of: "-> target", "source -> target", or "source ->". let edge_filter = EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e)); - let sources = node_set(query, &edge_filter.source); - let targets = node_set(query, &edge_filter.target); - filter_nodes(query, &sources, &targets) + let sources = node_set(graph, &edge_filter.source); + let targets = node_set(graph, &edge_filter.target); + filter_nodes(graph, &sources, &targets) } - Err(_) => query.nodes().into_iter().map(|n| n.kind).collect(), + Err(_) => graph.nodes().into_iter().map(|n| n.kind).collect(), }; - let edges = filter_edges(query, &nodes); + let edges = filter_edges(graph, &nodes); { // dump a .txt file with just the edges: @@ -279,51 +279,51 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph { // Given an optional filter like `"x,y,z"`, returns either `None` (no // filter) or the set of nodes whose labels contain all of those // substrings. -fn node_set<'q>( - query: &'q DepGraphQuery, +fn node_set<'g>( + graph: &'g RetainedDepGraph, filter: &DepNodeFilter, -) -> Option> { +) -> Option> { debug!("node_set(filter={:?})", filter); if filter.accepts_all() { return None; } - Some(query.nodes().into_iter().filter(|n| filter.test(n)).collect()) + Some(graph.nodes().into_iter().filter(|n| filter.test(n)).collect()) } -fn filter_nodes<'q>( - query: &'q DepGraphQuery, - sources: &Option>, - targets: &Option>, +fn filter_nodes<'g>( + graph: &'g RetainedDepGraph, + sources: &Option>, + targets: &Option>, ) -> FxIndexSet { if let Some(sources) = sources { if let Some(targets) = targets { - walk_between(query, sources, targets) + walk_between(graph, sources, targets) } else { - walk_nodes(query, sources, OUTGOING) + walk_nodes(graph, sources, OUTGOING) } } else if let Some(targets) = targets { - walk_nodes(query, targets, INCOMING) + walk_nodes(graph, targets, INCOMING) } else { - query.nodes().into_iter().map(|n| n.kind).collect() + graph.nodes().into_iter().map(|n| n.kind).collect() } } -fn walk_nodes<'q>( - query: &'q DepGraphQuery, - starts: &FxIndexSet<&'q DepNode>, +fn walk_nodes<'g>( + graph: &'g RetainedDepGraph, + starts: &FxIndexSet<&'g DepNode>, direction: Direction, ) -> FxIndexSet { let mut set = FxIndexSet::default(); for &start in starts { debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING); if set.insert(start.kind) { - let mut stack = vec![query.indices[start]]; + let mut stack = vec![graph.indices[start]]; while let Some(index) = stack.pop() { - for (_, edge) in query.graph.adjacent_edges(index, direction) { + for (_, edge) in graph.inner.adjacent_edges(index, direction) { let neighbor_index = edge.source_or_target(direction); - let neighbor = query.graph.node_data(neighbor_index); + let neighbor = graph.inner.node_data(neighbor_index); if set.insert(neighbor.kind) { stack.push(neighbor_index); } @@ -334,10 +334,10 @@ fn walk_nodes<'q>( set } -fn walk_between<'q>( - query: &'q DepGraphQuery, - sources: &FxIndexSet<&'q DepNode>, - targets: &FxIndexSet<&'q DepNode>, +fn walk_between<'g>( + graph: &'g RetainedDepGraph, + sources: &FxIndexSet<&'g DepNode>, + targets: &FxIndexSet<&'g DepNode>, ) -> FxIndexSet { // This is a bit tricky. We want to include a node only if it is: // (a) reachable from a source and (b) will reach a target. And we @@ -352,27 +352,27 @@ fn walk_between<'q>( Excluded, } - let mut node_states = vec![State::Undecided; query.graph.len_nodes()]; + let mut node_states = vec![State::Undecided; graph.inner.len_nodes()]; for &target in targets { - node_states[query.indices[target].0] = State::Included; + node_states[graph.indices[target].0] = State::Included; } - for source in sources.iter().map(|&n| query.indices[n]) { - recurse(query, &mut node_states, source); + for source in sources.iter().map(|&n| graph.indices[n]) { + recurse(graph, &mut node_states, source); } - return query + return graph .nodes() .into_iter() .filter(|&n| { - let index = query.indices[n]; + let index = graph.indices[n]; node_states[index.0] == State::Included }) .map(|n| n.kind) .collect(); - fn recurse(query: &DepGraphQuery, node_states: &mut [State], node: NodeIndex) -> bool { + fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool { match node_states[node.0] { // known to reach a target State::Included => return true, @@ -388,8 +388,8 @@ fn walk_between<'q>( node_states[node.0] = State::Deciding; - for neighbor_index in query.graph.successor_nodes(node) { - if recurse(query, node_states, neighbor_index) { + for neighbor_index in graph.inner.successor_nodes(node) { + if recurse(graph, node_states, neighbor_index) { node_states[node.0] = State::Included; } } @@ -405,8 +405,8 @@ fn walk_between<'q>( } } -fn filter_edges(query: &DepGraphQuery, nodes: &FxIndexSet) -> Vec<(DepKind, DepKind)> { - let uniq: FxIndexSet<_> = query +fn filter_edges(graph: &RetainedDepGraph, nodes: &FxIndexSet) -> Vec<(DepKind, DepKind)> { + let uniq: FxIndexSet<_> = graph .edges() .into_iter() .map(|(s, t)| (s.kind, t.kind)) diff --git a/compiler/rustc_middle/src/dep_graph/graph.rs b/compiler/rustc_middle/src/dep_graph/graph.rs index f54cd3c85fb4e..2ce01ab4c6650 100644 --- a/compiler/rustc_middle/src/dep_graph/graph.rs +++ b/compiler/rustc_middle/src/dep_graph/graph.rs @@ -21,7 +21,7 @@ use tracing::{debug, instrument}; #[cfg(debug_assertions)] use {super::debug::EdgeFilter, std::env}; -use super::query::DepGraphQuery; +use super::retained::RetainedDepGraph; use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex}; use super::{DepKind, DepNode, WorkProductId, read_deps, with_deps}; use crate::dep_graph::edges::EdgesVec; @@ -191,9 +191,9 @@ impl DepGraph { self.data.is_some() } - pub fn with_query(&self, f: impl Fn(&DepGraphQuery)) { + pub fn with_retained_dep_graph(&self, f: impl Fn(&RetainedDepGraph)) { if let Some(data) = &self.data { - data.current.encoder.with_query(f) + data.current.encoder.with_retained_dep_graph(f) } } diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 0f08a66caeeb0..e0ba944d81573 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -10,7 +10,7 @@ pub use self::graph::{ WorkProductMap, hash_result, }; use self::graph::{MarkFrame, print_markframe_trace}; -pub use self::query::DepGraphQuery; +pub use self::retained::RetainedDepGraph; pub use self::serialized::{SerializedDepGraph, SerializedDepNodeIndex}; pub use crate::dep_graph::debug::{DepNodeFilter, EdgeFilter}; use crate::ty::print::with_reduced_queries; @@ -21,7 +21,7 @@ pub(crate) mod dep_node; mod dep_node_key; mod edges; mod graph; -mod query; +mod retained; mod serialized; /// Describes the contents of the fingerprint generated by a given query. diff --git a/compiler/rustc_middle/src/dep_graph/query.rs b/compiler/rustc_middle/src/dep_graph/retained.rs similarity index 62% rename from compiler/rustc_middle/src/dep_graph/query.rs rename to compiler/rustc_middle/src/dep_graph/retained.rs index f145e1cba2d70..4427982e3708f 100644 --- a/compiler/rustc_middle/src/dep_graph/query.rs +++ b/compiler/rustc_middle/src/dep_graph/retained.rs @@ -4,26 +4,32 @@ use rustc_index::IndexVec; use super::{DepNode, DepNodeIndex}; -pub struct DepGraphQuery { - pub graph: LinkedGraph, +/// An in-memory copy of the current session's query dependency graph, which +/// is only enabled when `-Zquery-dep-graph` is set (for debugging/testing). +/// +/// Normally, dependencies recorded during the current session are written to +/// disk and then forgotten, to avoid wasting memory on information that is +/// not needed when the compiler is working correctly. +pub struct RetainedDepGraph { + pub inner: LinkedGraph, pub indices: FxHashMap, pub dep_index_to_index: IndexVec>, } -impl DepGraphQuery { - pub fn new(prev_node_count: usize) -> DepGraphQuery { +impl RetainedDepGraph { + pub fn new(prev_node_count: usize) -> Self { let node_count = prev_node_count + prev_node_count / 4; let edge_count = 6 * node_count; - let graph = LinkedGraph::with_capacity(node_count, edge_count); + let inner = LinkedGraph::with_capacity(node_count, edge_count); let indices = FxHashMap::default(); let dep_index_to_index = IndexVec::new(); - DepGraphQuery { graph, indices, dep_index_to_index } + Self { inner, indices, dep_index_to_index } } pub fn push(&mut self, index: DepNodeIndex, node: DepNode, edges: &[DepNodeIndex]) { - let source = self.graph.add_node(node); + let source = self.inner.add_node(node); self.dep_index_to_index.insert(index, source); self.indices.insert(node, source); @@ -31,27 +37,27 @@ impl DepGraphQuery { // We may miss the edges that are pushed while the `DepGraphQuery` is being accessed. // Skip them to issues. if let Some(&Some(target)) = self.dep_index_to_index.get(target) { - self.graph.add_edge(source, target, ()); + self.inner.add_edge(source, target, ()); } } } pub fn nodes(&self) -> Vec<&DepNode> { - self.graph.all_nodes().iter().map(|n| &n.data).collect() + self.inner.all_nodes().iter().map(|n| &n.data).collect() } pub fn edges(&self) -> Vec<(&DepNode, &DepNode)> { - self.graph + self.inner .all_edges() .iter() .map(|edge| (edge.source(), edge.target())) - .map(|(s, t)| (self.graph.node_data(s), self.graph.node_data(t))) + .map(|(s, t)| (self.inner.node_data(s), self.inner.node_data(t))) .collect() } fn reachable_nodes(&self, node: &DepNode, direction: Direction) -> Vec<&DepNode> { if let Some(&index) = self.indices.get(node) { - self.graph.depth_traverse(index, direction).map(|s| self.graph.node_data(s)).collect() + self.inner.depth_traverse(index, direction).map(|s| self.inner.node_data(s)).collect() } else { vec![] } diff --git a/compiler/rustc_middle/src/dep_graph/serialized.rs b/compiler/rustc_middle/src/dep_graph/serialized.rs index 7885b43535446..8a4ac4b5e5acd 100644 --- a/compiler/rustc_middle/src/dep_graph/serialized.rs +++ b/compiler/rustc_middle/src/dep_graph/serialized.rs @@ -59,7 +59,7 @@ use rustc_session::Session; use tracing::{debug, instrument}; use super::graph::{CurrentDepGraph, DepNodeColorMap}; -use super::query::DepGraphQuery; +use super::retained::RetainedDepGraph; use super::{DepKind, DepNode, DepNodeIndex}; use crate::dep_graph::edges::EdgesVec; @@ -615,21 +615,21 @@ impl EncoderState { index: DepNodeIndex, edge_count: usize, edges: impl FnOnce(&Self) -> Vec, - record_graph: &Option>, + retained_graph: &Option>, local: &mut LocalEncoderState, ) { local.kind_stats[node.kind.as_usize()] += 1; local.edge_count += edge_count; - if let Some(record_graph) = &record_graph { + if let Some(retained_graph) = &retained_graph { // Call `edges` before the outlined code to allow the closure to be optimized out. let edges = edges(self); // Outline the build of the full dep graph as it's typically disabled and cold. outline(move || { // Do not ICE when a query is called from within `with_query`. - if let Some(record_graph) = &mut record_graph.try_lock() { - record_graph.push(index, *node, &edges); + if let Some(retained_graph) = &mut retained_graph.try_lock() { + retained_graph.push(index, *node, &edges); } }); } @@ -662,7 +662,7 @@ impl EncoderState { &self, index: DepNodeIndex, node: &NodeInfo, - record_graph: &Option>, + retained_graph: &Option>, local: &mut LocalEncoderState, ) { node.encode(&mut local.encoder, index); @@ -672,7 +672,7 @@ impl EncoderState { index, node.edges.len(), |_| node.edges[..].to_vec(), - record_graph, + retained_graph, &mut *local, ); } @@ -688,7 +688,7 @@ impl EncoderState { &self, index: DepNodeIndex, prev_index: SerializedDepNodeIndex, - record_graph: &Option>, + retained_graph: &Option>, colors: &DepNodeColorMap, local: &mut LocalEncoderState, ) { @@ -714,7 +714,7 @@ impl EncoderState { .map(|i| colors.current(i).unwrap()) .collect() }, - record_graph, + retained_graph, &mut *local, ); } @@ -845,7 +845,8 @@ impl EncoderState { pub(crate) struct GraphEncoder { profiler: SelfProfilerRef, status: EncoderState, - record_graph: Option>, + /// In-memory copy of the dep graph; only present if `-Zquery-dep-graph` is set. + retained_graph: Option>, } impl GraphEncoder { @@ -855,18 +856,18 @@ impl GraphEncoder { prev_node_count: usize, previous: Arc, ) -> Self { - let record_graph = sess + let retained_graph = sess .opts .unstable_opts .query_dep_graph - .then(|| Lock::new(DepGraphQuery::new(prev_node_count))); + .then(|| Lock::new(RetainedDepGraph::new(prev_node_count))); let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous); - GraphEncoder { status, record_graph, profiler: sess.prof.clone() } + GraphEncoder { status, retained_graph, profiler: sess.prof.clone() } } - pub(crate) fn with_query(&self, f: impl Fn(&DepGraphQuery)) { - if let Some(record_graph) = &self.record_graph { - f(&record_graph.lock()) + pub(crate) fn with_retained_dep_graph(&self, f: impl Fn(&RetainedDepGraph)) { + if let Some(retained_graph) = &self.retained_graph { + f(&retained_graph.lock()) } } @@ -882,7 +883,7 @@ impl GraphEncoder { let mut local = self.status.local.borrow_mut(); let index = self.status.next_index(&mut *local); self.status.bump_index(&mut *local); - self.status.encode_node(index, &node, &self.record_graph, &mut *local); + self.status.encode_node(index, &node, &self.retained_graph, &mut *local); index } @@ -914,7 +915,7 @@ impl GraphEncoder { } self.status.bump_index(&mut *local); - self.status.encode_node(index, &node, &self.record_graph, &mut *local); + self.status.encode_node(index, &node, &self.retained_graph, &mut *local); index } @@ -942,7 +943,7 @@ impl GraphEncoder { self.status.encode_promoted_node( index, prev_index, - &self.record_graph, + &self.retained_graph, colors, &mut *local, );