Rollup merge of #139718 - folkertdev:unsafe-attributes-earlier-editions, r=fmease

enforce unsafe attributes in pre-2024 editions by default

New unsafe attributes should emit an error when used without the `unsafe(...)` in all editions.

The `no_mangle`, `link_section` and `export_name` attributes are exceptions, and can still be used without an unsafe in earlier editions. The only attributes for which this change is relevant right now are `#[ffi_const]` and `#[ffi_pure]`.

This change is required for making `#[unsafe(naked)]` sound in pre-2024 editions.
This commit is contained in:
Jacob Pratt 2025-04-13 23:57:40 -04:00 committed by GitHub
commit 4a1d0cd1bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 102 additions and 52 deletions

View file

@ -157,7 +157,7 @@ fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaIte
pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr: &Attribute) {
let attr_item = attr.get_normal_item();
if safety == AttributeSafety::Unsafe {
if let AttributeSafety::Unsafe { unsafe_since } = safety {
if let ast::Safety::Default = attr_item.unsafety {
let path_span = attr_item.path.span;
@ -167,7 +167,13 @@ pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr:
// square bracket respectively.
let diag_span = attr_item.span();
if attr.span.at_least_rust_2024() {
// Attributes can be safe in earlier editions, and become unsafe in later ones.
let emit_error = match unsafe_since {
None => true,
Some(unsafe_since) => attr.span.edition() >= unsafe_since,
};
if emit_error {
psess.dcx().emit_err(errors::UnsafeAttrOutsideUnsafe {
span: path_span,
suggestion: errors::UnsafeAttrOutsideUnsafeSuggestion {