From 211af03439e90d8ffd04cdb73769f5ad2e782622 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Tue, 4 Jun 2024 12:31:04 +0200 Subject: Cleanup some inert attribute stuff --- src/tools/rust-analyzer/crates/hir-def/src/attr.rs | 57 +- .../crates/hir-def/src/attr/builtin.rs | 697 --------------------- .../rust-analyzer/crates/hir-def/src/attr/tests.rs | 48 -- src/tools/rust-analyzer/crates/hir-def/src/data.rs | 2 +- src/tools/rust-analyzer/crates/hir-def/src/db.rs | 10 +- .../crates/hir-def/src/nameres/attr_resolution.rs | 11 +- .../crates/hir-def/src/nameres/collector.rs | 52 +- .../crates/hir-expand/src/builtin_attr_macro.rs | 2 - .../crates/hir-expand/src/cfg_process.rs | 4 +- .../rust-analyzer/crates/hir-expand/src/db.rs | 38 +- .../crates/hir-expand/src/inert_attr_macro.rs | 692 ++++++++++++++++++++ .../rust-analyzer/crates/hir-expand/src/lib.rs | 47 +- src/tools/rust-analyzer/crates/hir/src/lib.rs | 13 +- .../rust-analyzer/crates/hir/src/semantics.rs | 14 +- .../ide-diagnostics/src/handlers/macro_error.rs | 2 - src/tools/rust-analyzer/crates/mbe/src/lib.rs | 6 + src/tools/rust-analyzer/crates/salsa/src/lib.rs | 4 + src/tools/rust-analyzer/crates/tt/src/lib.rs | 2 +- 18 files changed, 847 insertions(+), 854 deletions(-) delete mode 100644 src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs delete mode 100644 src/tools/rust-analyzer/crates/hir-def/src/attr/tests.rs create mode 100644 src/tools/rust-analyzer/crates/hir-expand/src/inert_attr_macro.rs diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attr.rs b/src/tools/rust-analyzer/crates/hir-def/src/attr.rs index d9eeffd7983..369277633e9 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attr.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attr.rs @@ -1,10 +1,5 @@ //! A higher level attributes based on TokenTree, with also some shortcuts. -pub mod builtin; - -#[cfg(test)] -mod tests; - use std::{borrow::Cow, hash::Hash, ops, slice::Iter as SliceIter}; use base_db::CrateId; @@ -646,3 +641,55 @@ pub(crate) fn fields_attrs_source_map( Arc::new(res) } + +#[cfg(test)] +mod tests { + //! This module contains tests for doc-expression parsing. + //! Currently, it tests `#[doc(hidden)]` and `#[doc(alias)]`. + + use triomphe::Arc; + + use base_db::FileId; + use hir_expand::span_map::{RealSpanMap, SpanMap}; + use mbe::{syntax_node_to_token_tree, DocCommentDesugarMode}; + use syntax::{ast, AstNode, TextRange}; + + use crate::attr::{DocAtom, DocExpr}; + + fn assert_parse_result(input: &str, expected: DocExpr) { + let source_file = ast::SourceFile::parse(input, span::Edition::CURRENT).ok().unwrap(); + let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); + let map = SpanMap::RealSpanMap(Arc::new(RealSpanMap::absolute(FileId::from_raw(0)))); + let tt = syntax_node_to_token_tree( + tt.syntax(), + map.as_ref(), + map.span_for_range(TextRange::empty(0.into())), + DocCommentDesugarMode::ProcMacro, + ); + let cfg = DocExpr::parse(&tt); + assert_eq!(cfg, expected); + } + + #[test] + fn test_doc_expr_parser() { + assert_parse_result("#![doc(hidden)]", DocAtom::Flag("hidden".into()).into()); + + assert_parse_result( + r#"#![doc(alias = "foo")]"#, + DocAtom::KeyValue { key: "alias".into(), value: "foo".into() }.into(), + ); + + assert_parse_result(r#"#![doc(alias("foo"))]"#, DocExpr::Alias(["foo".into()].into())); + assert_parse_result( + r#"#![doc(alias("foo", "bar", "baz"))]"#, + DocExpr::Alias(["foo".into(), "bar".into(), "baz".into()].into()), + ); + + assert_parse_result( + r#" + #[doc(alias("Bar", "Qux"))] + struct Foo;"#, + DocExpr::Alias(["Bar".into(), "Qux".into()].into()), + ); + } +} diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs b/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs deleted file mode 100644 index 7b649496c48..00000000000 --- a/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs +++ /dev/null @@ -1,697 +0,0 @@ -//! Builtin attributes resolved by nameres. -//! -//! The actual definitions were copied from rustc's `compiler/rustc_feature/src/builtin_attrs.rs`. -//! -//! It was last synchronized with upstream commit c3def263a44e07e09ae6d57abfc8650227fb4972. -//! -//! The macros were adjusted to only expand to the attribute name, since that is all we need to do -//! name resolution, and `BUILTIN_ATTRIBUTES` is almost entirely unchanged from the original, to -//! ease updating. - -use std::sync::OnceLock; - -use rustc_hash::FxHashMap; - -pub struct BuiltinAttribute { - pub name: &'static str, - pub template: AttributeTemplate, -} - -/// A template that the attribute input must match. -/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now. -#[derive(Clone, Copy)] -pub struct AttributeTemplate { - pub word: bool, - pub list: Option<&'static str>, - pub name_value_str: Option<&'static str>, -} - -pub fn find_builtin_attr_idx(name: &str) -> Option { - static BUILTIN_LOOKUP_TABLE: OnceLock> = OnceLock::new(); - BUILTIN_LOOKUP_TABLE - .get_or_init(|| { - INERT_ATTRIBUTES.iter().map(|attr| attr.name).enumerate().map(|(a, b)| (b, a)).collect() - }) - .get(name) - .copied() -} - -// impl AttributeTemplate { -// const DEFAULT: AttributeTemplate = -// AttributeTemplate { word: false, list: None, name_value_str: None }; -// } - -/// A convenience macro for constructing attribute templates. -/// E.g., `template!(Word, List: "description")` means that the attribute -/// supports forms `#[attr]` and `#[attr(description)]`. -macro_rules! template { - (Word) => { template!(@ true, None, None) }; - (List: $descr: expr) => { template!(@ false, Some($descr), None) }; - (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) }; - (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) }; - (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) }; - (List: $descr1: expr, NameValueStr: $descr2: expr) => { - template!(@ false, Some($descr1), Some($descr2)) - }; - (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => { - template!(@ true, Some($descr1), Some($descr2)) - }; - (@ $word: expr, $list: expr, $name_value_str: expr) => { - AttributeTemplate { - word: $word, list: $list, name_value_str: $name_value_str - } - }; -} - -macro_rules! ungated { - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)? $(,)?) => { - BuiltinAttribute { name: stringify!($attr), template: $tpl } - }; -} - -macro_rules! gated { - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $gate:ident, $msg:expr $(,)?) => { - BuiltinAttribute { name: stringify!($attr), template: $tpl } - }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => { - BuiltinAttribute { name: stringify!($attr), template: $tpl } - }; -} - -macro_rules! rustc_attr { - (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr $(, @only_local: $only_local:expr)? $(,)?) => { - rustc_attr!( - $attr, - $typ, - $tpl, - $duplicate, - $(@only_local: $only_local,)? - concat!( - "the `#[", - stringify!($attr), - "]` attribute is just used for rustc unit tests \ - and will never be stable", - ), - ) - }; - ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => { - BuiltinAttribute { name: stringify!($attr), template: $tpl } - }; -} - -#[allow(unused_macros)] -macro_rules! experimental { - ($attr:ident) => { - concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature") - }; -} - -/// Attributes that have a special meaning to rustc or rustdoc. -#[rustfmt::skip] -pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[ - // ========================================================================== - // Stable attributes: - // ========================================================================== - - // Conditional compilation: - ungated!(cfg, Normal, template!(List: "predicate"), DuplicatesOk), - ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), DuplicatesOk), - - // Testing: - ungated!(ignore, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing), - ungated!( - should_panic, Normal, - template!(Word, List: r#"expected = "reason""#, NameValueStr: "reason"), FutureWarnFollowing, - ), - // FIXME(Centril): This can be used on stable but shouldn't. - ungated!(reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing), - - // Macros: - ungated!(automatically_derived, Normal, template!(Word), WarnFollowing), - ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ..."), WarnFollowingWordOnly), - ungated!(macro_escape, Normal, template!(Word), WarnFollowing), // Deprecated synonym for `macro_use`. - ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros"), WarnFollowing), - ungated!(proc_macro, Normal, template!(Word), ErrorFollowing), - ungated!( - proc_macro_derive, Normal, - template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing, - ), - ungated!(proc_macro_attribute, Normal, template!(Word), ErrorFollowing), - - // Lints: - ungated!( - warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), - DuplicatesOk, @only_local: true, - ), - ungated!( - allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), - DuplicatesOk, @only_local: true, - ), - gated!( - expect, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk, - lint_reasons, experimental!(expect) - ), - ungated!( - forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), - DuplicatesOk, @only_local: true, - ), - ungated!( - deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), - DuplicatesOk, @only_local: true, - ), - ungated!(must_use, Normal, template!(Word, NameValueStr: "reason"), FutureWarnFollowing), - gated!( - must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, - experimental!(must_not_suspend) - ), - ungated!( - deprecated, Normal, - template!( - Word, - List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#, - NameValueStr: "reason" - ), - ErrorFollowing - ), - - // Crate properties: - ungated!(crate_name, CrateLevel, template!(NameValueStr: "name"), FutureWarnFollowing), - ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), DuplicatesOk), - // crate_id is deprecated - ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored"), FutureWarnFollowing), - - // ABI, linking, symbols, and FFI - ungated!( - link, Normal, - template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...", /*opt*/ import_name_type = "decorated|noprefix|undecorated""#), - DuplicatesOk, - ), - ungated!(link_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), - ungated!(no_link, Normal, template!(Word), WarnFollowing), - ungated!(repr, Normal, template!(List: "C"), DuplicatesOk, @only_local: true), - ungated!(export_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), - ungated!(link_section, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), - ungated!(no_mangle, Normal, template!(Word), WarnFollowing, @only_local: true), - ungated!(used, Normal, template!(Word, List: "compiler|linker"), WarnFollowing, @only_local: true), - ungated!(link_ordinal, Normal, template!(List: "ordinal"), ErrorPreceding), - - // Limits: - ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing), - ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing), - gated!( - move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing, - large_assignments, experimental!(move_size_limit) - ), - - // Entry point: - ungated!(start, Normal, template!(Word), WarnFollowing), - ungated!(no_start, CrateLevel, template!(Word), WarnFollowing), - ungated!(no_main, CrateLevel, template!(Word), WarnFollowing), - - // Modules, prelude, and resolution: - ungated!(path, Normal, template!(NameValueStr: "file"), FutureWarnFollowing), - ungated!(no_std, CrateLevel, template!(Word), WarnFollowing), - ungated!(no_implicit_prelude, Normal, template!(Word), WarnFollowing), - ungated!(non_exhaustive, Normal, template!(Word), WarnFollowing), - - // Runtime - ungated!( - windows_subsystem, CrateLevel, - template!(NameValueStr: "windows|console"), FutureWarnFollowing - ), - ungated!(panic_handler, Normal, template!(Word), WarnFollowing), // RFC 2070 - - // Code generation: - ungated!(inline, Normal, template!(Word, List: "always|never"), FutureWarnFollowing, @only_local: true), - ungated!(cold, Normal, template!(Word), WarnFollowing, @only_local: true), - ungated!(no_builtins, CrateLevel, template!(Word), WarnFollowing), - ungated!( - target_feature, Normal, template!(List: r#"enable = "name""#), - DuplicatesOk, @only_local: true, - ), - ungated!(track_caller, Normal, template!(Word), WarnFollowing), - ungated!(instruction_set, Normal, template!(List: "set"), ErrorPreceding), - gated!( - no_sanitize, Normal, - template!(List: "address, kcfi, memory, thread"), DuplicatesOk, - experimental!(no_sanitize) - ), - gated!(coverage, Normal, template!(Word, List: "on|off"), WarnFollowing, coverage_attribute, experimental!(coverage)), - - ungated!( - doc, Normal, template!(List: "hidden|inline|...", NameValueStr: "string"), DuplicatesOk - ), - - // Debugging - ungated!( - debugger_visualizer, Normal, - template!(List: r#"natvis_file = "...", gdb_script_file = "...""#), DuplicatesOk - ), - - // ========================================================================== - // Unstable attributes: - // ========================================================================== - - // Linking: - gated!( - naked, Normal, template!(Word), WarnFollowing, @only_local: true, - naked_functions, experimental!(naked) - ), - - // Testing: - gated!( - test_runner, CrateLevel, template!(List: "path"), ErrorFollowing, custom_test_frameworks, - "custom test frameworks are an unstable feature", - ), - // RFC #1268 - gated!( - marker, Normal, template!(Word), WarnFollowing, @only_local: true, - marker_trait_attr, experimental!(marker) - ), - gated!( - thread_local, Normal, template!(Word), WarnFollowing, - "`#[thread_local]` is an experimental feature, and does not currently handle destructors", - ), - gated!(no_core, CrateLevel, template!(Word), WarnFollowing, experimental!(no_core)), - // RFC 2412 - gated!( - optimize, Normal, template!(List: "size|speed"), ErrorPreceding, optimize_attribute, - experimental!(optimize), - ), - - gated!(ffi_pure, Normal, template!(Word), WarnFollowing, experimental!(ffi_pure)), - gated!(ffi_const, Normal, template!(Word), WarnFollowing, experimental!(ffi_const)), - gated!( - register_tool, CrateLevel, template!(List: "tool1, tool2, ..."), DuplicatesOk, - experimental!(register_tool), - ), - - gated!( - cmse_nonsecure_entry, Normal, template!(Word), WarnFollowing, - experimental!(cmse_nonsecure_entry) - ), - // RFC 2632 - gated!( - const_trait, Normal, template!(Word), WarnFollowing, const_trait_impl, - "`const_trait` is a temporary placeholder for marking a trait that is suitable for `const` \ - `impls` and all default bodies as `const`, which may be removed or renamed in the \ - future." - ), - // lang-team MCP 147 - gated!( - deprecated_safe, Normal, template!(List: r#"since = "version", note = "...""#), ErrorFollowing, - experimental!(deprecated_safe), - ), - - // `#[collapse_debuginfo]` - gated!( - collapse_debuginfo, Normal, template!(Word), WarnFollowing, - experimental!(collapse_debuginfo) - ), - - // RFC 2397 - gated!(do_not_recommend, Normal, template!(Word), WarnFollowing, experimental!(do_not_recommend)), - - // `#[cfi_encoding = ""]` - gated!( - cfi_encoding, Normal, template!(NameValueStr: "encoding"), ErrorPreceding, - experimental!(cfi_encoding) - ), - - // ========================================================================== - // Internal attributes: Stability, deprecation, and unsafe: - // ========================================================================== - - ungated!( - feature, CrateLevel, - template!(List: "name1, name2, ..."), DuplicatesOk, @only_local: true, - ), - // DuplicatesOk since it has its own validation - ungated!( - stable, Normal, - template!(List: r#"feature = "name", since = "version""#), DuplicatesOk, @only_local: true, - ), - ungated!( - unstable, Normal, - template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk, - ), - ungated!(rustc_const_unstable, Normal, template!(List: r#"feature = "name""#), DuplicatesOk), - ungated!( - rustc_const_stable, Normal, - template!(List: r#"feature = "name""#), DuplicatesOk, @only_local: true, - ), - ungated!( - rustc_default_body_unstable, Normal, - template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk - ), - gated!( - allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, - "allow_internal_unstable side-steps feature gating and stability checks", - ), - gated!( - rustc_allow_const_fn_unstable, Normal, - template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, - "rustc_allow_const_fn_unstable side-steps feature gating and stability checks" - ), - gated!( - allow_internal_unsafe, Normal, template!(Word), WarnFollowing, - "allow_internal_unsafe side-steps the unsafe_code lint", - ), - rustc_attr!(rustc_allowed_through_unstable_modules, Normal, template!(Word), WarnFollowing, - "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \ - through unstable paths"), - - // ========================================================================== - // Internal attributes: Type system related: - // ========================================================================== - - gated!(fundamental, Normal, template!(Word), WarnFollowing, experimental!(fundamental)), - gated!( - may_dangle, Normal, template!(Word), WarnFollowing, dropck_eyepatch, - "`may_dangle` has unstable semantics and may be removed in the future", - ), - - // ========================================================================== - // Internal attributes: Runtime related: - // ========================================================================== - - rustc_attr!(rustc_allocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - rustc_attr!(rustc_nounwind, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - rustc_attr!(rustc_reallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - rustc_attr!(rustc_deallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - rustc_attr!(rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - gated!( - default_lib_allocator, Normal, template!(Word), WarnFollowing, allocator_internals, - experimental!(default_lib_allocator), - ), - gated!( - needs_allocator, Normal, template!(Word), WarnFollowing, allocator_internals, - experimental!(needs_allocator), - ), - gated!(panic_runtime, Normal, template!(Word), WarnFollowing, experimental!(panic_runtime)), - gated!( - needs_panic_runtime, Normal, template!(Word), WarnFollowing, - experimental!(needs_panic_runtime) - ), - gated!( - compiler_builtins, Normal, template!(Word), WarnFollowing, - "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \ - which contains compiler-rt intrinsics and will never be stable", - ), - gated!( - profiler_runtime, Normal, template!(Word), WarnFollowing, - "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \ - which contains the profiler runtime and will never be stable", - ), - - // ========================================================================== - // Internal attributes, Linkage: - // ========================================================================== - - gated!( - linkage, Normal, template!(NameValueStr: "external|internal|..."), ErrorPreceding, @only_local: true, - "the `linkage` attribute is experimental and not portable across platforms", - ), - rustc_attr!( - rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing, @only_local: true, INTERNAL_UNSTABLE - ), - - // ========================================================================== - // Internal attributes, Macro related: - // ========================================================================== - - rustc_attr!( - rustc_builtin_macro, Normal, - template!(Word, List: "name, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing, - IMPL_DETAIL, - ), - rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), - rustc_attr!( - rustc_macro_transparency, Normal, - template!(NameValueStr: "transparent|semitransparent|opaque"), ErrorFollowing, - "used internally for testing macro hygiene", - ), - - // ========================================================================== - // Internal attributes, Diagnostics related: - // ========================================================================== - - rustc_attr!( - rustc_on_unimplemented, Normal, - template!( - List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#, - NameValueStr: "message" - ), - ErrorFollowing, - INTERNAL_UNSTABLE - ), - rustc_attr!( - rustc_confusables, Normal, - template!(List: r#""name1", "name2", ..."#), - ErrorFollowing, - INTERNAL_UNSTABLE, - ), - // Enumerates "identity-like" conversion methods to suggest on type mismatch. - rustc_attr!( - rustc_conversion_suggestion, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE - ), - // Prevents field reads in the marked trait or method to be considered - // during dead code analysis. - rustc_attr!( - rustc_trivial_field_reads, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE - ), - // Used by the `rustc::potential_query_instability` lint to warn methods which - // might not be stable during incremental compilation. - rustc_attr!(rustc_lint_query_instability, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), - // Used by the `rustc::untranslatable_diagnostic` and `rustc::diagnostic_outside_of_impl` lints - // to assist in changes to diagnostic APIs. - rustc_attr!(rustc_lint_diagnostics, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), - // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions` - // types (as well as any others in future). - rustc_attr!(rustc_lint_opt_ty, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), - // Used by the `rustc::bad_opt_access` lint on fields - // types (as well as any others in future). - rustc_attr!(rustc_lint_opt_deny_field_access, Normal, template!(List: "message"), WarnFollowing, INTERNAL_UNSTABLE), - - // ========================================================================== - // Internal attributes, Const related: - // ========================================================================== - - rustc_attr!(rustc_promotable, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), - rustc_attr!( - rustc_legacy_const_generics, Normal, template!(List: "N"), ErrorFollowing, - INTERNAL_UNSTABLE - ), - // Do not const-check this function's body. It will always get replaced during CTFE. - rustc_attr!( - rustc_do_not_const_check, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE - ), - // Ensure the argument to this function is &&str during const-check. - rustc_attr!( - rustc_const_panic_str, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE - ), - - // ========================================================================== - // Internal attributes, Layout related: - // ========================================================================== - - rustc_attr!( - rustc_layout_scalar_valid_range_start, Normal, template!(List: "value"), ErrorFollowing, - "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \ - niche optimizations in libcore and libstd and will never be stable", - ), - rustc_attr!( - rustc_layout_scalar_valid_range_end, Normal, template!(List: "value"), ErrorFollowing, - "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \ - niche optimizations in libcore and libstd and will never be stable", - ), - rustc_attr!( - rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing, - "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \ - niche optimizations in libcore and libstd and will never be stable", - ), - - // ========================================================================== - // Internal attributes, Misc: - // ========================================================================== - gated!( - lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, @only_local: true, lang_items, - "language items are subject to change", - ), - rustc_attr!( - rustc_pass_by_value, Normal, template!(Word), ErrorFollowing, - "#[rustc_pass_by_value] is used to mark types that must be passed by value instead of reference." - ), - rustc_attr!( - rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing, - "#[rustc_never_returns_null_ptr] is used to mark functions returning non-null pointers." - ), - rustc_attr!( - rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, @only_local: true, - "#![rustc_coherence_is_core] allows inherent methods on builtin types, only intended to be used in `core`." - ), - rustc_attr!( - rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, @only_local: true, - "#![rustc_coinductive] changes a trait to be coinductive, allowing cycles in the trait solver." - ), - rustc_attr!( - rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, @only_local: true, - "#[rustc_allow_incoherent_impl] has to be added to all impl items of an incoherent inherent impl." - ), - rustc_attr!( - rustc_deny_explicit_impl, - AttributeType::Normal, - template!(List: "implement_via_object = (true|false)"), - ErrorFollowing, - @only_local: true, - "#[rustc_deny_explicit_impl] enforces that a trait can have no user-provided impls" - ), - rustc_attr!( - rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word), ErrorFollowing, - "#[rustc_has_incoherent_inherent_impls] allows the addition of incoherent inherent impls for \ - the given type by annotating all impl items with #[rustc_allow_incoherent_impl]." - ), - rustc_attr!( - rustc_box, AttributeType::Normal, template!(Word), ErrorFollowing, - "#[rustc_box] allows creating boxes \ - and it is only intended to be used in `alloc`." - ), - - BuiltinAttribute { - // name: sym::rustc_diagnostic_item, - name: "rustc_diagnostic_item", - // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`. - // only_local: false, - // type_: Normal, - template: template!(NameValueStr: "name"), - // duplicates: ErrorFollowing, - // gate: Gated( - // Stability::Unstable, - // sym::rustc_attrs, - // "diagnostic items compiler internal support for linting", - // cfg_fn!(rustc_attrs), - // ), - }, - gated!( - // Used in resolve: - prelude_import, Normal, template!(Word), WarnFollowing, - "`#[prelude_import]` is for use by rustc only", - ), - gated!( - rustc_paren_sugar, Normal, template!(Word), WarnFollowing, unboxed_closures, - "unboxed_closures are still evolving", - ), - rustc_attr!( - rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, @only_local: true, - "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \ - overflow checking behavior of several libcore functions that are inlined \ - across crates and will never be stable", - ), - rustc_attr!( - rustc_reservation_impl, Normal, - template!(NameValueStr: "reservation message"), ErrorFollowing, - "the `#[rustc_reservation_impl]` attribute is internally used \ - for reserving for `for From for T` impl" - ), - rustc_attr!( - rustc_test_marker, Normal, template!(NameValueStr: "name"), WarnFollowing, - "the `#[rustc_test_marker]` attribute is used internally to track tests", - ), - rustc_attr!( - rustc_unsafe_specialization_marker, Normal, template!(Word), WarnFollowing, - "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations" - ), - rustc_attr!( - rustc_specialization_trait, Normal, template!(Word), WarnFollowing, - "the `#[rustc_specialization_trait]` attribute is used to check specializations" - ), - rustc_attr!( - rustc_main, Normal, template!(Word), WarnFollowing, - "the `#[rustc_main]` attribute is used internally to specify test entry point function", - ), - rustc_attr!( - rustc_skip_array_during_method_dispatch, Normal, template!(Word), WarnFollowing, - "the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \ - from method dispatch when the receiver is an array, for compatibility in editions < 2021." - ), - rustc_attr!( - rustc_must_implement_one_of, Normal, template!(List: "function1, function2, ..."), ErrorFollowing, - "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \ - definition of a trait, it's currently in experimental form and should be changed before \ - being exposed outside of the std" - ), - rustc_attr!( - rustc_doc_primitive, Normal, template!(NameValueStr: "primitive name"), ErrorFollowing, - r#"`rustc_doc_primitive` is a rustc internal attribute"#, - ), - rustc_attr!( - rustc_safe_intrinsic, Normal, template!(Word), WarnFollowing, - "the `#[rustc_safe_intrinsic]` attribute is used internally to mark intrinsics as safe" - ), - rustc_attr!( - rustc_deprecated_safe_2024, Normal, template!(Word), WarnFollowing, - "the `#[rustc_safe_intrinsic]` marks functions as unsafe in Rust 2024", - ), - - // ========================================================================== - // Internal attributes, Testing: - // ========================================================================== - - rustc_attr!(TEST, rustc_effective_visibility, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_outlives, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_capture_analysis, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_insignificant_dtor, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_strict_coherence, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_variance, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_variance_of_opaques, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_hidden_type_of_opaques, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ..."), WarnFollowing), - rustc_attr!(TEST, rustc_abi, Normal, template!(List: "field1, field2, ..."), WarnFollowing), - rustc_attr!(TEST, rustc_regions, Normal, template!(Word), WarnFollowing), - rustc_attr!( - TEST, rustc_error, Normal, - template!(Word, List: "delayed_bug_from_inside_query"), WarnFollowingWordOnly - ), - rustc_attr!(TEST, rustc_dump_user_args, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing), - rustc_attr!( - TEST, rustc_if_this_changed, Normal, template!(Word, List: "DepNode"), DuplicatesOk - ), - rustc_attr!( - TEST, rustc_then_this_would_need, Normal, template!(List: "DepNode"), DuplicatesOk - ), - rustc_attr!( - TEST, rustc_clean, Normal, - template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#), - DuplicatesOk, - ), - rustc_attr!( - TEST, rustc_partition_reused, Normal, - template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk, - ), - rustc_attr!( - TEST, rustc_partition_codegened, Normal, - template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk, - ), - rustc_attr!( - TEST, rustc_expected_cgu_reuse, Normal, - template!(List: r#"cfg = "...", module = "...", kind = "...""#), DuplicatesOk, - ), - rustc_attr!(TEST, rustc_symbol_name, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_polymorphize_error, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_def_path, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_mir, Normal, template!(List: "arg1, arg2, ..."), DuplicatesOk), - gated!( - custom_mir, Normal, template!(List: r#"dialect = "...", phase = "...""#), - ErrorFollowing, "the `#[custom_mir]` attribute is just used for the Rust test suite", - ), - rustc_attr!(TEST, rustc_dump_program_clauses, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_dump_env_program_clauses, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_object_lifetime_default, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_dump_vtable, Normal, template!(Word), WarnFollowing), - rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/), DuplicatesOk), - gated!( - omit_gdb_pretty_printer_section, Normal, template!(Word), WarnFollowing, - "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite", - ), -]; diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attr/tests.rs b/src/tools/rust-analyzer/crates/hir-def/src/attr/tests.rs deleted file mode 100644 index 727f4429802..00000000000 --- a/src/tools/rust-analyzer/crates/hir-def/src/attr/tests.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! This module contains tests for doc-expression parsing. -//! Currently, it tests `#[doc(hidden)]` and `#[doc(alias)]`. - -use triomphe::Arc; - -use base_db::FileId; -use hir_expand::span_map::{RealSpanMap, SpanMap}; -use mbe::{syntax_node_to_token_tree, DocCommentDesugarMode}; -use syntax::{ast, AstNode, TextRange}; - -use crate::attr::{DocAtom, DocExpr}; - -fn assert_parse_result(input: &str, expected: DocExpr) { - let source_file = ast::SourceFile::parse(input, span::Edition::CURRENT).ok().unwrap(); - let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); - let map = SpanMap::RealSpanMap(Arc::new(RealSpanMap::absolute(FileId::from_raw(0)))); - let tt = syntax_node_to_token_tree( - tt.syntax(), - map.as_ref(), - map.span_for_range(TextRange::empty(0.into())), - DocCommentDesugarMode::ProcMacro, - ); - let cfg = DocExpr::parse(&tt); - assert_eq!(cfg, expected); -} - -#[test] -fn test_doc_expr_parser() { - assert_parse_result("#![doc(hidden)]", DocAtom::Flag("hidden".into()).into()); - - assert_parse_result( - r#"#![doc(alias = "foo")]"#, - DocAtom::KeyValue { key: "alias".into(), value: "foo".into() }.into(), - ); - - assert_parse_result(r#"#![doc(alias("foo"))]"#, DocExpr::Alias(["foo".into()].into())); - assert_parse_result( - r#"#![doc(alias("foo", "bar", "baz"))]"#, - DocExpr::Alias(["foo".into(), "bar".into(), "baz".into()].into()), - ); - - assert_parse_result( - r#" - #[doc(alias("Bar", "Qux"))] - struct Foo;"#, - DocExpr::Alias(["Bar".into(), "Qux".into()].into()), - ); -} diff --git a/src/tools/rust-analyzer/crates/hir-def/src/data.rs b/src/tools/rust-analyzer/crates/hir-def/src/data.rs index 51a4dd6f42a..0a7ca199109 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/data.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/data.rs @@ -642,7 +642,7 @@ impl<'a> AssocItemCollector<'a> { continue 'attrs; } let loc = self.db.lookup_intern_macro_call(call_id); - if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind { + if let MacroDefKind::ProcMacro(_, exp, _) = loc.def.kind { // If there's no expander for the proc macro (e.g. the // proc macro is ignored, or building the proc macro // crate failed), skip expansion like we would if it was diff --git a/src/tools/rust-analyzer/crates/hir-def/src/db.rs b/src/tools/rust-analyzer/crates/hir-def/src/db.rs index 55ecabdc38e..61fed71218e 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/db.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/db.rs @@ -294,10 +294,10 @@ fn macro_def(db: &dyn DefDatabase, id: MacroId) -> MacroDefId { let in_file = InFile::new(file_id, m); match expander { MacroExpander::Declarative => MacroDefKind::Declarative(in_file), - MacroExpander::BuiltIn(it) => MacroDefKind::BuiltIn(it, in_file), - MacroExpander::BuiltInAttr(it) => MacroDefKind::BuiltInAttr(it, in_file), - MacroExpander::BuiltInDerive(it) => MacroDefKind::BuiltInDerive(it, in_file), - MacroExpander::BuiltInEager(it) => MacroDefKind::BuiltInEager(it, in_file), + MacroExpander::BuiltIn(it) => MacroDefKind::BuiltIn(in_file, it), + MacroExpander::BuiltInAttr(it) => MacroDefKind::BuiltInAttr(in_file, it), + MacroExpander::BuiltInDerive(it) => MacroDefKind::BuiltInDerive(in_file, it), + MacroExpander::BuiltInEager(it) => MacroDefKind::BuiltInEager(in_file, it), } }; @@ -338,9 +338,9 @@ fn macro_def(db: &dyn DefDatabase, id: MacroId) -> MacroDefId { MacroDefId { krate: loc.container.krate, kind: MacroDefKind::ProcMacro( + InFile::new(loc.id.file_id(), makro.ast_id), loc.expander, loc.kind, - InFile::new(loc.id.file_id(), makro.ast_id), ), local_inner: false, allow_internal_unsafe: false, diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/attr_resolution.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/attr_resolution.rs index 3cb0666edf9..5829887c454 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/attr_resolution.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/attr_resolution.rs @@ -3,6 +3,7 @@ use base_db::CrateId; use hir_expand::{ attrs::{Attr, AttrId, AttrInput}, + inert_attr_macro::find_builtin_attr_idx, MacroCallId, MacroCallKind, MacroDefId, }; use span::SyntaxContextId; @@ -10,7 +11,6 @@ use syntax::{ast, SmolStr}; use triomphe::Arc; use crate::{ - attr::builtin::find_builtin_attr_idx, db::DefDatabase, item_scope::BuiltinShadowMode, nameres::path_resolution::ResolveMode, @@ -89,9 +89,12 @@ impl DefMap { } if segments.len() == 1 { - let mut registered = self.data.registered_attrs.iter().map(SmolStr::as_str); - let is_inert = find_builtin_attr_idx(&name).is_some() || registered.any(pred); - return is_inert; + if find_builtin_attr_idx(&name).is_some() { + return true; + } + if self.data.registered_attrs.iter().map(SmolStr::as_str).any(pred) { + return true; + } } } false diff --git a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs index 587997c4736..ba8c6ba645e 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/nameres/collector.rs @@ -10,7 +10,7 @@ use cfg::{CfgExpr, CfgOptions}; use either::Either; use hir_expand::{ attrs::{Attr, AttrId}, - builtin_attr_macro::{find_builtin_attr, BuiltinAttrExpander}, + builtin_attr_macro::find_builtin_attr, builtin_derive_macro::find_builtin_derive, builtin_fn_macro::find_builtin_macro, name::{name, AsName, Name}, @@ -270,6 +270,7 @@ struct DefCollector<'a> { /// /// This also stores the attributes to skip when we resolve derive helpers and non-macro /// non-builtin attributes in general. + // FIXME: There has to be a better way to do this skip_attrs: FxHashMap, AttrId>, } @@ -1255,17 +1256,23 @@ impl DefCollector<'_> { _ => return Resolved::No, }; - let call_id = - attr_macro_as_call_id(self.db, file_ast_id, attr, self.def_map.krate, def); - if let MacroDefId { - kind: - MacroDefKind::BuiltInAttr( - BuiltinAttrExpander::Derive | BuiltinAttrExpander::DeriveConst, - _, - ), - .. - } = def - { + // Skip #[test]/#[bench] expansion, which would merely result in more memory usage + // due to duplicating functions into macro expansions + if matches!( + def.kind, + MacroDefKind::BuiltInAttr(_, expander) + if expander.is_test() || expander.is_bench() + ) { + return recollect_without(self); + } + + let call_id = || { + attr_macro_as_call_id(self.db, file_ast_id, attr, self.def_map.krate, def) + }; + if matches!(def, + MacroDefId { kind: MacroDefKind::BuiltInAttr(_, exp), .. } + if exp.is_derive() + ) { // Resolved to `#[derive]`, we don't actually expand this attribute like // normal (as that would just be an identity expansion with extra output) // Instead we treat derive attributes special and apply them separately. @@ -1290,6 +1297,7 @@ impl DefCollector<'_> { match attr.parse_path_comma_token_tree(self.db.upcast()) { Some(derive_macros) => { + let call_id = call_id(); let mut len = 0; for (idx, (path, call_site)) in derive_macros.enumerate() { let ast_id = AstIdWithPath::new(file_id, ast_id.value, path); @@ -1312,13 +1320,6 @@ impl DefCollector<'_> { // This is just a trick to be able to resolve the input to derives // as proper paths in `Semantics`. // Check the comment in [`builtin_attr_macro`]. - let call_id = attr_macro_as_call_id( - self.db, - file_ast_id, - attr, - self.def_map.krate, - def, - ); self.def_map.modules[directive.module_id] .scope .init_derive_attribute(ast_id, attr.id, call_id, len + 1); @@ -1336,17 +1337,8 @@ impl DefCollector<'_> { return recollect_without(self); } - // Skip #[test]/#[bench] expansion, which would merely result in more memory usage - // due to duplicating functions into macro expansions - if matches!( - def.kind, - MacroDefKind::BuiltInAttr(expander, _) - if expander.is_test() || expander.is_bench() - ) { - return recollect_without(self); - } - - if let MacroDefKind::ProcMacro(exp, ..) = def.kind { + let call_id = call_id(); + if let MacroDefKind::ProcMacro(_, exp, _) = def.kind { // If proc attribute macro expansion is disabled, skip expanding it here if !self.db.expand_proc_attr_macros() { self.def_map.diagnostics.push(DefDiagnostic::unresolved_proc_macro( diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/builtin_attr_macro.rs b/src/tools/rust-analyzer/crates/hir-expand/src/builtin_attr_macro.rs index 9ff29b484d3..2e115f47932 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/builtin_attr_macro.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/builtin_attr_macro.rs @@ -52,8 +52,6 @@ impl BuiltinAttrExpander { register_builtin! { (bench, Bench) => dummy_attr_expand, - (cfg, Cfg) => dummy_attr_expand, - (cfg_attr, CfgAttr) => dummy_attr_expand, (cfg_accessible, CfgAccessible) => dummy_attr_expand, (cfg_eval, CfgEval) => dummy_attr_expand, (derive, Derive) => derive_expand, diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs b/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs index 9dd44262ba9..55ae19068f9 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/cfg_process.rs @@ -189,8 +189,8 @@ pub(crate) fn process_cfg_attrs( // FIXME: #[cfg_eval] is not implemented. But it is not stable yet let is_derive = match loc.def.kind { MacroDefKind::BuiltInDerive(..) - | MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _) => true, - MacroDefKind::BuiltInAttr(expander, _) => expander.is_derive(), + | MacroDefKind::ProcMacro(_, _, ProcMacroKind::CustomDerive) => true, + MacroDefKind::BuiltInAttr(_, expander) => expander.is_derive(), _ => false, }; if !is_derive { diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/db.rs b/src/tools/rust-analyzer/crates/hir-expand/src/db.rs index 12421bbe702..8b49a6877a2 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/db.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/db.rs @@ -252,7 +252,7 @@ pub fn expand_speculative( // Otherwise the expand query will fetch the non speculative attribute args and pass those instead. let mut speculative_expansion = match loc.def.kind { - MacroDefKind::ProcMacro(expander, _, ast) => { + MacroDefKind::ProcMacro(ast, expander, _) => { let span = db.proc_macro_span(ast); tt.delimiter = tt::Delimiter::invisible_spanned(span); expander.expand( @@ -266,22 +266,22 @@ pub fn expand_speculative( span_with_mixed_site_ctxt(db, span, actual_macro_call), ) } - MacroDefKind::BuiltInAttr(BuiltinAttrExpander::Derive, _) => { + MacroDefKind::BuiltInAttr(_, it) if it.is_derive() => { pseudo_derive_attr_expansion(&tt, attr_arg.as_ref()?, span) } MacroDefKind::Declarative(it) => db .decl_macro_expander(loc.krate, it) .expand_unhygienic(db, tt, loc.def.krate, span, loc.def.edition), - MacroDefKind::BuiltIn(it, _) => { + MacroDefKind::BuiltIn(_, it) => { it.expand(db, actual_macro_call, &tt, span).map_err(Into::into) } - MacroDefKind::BuiltInDerive(it, ..) => { + MacroDefKind::BuiltInDerive(_, it) => { it.expand(db, actual_macro_call, &tt, span).map_err(Into::into) } - MacroDefKind::BuiltInEager(it, _) => { + MacroDefKind::BuiltInEager(_, it) => { it.expand(db, actual_macro_call, &tt, span).map_err(Into::into) } - MacroDefKind::BuiltInAttr(it, _) => it.expand(db, actual_macro_call, &tt, span), + MacroDefKind::BuiltInAttr(_, it) => it.expand(db, actual_macro_call, &tt, span), }; let expand_to = loc.expand_to(); @@ -493,7 +493,7 @@ fn macro_arg(db: &dyn ExpandDatabase, id: MacroCallId) -> MacroArgResult { .map_or_else(|| node.syntax().text_range(), |it| it.syntax().text_range()), ); // If derive attribute we need to censor the derive input - if matches!(loc.def.kind, MacroDefKind::BuiltInAttr(expander, ..) if expander.is_derive()) + if matches!(loc.def.kind, MacroDefKind::BuiltInAttr(_, expander) if expander.is_derive()) && ast::Adt::can_cast(node.syntax().kind()) { let adt = ast::Adt::cast(node.syntax().clone()).unwrap(); @@ -569,11 +569,11 @@ impl TokenExpander { MacroDefKind::Declarative(ast_id) => { TokenExpander::DeclarativeMacro(db.decl_macro_expander(id.krate, ast_id)) } - MacroDefKind::BuiltIn(expander, _) => TokenExpander::BuiltIn(expander), - MacroDefKind::BuiltInAttr(expander, _) => TokenExpander::BuiltInAttr(expander), - MacroDefKind::BuiltInDerive(expander, _) => TokenExpander::BuiltInDerive(expander), - MacroDefKind::BuiltInEager(expander, ..) => TokenExpander::BuiltInEager(expander), - MacroDefKind::ProcMacro(expander, ..) => TokenExpander::ProcMacro(expander), + MacroDefKind::BuiltIn(_, expander) => TokenExpander::BuiltIn(expander), + MacroDefKind::BuiltInAttr(_, expander) => TokenExpander::BuiltInAttr(expander), + MacroDefKind::BuiltInDerive(_, expander) => TokenExpander::BuiltInDerive(expander), + MacroDefKind::BuiltInEager(_, expander) => TokenExpander::BuiltInEager(expander), + MacroDefKind::ProcMacro(_, expander, _) => TokenExpander::ProcMacro(expander), } } } @@ -604,13 +604,13 @@ fn macro_expand( MacroDefKind::Declarative(id) => db .decl_macro_expander(loc.def.krate, id) .expand(db, arg.clone(), macro_call_id, span), - MacroDefKind::BuiltIn(it, _) => { + MacroDefKind::BuiltIn(_, it) => { it.expand(db, macro_call_id, arg, span).map_err(Into::into).zip_val(None) } - MacroDefKind::BuiltInDerive(it, _) => { + MacroDefKind::BuiltInDerive(_, it) => { it.expand(db, macro_call_id, arg, span).map_err(Into::into).zip_val(None) } - MacroDefKind::BuiltInEager(it, _) => { + MacroDefKind::BuiltInEager(_, it) => { // This might look a bit odd, but we do not expand the inputs to eager macros here. // Eager macros inputs are expanded, well, eagerly when we collect the macro calls. // That kind of expansion uses the ast id map of an eager macros input though which goes through @@ -634,12 +634,12 @@ fn macro_expand( } res.zip_val(None) } - MacroDefKind::BuiltInAttr(it, _) => { + MacroDefKind::BuiltInAttr(_, it) => { let mut res = it.expand(db, macro_call_id, arg, span); fixup::reverse_fixups(&mut res.value, &undo_info); res.zip_val(None) } - _ => unreachable!(), + MacroDefKind::ProcMacro(_, _, _) => unreachable!(), }; (ExpandResult { value: res.value, err: res.err }, span) } @@ -678,8 +678,8 @@ fn expand_proc_macro(db: &dyn ExpandDatabase, id: MacroCallId) -> ExpandResult (expander, ast), + let (ast, expander) = match loc.def.kind { + MacroDefKind::ProcMacro(ast, expander, _) => (ast, expander), _ => unreachable!(), }; diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/inert_attr_macro.rs b/src/tools/rust-analyzer/crates/hir-expand/src/inert_attr_macro.rs new file mode 100644 index 00000000000..35fd85bf451 --- /dev/null +++ b/src/tools/rust-analyzer/crates/hir-expand/src/inert_attr_macro.rs @@ -0,0 +1,692 @@ +//! Builtin attributes resolved by nameres. +//! +//! The actual definitions were copied from rustc's `compiler/rustc_feature/src/builtin_attrs.rs`. +//! +//! It was last synchronized with upstream commit c3def263a44e07e09ae6d57abfc8650227fb4972. +//! +//! The macros were adjusted to only expand to the attribute name, since that is all we need to do +//! name resolution, and `BUILTIN_ATTRIBUTES` is almost entirely unchanged from the original, to +//! ease updating. + +use std::sync::OnceLock; + +use rustc_hash::FxHashMap; + +pub struct BuiltinAttribute { + pub name: &'static str, + pub template: AttributeTemplate, +} + +/// A template that the attribute input must match. +/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now. +#[derive(Clone, Copy)] +pub struct AttributeTemplate { + pub word: bool, + pub list: Option<&'static str>, + pub name_value_str: Option<&'static str>, +} + +pub fn find_builtin_attr_idx(name: &str) -> Option { + static BUILTIN_LOOKUP_TABLE: OnceLock> = OnceLock::new(); + BUILTIN_LOOKUP_TABLE + .get_or_init(|| { + INERT_ATTRIBUTES.iter().map(|attr| attr.name).enumerate().map(|(a, b)| (b, a)).collect() + }) + .get(name) + .copied() +} + +/// A convenience macro for constructing attribute templates. +/// E.g., `template!(Word, List: "description")` means that the attribute +/// supports forms `#[attr]` and `#[attr(description)]`. +macro_rules! template { + (Word) => { template!(@ true, None, None) }; + (List: $descr: expr) => { template!(@ false, Some($descr), None) }; + (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) }; + (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) }; + (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) }; + (List: $descr1: expr, NameValueStr: $descr2: expr) => { + template!(@ false, Some($descr1), Some($descr2)) + }; + (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => { + template!(@ true, Some($descr1), Some($descr2)) + }; + (@ $word: expr, $list: expr, $name_value_str: expr) => { + AttributeTemplate { + word: $word, list: $list, name_value_str: $name_value_str + } + }; +} + +macro_rules! ungated { + ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)? $(,)?) => { + BuiltinAttribute { name: stringify!($attr), template: $tpl } + }; +} + +macro_rules! gated { + ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $gate:ident, $msg:expr $(,)?) => { + BuiltinAttribute { name: stringify!($attr), template: $tpl } + }; + ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => { + BuiltinAttribute { name: stringify!($attr), template: $tpl } + }; +} + +macro_rules! rustc_attr { + (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr $(, @only_local: $only_local:expr)? $(,)?) => { + rustc_attr!( + $attr, + $typ, + $tpl, + $duplicate, + $(@only_local: $only_local,)? + concat!( + "the `#[", + stringify!($attr), + "]` attribute is just used for rustc unit tests \ + and will never be stable", + ), + ) + }; + ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => { + BuiltinAttribute { name: stringify!($attr), template: $tpl } + }; +} + +#[allow(unused_macros)] +macro_rules! experimental { + ($attr:ident) => { + concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature") + }; +} + +/// Attributes that have a special meaning to rustc or rustdoc. +#[rustfmt::skip] +pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[ + // ========================================================================== + // Stable attributes: + // ========================================================================== + + // Conditional compilation: + ungated!(cfg, Normal, template!(List: "predicate"), DuplicatesOk), + ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), DuplicatesOk), + + // Testing: + ungated!(ignore, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing), + ungated!( + should_panic, Normal, + template!(Word, List: r#"expected = "reason""#, NameValueStr: "reason"), FutureWarnFollowing, + ), + // FIXME(Centril): This can be used on stable but shouldn't. + ungated!(reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing), + + // Macros: + ungated!(automatically_derived, Normal, template!(Word), WarnFollowing), + ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ..."), WarnFollowingWordOnly), + ungated!(macro_escape, Normal, template!(Word), WarnFollowing), // Deprecated synonym for `macro_use`. + ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros"), WarnFollowing), + ungated!(proc_macro, Normal, template!(Word), ErrorFollowing), + ungated!( + proc_macro_derive, Normal, + template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing, + ), + ungated!(proc_macro_attribute, Normal, template!(Word), ErrorFollowing), + + // Lints: + ungated!( + warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), + DuplicatesOk, @only_local: true, + ), + ungated!( + allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), + DuplicatesOk, @only_local: true, + ), + gated!( + expect, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk, + lint_reasons, experimental!(expect) + ), + ungated!( + forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), + DuplicatesOk, @only_local: true, + ), + ungated!( + deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), + DuplicatesOk, @only_local: true, + ), + ungated!(must_use, Normal, template!(Word, NameValueStr: "reason"), FutureWarnFollowing), + gated!( + must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, + experimental!(must_not_suspend) + ), + ungated!( + deprecated, Normal, + template!( + Word, + List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#, + NameValueStr: "reason" + ), + ErrorFollowing + ), + + // Crate properties: + ungated!(crate_name, CrateLevel, template!(NameValueStr: "name"), FutureWarnFollowing), + ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), DuplicatesOk), + // crate_id is deprecated + ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored"), FutureWarnFollowing), + + // ABI, linking, symbols, and FFI + ungated!( + link, Normal, + template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...", /*opt*/ import_name_type = "decorated|noprefix|undecorated""#), + DuplicatesOk, + ), + ungated!(link_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), + ungated!(no_link, Normal, template!(Word), WarnFollowing), + ungated!(repr, Normal, template!(List: "C"), DuplicatesOk, @only_local: true), + ungated!(export_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), + ungated!(link_section, Normal, template!(NameValueStr: "name"), FutureWarnPreceding), + ungated!(no_mangle, Normal, template!(Word), WarnFollowing, @only_local: true), + ungated!(used, Normal, template!(Word, List: "compiler|linker"), WarnFollowing, @only_local: true), + ungated!(link_ordinal, Normal, template!(List: "ordinal"), ErrorPreceding), + + // Limits: + ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing), + ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing), + gated!( + move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing, + large_assignments, experimental!(move_size_limit) + ), + + // Entry point: + ungated!(start, Normal, template!(Word), WarnFollowing), + ungated!(no_start, CrateLevel, template!(Word), WarnFollowing), + ungated!(no_main, CrateLevel, template!(Word), WarnFollowing), + + // Modules, prelude, and resolution: + ungated!(path, Normal, template!(NameValueStr: "file"), FutureWarnFollowing), + ungated!(no_std, CrateLevel, template!(Word), WarnFollowing), + ungated!(no_implicit_prelude, Normal, template!(Word), WarnFollowing), + ungated!(non_exhaustive, Normal, template!(Word), WarnFollowing), + + // Runtime + ungated!( + windows_subsystem, CrateLevel, + template!(NameValueStr: "windows|console"), FutureWarnFollowing + ), + ungated!(panic_handler, Normal, template!(Word), WarnFollowing), // RFC 2070 + + // Code generation: + ungated!(inline, Normal, template!(Word, List: "always|never"), FutureWarnFollowing, @only_local: true), + ungated!(cold, Normal, template!(Word), WarnFollowing, @only_local: true), + ungated!(no_builtins, CrateLevel, template!(Word), WarnFollowing), + ungated!( + target_feature, Normal, template!(List: r#"enable = "name""#), + DuplicatesOk, @only_local: true, + ), + ungated!(track_caller, Normal, template!(Word), WarnFollowing), + ungated!(instruction_set, Normal, template!(List: "set"), ErrorPreceding), + gated!( + no_sanitize, Normal, + template!(List: "address, kcfi, memory, thread"), DuplicatesOk, + experimental!(no_sanitize) + ), + gated!(coverage, Normal, template!(Word, List: "on|off"), WarnFollowing, coverage_attribute, experimental!(coverage)), + + ungated!( + doc, Normal, template!(List: "hidden|inline|...", NameValueStr: "string"), DuplicatesOk + ), + + // Debugging + ungated!( + debugger_visualizer, Normal, + template!(List: r#"natvis_file = "...", gdb_script_file = "...""#), DuplicatesOk + ), + + // ========================================================================== + // Unstable attributes: + // ========================================================================== + + // Linking: + gated!( + naked, Normal, template!(Word), WarnFollowing, @only_local: true, + naked_functions, experimental!(naked) + ), + + // Testing: + gated!( + test_runner, CrateLevel, template!(List: "path"), ErrorFollowing, custom_test_frameworks, + "custom test frameworks are an unstable feature", + ), + // RFC #1268 + gated!( + marker, Normal, template!(Word), WarnFollowing, @only_local: true, + marker_trait_attr, experimental!(marker) + ), + gated!( + thread_local, Normal, template!(Word), WarnFollowing, + "`#[thread_local]` is an experimental feature, and does not currently handle destructors", + ), + gated!(no_core, CrateLevel, template!(Word), WarnFollowing, experimental!(no_core)), + // RFC 2412 + gated!( + optimize, Normal, template!(List: "size|speed"), ErrorPreceding, optimize_attribute, + experimental!(optimize), + ), + + gated!(ffi_pure, Normal, template!(Word), WarnFollowing, experimental!(ffi_pure)), + gated!(ffi_const, Normal, template!(Word), WarnFollowing, experimental!(ffi_const)), + gated!( + register_tool, CrateLevel, template!(List: "tool1, tool2, ..."), DuplicatesOk, + experimental!(register_tool), + ), + + gated!( + cmse_nonsecure_entry, Normal, template!(Word), WarnFollowing, + experimental!(cmse_nonsecure_entry) + ), + // RFC 2632 + gated!( + const_trait, Normal, template!(Word), WarnFollowing, const_trait_impl, + "`const_trait` is a temporary placeholder for marking a trait that is suitable for `const` \ + `impls` and all default bodies as `const`, which may be removed or renamed in the \ + future." + ), + // lang-team MCP 147 + gated!( + deprecated_safe, Normal, template!(List: r#"since = "version", note = "...""#), ErrorFollowing, + experimental!(deprecated_safe), + ), + + // `#[collapse_debuginfo]` + gated!( + collapse_debuginfo, Normal, template!(Word), WarnFollowing, + experimental!(collapse_debuginfo) + ), + + // RFC 2397 + gated!(do_not_recommend, Normal, template!(Word), WarnFollowing, experimental!(do_not_recommend)), + + // `#[cfi_encoding = ""]` + gated!( + cfi_encoding, Normal, template!(NameValueStr: "encoding"), ErrorPreceding, + experimental!(cfi_encoding) + ), + + // ========================================================================== + // Internal attributes: Stability, deprecation, and unsafe: + // ========================================================================== + + ungated!( + feature, CrateLevel, + template!(List: "name1, name2, ..."), DuplicatesOk, @only_local: true, + ), + // DuplicatesOk since it has its own validation + ungated!( + stable, Normal, + template!(List: r#"feature = "name", since = "version""#), DuplicatesOk, @only_local: true, + ), + ungated!( + unstable, Normal, + template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk, + ), + ungated!(rustc_const_unstable, Normal, template!(List: r#"feature = "name""#), DuplicatesOk), + ungated!( + rustc_const_stable, Normal, + template!(List: r#"feature = "name""#), DuplicatesOk, @only_local: true, + ), + ungated!( + rustc_default_body_unstable, Normal, + template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk + ), + gated!( + allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, + "allow_internal_unstable side-steps feature gating and stability checks", + ), + gated!( + rustc_allow_const_fn_unstable, Normal, + template!(Word, List: "feat1, feat2, ..."), DuplicatesOk, + "rustc_allow_const_fn_unstable side-steps feature gating and stability checks" + ), + gated!( + allow_internal_unsafe, Normal, template!(Word), WarnFollowing, + "allow_internal_unsafe side-steps the unsafe_code lint", + ), + rustc_attr!(rustc_allowed_through_unstable_modules, Normal, template!(Word), WarnFollowing, + "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \ + through unstable paths"), + + // ========================================================================== + // Internal attributes: Type system related: + // ========================================================================== + + gated!(fundamental, Normal, template!(Word), WarnFollowing, experimental!(fundamental)), + gated!( + may_dangle, Normal, template!(Word), WarnFollowing, dropck_eyepatch, + "`may_dangle` has unstable semantics and may be removed in the future", + ), + + // ========================================================================== + // Internal attributes: Runtime related: + // ========================================================================== + + rustc_attr!(rustc_allocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + rustc_attr!(rustc_nounwind, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + rustc_attr!(rustc_reallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + rustc_attr!(rustc_deallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + rustc_attr!(rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + gated!( + default_lib_allocator, Normal, template!(Word), WarnFollowing, allocator_internals, + experimental!(default_lib_allocator), + ), + gated!( + needs_allocator, Normal, template!(Word), WarnFollowing, allocator_internals, + experimental!(needs_allocator), + ), + gated!(panic_runtime, Normal, template!(Word), WarnFollowing, experimental!(panic_runtime)), + gated!( + needs_panic_runtime, Normal, template!(Word), WarnFollowing, + experimental!(needs_panic_runtime) + ), + gated!( + compiler_builtins, Normal, template!(Word), WarnFollowing, + "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \ + which contains compiler-rt intrinsics and will never be stable", + ), + gated!( + profiler_runtime, Normal, template!(Word), WarnFollowing, + "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \ + which contains the profiler runtime and will never be stable", + ), + + // ========================================================================== + // Internal attributes, Linkage: + // ========================================================================== + + gated!( + linkage, Normal, template!(NameValueStr: "external|internal|..."), ErrorPreceding, @only_local: true, + "the `linkage` attribute is experimental and not portable across platforms", + ), + rustc_attr!( + rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing, @only_local: true, INTERNAL_UNSTABLE + ), + + // ========================================================================== + // Internal attributes, Macro related: + // ========================================================================== + + rustc_attr!( + rustc_builtin_macro, Normal, + template!(Word, List: "name, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing, + IMPL_DETAIL, + ), + rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), + rustc_attr!( + rustc_macro_transparency, Normal, + template!(NameValueStr: "transparent|semitransparent|opaque"), ErrorFollowing, + "used internally for testing macro hygiene", + ), + + // ========================================================================== + // Internal attributes, Diagnostics related: + // ========================================================================== + + rustc_attr!( + rustc_on_unimplemented, Normal, + template!( + List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#, + NameValueStr: "message" + ), + ErrorFollowing, + INTERNAL_UNSTABLE + ), + rustc_attr!( + rustc_confusables, Normal, + template!(List: r#""name1", "name2", ..."#), + ErrorFollowing, + INTERNAL_UNSTABLE, + ), + // Enumerates "identity-like" conversion methods to suggest on type mismatch. + rustc_attr!( + rustc_conversion_suggestion, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE + ), + // Prevents field reads in the marked trait or method to be considered + // during dead code analysis. + rustc_attr!( + rustc_trivial_field_reads, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE + ), + // Used by the `rustc::potential_query_instability` lint to warn methods which + // might not be stable during incremental compilation. + rustc_attr!(rustc_lint_query_instability, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), + // Used by the `rustc::untranslatable_diagnostic` and `rustc::diagnostic_outside_of_impl` lints + // to assist in changes to diagnostic APIs. + rustc_attr!(rustc_lint_diagnostics, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), + // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions` + // types (as well as any others in future). + rustc_attr!(rustc_lint_opt_ty, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE), + // Used by the `rustc::bad_opt_access` lint on fields + // types (as well as any others in future). + rustc_attr!(rustc_lint_opt_deny_field_access, Normal, template!(List: "message"), WarnFollowing, INTERNAL_UNSTABLE), + + // ========================================================================== + // Internal attributes, Const related: + // ========================================================================== + + rustc_attr!(rustc_promotable, Normal, template!(Word), WarnFollowing, IMPL_DETAIL), + rustc_attr!( + rustc_legacy_const_generics, Normal, template!(List: "N"), ErrorFollowing, + INTERNAL_UNSTABLE + ), + // Do not const-check this function's body. It will always get replaced during CTFE. + rustc_attr!( + rustc_do_not_const_check, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE + ), + // Ensure the argument to this function is &&str during const-check. + rustc_attr!( + rustc_const_panic_str, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE + ), + + // ========================================================================== + // Internal attributes, Layout related: + // ========================================================================== + + rustc_attr!( + rustc_layout_scalar_valid_range_start, Normal, template!(List: "value"), ErrorFollowing, + "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \ + niche optimizations in libcore and libstd and will never be stable", + ), + rustc_attr!( + rustc_layout_scalar_valid_range_end, Normal, template!(List: "value"), ErrorFollowing, + "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \ + niche optimizations in libcore and libstd and will never be stable", + ), + rustc_attr!( + rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing, + "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \ + niche optimizations in libcore and libstd and will never be stable", + ), + + // ========================================================================== + // Internal attributes, Misc: + // ========================================================================== + gated!( + lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, @only_local: true, lang_items, + "language items are subject to change", + ), + rustc_attr!( + rustc_pass_by_value, Normal, template!(Word), ErrorFollowing, + "#[rustc_pass_by_value] is used to mark types that must be passed by value instead of reference." + ), + rustc_attr!( + rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing, + "#[rustc_never_returns_null_ptr] is used to mark functions returning non-null pointers." + ), + rustc_attr!( + rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, @only_local: true, + "#![rustc_coherence_is_core] allows inherent methods on builtin types, only intended to be used in `core`." + ), + rustc_attr!( + rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, @only_local: true, + "#![rustc_coinductive] changes a trait to be coinductive, allowing cycles in the trait solver." + ), + rustc_attr!( + rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, @only_local: true, + "#[rustc_allow_incoherent_impl] has to be added to all impl items of an incoherent inherent impl." + ), + rustc_attr!( + rustc_deny_explicit_impl, + AttributeType::Normal, + template!(List: "implement_via_object = (true|false)"), + ErrorFollowing, + @only_local: true, + "#[rustc_deny_explicit_impl] enforces that a trait can have no user-provided impls" + ), + rustc_attr!( + rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word), ErrorFollowing, + "#[rustc_has_incoherent_inherent_impls] allows the addition of incoherent inherent impls for \ + the given type by annotating all impl items with #[rustc_allow_incoherent_impl]." + ), + rustc_attr!( + rustc_box, AttributeType::Normal, template!(Word), ErrorFollowing, + "#[rustc_box] allows creating boxes \ + and it is only intended to be used in `alloc`." + ), + + BuiltinAttribute { + // name: sym::rustc_diagnostic_item, + name: "rustc_diagnostic_item", + // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`. + // only_local: false, + // type_: Normal, + template: template!(NameValueStr: "name"), + // duplicates: ErrorFollowing, + // gate: Gated( + // Stability::Unstable, + // sym::rustc_attrs, + // "diagnostic items compiler internal support for linting", + // cfg_fn!(rustc_attrs), + // ), + }, + gated!( + // Used in resolve: + prelude_import, Normal, template!(Word), WarnFollowing, + "`#[prelude_import]` is for use by rustc only", + ), + gated!( + rustc_paren_sugar, Normal, template!(Word), WarnFollowing, unboxed_closures, + "unboxed_closures are still evolving", + ), + rustc_attr!( + rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, @only_local: true, + "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \ + overflow checking behavior of several libcore functions that are inlined \ + across crates and will never be stable", + ), + rustc_attr!( + rustc_reservation_impl, Normal, + template!(NameValueStr: "reservation message"), ErrorFollowing, + "the `#[rustc_reservation_impl]` attribute is internally used \ + for reserving for `for From for T` impl" + ), + rustc_attr!( + rustc_test_marker, Normal, template!(NameValueStr: "name"), WarnFollowing, + "the `#[rustc_test_marker]` attribute is used internally to track tests", + ), + rustc_attr!( + rustc_unsafe_specialization_marker, Normal, template!(Word), WarnFollowing, + "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations" + ), + rustc_attr!( + rustc_specialization_trait, Normal, template!(Word), WarnFollowing, + "the `#[rustc_specialization_trait]` attribute is used to check specializations" + ), + rustc_attr!( + rustc_main, Normal, template!(Word), WarnFollowing, + "the `#[rustc_main]` attribute is used internally to specify test entry point function", + ), + rustc_attr!( + rustc_skip_array_during_method_dispatch, Normal, template!(Word), WarnFollowing, + "the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \ + from method dispatch when the receiver is an array, for compatibility in editions < 2021." + ), + rustc_attr!( + rustc_must_implement_one_of, Normal, template!(List: "function1, function2, ..."), ErrorFollowing, + "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \ + definition of a trait, it's currently in experimental form and should be changed before \ + being exposed outside of the std" + ), + rustc_attr!( + rustc_doc_primitive, Normal, template!(NameValueStr: "primitive name"), ErrorFollowing, + r#"`rustc_doc_primitive` is a rustc internal attribute"#, + ), + rustc_attr!( + rustc_safe_intrinsic, Normal, template!(Word), WarnFollowing, + "the `#[rustc_safe_intrinsic]` attribute is used internally to mark intrinsics as safe" + ), + rustc_attr!( + rustc_deprecated_safe_2024, Normal, template!(Word), WarnFollowing, + "the `#[rustc_safe_intrinsic]` marks functions as unsafe in Rust 2024", + ), + + // ========================================================================== + // Internal attributes, Testing: + // ========================================================================== + + rustc_attr!(TEST, rustc_effective_visibility, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_outlives, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_capture_analysis, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_insignificant_dtor, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_strict_coherence, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_variance, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_variance_of_opaques, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_hidden_type_of_opaques, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ..."), WarnFollowing), + rustc_attr!(TEST, rustc_abi, Normal, template!(List: "field1, field2, ..."), WarnFollowing), + rustc_attr!(TEST, rustc_regions, Normal, template!(Word), WarnFollowing), + rustc_attr!( + TEST, rustc_error, Normal, + template!(Word, List: "delayed_bug_from_inside_query"), WarnFollowingWordOnly + ), + rustc_attr!(TEST, rustc_dump_user_args, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing), + rustc_attr!( + TEST, rustc_if_this_changed, Normal, template!(Word, List: "DepNode"), DuplicatesOk + ), + rustc_attr!( + TEST, rustc_then_this_would_need, Normal, template!(List: "DepNode"), DuplicatesOk + ), + rustc_attr!( + TEST, rustc_clean, Normal, + template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#), + DuplicatesOk, + ), + rustc_attr!( + TEST, rustc_partition_reused, Normal, + template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk, + ), + rustc_attr!( + TEST, rustc_partition_codegened, Normal, + template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk, + ), + rustc_attr!( + TEST, rustc_expected_cgu_reuse, Normal, + template!(List: r#"cfg = "...", module = "...", kind = "...""#), DuplicatesOk, + ), + rustc_attr!(TEST, rustc_symbol_name, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_polymorphize_error, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_def_path, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_mir, Normal, template!(List: "arg1, arg2, ..."), DuplicatesOk), + gated!( + custom_mir, Normal, template!(List: r#"dialect = "...", phase = "...""#), + ErrorFollowing, "the `#[custom_mir]` attribute is just used for the Rust test suite", + ), + rustc_attr!(TEST, rustc_dump_program_clauses, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_dump_env_program_clauses, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_object_lifetime_default, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_dump_vtable, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/), DuplicatesOk), + gated!( + omit_gdb_pretty_printer_section, Normal, template!(Word), WarnFollowing, + "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite", + ), +]; diff --git a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs index 83e92565f4d..b34649d972f 100644 --- a/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir-expand/src/lib.rs @@ -16,6 +16,7 @@ pub mod declarative; pub mod eager; pub mod files; pub mod hygiene; +pub mod inert_attr_macro; pub mod mod_path; pub mod name; pub mod proc_macro; @@ -186,11 +187,11 @@ pub struct MacroDefId { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum MacroDefKind { Declarative(AstId), - BuiltIn(BuiltinFnLikeExpander, AstId), - BuiltInAttr(BuiltinAttrExpander, AstId), - BuiltInDerive(BuiltinDeriveExpander, AstId), - BuiltInEager(EagerExpander, AstId), - ProcMacro(CustomProcMacroExpander, ProcMacroKind, AstId), + BuiltIn(AstId, BuiltinFnLikeExpander), + BuiltInAttr(AstId, BuiltinAttrExpander), + BuiltInDerive(AstId, BuiltinDeriveExpander), + BuiltInEager(AstId, EagerExpander), + ProcMacro(AstId, CustomProcMacroExpander, ProcMacroKind), } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -379,7 +380,7 @@ impl MacroFileIdExt for MacroFileId { fn is_custom_derive(&self, db: &dyn ExpandDatabase) -> bool { matches!( db.lookup_intern_macro_call(self.macro_call_id).def.kind, - MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _) + MacroDefKind::ProcMacro(_, _, ProcMacroKind::CustomDerive) ) } @@ -440,13 +441,13 @@ impl MacroDefId { pub fn definition_range(&self, db: &dyn ExpandDatabase) -> InFile { match self.kind { MacroDefKind::Declarative(id) - | MacroDefKind::BuiltIn(_, id) - | MacroDefKind::BuiltInAttr(_, id) - | MacroDefKind::BuiltInDerive(_, id) - | MacroDefKind::BuiltInEager(_, id) => { + | MacroDefKind::BuiltIn(id, _) + | MacroDefKind::BuiltInAttr(id, _) + | MacroDefKind::BuiltInDerive(id, _) + | MacroDefKind::BuiltInEager(id, _) => { id.with_value(db.ast_id_map(id.file_id).get(id.value).text_range()) } - MacroDefKind::ProcMacro(_, _, id) => { + MacroDefKind::ProcMacro(id, _, _) => { id.with_value(db.ast_id_map(id.file_id).get(id.value).text_range()) } } @@ -454,12 +455,12 @@ impl MacroDefId { pub fn ast_id(&self) -> Either, AstId> { match self.kind { - MacroDefKind::ProcMacro(.., id) => Either::Right(id), + MacroDefKind::ProcMacro(id, ..) => Either::Right(id), MacroDefKind::Declarative(id) - | MacroDefKind::BuiltIn(_, id) - | MacroDefKind::BuiltInAttr(_, id) - | MacroDefKind::BuiltInDerive(_, id) - | MacroDefKind::BuiltInEager(_, id) => Either::Left(id), + | MacroDefKind::BuiltIn(id, _) + | MacroDefKind::BuiltInAttr(id, _) + | MacroDefKind::BuiltInDerive(id, _) + | MacroDefKind::BuiltInEager(id, _) => Either::Left(id), } } @@ -470,7 +471,7 @@ impl MacroDefId { pub fn is_attribute(&self) -> bool { matches!( self.kind, - MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, ProcMacroKind::Attr, _) + MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, _, ProcMacroKind::Attr) ) } @@ -478,7 +479,7 @@ impl MacroDefId { matches!( self.kind, MacroDefKind::BuiltInDerive(..) - | MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _) + | MacroDefKind::ProcMacro(_, _, ProcMacroKind::CustomDerive) ) } @@ -486,26 +487,26 @@ impl MacroDefId { matches!( self.kind, MacroDefKind::BuiltIn(..) - | MacroDefKind::ProcMacro(_, ProcMacroKind::Bang, _) + | MacroDefKind::ProcMacro(_, _, ProcMacroKind::Bang) | MacroDefKind::BuiltInEager(..) | MacroDefKind::Declarative(..) ) } pub fn is_attribute_derive(&self) -> bool { - matches!(self.kind, MacroDefKind::BuiltInAttr(expander, ..) if expander.is_derive()) + matches!(self.kind, MacroDefKind::BuiltInAttr(_, expander) if expander.is_derive()) } pub fn is_include(&self) -> bool { - matches!(self.kind, MacroDefKind::BuiltInEager(expander, ..) if expander.is_include()) + matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_include()) } pub fn is_include_like(&self) -> bool { - matches!(self.kind, MacroDefKind::BuiltInEager(expander, ..) if expander.is_include_like()) + matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_include_like()) } pub fn is_env_or_option_env(&self) -> bool { - matches!(self.kind, MacroDefKind::BuiltInEager(expander, ..) if expander.is_env_or_option_env()) + matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_env_or_option_env()) } } diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 8a91179cd4b..79321df6b6a 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -113,7 +113,7 @@ pub use hir_ty::method_resolution::TyFingerprint; pub use { cfg::{CfgAtom, CfgExpr, CfgOptions}, hir_def::{ - attr::{builtin::AttributeTemplate, AttrSourceMap, Attrs, AttrsWithOwner}, + attr::{AttrSourceMap, Attrs, AttrsWithOwner}, data::adt::StructKind, find_path::PrefixKind, import_map, @@ -132,6 +132,7 @@ pub use { attrs::{Attr, AttrId}, change::ChangeWithProcMacros, hygiene::{marks_rev, SyntaxContextExt}, + inert_attr_macro::AttributeTemplate, name::{known, Name}, proc_macro::ProcMacros, tt, ExpandResult, HirFileId, HirFileIdExt, InFile, InMacroFile, InRealFile, MacroFileId, @@ -3389,7 +3390,7 @@ impl BuiltinAttr { } fn builtin(name: &str) -> Option { - hir_def::attr::builtin::find_builtin_attr_idx(name) + hir_expand::inert_attr_macro::find_builtin_attr_idx(name) .map(|idx| BuiltinAttr { krate: None, idx: idx as u32 }) } @@ -3397,14 +3398,18 @@ impl BuiltinAttr { // FIXME: Return a `Name` here match self.krate { Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx as usize].clone(), - None => SmolStr::new(hir_def::attr::builtin::INERT_ATTRIBUTES[self.idx as usize].name), + None => { + SmolStr::new(hir_expand::inert_attr_macro::INERT_ATTRIBUTES[self.idx as usize].name) + } } } pub fn template(&self, _: &dyn HirDatabase) -> Option { match self.krate { Some(_) => None, - None => Some(hir_def::attr::builtin::INERT_ATTRIBUTES[self.idx as usize].template), + None => { + Some(hir_expand::inert_attr_macro::INERT_ATTRIBUTES[self.idx as usize].template) + } } } } diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 43de2a6ee7d..0cde3f000a5 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -1617,17 +1617,9 @@ fn macro_call_to_macro_id( macro_call_id: MacroCallId, ) -> Option { let loc = db.lookup_intern_macro_call(macro_call_id); - match loc.def.kind { - hir_expand::MacroDefKind::Declarative(it) - | hir_expand::MacroDefKind::BuiltIn(_, it) - | hir_expand::MacroDefKind::BuiltInAttr(_, it) - | hir_expand::MacroDefKind::BuiltInDerive(_, it) - | hir_expand::MacroDefKind::BuiltInEager(_, it) => { - ctx.macro_to_def(InFile::new(it.file_id, it.to_node(db))) - } - hir_expand::MacroDefKind::ProcMacro(_, _, it) => { - ctx.proc_macro_to_def(InFile::new(it.file_id, it.to_node(db))) - } + match loc.def.ast_id() { + Either::Left(it) => ctx.macro_to_def(InFile::new(it.file_id, it.to_node(db))), + Either::Right(it) => ctx.proc_macro_to_def(InFile::new(it.file_id, it.to_node(db))), } } diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs index 6a957ac1c97..f8780fc0da7 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/macro_error.rs @@ -11,7 +11,6 @@ pub(crate) fn macro_error(ctx: &DiagnosticsContext<'_>, d: &hir::MacroError) -> d.message.clone(), display_range, ) - .experimental() } // Diagnostic: macro-error @@ -26,7 +25,6 @@ pub(crate) fn macro_def_error(ctx: &DiagnosticsContext<'_>, d: &hir::MacroDefErr d.message.clone(), display_range, ) - .experimental() } #[cfg(test)] diff --git a/src/tools/rust-analyzer/crates/mbe/src/lib.rs b/src/tools/rust-analyzer/crates/mbe/src/lib.rs index 6920832dd2e..ed3200964df 100644 --- a/src/tools/rust-analyzer/crates/mbe/src/lib.rs +++ b/src/tools/rust-analyzer/crates/mbe/src/lib.rs @@ -317,6 +317,12 @@ pub struct ValueResult { pub err: Option, } +impl Default for ValueResult { + fn default() -> Self { + Self { value: Default::default(), err: Default::default() } + } +} + impl ValueResult { pub fn new(value: T, err: E) -> Self { Self { value, err: Some(err) } diff --git a/src/tools/rust-analyzer/crates/salsa/src/lib.rs b/src/tools/rust-analyzer/crates/salsa/src/lib.rs index 5dde0d560f1..9219a556349 100644 --- a/src/tools/rust-analyzer/crates/salsa/src/lib.rs +++ b/src/tools/rust-analyzer/crates/salsa/src/lib.rs @@ -513,6 +513,10 @@ where { self.storage.purge(); } + + pub fn storage(&self) -> &::Storage { + self.storage + } } /// Return value from [the `query_mut` method] on `Database`. diff --git a/src/tools/rust-analyzer/crates/tt/src/lib.rs b/src/tools/rust-analyzer/crates/tt/src/lib.rs index ab0efff6512..e9de3f97b0e 100644 --- a/src/tools/rust-analyzer/crates/tt/src/lib.rs +++ b/src/tools/rust-analyzer/crates/tt/src/lib.rs @@ -147,7 +147,7 @@ pub struct Punct { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Spacing { Alone, - /// Whether the following token is joint to the current one. + /// Whether the following token is joint to this one. Joint, } -- cgit 1.4.1-3-g733a5