Skip to content

Commit 5d9dff6

Browse files
committed
move naked checks out of check_attr.rs
1 parent 644411e commit 5d9dff6

File tree

14 files changed

+203
-183
lines changed

14 files changed

+203
-183
lines changed

compiler/rustc_attr_parsing/messages.ftl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ attr_parsing_missing_since =
8989
attr_parsing_multiple_stability_levels =
9090
multiple stability levels
9191
92+
attr_parsing_naked_functions_incompatible_attribute =
93+
attribute incompatible with `#[unsafe(naked)]`
94+
.label = the `{$attr}` attribute is incompatible with `#[unsafe(naked)]`
95+
.naked_attribute = function marked with `#[unsafe(naked)]` here
9296
attr_parsing_non_ident_feature =
9397
'feature' is not an identifier
9498

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 101 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr};
22
use rustc_feature::{AttributeTemplate, template};
3-
use rustc_span::sym;
3+
use rustc_session::parse::feature_err;
4+
use rustc_span::{Span, sym};
45

5-
use super::{AttributeOrder, OnDuplicate, SingleAttributeParser};
6-
use crate::context::{AcceptContext, Stage};
6+
use super::{AcceptMapping, AttributeOrder, AttributeParser, OnDuplicate, SingleAttributeParser};
7+
use crate::context::{AcceptContext, FinalizeContext, Stage};
78
use crate::parser::ArgParser;
9+
use crate::session_diagnostics::NakedFunctionIncompatibleAttribute;
810

911
pub(crate) struct OptimizeParser;
1012

@@ -57,19 +59,105 @@ impl<S: Stage> SingleAttributeParser<S> for ColdParser {
5759
}
5860
}
5961

60-
pub(crate) struct NakedParser;
62+
#[derive(Default)]
63+
pub(crate) struct NakedParser {
64+
span: Option<Span>,
65+
}
6166

62-
impl<S: Stage> SingleAttributeParser<S> for NakedParser {
63-
const PATH: &[rustc_span::Symbol] = &[sym::naked];
64-
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast;
65-
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
66-
const TEMPLATE: AttributeTemplate = template!(Word);
67+
impl<S: Stage> AttributeParser<S> for NakedParser {
68+
const ATTRIBUTES: AcceptMapping<Self, S> =
69+
&[(&[sym::naked], template!(Word), |this, cx, args| {
70+
if !args.no_args() {
71+
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
72+
return;
73+
}
6774

68-
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
69-
if !args.no_args() {
70-
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
75+
if let Some(earlier) = this.span {
76+
let span = cx.attr_span;
77+
cx.warn_unused_duplicate(earlier, span);
78+
} else {
79+
this.span = Some(cx.attr_span);
80+
}
81+
})];
82+
83+
fn finalize(self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
84+
// FIXME(jdonszelmann): upgrade this list to *parsed* attributes
85+
// once all of these have parsed forms. That'd make the check much nicer...
86+
//
87+
// many attributes don't make sense in combination with #[naked].
88+
// Notable attributes that are incompatible with `#[naked]` are:
89+
//
90+
// * `#[inline]`
91+
// * `#[track_caller]`
92+
// * `#[test]`, `#[ignore]`, `#[should_panic]`
93+
//
94+
// NOTE: when making changes to this list, check that `error_codes/E0736.md` remains
95+
// accurate.
96+
const ALLOW_LIST: &[rustc_span::Symbol] = &[
97+
// conditional compilation
98+
sym::cfg_trace,
99+
sym::cfg_attr_trace,
100+
// testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`)
101+
sym::test,
102+
sym::ignore,
103+
sym::should_panic,
104+
sym::bench,
105+
// diagnostics
106+
sym::allow,
107+
sym::warn,
108+
sym::deny,
109+
sym::forbid,
110+
sym::deprecated,
111+
sym::must_use,
112+
// abi, linking and FFI
113+
sym::cold,
114+
sym::export_name,
115+
sym::link_section,
116+
sym::linkage,
117+
sym::no_mangle,
118+
sym::instruction_set,
119+
sym::repr,
120+
sym::rustc_std_internal_symbol,
121+
sym::align,
122+
// obviously compatible with self
123+
sym::naked,
124+
// documentation
125+
sym::doc,
126+
];
127+
128+
let Some(span) = self.span else {
71129
return None;
130+
};
131+
132+
// only if we found a naked attribute do we do the somewhat expensive check
133+
'outer: for other_attr in cx.all_attrs {
134+
for allowed_attr in ALLOW_LIST {
135+
if other_attr.word_is(*allowed_attr) || other_attr.starts_with(&[sym::rustfmt]) {
136+
// effectively skips the error message being emitted below
137+
continue 'outer;
138+
}
139+
140+
if other_attr.word_is(sym::target_feature) {
141+
if !cx.features().naked_functions_target_feature() {
142+
feature_err(
143+
&cx.sess(),
144+
sym::naked_functions_target_feature,
145+
other_attr.span(),
146+
"`#[target_feature(/* ... */)]` is currently unstable on `#[naked]` functions",
147+
).emit();
148+
}
149+
150+
continue 'outer;
151+
}
152+
}
153+
154+
cx.emit_err(NakedFunctionIncompatibleAttribute {
155+
span: other_attr.span(),
156+
naked_span: span,
157+
attr: other_attr.get_attribute_path().to_string(),
158+
});
72159
}
73-
Some(AttributeKind::Naked(cx.attr_span))
160+
161+
Some(AttributeKind::Naked(span))
74162
}
75163
}

compiler/rustc_attr_parsing/src/attributes/inline.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,8 @@ impl<S: Stage> SingleAttributeParser<S> for InlineParser {
4545
ArgParser::NameValue(_) => {
4646
let suggestions =
4747
<Self as SingleAttributeParser<S>>::TEMPLATE.suggestions(false, "inline");
48-
cx.emit_lint(
49-
AttributeLintKind::IllFormedAttributeInput { suggestions },
50-
cx.attr_span,
51-
);
48+
let span = cx.attr_span;
49+
cx.emit_lint(AttributeLintKind::IllFormedAttributeInput { suggestions }, span);
5250
return None;
5351
}
5452
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
use std::marker::PhantomData;
1818

1919
use rustc_attr_data_structures::AttributeKind;
20-
use rustc_attr_data_structures::lints::AttributeLintKind;
2120
use rustc_feature::AttributeTemplate;
2221
use rustc_span::{Span, Symbol};
2322
use thin_vec::ThinVec;

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::attributes::stability::{
2626
};
2727
use crate::attributes::transparency::TransparencyParser;
2828
use crate::attributes::{AttributeParser as _, Combine, Single};
29-
use crate::parser::{ArgParser, MetaItemParser};
29+
use crate::parser::{ArgParser, MetaItemParser, PathParser};
3030
use crate::session_diagnostics::{AttributeParseError, AttributeParseErrorReason, UnknownMetaItem};
3131

3232
macro_rules! group_type {
@@ -95,6 +95,7 @@ attribute_parsers!(
9595
BodyStabilityParser,
9696
ConfusablesParser,
9797
ConstStabilityParser,
98+
NakedParser,
9899
StabilityParser,
99100
// tidy-alphabetical-end
100101

@@ -110,7 +111,6 @@ attribute_parsers!(
110111
Single<ConstStabilityIndirectParser>,
111112
Single<DeprecationParser>,
112113
Single<InlineParser>,
113-
Single<NakedParser>,
114114
Single<OptimizeParser>,
115115
Single<RustcForceInlineParser>,
116116
Single<TransparencyParser>,
@@ -169,7 +169,7 @@ pub struct Late;
169169
///
170170
/// Gives [`AttributeParser`]s enough information to create errors, for example.
171171
pub(crate) struct AcceptContext<'f, 'sess, S: Stage> {
172-
pub(crate) finalize_cx: FinalizeContext<'f, 'sess, S>,
172+
pub(crate) shared: SharedContext<'f, 'sess, S>,
173173
/// The span of the attribute currently being parsed
174174
pub(crate) attr_span: Span,
175175

@@ -182,7 +182,7 @@ pub(crate) struct AcceptContext<'f, 'sess, S: Stage> {
182182
pub(crate) attr_path: AttrPath,
183183
}
184184

185-
impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
185+
impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
186186
pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
187187
S::emit_err(&self.sess, diag)
188188
}
@@ -220,7 +220,9 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
220220
unused_span,
221221
)
222222
}
223+
}
223224

225+
impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
224226
pub(crate) fn unknown_key(
225227
&self,
226228
span: Span,
@@ -353,24 +355,24 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
353355
}
354356

355357
impl<'f, 'sess, S: Stage> Deref for AcceptContext<'f, 'sess, S> {
356-
type Target = FinalizeContext<'f, 'sess, S>;
358+
type Target = SharedContext<'f, 'sess, S>;
357359

358360
fn deref(&self) -> &Self::Target {
359-
&self.finalize_cx
361+
&self.shared
360362
}
361363
}
362364

363365
impl<'f, 'sess, S: Stage> DerefMut for AcceptContext<'f, 'sess, S> {
364366
fn deref_mut(&mut self) -> &mut Self::Target {
365-
&mut self.finalize_cx
367+
&mut self.shared
366368
}
367369
}
368370

369371
/// Context given to every attribute parser during finalization.
370372
///
371373
/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
372374
/// errors, for example.
373-
pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
375+
pub(crate) struct SharedContext<'p, 'sess, S: Stage> {
374376
/// The parse context, gives access to the session and the
375377
/// diagnostics context.
376378
pub(crate) cx: &'p mut AttributeParser<'sess, S>,
@@ -379,18 +381,48 @@ pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
379381
/// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to
380382
pub(crate) target_id: S::Id,
381383

382-
pub(crate) emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
384+
emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
385+
}
386+
387+
/// Context given to every attribute parser during finalization.
388+
///
389+
/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
390+
/// errors, for example.
391+
pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
392+
pub(crate) shared: SharedContext<'p, 'sess, S>,
393+
394+
/// A list of all attribute on this syntax node.
395+
///
396+
/// Useful for allowlists in finalize.
397+
///
398+
/// Usually, you should use normal attribute parsing logic instead,
399+
/// especially when making a *denylist* of other attributes.
400+
pub(crate) all_attrs: &'p [PathParser<'p>],
383401
}
384402

385403
impl<'p, 'sess: 'p, S: Stage> Deref for FinalizeContext<'p, 'sess, S> {
404+
type Target = SharedContext<'p, 'sess, S>;
405+
406+
fn deref(&self) -> &Self::Target {
407+
&self.shared
408+
}
409+
}
410+
411+
impl<'p, 'sess: 'p, S: Stage> DerefMut for FinalizeContext<'p, 'sess, S> {
412+
fn deref_mut(&mut self) -> &mut Self::Target {
413+
&mut self.shared
414+
}
415+
}
416+
417+
impl<'p, 'sess: 'p, S: Stage> Deref for SharedContext<'p, 'sess, S> {
386418
type Target = AttributeParser<'sess, S>;
387419

388420
fn deref(&self) -> &Self::Target {
389421
self.cx
390422
}
391423
}
392424

393-
impl<'p, 'sess: 'p, S: Stage> DerefMut for FinalizeContext<'p, 'sess, S> {
425+
impl<'p, 'sess: 'p, S: Stage> DerefMut for SharedContext<'p, 'sess, S> {
394426
fn deref_mut(&mut self) -> &mut Self::Target {
395427
self.cx
396428
}
@@ -500,6 +532,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
500532
mut emit_lint: impl FnMut(AttributeLint<S::Id>),
501533
) -> Vec<Attribute> {
502534
let mut attributes = Vec::new();
535+
let mut attr_paths = Vec::new();
503536

504537
for attr in attrs {
505538
// If we're only looking for a single attribute, skip all the ones we don't care about.
@@ -543,6 +576,8 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
543576
// }))
544577
// }
545578
ast::AttrKind::Normal(n) => {
579+
attr_paths.push(PathParser::Ast(&n.item.path));
580+
546581
let parser = MetaItemParser::from_attr(n, self.dcx());
547582
let path = parser.path();
548583
let args = parser.args();
@@ -551,7 +586,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
551586
if let Some(accepts) = S::parsers().0.get(parts.as_slice()) {
552587
for (template, accept) in accepts {
553588
let mut cx: AcceptContext<'_, 'sess, S> = AcceptContext {
554-
finalize_cx: FinalizeContext {
589+
shared: SharedContext {
555590
cx: self,
556591
target_span,
557592
target_id,
@@ -595,10 +630,13 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
595630
let mut parsed_attributes = Vec::new();
596631
for f in &S::parsers().1 {
597632
if let Some(attr) = f(&mut FinalizeContext {
598-
cx: self,
599-
target_span,
600-
target_id,
601-
emit_lint: &mut emit_lint,
633+
shared: SharedContext {
634+
cx: self,
635+
target_span,
636+
target_id,
637+
emit_lint: &mut emit_lint,
638+
},
639+
all_attrs: &attr_paths,
602640
}) {
603641
parsed_attributes.push(Attribute::Parsed(attr));
604642
}

compiler/rustc_attr_parsing/src/parser.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,14 @@ impl<'a> PathParser<'a> {
8787
pub fn word_is(&self, sym: Symbol) -> bool {
8888
self.word().map(|i| i.name == sym).unwrap_or(false)
8989
}
90+
91+
/// Checks whether the first segments match the givens.
92+
///
93+
/// Unlike [`segments_is`](Self::segments_is),
94+
/// `self` may contain more segments than the number matched against.
95+
pub fn starts_with(&self, segments: &[Symbol]) -> bool {
96+
self.segments().zip(segments).all(|(a, b)| a.name == *b)
97+
}
9098
}
9199

92100
impl Display for PathParser<'_> {

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,17 @@ pub(crate) struct UnrecognizedReprHint {
473473
pub span: Span,
474474
}
475475

476+
#[derive(Diagnostic)]
477+
#[diag(attr_parsing_naked_functions_incompatible_attribute, code = E0736)]
478+
pub(crate) struct NakedFunctionIncompatibleAttribute {
479+
#[primary_span]
480+
#[label]
481+
pub span: Span,
482+
#[label(attr_parsing_naked_attribute)]
483+
pub naked_span: Span,
484+
pub attr: String,
485+
}
486+
476487
pub(crate) enum AttributeParseErrorReason {
477488
ExpectedNoArgs,
478489
ExpectedStringLiteral { byte_string: Option<Span> },

compiler/rustc_passes/messages.ftl

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -491,11 +491,6 @@ passes_must_not_suspend =
491491
passes_must_use_no_effect =
492492
`#[must_use]` has no effect when applied to {$article} {$target}
493493
494-
passes_naked_functions_incompatible_attribute =
495-
attribute incompatible with `#[unsafe(naked)]`
496-
.label = the `{$attr}` attribute is incompatible with `#[unsafe(naked)]`
497-
.naked_attribute = function marked with `#[unsafe(naked)]` here
498-
499494
passes_no_link =
500495
attribute should be applied to an `extern crate` item
501496
.label = not an `extern crate` item

0 commit comments

Comments
 (0)