Skip to content

Report the unsafe_attr_outside_unsafe lint at the closest node #140617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ struct AstValidator<'a> {
/// Used to ban explicit safety on foreign items when the extern block is not marked as unsafe.
extern_mod_safety: Option<Safety>,

lint_node_id: NodeId,

lint_buffer: &'a mut LintBuffer,
}

Expand Down Expand Up @@ -826,7 +828,7 @@ fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericPara

impl<'a> Visitor<'a> for AstValidator<'a> {
fn visit_attribute(&mut self, attr: &Attribute) {
validate_attr::check_attr(&self.sess.psess, attr);
validate_attr::check_attr(&self.sess.psess, attr, self.lint_node_id);
}

fn visit_ty(&mut self, ty: &'a Ty) {
Expand All @@ -839,6 +841,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.has_proc_macro_decls = true;
}

let previous_lint_node_id = mem::replace(&mut self.lint_node_id, item.id);

if let Some(ident) = item.kind.ident()
&& attr::contains_name(&item.attrs, sym::no_mangle)
{
Expand Down Expand Up @@ -1128,6 +1132,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
_ => visit::walk_item(self, item),
}

self.lint_node_id = previous_lint_node_id;
}

fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
Expand Down Expand Up @@ -1694,6 +1700,7 @@ pub fn check_crate(
outer_impl_trait_span: None,
disallow_tilde_const: Some(TildeConstReason::Item),
extern_mod_safety: None,
lint_node_id: CRATE_NODE_ID,
lint_buffer: lints,
};
visit::walk_crate(&mut validator, krate);
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,12 @@ impl<'a> StripUnconfigured<'a> {
/// is in the original source file. Gives a compiler error if the syntax of
/// the attribute is incorrect.
pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
validate_attr::check_attribute_safety(&self.sess.psess, AttributeSafety::Normal, &cfg_attr);
validate_attr::check_attribute_safety(
&self.sess.psess,
AttributeSafety::Normal,
&cfg_attr,
ast::CRATE_NODE_ID,
);

// A trace attribute left in AST in place of the original `cfg_attr` attribute.
// It can later be used by lints or other diagnostics.
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1983,7 +1983,11 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
let mut span: Option<Span> = None;
while let Some(attr) = attrs.next() {
rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
validate_attr::check_attr(&self.cx.sess.psess, attr);
validate_attr::check_attr(
&self.cx.sess.psess,
attr,
self.cx.current_expansion.lint_node_id,
);

let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
span = Some(current_span);
Expand Down
16 changes: 11 additions & 5 deletions compiler/rustc_parse/src/validate_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
use rustc_ast::token::Delimiter;
use rustc_ast::tokenstream::DelimSpan;
use rustc_ast::{
self as ast, AttrArgs, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, Safety,
self as ast, AttrArgs, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, NodeId,
Safety,
};
use rustc_errors::{Applicability, FatalError, PResult};
use rustc_feature::{AttributeSafety, AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute};
Expand All @@ -15,7 +16,7 @@ use rustc_span::{Span, Symbol, sym};

use crate::{errors, parse_in};

pub fn check_attr(psess: &ParseSess, attr: &Attribute) {
pub fn check_attr(psess: &ParseSess, attr: &Attribute, id: NodeId) {
if attr.is_doc_comment() || attr.has_name(sym::cfg_trace) || attr.has_name(sym::cfg_attr_trace)
{
return;
Expand All @@ -26,7 +27,7 @@ pub fn check_attr(psess: &ParseSess, attr: &Attribute) {

// All non-builtin attributes are considered safe
let safety = attr_info.map(|x| x.safety).unwrap_or(AttributeSafety::Normal);
check_attribute_safety(psess, safety, attr);
check_attribute_safety(psess, safety, attr, id);

// Check input tokens for built-in and key-value attributes.
match attr_info {
Expand Down Expand Up @@ -154,7 +155,12 @@ fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaIte
}
}

pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr: &Attribute) {
pub fn check_attribute_safety(
psess: &ParseSess,
safety: AttributeSafety,
attr: &Attribute,
id: NodeId,
) {
let attr_item = attr.get_normal_item();

if let AttributeSafety::Unsafe { unsafe_since } = safety {
Expand Down Expand Up @@ -185,7 +191,7 @@ pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr:
psess.buffer_lint(
UNSAFE_ATTR_OUTSIDE_UNSAFE,
path_span,
ast::CRATE_NODE_ID,
id,
BuiltinLintDiag::UnsafeAttrOutsideUnsafe {
attribute_name_span: path_span,
sugg_spans: (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()),
Expand Down
16 changes: 16 additions & 0 deletions tests/ui/rust-2024/unsafe-attributes/unsafe-attributes-allow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//@ check-pass
//@ edition: 2021
//
// Anti-regression test for https://github.com/rust-lang/rust/issues/140602
// where the generated warning couldn't be allowed due too being attached to
// the wrong AST node.

#![deny(unsafe_attr_outside_unsafe)]

#[allow(unsafe_attr_outside_unsafe)]
mod generated {
#[no_mangle]
fn _generated_foo() {}
}

fn main() {}
Loading