diff --git a/Cargo.lock b/Cargo.lock index 6b5491fb754de..4648a12da487b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3586,6 +3586,7 @@ dependencies = [ "rustc_feature", "rustc_hir", "rustc_lexer", + "rustc_lint_defs", "rustc_macros", "rustc_parse", "rustc_parse_format", diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 86eb721ad284c..d017c29a22f7f 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1063,7 +1063,8 @@ 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, 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/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 3c8abf3ee2bbb..75dab290d6031 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -164,7 +164,6 @@ struct LoweringContext<'a, 'hir> { impl<'a, 'hir> LoweringContext<'a, 'hir> { fn new(tcx: TyCtxt<'hir>, resolver: &'a ResolverAstLowering<'hir>) -> Self { - let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect(); Self { tcx, resolver, @@ -220,7 +219,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { attribute_parser: AttributeParser::new( tcx.sess, tcx.features(), - registered_tools, + tcx.registered_tools(()), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, ), delayed_lints: Vec::new(), diff --git a/compiler/rustc_attr_parsing/Cargo.toml b/compiler/rustc_attr_parsing/Cargo.toml index fc83c3b6e9bca..fccc36a128057 100644 --- a/compiler/rustc_attr_parsing/Cargo.toml +++ b/compiler/rustc_attr_parsing/Cargo.toml @@ -13,6 +13,7 @@ rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } rustc_hir = { path = "../rustc_hir" } rustc_lexer = { path = "../rustc_lexer" } +rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } rustc_parse = { path = "../rustc_parse" } rustc_parse_format = { path = "../rustc_parse_format" } diff --git a/compiler/rustc_attr_parsing/src/attributes/body.rs b/compiler/rustc_attr_parsing/src/attributes/body.rs index 8c8a38d269382..ff1c78bc10881 100644 --- a/compiler/rustc_attr_parsing/src/attributes/body.rs +++ b/compiler/rustc_attr_parsing/src/attributes/body.rs @@ -7,5 +7,5 @@ pub(crate) struct CoroutineParser; impl NoArgsAttributeParser for CoroutineParser { const PATH: &[Symbol] = &[sym::coroutine]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Closure)]); - const CREATE: fn(rustc_span::Span) -> AttributeKind = |span| AttributeKind::Coroutine(span); + const CREATE: fn(rustc_span::Span) -> AttributeKind = |_| AttributeKind::Coroutine; } diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index 2651d97cf63e0..6e606def83625 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -54,7 +54,7 @@ impl NoArgsAttributeParser for ColdParser { Allow(Target::ForeignFn), Allow(Target::Closure), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::Cold; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Cold; } pub(crate) struct CoverageParser; @@ -94,7 +94,7 @@ impl SingleAttributeParser for CoverageParser { } }; - Some(AttributeKind::Coverage(cx.attr_span, kind)) + Some(AttributeKind::Coverage(kind)) } } @@ -156,7 +156,7 @@ impl SingleAttributeParser for RustcObjcClassParser { cx.emit_err(NullOnObjcClass { span: nv.value_span }); return None; } - Some(AttributeKind::RustcObjcClass { classname, span: cx.attr_span }) + Some(AttributeKind::RustcObjcClass { classname }) } } @@ -183,7 +183,7 @@ impl SingleAttributeParser for RustcObjcSelectorParser { cx.emit_err(NullOnObjcSelector { span: nv.value_span }); return None; } - Some(AttributeKind::RustcObjcSelector { methname, span: cx.attr_span }) + Some(AttributeKind::RustcObjcSelector { methname }) } } @@ -264,10 +264,18 @@ impl AttributeParser for NakedParser { let span = self.span?; + let Some(tools) = cx.tools else { + unreachable!("tools required while parsing attributes"); + }; + // only if we found a naked attribute do we do the somewhat expensive check 'outer: for other_attr in cx.all_attrs { for allowed_attr in ALLOW_LIST { - if other_attr.segments().next().is_some_and(|i| cx.tools.contains(&i.name)) { + if other_attr + .segments() + .next() + .is_some_and(|i| tools.iter().any(|tool| tool.name == i.name)) + { // effectively skips the error message being emitted below // if it's a tool attribute continue 'outer; @@ -436,9 +444,9 @@ impl AttributeParser for UsedParser { // If a specific form of `used` is specified, it takes precedence over generic `#[used]`. // If both `linker` and `compiler` are specified, use `linker`. Some(match (self.first_compiler, self.first_linker, self.first_default) { - (_, Some(span), _) => AttributeKind::Used { used_by: UsedBy::Linker, span }, - (Some(span), _, _) => AttributeKind::Used { used_by: UsedBy::Compiler, span }, - (_, _, Some(span)) => AttributeKind::Used { used_by: UsedBy::Default, span }, + (_, Some(_), _) => AttributeKind::Used { used_by: UsedBy::Linker }, + (Some(_), _, _) => AttributeKind::Used { used_by: UsedBy::Compiler }, + (_, _, Some(_)) => AttributeKind::Used { used_by: UsedBy::Default }, (None, None, None) => return None, }) } diff --git a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs index 75c777f1a9c4e..038246536a63f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs +++ b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs @@ -84,11 +84,7 @@ impl SingleAttributeParser for RecursionLimitParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { let nv = cx.expect_name_value(args, cx.attr_span, None)?; - Some(AttributeKind::RecursionLimit { - limit: cx.parse_limit_int(nv)?, - attr_span: cx.attr_span, - limit_span: nv.value_span, - }) + Some(AttributeKind::RecursionLimit { limit: cx.parse_limit_int(nv)? }) } } @@ -102,11 +98,7 @@ impl SingleAttributeParser for MoveSizeLimitParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { let nv = cx.expect_name_value(args, cx.attr_span, None)?; - Some(AttributeKind::MoveSizeLimit { - limit: cx.parse_limit_int(nv)?, - attr_span: cx.attr_span, - limit_span: nv.value_span, - }) + Some(AttributeKind::MoveSizeLimit { limit: cx.parse_limit_int(nv)? }) } } @@ -121,11 +113,7 @@ impl SingleAttributeParser for TypeLengthLimitParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { let nv = cx.expect_name_value(args, cx.attr_span, None)?; - Some(AttributeKind::TypeLengthLimit { - limit: cx.parse_limit_int(nv)?, - attr_span: cx.attr_span, - limit_span: nv.value_span, - }) + Some(AttributeKind::TypeLengthLimit { limit: cx.parse_limit_int(nv)? }) } } @@ -139,11 +127,7 @@ impl SingleAttributeParser for PatternComplexityLimitParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { let nv = cx.expect_name_value(args, cx.attr_span, None)?; - Some(AttributeKind::PatternComplexityLimit { - limit: cx.parse_limit_int(nv)?, - attr_span: cx.attr_span, - limit_span: nv.value_span, - }) + Some(AttributeKind::PatternComplexityLimit { limit: cx.parse_limit_int(nv)? }) } } @@ -152,7 +136,7 @@ pub(crate) struct NoCoreParser; impl NoArgsAttributeParser for NoCoreParser { const PATH: &[Symbol] = &[sym::no_core]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoCore; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NoCore; } pub(crate) struct NoStdParser; @@ -161,7 +145,7 @@ impl NoArgsAttributeParser for NoStdParser { const PATH: &[Symbol] = &[sym::no_std]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoStd; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NoStd; } pub(crate) struct NoMainParser; @@ -178,7 +162,7 @@ pub(crate) struct RustcCoherenceIsCoreParser; impl NoArgsAttributeParser for RustcCoherenceIsCoreParser { const PATH: &[Symbol] = &[sym::rustc_coherence_is_core]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcCoherenceIsCore; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcCoherenceIsCore; } pub(crate) struct WindowsSubsystemParser; @@ -204,7 +188,7 @@ impl SingleAttributeParser for WindowsSubsystemParser { } }; - Some(AttributeKind::WindowsSubsystem(kind, cx.attr_span)) + Some(AttributeKind::WindowsSubsystem(kind)) } } @@ -314,7 +298,7 @@ pub(crate) struct RegisterToolParser; impl CombineAttributeParser for RegisterToolParser { const PATH: &[Symbol] = &[sym::register_tool]; type Item = Ident; - const CONVERT: ConvertFn = AttributeKind::RegisterTool; + const CONVERT: ConvertFn = |tools, _span| AttributeKind::RegisterTool(tools); const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); const TEMPLATE: AttributeTemplate = template!(List: &["tool1, tool2, ..."]); diff --git a/compiler/rustc_attr_parsing/src/attributes/diagnostic/do_not_recommend.rs b/compiler/rustc_attr_parsing/src/attributes/diagnostic/do_not_recommend.rs index 4631639da5ff4..1d4bcb63980ce 100644 --- a/compiler/rustc_attr_parsing/src/attributes/diagnostic/do_not_recommend.rs +++ b/compiler/rustc_attr_parsing/src/attributes/diagnostic/do_not_recommend.rs @@ -40,6 +40,6 @@ impl SingleAttributeParser for DoNotRecommendParser { return None; } - Some(AttributeKind::DoNotRecommend { attr_span }) + Some(AttributeKind::DoNotRecommend) } } diff --git a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_move.rs b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_move.rs index 260815b4718c1..b3c6c93a480ee 100644 --- a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_move.rs +++ b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_move.rs @@ -51,8 +51,8 @@ impl AttributeParser for OnMoveParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { - if let Some(span) = self.span { - Some(AttributeKind::OnMove { span, directive: self.directive.map(|d| Box::new(d.1)) }) + if let Some(_span) = self.span { + Some(AttributeKind::OnMove { directive: self.directive.map(|d| Box::new(d.1)) }) } else { None } diff --git a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unimplemented.rs b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unimplemented.rs index e4d01b006c226..82876c41de605 100644 --- a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unimplemented.rs +++ b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unimplemented.rs @@ -54,9 +54,8 @@ impl AttributeParser for OnUnimplementedParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { - if let Some(span) = self.span { + if let Some(_span) = self.span { Some(AttributeKind::OnUnimplemented { - span, directive: self.directive.map(|d| Box::new(d.1)), }) } else { diff --git a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unknown.rs b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unknown.rs index 7d77497f04294..4c327804dd5b9 100644 --- a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unknown.rs +++ b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unknown.rs @@ -57,11 +57,8 @@ impl AttributeParser for OnUnknownParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { - if let Some(span) = self.span { - Some(AttributeKind::OnUnknown { - span, - directive: self.directive.map(|d| Box::new(d.1)), - }) + if let Some(_span) = self.span { + Some(AttributeKind::OnUnknown { directive: self.directive.map(|d| Box::new(d.1)) }) } else { None } diff --git a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unmatch_args.rs b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unmatch_args.rs index 923e5ca2b96df..a3204e6599cf1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unmatch_args.rs +++ b/compiler/rustc_attr_parsing/src/attributes/diagnostic/on_unmatch_args.rs @@ -45,11 +45,8 @@ impl AttributeParser for OnUnmatchArgsParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { - if let Some(span) = self.span { - Some(AttributeKind::OnUnmatchArgs { - span, - directive: self.directive.map(|d| Box::new(d.1)), - }) + if let Some(_span) = self.span { + Some(AttributeKind::OnUnmatchArgs { directive: self.directive.map(|d| Box::new(d.1)) }) } else { None } diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index 039977c74c1bb..d9310906dfeef 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -521,7 +521,7 @@ impl SingleAttributeParser for LinkSectionParser { BinaryFormat::Coff | BinaryFormat::Elf | BinaryFormat::Wasm | BinaryFormat::Xcoff => {} } - Some(LinkSection { name, span: cx.attr_span }) + Some(LinkSection { name }) } } @@ -537,7 +537,7 @@ impl NoArgsAttributeParser for FfiConstParser { const PATH: &[Symbol] = &[sym::ffi_const]; const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None }; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::FfiConst; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::FfiConst; } pub(crate) struct FfiPureParser; @@ -557,7 +557,7 @@ impl NoArgsAttributeParser for RustcStdInternalSymbolParser { Allow(Target::Static), Allow(Target::ForeignStatic), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcStdInternalSymbol; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcStdInternalSymbol; } pub(crate) struct LinkOrdinalParser; diff --git a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs index 43265e15eec5e..3e01844f45185 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs @@ -10,7 +10,7 @@ impl NoArgsAttributeParser for RustcAsPtrParser { Allow(Target::Method(MethodKind::Trait { body: true })), Allow(Target::Method(MethodKind::TraitImpl)), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcAsPtr; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAsPtr; } pub(crate) struct RustcPubTransparentParser; @@ -32,7 +32,7 @@ impl NoArgsAttributeParser for RustcPassByValueParser { Allow(Target::Enum), Allow(Target::TyAlias), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcPassByValue; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcPassByValue; } pub(crate) struct RustcShouldNotBeCalledOnConstItemsParser; @@ -42,7 +42,7 @@ impl NoArgsAttributeParser for RustcShouldNotBeCalledOnConstItemsParser { Allow(Target::Method(MethodKind::Inherent)), Allow(Target::Method(MethodKind::TraitImpl)), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcShouldNotBeCalledOnConstItems; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcShouldNotBeCalledOnConstItems; } pub(crate) struct AutomaticallyDerivedParser; @@ -54,5 +54,5 @@ impl NoArgsAttributeParser for AutomaticallyDerivedParser { Error(Target::Crate), Error(Target::WherePredicate), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::AutomaticallyDerived; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::AutomaticallyDerived; } diff --git a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs index 80555053174f7..067590d23fc8d 100644 --- a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs @@ -8,7 +8,7 @@ impl NoArgsAttributeParser for MacroEscapeParser { const PATH: &[Symbol] = &[sym::macro_escape]; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; const ALLOWED_TARGETS: AllowedTargets = MACRO_USE_ALLOWED_TARGETS; - const CREATE: fn(Span) -> AttributeKind = AttributeKind::MacroEscape; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::MacroEscape; } /// `#[macro_use]` attributes can either: diff --git a/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs b/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs index 5036869b03bd9..eb56e28cbdd47 100644 --- a/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs +++ b/compiler/rustc_attr_parsing/src/attributes/no_implicit_prelude.rs @@ -7,5 +7,5 @@ impl NoArgsAttributeParser for NoImplicitPreludeParser { const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[Allow(Target::Mod), Allow(Target::Crate)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoImplicitPrelude; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NoImplicitPrelude; } diff --git a/compiler/rustc_attr_parsing/src/attributes/path.rs b/compiler/rustc_attr_parsing/src/attributes/path.rs index cf0a28c2ea8e1..0ff87866d6245 100644 --- a/compiler/rustc_attr_parsing/src/attributes/path.rs +++ b/compiler/rustc_attr_parsing/src/attributes/path.rs @@ -19,6 +19,6 @@ impl SingleAttributeParser for PathParser { return None; }; - Some(AttributeKind::Path(path, cx.attr_span)) + Some(AttributeKind::Path(path)) } } diff --git a/compiler/rustc_attr_parsing/src/attributes/pin_v2.rs b/compiler/rustc_attr_parsing/src/attributes/pin_v2.rs index 06e4bc7374e08..c7e78e1c0df54 100644 --- a/compiler/rustc_attr_parsing/src/attributes/pin_v2.rs +++ b/compiler/rustc_attr_parsing/src/attributes/pin_v2.rs @@ -15,5 +15,5 @@ impl NoArgsAttributeParser for PinV2Parser { Allow(Target::Struct), Allow(Target::Union), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::PinV2; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::PinV2; } diff --git a/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs index d7bc60153f269..3c9e80cef0083 100644 --- a/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/proc_macro_attrs.rs @@ -9,14 +9,14 @@ pub(crate) struct ProcMacroParser; impl NoArgsAttributeParser for ProcMacroParser { const PATH: &[Symbol] = &[sym::proc_macro]; const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS; - const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacro; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ProcMacro; } pub(crate) struct ProcMacroAttributeParser; impl NoArgsAttributeParser for ProcMacroAttributeParser { const PATH: &[Symbol] = &[sym::proc_macro_attribute]; const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS; - const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacroAttribute; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ProcMacroAttribute; } pub(crate) struct ProcMacroDeriveParser; @@ -33,7 +33,6 @@ impl SingleAttributeParser for ProcMacroDeriveParser { Some(AttributeKind::ProcMacroDerive { trait_name: trait_name.expect("Trait name is mandatory, so it is present"), helper_attrs, - span: cx.attr_span, }) } } @@ -47,7 +46,7 @@ impl SingleAttributeParser for RustcBuiltinMacroParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { let (builtin_name, helper_attrs) = parse_derive_like(cx, args, false)?; - Some(AttributeKind::RustcBuiltinMacro { builtin_name, helper_attrs, span: cx.attr_span }) + Some(AttributeKind::RustcBuiltinMacro { builtin_name, helper_attrs }) } } diff --git a/compiler/rustc_attr_parsing/src/attributes/prototype.rs b/compiler/rustc_attr_parsing/src/attributes/prototype.rs index 0dfc666beac82..fbc27a8d0fd16 100644 --- a/compiler/rustc_attr_parsing/src/attributes/prototype.rs +++ b/compiler/rustc_attr_parsing/src/attributes/prototype.rs @@ -56,7 +56,7 @@ impl SingleAttributeParser for CustomMirParser { return None; } - Some(AttributeKind::CustomMir(dialect, phase, cx.attr_span)) + Some(AttributeKind::CustomMir(dialect, phase)) } } diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 697d3f8cc2a23..9dffc083c49de 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -556,10 +556,7 @@ impl SingleAttributeParser for RustcScalableVectorParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { if args.as_no_args().is_ok() { - return Some(AttributeKind::RustcScalableVector { - element_count: None, - span: cx.attr_span, - }); + return Some(AttributeKind::RustcScalableVector { element_count: None }); } let n = parse_single_integer(cx, args)?; @@ -567,7 +564,7 @@ impl SingleAttributeParser for RustcScalableVectorParser { cx.emit_err(RustcScalableVectorCountOutOfRange { span: cx.attr_span, n }); return None; }; - Some(AttributeKind::RustcScalableVector { element_count: Some(n), span: cx.attr_span }) + Some(AttributeKind::RustcScalableVector { element_count: Some(n) }) } } @@ -588,7 +585,7 @@ impl SingleAttributeParser for LangParser { cx.emit_err(UnknownLangItem { span: cx.attr_span, name }); return None; }; - Some(AttributeKind::Lang(lang_item, cx.attr_span)) + Some(AttributeKind::Lang(lang_item)) } } @@ -611,7 +608,7 @@ pub(crate) struct PanicHandlerParser; impl NoArgsAttributeParser for PanicHandlerParser { const PATH: &[Symbol] = &[sym::panic_handler]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); // Targets are checked per lang item in `rustc_passes` - const CREATE: fn(Span) -> AttributeKind = |span| AttributeKind::Lang(LangItem::PanicImpl, span); + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Lang(LangItem::PanicImpl); } pub(crate) struct RustcNounwindParser; @@ -892,7 +889,7 @@ impl CombineAttributeParser for RustcThenThisWouldNeedParser { type Item = Ident; const CONVERT: ConvertFn = - |items, span| AttributeKind::RustcThenThisWouldNeed(span, items); + |items, _span| AttributeKind::RustcThenThisWouldNeed(items); const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ // tidy-alphabetical-start Allow(Target::AssocConst), @@ -1073,7 +1070,7 @@ impl SingleAttributeParser for RustcReservationImplParser { return None; }; - Some(AttributeKind::RustcReservationImpl(cx.attr_span, value_str)) + Some(AttributeKind::RustcReservationImpl(value_str)) } } diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index 89f5e3747c1d6..1ae8dd0e37c20 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -58,7 +58,6 @@ impl SingleAttributeParser for ShouldPanicParser { fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { Some(AttributeKind::ShouldPanic { - span: cx.attr_span, reason: match args { ArgParser::NoArgs => None, ArgParser::NameValue(name_value) => { diff --git a/compiler/rustc_attr_parsing/src/attributes/traits.rs b/compiler/rustc_attr_parsing/src/attributes/traits.rs index fe5af66f2a9cb..919e8b6ce3974 100644 --- a/compiler/rustc_attr_parsing/src/attributes/traits.rs +++ b/compiler/rustc_attr_parsing/src/attributes/traits.rs @@ -42,11 +42,7 @@ impl SingleAttributeParser for RustcSkipDuringMethodDispatchParser { cx.adcx().duplicate_key(arg.span(), key); } } - Some(AttributeKind::RustcSkipDuringMethodDispatch { - array, - boxed_slice, - span: cx.attr_span, - }) + Some(AttributeKind::RustcSkipDuringMethodDispatch { array, boxed_slice }) } } @@ -54,7 +50,7 @@ pub(crate) struct RustcParenSugarParser; impl NoArgsAttributeParser for RustcParenSugarParser { const PATH: &[Symbol] = &[sym::rustc_paren_sugar]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcParenSugar; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcParenSugar; } // Markers @@ -68,14 +64,14 @@ impl NoArgsAttributeParser for MarkerParser { Warn(Target::Arm), Warn(Target::MacroDef), ]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::Marker; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Marker; } pub(crate) struct RustcDenyExplicitImplParser; impl NoArgsAttributeParser for RustcDenyExplicitImplParser { const PATH: &[Symbol] = &[sym::rustc_deny_explicit_impl]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcDenyExplicitImpl; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDenyExplicitImpl; } pub(crate) struct RustcDynIncompatibleTraitParser; @@ -91,14 +87,14 @@ pub(crate) struct RustcSpecializationTraitParser; impl NoArgsAttributeParser for RustcSpecializationTraitParser { const PATH: &[Symbol] = &[sym::rustc_specialization_trait]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcSpecializationTrait; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcSpecializationTrait; } pub(crate) struct RustcUnsafeSpecializationMarkerParser; impl NoArgsAttributeParser for RustcUnsafeSpecializationMarkerParser { const PATH: &[Symbol] = &[sym::rustc_unsafe_specialization_marker]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcUnsafeSpecializationMarker; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcUnsafeSpecializationMarker; } // Coherence @@ -107,7 +103,7 @@ pub(crate) struct RustcCoinductiveParser; impl NoArgsAttributeParser for RustcCoinductiveParser { const PATH: &[Symbol] = &[sym::rustc_coinductive]; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]); - const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcCoinductive; + const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcCoinductive; } pub(crate) struct RustcAllowIncoherentImplParser; diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 567cdc7701eae..8260663850344 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -8,6 +8,7 @@ use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan}; use rustc_feature::{AttributeTemplate, Features}; use rustc_hir::attrs::AttributeKind; use rustc_hir::{AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, Target}; +use rustc_lint_defs::RegisteredTools; use rustc_session::Session; use rustc_session::lint::LintId; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; @@ -33,7 +34,7 @@ pub struct EmitAttribute( /// Context created once, for example as part of the ast lowering /// context, through which all attributes can be lowered. pub struct AttributeParser<'sess> { - pub(crate) tools: Vec, + pub(crate) tools: Option<&'sess RegisteredTools>, pub(crate) features: Option<&'sess Features>, pub(crate) sess: &'sess Session, pub(crate) should_emit: ShouldEmit, @@ -59,6 +60,8 @@ impl<'sess> AttributeParser<'sess> { /// No diagnostics will be emitted when parsing limited. Lints are not emitted at all, while /// errors will be emitted as a delayed bugs. in other words, we *expect* attributes parsed /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors + /// + /// Due to this function not taking in RegisteredTools, *do not* use this for parsing any lint attributes pub fn parse_limited( sess: &'sess Session, attrs: &[ast::Attribute], @@ -79,6 +82,8 @@ impl<'sess> AttributeParser<'sess> { /// This does the same as `parse_limited`, except it has a `should_emit` parameter which allows it to emit errors. /// Usually you want `parse_limited`, which emits no errors. + /// + /// Due to this function not taking in RegisteredTools, *do not* use this for parsing any lint attributes pub fn parse_limited_should_emit( sess: &'sess Session, attrs: &[ast::Attribute], @@ -98,6 +103,7 @@ impl<'sess> AttributeParser<'sess> { target_node_id, features, should_emit, + None, ); assert!(parsed.len() <= 1); parsed.pop() @@ -119,8 +125,9 @@ impl<'sess> AttributeParser<'sess> { target_node_id: NodeId, features: Option<&'sess Features>, should_emit: ShouldEmit, + tools: Option<&'sess RegisteredTools>, ) -> Vec { - let mut p = Self { features, tools: Vec::new(), parse_only, sess, should_emit }; + let mut p = Self { features, tools, parse_only, sess, should_emit }; p.parse_attribute_list( attrs, target_span, @@ -202,7 +209,7 @@ impl<'sess> AttributeParser<'sess> { parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T, template: &AttributeTemplate, ) -> T { - let mut parser = Self { features, tools: Vec::new(), parse_only: None, sess, should_emit }; + let mut parser = Self { features, tools: None, parse_only: None, sess, should_emit }; let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| { sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0) }; @@ -237,10 +244,10 @@ impl<'sess> AttributeParser<'sess> { pub fn new( sess: &'sess Session, features: &'sess Features, - tools: Vec, + tools: &'sess RegisteredTools, should_emit: ShouldEmit, ) -> Self { - Self { features: Some(features), tools, parse_only: None, sess, should_emit } + Self { features: Some(features), tools: Some(tools), parse_only: None, sess, should_emit } } pub(crate) fn sess(&self) -> &'sess Session { @@ -432,12 +439,13 @@ impl<'sess> AttributeParser<'sess> { let attr = Attribute::Unparsed(Box::new(attr)); - if self.tools.contains(&parts[0]) + if self.tools.is_some_and(|tools| { + tools.iter().any(|tool| tool.name == parts[0]) // FIXME: this can be removed once #152369 has been merged. // https://github.com/rust-lang/rust/pull/152369 || [sym::allow, sym::deny, sym::expect, sym::forbid, sym::warn] .contains(&parts[0]) - { + }) { attributes.push(attr); } else { dropped_attributes.push(attr); diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 14f4dca532737..4e2884c8cb63f 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -909,7 +909,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, 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 3e19f7f95470f..1e1be9d3a544f 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -69,7 +69,7 @@ fn process_builtin_attrs( .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None }); for attr in parsed_attrs { match attr { - AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD, + AttributeKind::Cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD, AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name), AttributeKind::Inline(inline, span) => { codegen_fn_attrs.inline = *inline; @@ -88,7 +88,7 @@ fn process_builtin_attrs( codegen_fn_attrs.link_ordinal = Some(*ordinal); interesting_spans.link_ordinal = Some(*span); } - AttributeKind::LinkSection { name, .. } => codegen_fn_attrs.link_section = Some(*name), + AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name), AttributeKind::NoMangle(attr_span) => { interesting_spans.no_mangle = Some(*attr_span); if tcx.opt_item_name(did.to_def_id()).is_some() { @@ -167,7 +167,7 @@ fn process_builtin_attrs( } codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER } - AttributeKind::Used { used_by, .. } => match used_by { + AttributeKind::Used { used_by } => match used_by { UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER, UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER, UsedBy::Default => { @@ -184,9 +184,9 @@ fn process_builtin_attrs( codegen_fn_attrs.flags |= used_form; } }, - AttributeKind::FfiConst(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST, + AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST, AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE, - AttributeKind::RustcStdInternalSymbol(_) => { + AttributeKind::RustcStdInternalSymbol => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL } AttributeKind::Linkage(linkage, span) => { @@ -214,10 +214,10 @@ fn process_builtin_attrs( AttributeKind::Sanitize { span, .. } => { interesting_spans.sanitize = Some(*span); } - AttributeKind::RustcObjcClass { classname, .. } => { + AttributeKind::RustcObjcClass { classname } => { codegen_fn_attrs.objc_class = Some(*classname); } - AttributeKind::RustcObjcSelector { methname, .. } => { + AttributeKind::RustcObjcSelector { methname } => { codegen_fn_attrs.objc_selector = Some(*methname); } AttributeKind::RustcEiiForeignItem => { @@ -508,7 +508,7 @@ fn handle_lang_items( attrs: &[Attribute], codegen_fn_attrs: &mut CodegenFnAttrs, ) { - let lang_item = find_attr!(attrs, 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 diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index cc4f1c300f391..1c380e19c5e4d 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -268,6 +268,27 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } + /// Determine whether this argument can be safely ignored. + fn is_ignored_arg(arg: &ArgAbi<'tcx, Ty<'tcx>>) -> bool { + // According to *documentation*, we should ignore nothing here. If we go by what *actually* + // gets ignored, we'd check `arg.is_ignore()`; then we'd ignore zero-sized types (on most + // targets). But we don't want to accept code that relies on such an undocumented property. + // That said, the compiler itself relies on some arguments being ignored when coercing + // non-capturing closures to function pointers: the `self` parameter of the closure is just + // ignored as part of that coercion. Therefore, we ignore *just* those types, and we + // double-check that indeed they do actually get ignored. + let can_ignore = matches!(arg.layout.ty.kind(), ty::Closure (_def, closure_args) if { + closure_args.as_closure().upvar_tys().is_empty() + }); + if can_ignore { + assert!( + arg.is_ignore(), + "an argument we expected to be ignored has the wrong PassMode: {arg:?}" + ); + } + can_ignore + } + /// Initialize a single callee argument, checking the types for compatibility. fn pass_argument<'x, 'y>( &mut self, @@ -285,7 +306,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { 'tcx: 'y, { assert_eq!(callee_ty, callee_abi.layout.ty); - if callee_abi.is_ignore() { + if Self::is_ignored_arg(callee_abi) { // This one is skipped. Still must be made live though! if !already_live { self.storage_live(callee_arg.as_local().unwrap())?; @@ -444,7 +465,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let mut caller_args = args .iter() .zip(caller_fn_abi.args.iter()) - .filter(|arg_and_abi| !arg_and_abi.1.is_ignore()); + .filter(|arg_and_abi| !Self::is_ignored_arg(arg_and_abi.1)); // Now we have to spread them out across the callee's locals, // taking into account the `spread_arg`. If we could write @@ -475,12 +496,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Consume the remaining arguments by putting them into the variable argument // list. - let varargs = self.allocate_varargs( - &mut caller_args, - // "Ignored" arguments aren't actually passed, so the callee should also - // ignore them. (`pass_argument` does this for regular arguments.) - (&mut callee_args_abis).filter(|(_, abi)| !abi.is_ignore()), - )?; + let varargs = self.allocate_varargs(&mut caller_args, &mut callee_args_abis)?; // When the frame is dropped, these variable arguments are deallocated. self.frame_mut().va_list = varargs.clone(); let key = self.va_list_ptr(varargs.into()); diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index e50c232df2d86..bf574cf463cc0 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -941,7 +941,7 @@ impl SyntaxExtension { 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, 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. diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 2bb6c43f3dd62..b6611e7e0ca0c 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2250,6 +2250,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { self.cx.current_expansion.lint_node_id, Some(self.cx.ecfg.features), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + Some(self.cx.resolver.registered_tools()), ); let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 4691116442864..ffee84f4ed8b2 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -945,7 +945,7 @@ pub enum AttributeKind { AllowInternalUnstable(ThinVec<(Symbol, Span)>, Span), /// Represents `#[automatically_derived]` - AutomaticallyDerived(Span), + AutomaticallyDerived, /// Represents the trace attribute of `#[cfg_attr]` CfgAttrTrace, @@ -959,7 +959,7 @@ pub enum AttributeKind { }, /// Represents `#[cold]`. - Cold(Span), + Cold, /// Represents `#[collapse_debuginfo]`. CollapseDebugInfo(CollapseMacroDebuginfo), @@ -971,10 +971,10 @@ pub enum AttributeKind { ConstContinue(Span), /// Represents `#[coroutine]`. - Coroutine(Span), + Coroutine, /// Represents `#[coverage(..)]`. - Coverage(Span, CoverageAttrKind), + Coverage(CoverageAttrKind), /// Represents `#[crate_name = ...]` CrateName { @@ -987,7 +987,7 @@ pub enum AttributeKind { CrateType(ThinVec), /// Represents `#[custom_mir]`. - CustomMir(Option<(MirDialect, Span)>, Option<(MirPhase, Span)>, Span), + CustomMir(Option<(MirDialect, Span)>, Option<(MirPhase, Span)>), /// Represents `#[debugger_visualizer]`. DebuggerVisualizer(ThinVec), @@ -1002,9 +1002,7 @@ pub enum AttributeKind { }, /// Represents `#[diagnostic::do_not_recommend]`. - DoNotRecommend { - attr_span: Span, - }, + DoNotRecommend, /// 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) @@ -1041,7 +1039,7 @@ pub enum AttributeKind { Feature(ThinVec, Span), /// Represents `#[ffi_const]`. - FfiConst(Span), + FfiConst, /// Represents `#[ffi_pure]`. FfiPure(Span), @@ -1063,7 +1061,7 @@ pub enum AttributeKind { InstructionSet(InstructionSetAttr), /// Represents `#[lang]` - Lang(LangItem, Span), + Lang(LangItem), /// Represents `#[link]`. Link(ThinVec, Span), @@ -1082,7 +1080,6 @@ pub enum AttributeKind { /// Represents [`#[link_section]`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute) LinkSection { - span: Span, name: Symbol, }, @@ -1093,7 +1090,7 @@ pub enum AttributeKind { LoopMatch(Span), /// Represents `#[macro_escape]`. - MacroEscape(Span), + MacroEscape, /// Represents [`#[macro_export]`](https://doc.rust-lang.org/reference/macros-by-example.html#r-macro.decl.scope.path). MacroExport { @@ -1108,15 +1105,13 @@ pub enum AttributeKind { }, /// Represents `#[marker]`. - Marker(Span), + Marker, /// Represents [`#[may_dangle]`](https://std-dev-guide.rust-lang.org/tricky/may-dangle.html). MayDangle(Span), /// Represents `#[move_size_limit]` MoveSizeLimit { - attr_span: Span, - limit_span: Span, limit: Limit, }, @@ -1127,6 +1122,7 @@ pub enum AttributeKind { /// Represents `#[must_use]`. MustUse { + /// Used by `clippy`. span: Span, /// must_use can optionally have a reason: `#[must_use = "reason this must be used"]` reason: Option, @@ -1145,10 +1141,10 @@ pub enum AttributeKind { NoBuiltins, /// Represents `#[no_core]` - NoCore(Span), + NoCore, /// Represents `#[no_implicit_prelude]` - NoImplicitPrelude(Span), + NoImplicitPrelude, /// Represents `#[no_link]` NoLink, @@ -1160,7 +1156,7 @@ pub enum AttributeKind { NoMangle(Span), /// Represents `#[no_std]` - NoStd(Span), + NoStd, /// Represents `#[non_exhaustive]` NonExhaustive(Span), @@ -1174,27 +1170,23 @@ pub enum AttributeKind { /// Represents `#[diagnostic::on_move]` OnMove { - span: Span, directive: Option>, }, /// Represents `#[rustc_on_unimplemented]` and `#[diagnostic::on_unimplemented]`. OnUnimplemented { - span: Span, /// None if the directive was malformed in some way. directive: Option>, }, /// Represents `#[diagnostic::on_unknown]` OnUnknown { - span: Span, /// None if the directive was malformed in some way. directive: Option>, }, /// Represents `#[diagnostic::on_unmatch_args]`. OnUnmatchArgs { - span: Span, /// None if the directive was malformed in some way. directive: Option>, }, @@ -1212,32 +1204,29 @@ pub enum AttributeKind { }, /// Represents `#[path]` - Path(Symbol, Span), + Path(Symbol), /// Represents `#[pattern_complexity_limit]` PatternComplexityLimit { - attr_span: Span, - limit_span: Span, limit: Limit, }, /// Represents `#[pin_v2]` - PinV2(Span), + PinV2, /// Represents `#[prelude_import]` PreludeImport, /// Represents `#[proc_macro]` - ProcMacro(Span), + ProcMacro, /// Represents `#[proc_macro_attribute]` - ProcMacroAttribute(Span), + ProcMacroAttribute, /// Represents `#[proc_macro_derive]` ProcMacroDerive { trait_name: Symbol, helper_attrs: ThinVec, - span: Span, }, /// Represents `#[profiler_runtime]` @@ -1245,8 +1234,6 @@ pub enum AttributeKind { /// 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, }, @@ -1254,7 +1241,7 @@ pub enum AttributeKind { ReexportTestHarnessMain(Symbol), /// Represents `#[register_tool]` - RegisterTool(ThinVec, Span), + RegisterTool(ThinVec), /// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations). Repr { @@ -1293,7 +1280,7 @@ pub enum AttributeKind { RustcAllowIncoherentImpl(Span), /// Represents `#[rustc_as_ptr]` (used by the `dangling_pointers_from_temporaries` lint). - RustcAsPtr(Span), + RustcAsPtr, /// Represents `#[rustc_autodiff]`. RustcAutodiff(Option>), @@ -1308,7 +1295,6 @@ pub enum AttributeKind { RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, - span: Span, }, /// Represents `#[rustc_capture_analysis]` RustcCaptureAnalysis, @@ -1320,10 +1306,10 @@ pub enum AttributeKind { RustcClean(ThinVec), /// Represents `#[rustc_coherence_is_core]` - RustcCoherenceIsCore(Span), + RustcCoherenceIsCore, /// Represents `#[rustc_coinductive]`. - RustcCoinductive(Span), + RustcCoinductive, /// Represents `#[rustc_confusables]`. RustcConfusables { @@ -1349,7 +1335,7 @@ pub enum AttributeKind { RustcDelayedBugFromInsideQuery, /// Represents `#[rustc_deny_explicit_impl]`. - RustcDenyExplicitImpl(Span), + RustcDenyExplicitImpl, /// Represents `#[rustc_deprecated_safe_2024]` RustcDeprecatedSafe2024 { @@ -1512,23 +1498,21 @@ pub enum AttributeKind { /// Represents `#[rustc_objc_class]` RustcObjcClass { classname: Symbol, - span: Span, }, /// Represents `#[rustc_objc_selector]` RustcObjcSelector { methname: Symbol, - span: Span, }, /// Represents `#[rustc_offload_kernel]` RustcOffloadKernel, /// Represents `#[rustc_paren_sugar]`. - RustcParenSugar(Span), + RustcParenSugar, /// Represents `#[rustc_pass_by_value]` (used by the `rustc_pass_by_value` lint). - RustcPassByValue(Span), + RustcPassByValue, /// Represents `#[rustc_pass_indirectly_in_non_rustic_abis]` RustcPassIndirectlyInNonRusticAbis(Span), @@ -1549,18 +1533,17 @@ pub enum AttributeKind { RustcRegions, /// Represents `#[rustc_reservation_impl]` - RustcReservationImpl(Span, Symbol), + RustcReservationImpl(Symbol), /// Represents `#[rustc_scalable_vector(N)]` RustcScalableVector { /// The base multiple of lanes that are in a scalable vector, if provided. `element_count` /// is not provided for representing tuple types. element_count: Option, - span: Span, }, /// Represents `#[rustc_should_not_be_called_on_const_items]` - RustcShouldNotBeCalledOnConstItems(Span), + RustcShouldNotBeCalledOnConstItems, /// Represents `#[rustc_simd_monomorphize_lane_limit = "N"]`. RustcSimdMonomorphizeLaneLimit(Limit), @@ -1569,14 +1552,13 @@ pub enum AttributeKind { RustcSkipDuringMethodDispatch { array: bool, boxed_slice: bool, - span: Span, }, /// Represents `#[rustc_specialization_trait]`. - RustcSpecializationTrait(Span), + RustcSpecializationTrait, /// Represents `#[rustc_std_internal_symbol]`. - RustcStdInternalSymbol(Span), + RustcStdInternalSymbol, /// Represents `#[rustc_strict_coherence]`. RustcStrictCoherence(Span), @@ -1585,13 +1567,13 @@ pub enum AttributeKind { RustcTestMarker(Symbol), /// Represents `#[rustc_then_this_would_need]` - RustcThenThisWouldNeed(Span, ThinVec), + RustcThenThisWouldNeed(ThinVec), /// Represents `#[rustc_trivial_field_reads]` RustcTrivialFieldReads, /// Represents `#[rustc_unsafe_specialization_marker]`. - RustcUnsafeSpecializationMarker(Span), + RustcUnsafeSpecializationMarker, /// Represents `#[sanitize]` /// @@ -1608,7 +1590,6 @@ pub enum AttributeKind { /// Represents `#[should_panic]` ShouldPanic { reason: Option, - span: Span, }, /// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`. @@ -1637,8 +1618,6 @@ pub enum AttributeKind { /// Represents `#[type_length_limit]` TypeLengthLimit { - attr_span: Span, - limit_span: Span, limit: Limit, }, @@ -1651,10 +1630,9 @@ pub enum AttributeKind { /// Represents `#[used]` Used { used_by: UsedBy, - span: Span, }, /// Represents `#[windows_subsystem]`. - WindowsSubsystem(WindowsSubsystemKind, Span), + WindowsSubsystem(WindowsSubsystemKind), // tidy-alphabetical-end } diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 41e466a9d16b7..c98e1a0a3cbaa 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -20,23 +20,23 @@ impl AttributeKind { // tidy-alphabetical-start AllowInternalUnsafe(..) => Yes, AllowInternalUnstable(..) => Yes, - AutomaticallyDerived(..) => Yes, + AutomaticallyDerived => Yes, CfgAttrTrace => Yes, CfgTrace(..) => Yes, CfiEncoding { .. } => Yes, - Cold(..) => No, + Cold => No, CollapseDebugInfo(..) => Yes, CompilerBuiltins => No, ConstContinue(..) => No, - Coroutine(..) => No, + Coroutine => No, Coverage(..) => No, CrateName { .. } => No, CrateType(_) => No, - CustomMir(_, _, _) => Yes, + CustomMir(_, _) => Yes, DebuggerVisualizer(..) => No, DefaultLibAllocator => No, Deprecated { .. } => Yes, - DoNotRecommend { .. } => Yes, + DoNotRecommend => Yes, Doc(_) => Yes, DocComment { .. } => Yes, EiiDeclaration(_) => Yes, @@ -44,7 +44,7 @@ impl AttributeKind { ExportName { .. } => Yes, ExportStable => No, Feature(..) => No, - FfiConst(..) => No, + FfiConst => No, FfiPure(..) => No, Fundamental { .. } => Yes, Ignore { .. } => No, @@ -57,10 +57,10 @@ impl AttributeKind { LinkSection { .. } => Yes, // Needed for rustdoc Linkage(..) => No, LoopMatch(..) => No, - MacroEscape(..) => No, + MacroEscape => No, MacroExport { .. } => Yes, MacroUse { .. } => No, - Marker(..) => No, + Marker => No, MayDangle(..) => No, MoveSizeLimit { .. } => No, MustNotSupend { .. } => Yes, @@ -69,12 +69,12 @@ impl AttributeKind { NeedsAllocator => No, NeedsPanicRuntime => No, NoBuiltins => Yes, - NoCore(..) => No, - NoImplicitPrelude(..) => No, + NoCore => No, + NoImplicitPrelude => No, NoLink => No, NoMain => No, NoMangle(..) => Yes, // Needed for rustdoc - NoStd(..) => No, + NoStd => No, NonExhaustive(..) => Yes, // Needed for rustdoc OnConst { .. } => Yes, OnMove { .. } => Yes, @@ -86,10 +86,10 @@ impl AttributeKind { PatchableFunctionEntry { .. } => Yes, Path(..) => No, PatternComplexityLimit { .. } => No, - PinV2(..) => Yes, + PinV2 => Yes, PreludeImport => No, - ProcMacro(..) => No, - ProcMacroAttribute(..) => No, + ProcMacro => No, + ProcMacroAttribute => No, ProcMacroDerive { .. } => No, ProfilerRuntime => No, RecursionLimit { .. } => No, @@ -103,22 +103,22 @@ impl AttributeKind { RustcAllocatorZeroedVariant { .. } => Yes, RustcAllowConstFnUnstable(..) => No, RustcAllowIncoherentImpl(..) => No, - RustcAsPtr(..) => Yes, + RustcAsPtr => Yes, RustcAutodiff(..) => Yes, RustcBodyStability { .. } => No, RustcBuiltinMacro { .. } => Yes, RustcCaptureAnalysis => No, RustcCguTestAttr { .. } => No, RustcClean { .. } => No, - RustcCoherenceIsCore(..) => No, - RustcCoinductive(..) => No, + RustcCoherenceIsCore => No, + RustcCoinductive => No, RustcConfusables { .. } => Yes, RustcConstStability { .. } => Yes, RustcConstStableIndirect => No, RustcConversionSuggestion => Yes, RustcDeallocator => No, RustcDelayedBugFromInsideQuery => No, - RustcDenyExplicitImpl(..) => No, + RustcDenyExplicitImpl => No, RustcDeprecatedSafe2024 { .. } => Yes, RustcDiagnosticItem(..) => Yes, RustcDoNotConstCheck => Yes, @@ -171,8 +171,8 @@ impl AttributeKind { RustcObjcClass { .. } => No, RustcObjcSelector { .. } => No, RustcOffloadKernel => Yes, - RustcParenSugar(..) => No, - RustcPassByValue(..) => Yes, + RustcParenSugar => No, + RustcPassByValue => Yes, RustcPassIndirectlyInNonRusticAbis(..) => No, RustcPreserveUbChecks => No, RustcProcMacroDecls => No, @@ -181,16 +181,16 @@ impl AttributeKind { RustcRegions => No, RustcReservationImpl(..) => Yes, RustcScalableVector { .. } => Yes, - RustcShouldNotBeCalledOnConstItems(..) => Yes, + RustcShouldNotBeCalledOnConstItems => Yes, RustcSimdMonomorphizeLaneLimit(..) => Yes, // Affects layout computation, which needs to work cross-crate RustcSkipDuringMethodDispatch { .. } => No, - RustcSpecializationTrait(..) => No, - RustcStdInternalSymbol(..) => No, + RustcSpecializationTrait => No, + RustcStdInternalSymbol => No, RustcStrictCoherence(..) => Yes, RustcTestMarker(..) => No, RustcThenThisWouldNeed(..) => No, RustcTrivialFieldReads => Yes, - RustcUnsafeSpecializationMarker(..) => No, + RustcUnsafeSpecializationMarker => No, Sanitize { .. } => No, ShouldPanic { .. } => No, Stability { .. } => Yes, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 0d06672f1266d..2f18b09cf1ae8 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1426,7 +1426,7 @@ impl AttributeExt for Attribute { } fn is_automatically_derived_attr(&self) -> bool { - matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived(..))) + matches!(self, Attribute::Parsed(AttributeKind::AutomaticallyDerived)) } #[inline] @@ -1453,8 +1453,8 @@ impl AttributeExt for Attribute { matches!( self, Attribute::Parsed( - AttributeKind::ProcMacro(..) - | AttributeKind::ProcMacroAttribute(..) + AttributeKind::ProcMacro + | AttributeKind::ProcMacroAttribute | AttributeKind::ProcMacroDerive { .. } ) ) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 2a09962789a52..818fda237e7dc 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -920,26 +920,26 @@ 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, 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, Marker(_)); + let is_marker = !is_alias && find_attr!(attrs, Marker); - let rustc_coinductive = find_attr!(attrs, RustcCoinductive(_)); + 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, - RustcSkipDuringMethodDispatch { array, boxed_slice, span: _ } => [*array, *boxed_slice] + RustcSkipDuringMethodDispatch { array, boxed_slice } => [*array, *boxed_slice] ) .unwrap_or([false; 2]); - let specialization_kind = if find_attr!(attrs, RustcUnsafeSpecializationMarker(_)) { + let specialization_kind = if find_attr!(attrs, RustcUnsafeSpecializationMarker) { ty::trait_def::TraitSpecializationKind::Marker - } else if find_attr!(attrs, RustcSpecializationTrait(_)) { + } else if find_attr!(attrs, RustcSpecializationTrait) { ty::trait_def::TraitSpecializationKind::AlwaysApplicable } else { ty::trait_def::TraitSpecializationKind::None @@ -954,7 +954,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { .collect::>() ); - let deny_explicit_impl = find_attr!(attrs, RustcDenyExplicitImpl(_)); + let deny_explicit_impl = find_attr!(attrs, RustcDenyExplicitImpl); let force_dyn_incompatible = find_attr!(attrs, RustcDynIncompatibleTrait(span) => *span); ty::TraitDef { diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 61ddd2ca566b1..d428249e546f7 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -129,10 +129,7 @@ impl<'tcx> IfThisChanged<'tcx> { } }; self.if_this_changed.push((span, def_id.to_def_id(), dep_node)); - } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed( - _, - ref dep_nodes, - )) = *attr + } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed(dep_nodes)) = attr { for &n in dep_nodes { let Ok(dep_node) = diff --git a/compiler/rustc_interface/src/limits.rs b/compiler/rustc_interface/src/limits.rs index 8ae0743886ce5..973a01f4658ec 100644 --- a/compiler/rustc_interface/src/limits.rs +++ b/compiler/rustc_interface/src/limits.rs @@ -18,21 +18,19 @@ pub(crate) fn provide(providers: &mut Providers) { let attrs = tcx.hir_krate_attrs(); Limits { recursion_limit: get_recursion_limit(tcx.hir_krate_attrs(), tcx.sess), - move_size_limit: find_attr!(attrs, MoveSizeLimit { limit, .. } => *limit) + 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) + type_length_limit: find_attr!(attrs, TypeLengthLimit { limit } => *limit) .unwrap_or(Limit::new(2usize.pow(24))), - pattern_complexity_limit: - find_attr!(attrs, PatternComplexityLimit { limit, .. } => *limit) - .unwrap_or(Limit::unlimited()), + pattern_complexity_limit: find_attr!(attrs, PatternComplexityLimit { limit } => *limit) + .unwrap_or(Limit::unlimited()), } } } // This one is separate because it must be read prior to macro expansion. pub(crate) fn get_recursion_limit(attrs: &[Attribute], sess: &Session) -> Limit { - let limit_from_crate = - find_attr!(attrs, RecursionLimit { limit, .. } => limit.0).unwrap_or(128); + let limit_from_crate = find_attr!(attrs, RecursionLimit { limit } => limit.0).unwrap_or(128); Limit::new( sess.opts .unstable_opts diff --git a/compiler/rustc_lint/src/dangling.rs b/compiler/rustc_lint/src/dangling.rs index e57c0d806ded4..cb5c2adf19aa8 100644 --- a/compiler/rustc_lint/src/dangling.rs +++ b/compiler/rustc_lint/src/dangling.rs @@ -267,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, RustcAsPtr(_)) + && find_attr!(cx.tcx, fn_id, RustcAsPtr) { cx.tcx.emit_node_span_lint( DANGLING_POINTERS_FROM_TEMPORARIES, diff --git a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs index 7b8c582936149..ccd817da38faf 100644 --- a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs +++ b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs @@ -42,7 +42,7 @@ impl<'tcx> LateLintPass<'tcx> for DisallowedPassByRef { fn path_for_rustc_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, 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))); @@ -51,7 +51,7 @@ fn path_for_rustc_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Optio if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().skip_norm_wip().kind() { - if find_attr!(cx.tcx, adt.did(), 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/interior_mutable_consts.rs b/compiler/rustc_lint/src/interior_mutable_consts.rs index 5e6a5abc51170..27b2a0b03c577 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 { // Let's do the attribute check after the other checks for perf reasons && find_attr!( cx.tcx, method_did, - 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_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index c77711354f459..729a0dda7cf3b 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2016,9 +2016,9 @@ 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, ProcMacro(..)) { + let macro_kind = if find_attr!(attrs, ProcMacro) { MacroKind::Bang - } else if find_attr!(attrs, ProcMacroAttribute(..)) { + } else if find_attr!(attrs, ProcMacroAttribute) { MacroKind::Attr } else if let Some(trait_name) = find_attr!(attrs, ProcMacroDerive { trait_name, ..} => trait_name) diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index c2357e370182e..37273928d7d1f 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -370,7 +370,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn hir_rustc_coherence_is_core(self) -> bool { - find_attr!(self.hir_krate_attrs(), 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/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 1b26d0a269943..6381a5c49835d 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -349,7 +349,7 @@ impl AdtDefData { debug!("found non-exhaustive variant list for {:?}", did); flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE; } - if find_attr!(tcx, did, PinV2(..)) { + if find_attr!(tcx, did, PinV2) { debug!("found pin-project type {:?}", did); flags |= AdtFlags::IS_PIN_PROJECT; } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index bbe241c574d41..33f6dc7692043 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2718,7 +2718,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, DoNotRecommend { .. }) + find_attr!(self, def_id, DoNotRecommend) } pub fn is_trivial_const(self, def_id: impl IntoQueryKey) -> bool { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index df62e566032a5..93da73e1e4505 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1479,7 +1479,7 @@ impl<'tcx> TyCtxt<'tcx> { field_shuffle_seed ^= user_seed; } - let elt = find_attr!(self, did, 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), @@ -2021,7 +2021,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, 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_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 5a33963b2b654..0694770193f00 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -491,7 +491,7 @@ fn construct_fn<'tcx>( }; if let Some((dialect, phase)) = - find_attr!(tcx, fn_id, CustomMir(dialect, phase, _) => (dialect, phase)) + find_attr!(tcx, fn_id, CustomMir(dialect, phase) => (dialect, phase)) { return custom::build_custom_mir( tcx, 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 630770115a35f..0c6e1b83c9535 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 @@ -568,7 +568,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, 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_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 85870be912b56..39e0769373ede 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -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, Coverage(_sp, kind) => kind) { + if let Some(kind) = find_attr!(tcx, def_id, Coverage(kind) => kind) { match kind { CoverageAttrKind::On => return true, CoverageAttrKind::Off => return false, diff --git a/compiler/rustc_mir_transform/src/liveness.rs b/compiler/rustc_mir_transform/src/liveness.rs index 256d511ecff7c..ba36c8ef1088d 100644 --- a/compiler/rustc_mir_transform/src/liveness.rs +++ b/compiler/rustc_mir_transform/src/liveness.rs @@ -69,7 +69,7 @@ pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Den // Don't run unused pass for #[derive] let parent = tcx.local_parent(tcx.typeck_root_def_id_local(def_id)); if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent) - && find_attr!(tcx, parent, AutomaticallyDerived(..)) + && find_attr!(tcx, parent, AutomaticallyDerived) { return DenseBitSet::new_empty(0); } diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index c7ffc1e5f3681..20f4646490a6b 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -310,24 +310,49 @@ impl<'input> Parser<'input> { let (is_source_literal, end_of_snippet, pre_input_vec) = if let Some(snippet) = snippet { if let Some(nr_hashes) = style { - // snippet is a raw string, which starts with 'r', a number of hashes, and a quote - // and ends with a quote and the same number of hashes - (true, snippet.len() - nr_hashes - 1, vec![]) + // snippet is a raw string + + // validate snippet because a proc macro may have + // respanned it to something completely different (fixes #114865) + let prefix_len = nr_hashes + 2; // r + hashes + opening " + let suffix_len = nr_hashes + 1; // closing " + hashes + let snippet_bytes = snippet.as_bytes(); + let content_end = snippet.len() - suffix_len; + if snippet.len() >= prefix_len + suffix_len // is sufficiently long + && snippet_bytes[0] == b'r' + && snippet_bytes[1..1 + nr_hashes].iter().all(|&c| c == b'#') + && snippet_bytes[1 + nr_hashes] == b'"' + && snippet_bytes[content_end] == b'"' + && snippet_bytes[content_end + 1..].iter().all(|&c| c == b'#') + { + let snippet_without_quotes = &snippet[prefix_len..content_end]; + let input_without_newline = + if appended_newline { &input[..input.len() - 1] } else { input }; + if snippet_without_quotes == input_without_newline { + (true, snippet.len() - suffix_len, vec![]) + } else { + (false, snippet.len(), vec![]) + } + } else { + (false, snippet.len(), vec![]) + } } else { // snippet is not a raw string if snippet.starts_with('"') { // snippet looks like an ordinary string literal // check whether it is the escaped version of input - let without_quotes = &snippet[1..snippet.len() - 1]; + let snippet_without_quotes = &snippet[1..snippet.len() - 1]; let (mut ok, mut vec) = (true, vec![]); let mut chars = input.chars(); - rustc_literal_escaper::unescape_str(without_quotes, |range, res| match res { - Ok(ch) if ok && chars.next().is_some_and(|c| ch == c) => { - vec.push((range, ch)); - } - _ => { - ok = false; - vec = vec![]; + rustc_literal_escaper::unescape_str(snippet_without_quotes, |range, res| { + match res { + Ok(ch) if ok && chars.next().is_some_and(|c| ch == c) => { + vec.push((range, ch)); + } + _ => { + ok = false; + vec = vec![]; + } } }); let end = vec.last().map(|(r, _)| r.end).unwrap_or(0); diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 2817cf3020ff9..3331fd537ef93 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -125,10 +125,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { for attr in attrs { let mut style = None; match attr { - Attribute::Parsed(AttributeKind::ProcMacro(_)) => { + Attribute::Parsed(AttributeKind::ProcMacro) => { self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike) } - Attribute::Parsed(AttributeKind::ProcMacroAttribute(_)) => { + Attribute::Parsed(AttributeKind::ProcMacroAttribute) => { self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute); } Attribute::Parsed(AttributeKind::ProcMacroDerive { .. }) => { @@ -199,36 +199,36 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Attribute::Parsed(AttributeKind::RustcMustImplementOneOf { attr_span, fn_names }) => { self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id,target) }, - Attribute::Parsed(AttributeKind::OnUnimplemented{directive,..}) => {self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())}, + Attribute::Parsed(AttributeKind::OnUnimplemented{directive}) => {self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())}, Attribute::Parsed(AttributeKind::OnConst{span, ..}) => {self.check_diagnostic_on_const(*span, hir_id, target, item)}, - Attribute::Parsed(AttributeKind::OnMove { directive , .. }) => { + Attribute::Parsed(AttributeKind::OnMove { directive }) => { self.check_diagnostic_on_move(hir_id, directive.as_deref()) }, Attribute::Parsed( // tidy-alphabetical-start AttributeKind::RustcAllowIncoherentImpl(..) - | AttributeKind::AutomaticallyDerived(..) + | AttributeKind::AutomaticallyDerived | AttributeKind::CfgAttrTrace | AttributeKind::CfgTrace(..) | AttributeKind::CfiEncoding { .. } - | AttributeKind::Cold(..) + | AttributeKind::Cold | AttributeKind::CollapseDebugInfo(..) | AttributeKind::CompilerBuiltins - | AttributeKind::Coroutine(..) + | AttributeKind::Coroutine | AttributeKind::Coverage (..) | AttributeKind::CrateName { .. } | AttributeKind::CrateType(..) | AttributeKind::CustomMir(..) | AttributeKind::DebuggerVisualizer(..) | AttributeKind::DefaultLibAllocator - | AttributeKind::DoNotRecommend {..} + | AttributeKind::DoNotRecommend // `#[doc]` is actually a lot more than just doc comments, so is checked below | AttributeKind::DocComment {..} | AttributeKind::EiiDeclaration { .. } | AttributeKind::ExportName { .. } | AttributeKind::ExportStable | AttributeKind::Feature(..) - | AttributeKind::FfiConst(..) + | AttributeKind::FfiConst | AttributeKind::Fundamental | AttributeKind::Ignore { .. } | AttributeKind::InstructionSet(..) @@ -237,9 +237,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::LinkOrdinal { .. } | AttributeKind::LinkSection { .. } | AttributeKind::Linkage(..) - | AttributeKind::MacroEscape( .. ) + | AttributeKind::MacroEscape | AttributeKind::MacroUse { .. } - | AttributeKind::Marker(..) + | AttributeKind::Marker | AttributeKind::MoveSizeLimit { .. } | AttributeKind::MustNotSupend { .. } | AttributeKind::MustUse { .. } @@ -247,7 +247,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::NeedsPanicRuntime | AttributeKind::NoBuiltins | AttributeKind::NoCore { .. } - | AttributeKind::NoImplicitPrelude(..) + | AttributeKind::NoImplicitPrelude | AttributeKind::NoLink | AttributeKind::NoMain | AttributeKind::NoMangle(..) @@ -259,7 +259,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::PatchableFunctionEntry { .. } | AttributeKind::Path(..) | AttributeKind::PatternComplexityLimit { .. } - | AttributeKind::PinV2(..) + | AttributeKind::PinV2 | AttributeKind::PreludeImport | AttributeKind::ProfilerRuntime | AttributeKind::RecursionLimit { .. } @@ -271,22 +271,22 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcAllocator | AttributeKind::RustcAllocatorZeroed | AttributeKind::RustcAllocatorZeroedVariant { .. } - | AttributeKind::RustcAsPtr(..) + | AttributeKind::RustcAsPtr | AttributeKind::RustcAutodiff(..) | AttributeKind::RustcBodyStability { .. } | AttributeKind::RustcBuiltinMacro { .. } | AttributeKind::RustcCaptureAnalysis | AttributeKind::RustcCguTestAttr(..) | AttributeKind::RustcClean(..) - | AttributeKind::RustcCoherenceIsCore(..) - | AttributeKind::RustcCoinductive(..) + | AttributeKind::RustcCoherenceIsCore + | AttributeKind::RustcCoinductive | AttributeKind::RustcConfusables { .. } | AttributeKind::RustcConstStability { .. } | AttributeKind::RustcConstStableIndirect | AttributeKind::RustcConversionSuggestion | AttributeKind::RustcDeallocator | AttributeKind::RustcDelayedBugFromInsideQuery - | AttributeKind::RustcDenyExplicitImpl(..) + | AttributeKind::RustcDenyExplicitImpl | AttributeKind::RustcDeprecatedSafe2024 {..} | AttributeKind::RustcDiagnosticItem(..) | AttributeKind::RustcDoNotConstCheck @@ -336,8 +336,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcObjcClass { .. } | AttributeKind::RustcObjcSelector { .. } | AttributeKind::RustcOffloadKernel - | AttributeKind::RustcParenSugar(..) - | AttributeKind::RustcPassByValue (..) + | AttributeKind::RustcParenSugar + | AttributeKind::RustcPassByValue | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..) | AttributeKind::RustcPreserveUbChecks | AttributeKind::RustcProcMacroDecls @@ -345,16 +345,16 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcRegions | AttributeKind::RustcReservationImpl(..) | AttributeKind::RustcScalableVector { .. } - | AttributeKind::RustcShouldNotBeCalledOnConstItems(..) + | AttributeKind::RustcShouldNotBeCalledOnConstItems | AttributeKind::RustcSimdMonomorphizeLaneLimit(..) | AttributeKind::RustcSkipDuringMethodDispatch { .. } - | AttributeKind::RustcSpecializationTrait(..) - | AttributeKind::RustcStdInternalSymbol (..) + | AttributeKind::RustcSpecializationTrait + | AttributeKind::RustcStdInternalSymbol | AttributeKind::RustcStrictCoherence(..) | AttributeKind::RustcTestMarker(..) | AttributeKind::RustcThenThisWouldNeed(..) | AttributeKind::RustcTrivialFieldReads - | AttributeKind::RustcUnsafeSpecializationMarker(..) + | AttributeKind::RustcUnsafeSpecializationMarker | AttributeKind::ShouldPanic { .. } | AttributeKind::Stability { .. } | AttributeKind::TestRunner(..) @@ -724,7 +724,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, Lang(item, _) => item) + if let Some(item) = find_attr!(attrs, Lang(item) => item) && item.is_weak() { let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap(); @@ -795,7 +795,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, 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 @@ -1093,7 +1093,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) { - if find_attr!(attrs, FfiConst(_)) { + if find_attr!(attrs, FfiConst) { // `#[ffi_const]` functions cannot be `#[ffi_pure]` self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span }); } diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 90c385ef6f5ab..0040ddbf5e24a 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -149,7 +149,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { let mut parser = AttributeParser::new( &self.r.tcx.sess, self.r.tcx.features(), - Vec::new(), + self.r.tcx().registered_tools(()), ShouldEmit::Nothing, ); let attrs = parser.parse_attribute_list( diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 998cf27a85de1..dd9f500ff88d0 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -133,7 +133,7 @@ pub fn registered_tools_ast( ) -> RegisteredTools { let mut registered_tools = RegisteredTools::default(); - if let Some(Attribute::Parsed(AttributeKind::RegisterTool(tools, _))) = + if let Some(Attribute::Parsed(AttributeKind::RegisterTool(tools))) = AttributeParser::parse_limited(sess, pre_configured_attrs, &[sym::register_tool]) { for tool in tools { diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 7b316f383997c..49cc2833cd978 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -775,7 +775,7 @@ impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> { && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) { if let Some(message) = - find_attr!(infcx.tcx, def_id, RustcReservationImpl(_, message) => *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 2bbc04b8ac35d..9eca0f31a4402 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1459,7 +1459,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, 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/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 3afe367a45ed3..f020a26a23bc2 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1076,11 +1076,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, ProcMacro(..)) { + let macro_kind = if find_attr!(attrs, ProcMacro) { Some(MacroKind::Bang) } else if find_attr!(attrs, ProcMacroDerive { .. }) { Some(MacroKind::Derive) - } else if find_attr!(attrs, ProcMacroAttribute(..)) { + } else if find_attr!(attrs, ProcMacroAttribute) { Some(MacroKind::Attr) } else { None diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 44749fd4c0ec6..623ad55f6e994 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -932,14 +932,14 @@ fn maybe_from_hir_attr(attr: &hir::Attribute, item_id: ItemId, tcx: TyCtxt<'_>) item_id.as_def_id().expect("all items that could have #[repr] have a DefId"), ), AK::ExportName { name, span: _ } => Attribute::ExportName(name.to_string()), - AK::LinkSection { name, span: _ } => Attribute::LinkSection(name.to_string()), + AK::LinkSection { name } => Attribute::LinkSection(name.to_string()), AK::TargetFeature { features, .. } => Attribute::TargetFeature { enable: features.iter().map(|(feat, _span)| feat.to_string()).collect(), }, AK::NoMangle(_) => Attribute::NoMangle, AK::NonExhaustive(_) => Attribute::NonExhaustive, - AK::AutomaticallyDerived(_) => Attribute::AutomaticallyDerived, + AK::AutomaticallyDerived => Attribute::AutomaticallyDerived, AK::Doc(d) => { fn toggle_attr(ret: &mut Vec, name: &str, v: &Option) { if v.is_some() { diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index fd2b9826bb20f..7e23794144366 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -716,7 +716,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, data.impl_def_id, AutomaticallyDerived(..)) + find_attr!(tcx, data.impl_def_id, AutomaticallyDerived) } else { false }; diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index e5420f9f9d166..b7c08c380903f 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -1736,8 +1736,9 @@ pub fn in_automatically_derived(tcx: TyCtxt<'_>, id: HirId) -> bool { .filter(|(_, node)| matches!(node, OwnerNode::Item(item) if matches!(item.kind, ItemKind::Impl(_)))) .any(|(id, _)| { find_attr!( - tcx.hir_attrs(tcx.local_def_id_to_hir_id(id.def_id)), - AutomaticallyDerived(..) + tcx, + id.def_id, + AutomaticallyDerived ) }) } @@ -2101,11 +2102,11 @@ pub fn std_or_core(cx: &LateContext<'_>) -> Option<&'static str> { } pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool { - find_attr!(cx.tcx, crate, NoStd(..)) + find_attr!(cx.tcx, crate, NoStd) } pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool { - find_attr!(cx.tcx, crate, NoCore(..)) + find_attr!(cx.tcx, crate, NoCore) } /// Check if parent of a hir node is a trait implementation block. diff --git a/src/tools/miri/tests/fail/c-variadic-ignored-argument.rs b/src/tools/miri/tests/fail/c-variadic-ignored-argument.rs new file mode 100644 index 0000000000000..3a666b549ce5d --- /dev/null +++ b/src/tools/miri/tests/fail/c-variadic-ignored-argument.rs @@ -0,0 +1,14 @@ +//@error-in-other-file: requested `i32` is incompatible with next argument of type `()` +#![feature(c_variadic)] + +// While 1-ZST are currently ignored on most ABIs, we don't guarantee that, and it's UB to +// rely on it. + +fn main() { + unsafe extern "C" fn variadic(mut ap: ...) { + ap.next_arg::(); + ap.next_arg::(); // this one errors + } + + unsafe { variadic(0i32, (), 1i32) } +} diff --git a/src/tools/miri/tests/fail/c-variadic-ignored-argument.stderr b/src/tools/miri/tests/fail/c-variadic-ignored-argument.stderr new file mode 100644 index 0000000000000..c7e5c9705bebe --- /dev/null +++ b/src/tools/miri/tests/fail/c-variadic-ignored-argument.stderr @@ -0,0 +1,20 @@ +error: Undefined Behavior: va_arg type mismatch: requested `i32` is incompatible with next argument of type `()` + --> RUSTLIB/core/src/ffi/va_list.rs:LL:CC + | +LL | unsafe { va_arg(self) } + | ^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: stack backtrace: + 0: std::ffi::VaList::<'_>::next_arg + at RUSTLIB/core/src/ffi/va_list.rs:LL:CC + 1: main::variadic + at tests/fail/c-variadic-ignored-argument.rs:LL:CC + 2: main + at tests/fail/c-variadic-ignored-argument.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/validity/fn_arg_never_type.rs b/src/tools/miri/tests/fail/validity/fn_arg_never_type.rs new file mode 100644 index 0000000000000..a6ffb325191b0 --- /dev/null +++ b/src/tools/miri/tests/fail/validity/fn_arg_never_type.rs @@ -0,0 +1,13 @@ +use std::mem::transmute; + +enum Never {} + +fn foo(x: Never) { //~ERROR: invalid value of type Never + let ptr = &raw const x; + println!("{ptr:p}"); +} + +fn main() { + let f = unsafe { transmute::(foo) }; + f(()); +} diff --git a/src/tools/miri/tests/fail/validity/fn_arg_never_type.stderr b/src/tools/miri/tests/fail/validity/fn_arg_never_type.stderr new file mode 100644 index 0000000000000..36ffcf24790a3 --- /dev/null +++ b/src/tools/miri/tests/fail/validity/fn_arg_never_type.stderr @@ -0,0 +1,18 @@ +error: Undefined Behavior: constructing invalid value of type Never: encountered a value of uninhabited type `Never` + --> tests/fail/validity/fn_arg_never_type.rs:LL:CC + | +LL | fn foo(x: Never) { + | ^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: stack backtrace: + 0: foo + at tests/fail/validity/fn_arg_never_type.rs:LL:CC + 1: main + at tests/fail/validity/fn_arg_never_type.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/pass/c-variadic-ignored-argument.rs b/src/tools/miri/tests/pass/c-variadic-ignored-argument.rs deleted file mode 100644 index fe09a03edfffc..0000000000000 --- a/src/tools/miri/tests/pass/c-variadic-ignored-argument.rs +++ /dev/null @@ -1,21 +0,0 @@ -//@ ignore-target: windows # does not ignore ZST arguments -//@ ignore-target: powerpc # does not ignore ZST arguments -//@ ignore-target: s390x # does not ignore ZST arguments -//@ ignore-target: sparc # does not ignore ZST arguments -#![feature(c_variadic)] - -// Some platforms ignore ZSTs, meaning that the argument is not passed, even though it is part -// of the callee's ABI. Test that this doesn't trip any asserts. -// -// NOTE: this test only succeeds when the `()` argument uses `Passmode::Ignore`. For some targets, -// notably msvc, such arguments are not ignored, which would cause UB when attempting to read the -// second `i32` argument while the next item in the variable argument list is `()`. - -fn main() { - unsafe extern "C" fn variadic(mut ap: ...) { - ap.next_arg::(); - ap.next_arg::(); - } - - unsafe { variadic(0i32, (), 1i32) } -} diff --git a/tests/ui/type/never-type-inference-fail.rs b/tests/ui/never_type/basic/clone-never.rs similarity index 100% rename from tests/ui/type/never-type-inference-fail.rs rename to tests/ui/never_type/basic/clone-never.rs diff --git a/tests/ui/type/never-type-inference-fail.stderr b/tests/ui/never_type/basic/clone-never.stderr similarity index 89% rename from tests/ui/type/never-type-inference-fail.stderr rename to tests/ui/never_type/basic/clone-never.stderr index 1d2457103f1ca..ea2f55f17381e 100644 --- a/tests/ui/type/never-type-inference-fail.stderr +++ b/tests/ui/never_type/basic/clone-never.stderr @@ -1,5 +1,5 @@ error[E0282]: type annotations needed - --> $DIR/never-type-inference-fail.rs:4:9 + --> $DIR/clone-never.rs:4:9 | LL | let x = panic!(); | ^ diff --git a/tests/ui/proc-macro/auxiliary/ice-wrong-span-114865.rs b/tests/ui/proc-macro/auxiliary/ice-wrong-span-114865.rs new file mode 100644 index 0000000000000..45f0b528bb2b4 --- /dev/null +++ b/tests/ui/proc-macro/auxiliary/ice-wrong-span-114865.rs @@ -0,0 +1,48 @@ +#![feature(proc_macro_span)] + +extern crate proc_macro; + +use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; + +/// Builds a `println!()` token stream with the given span on the format string literal. +fn make_println(fmt_str: &str, span: Span) -> TokenStream { + let mut lit: Literal = fmt_str.parse().unwrap(); + lit.set_span(span); + FromIterator::::from_iter([ + Ident::new("println", Span::mixed_site()).into(), + Punct::new('!', Spacing::Alone).into(), + Group::new(Delimiter::Parenthesis, TokenTree::from(lit).into()).into(), + ]) +} + +/// Expands to `println!(r"{}")` with the span of the first input token. +#[proc_macro] +pub fn foo(input: TokenStream) -> TokenStream { + let span = input.into_iter().next().unwrap().span(); + make_println(r#"r"{}""#, span) +} + +/// Same as `foo` but with hashes: expands to `println!(r##"{}"##)`. +#[proc_macro] +pub fn foo2(input: TokenStream) -> TokenStream { + let span = input.into_iter().next().unwrap().span(); + make_println(r###"r##"{}"##"###, span) +} + +/// Expands to `println!(r"{}")` with a span joining two input tokens, +/// creating a span whose source text may not be a valid raw string. +#[proc_macro] +pub fn foo3(input: TokenStream) -> TokenStream { + let mut iter = input.into_iter(); + let span = iter.next().unwrap().span().join(iter.next().unwrap().span()).unwrap(); + make_println(r#"r"{}""#, span) +} + +/// Same as `foo3` but with hashes: expands to `println!(r##"{}"##)`. +#[proc_macro] +pub fn foo4(input: TokenStream) -> TokenStream { + let mut iter = input.into_iter(); + let span = iter.next().unwrap().span().join(iter.next().unwrap().span()).unwrap(); + make_println(r###"r##"{}"##"###, span) +} diff --git a/tests/ui/proc-macro/ice-wrong-span-114865.rs b/tests/ui/proc-macro/ice-wrong-span-114865.rs new file mode 100644 index 0000000000000..1eddc00de55c4 --- /dev/null +++ b/tests/ui/proc-macro/ice-wrong-span-114865.rs @@ -0,0 +1,25 @@ +// Regression test for ICE https://github.com/rust-lang/rust/issues/114865 + +// Tests that we do not ICE when a proc macro expands +// to a string formatting macro (like println!) and respans +// this formatting macro's arg to that of its own input which +// happens to be a multi-byte string (see the auxiliary file +// ice-wrong-span-114865.rs). + +//@ proc-macro: ice-wrong-span-114865.rs + +extern crate ice_wrong_span_114865; + +use ice_wrong_span_114865::{foo, foo2, foo3, foo4}; + +fn main() { + foo!("字"); //~ ERROR 1 positional argument in format string, but no arguments were given + foo!("r字字"); //~ ERROR 1 positional argument in format string, but no arguments were given + + foo2!("字"); //~ ERROR 1 positional argument in format string, but no arguments were given + foo2!("r字字"); //~ ERROR 1 positional argument in format string, but no arguments were given + + foo3!(r"abc" 字); //~ ERROR 1 positional argument in format string, but no arguments were given + + foo4!(r##"abcd"## 字); //~ ERROR 1 positional argument in format string, but no arguments were given +} diff --git a/tests/ui/proc-macro/ice-wrong-span-114865.stderr b/tests/ui/proc-macro/ice-wrong-span-114865.stderr new file mode 100644 index 0000000000000..2324e6d5d60ca --- /dev/null +++ b/tests/ui/proc-macro/ice-wrong-span-114865.stderr @@ -0,0 +1,38 @@ +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:16:10 + | +LL | foo!("字"); + | ^^^^ + +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:17:10 + | +LL | foo!("r字字"); + | ^^^^^^^ + +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:19:11 + | +LL | foo2!("字"); + | ^^^^ + +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:20:11 + | +LL | foo2!("r字字"); + | ^^^^^^^ + +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:22:11 + | +LL | foo3!(r"abc" 字); + | ^^^^^^^^^ + +error: 1 positional argument in format string, but no arguments were given + --> $DIR/ice-wrong-span-114865.rs:24:11 + | +LL | foo4!(r##"abcd"## 字); + | ^^^^^^^^^^^^^^ + +error: aborting due to 6 previous errors +