Skip to content

Commit aa80a2b

Browse files
committed
Port #[rustc_skip_during_method_dispatch] to the new attribute system
1 parent 42245d3 commit aa80a2b

File tree

17 files changed

+246
-41
lines changed

17 files changed

+246
-41
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,9 @@ pub enum AttributeKind {
259259
/// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations).
260260
Repr(ThinVec<(ReprAttr, Span)>),
261261

262+
/// Represents `#[rustc_skip_during_method_dispatch]`.
263+
SkipDuringMethodDispatch { array: bool, boxed_slice: bool, span: Span },
264+
262265
/// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`.
263266
Stability {
264267
stability: Stability,

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ impl<S: Stage> SingleAttributeParser<S> for ColdParser {
5050
const TEMPLATE: AttributeTemplate = template!(Word);
5151

5252
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
53-
if !args.no_args() {
54-
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
53+
if let Err(span) = args.no_args() {
54+
cx.expected_no_args(span);
5555
return None;
5656
}
5757

@@ -67,8 +67,8 @@ pub(crate) struct NakedParser {
6767
impl<S: Stage> AttributeParser<S> for NakedParser {
6868
const ATTRIBUTES: AcceptMapping<Self, S> =
6969
&[(&[sym::naked], template!(Word), |this, cx, args| {
70-
if !args.no_args() {
71-
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
70+
if let Err(span) = args.no_args() {
71+
cx.expected_no_args(span);
7272
return;
7373
}
7474

@@ -175,10 +175,10 @@ impl<S: Stage> SingleAttributeParser<S> for NoMangleParser {
175175
const TEMPLATE: AttributeTemplate = template!(Word);
176176

177177
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
178-
if !args.no_args() {
179-
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
178+
if let Err(span) = args.no_args() {
179+
cx.expected_no_args(span);
180180
return None;
181-
};
181+
}
182182

183183
Some(AttributeKind::NoMangle(cx.attr_span))
184184
}

compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ impl<S: Stage> SingleAttributeParser<S> for AsPtrParser {
1414
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
1515
const TEMPLATE: AttributeTemplate = template!(Word);
1616

17-
fn convert(cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
18-
// FIXME: check that there's no args (this is currently checked elsewhere)
17+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
18+
if let Err(span) = args.no_args() {
19+
cx.expected_no_args(span);
20+
}
1921
Some(AttributeKind::AsPtr(cx.attr_span))
2022
}
2123
}
@@ -27,8 +29,10 @@ impl<S: Stage> SingleAttributeParser<S> for PubTransparentParser {
2729
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
2830
const TEMPLATE: AttributeTemplate = template!(Word);
2931

30-
fn convert(cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
31-
// FIXME: check that there's no args (this is currently checked elsewhere)
32+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
33+
if let Err(span) = args.no_args() {
34+
cx.expected_no_args(span);
35+
}
3236
Some(AttributeKind::PubTransparent(cx.attr_span))
3337
}
3438
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ pub(crate) mod must_use;
3636
pub(crate) mod repr;
3737
pub(crate) mod semantics;
3838
pub(crate) mod stability;
39+
pub(crate) mod traits;
3940
pub(crate) mod transparency;
4041
pub(crate) mod util;
4142

compiler/rustc_attr_parsing/src/attributes/semantics.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ impl<S: Stage> SingleAttributeParser<S> for MayDangleParser {
1313
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
1414
const TEMPLATE: AttributeTemplate = template!(Word);
1515

16-
fn convert(cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
16+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
17+
if let Err(span) = args.no_args() {
18+
cx.expected_no_args(span);
19+
}
1720
Some(AttributeKind::MayDangle(cx.attr_span))
1821
}
1922
}

compiler/rustc_attr_parsing/src/attributes/stability.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,10 @@ impl<S: Stage> SingleAttributeParser<S> for ConstStabilityIndirectParser {
139139
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Ignore;
140140
const TEMPLATE: AttributeTemplate = template!(Word);
141141

142-
fn convert(_cx: &mut AcceptContext<'_, '_, S>, _args: &ArgParser<'_>) -> Option<AttributeKind> {
142+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
143+
if let Err(span) = args.no_args() {
144+
cx.expected_no_args(span);
145+
}
143146
Some(AttributeKind::ConstStabilityIndirect)
144147
}
145148
}
@@ -361,8 +364,8 @@ pub(crate) fn parse_unstability<S: Stage>(
361364
};
362365
}
363366
Some(sym::soft) => {
364-
if !param.args().no_args() {
365-
cx.emit_err(session_diagnostics::SoftNoArgs { span: param.span() });
367+
if let Err(span) = args.no_args() {
368+
cx.emit_err(session_diagnostics::SoftNoArgs { span });
366369
}
367370
is_soft = true;
368371
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
use core::mem;
2+
3+
use rustc_attr_data_structures::AttributeKind;
4+
use rustc_feature::{AttributeTemplate, template};
5+
use rustc_span::{Symbol, sym};
6+
7+
use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser};
8+
use crate::context::{AcceptContext, Stage};
9+
use crate::parser::ArgParser;
10+
11+
pub(crate) struct SkipDuringMethodDispatchParser;
12+
13+
impl<S: Stage> SingleAttributeParser<S> for SkipDuringMethodDispatchParser {
14+
const PATH: &[Symbol] = &[sym::rustc_skip_during_method_dispatch];
15+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst;
16+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
17+
18+
const TEMPLATE: AttributeTemplate = template!(List: "array, boxed_slice");
19+
20+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
21+
let mut array = false;
22+
let mut boxed_slice = false;
23+
let Some(args) = args.list() else {
24+
cx.expected_list(cx.attr_span);
25+
return None;
26+
};
27+
if args.is_empty() {
28+
cx.expected_at_least_one_argument(args.span);
29+
return None;
30+
}
31+
for arg in args.mixed() {
32+
let Some(arg) = arg.meta_item() else {
33+
cx.unexpected_literal(arg.span());
34+
continue;
35+
};
36+
if let Err(span) = arg.args().no_args() {
37+
cx.expected_no_args(span);
38+
}
39+
let path = arg.path();
40+
let (key, skip): (Symbol, &mut bool) = match path.word_sym() {
41+
Some(key @ sym::array) => (key, &mut array),
42+
Some(key @ sym::boxed_slice) => (key, &mut boxed_slice),
43+
_ => {
44+
cx.expected_specific_argument(path.span(), vec!["array", "boxed_slice"]);
45+
continue;
46+
}
47+
};
48+
if mem::replace(skip, true) {
49+
cx.duplicate_key(arg.span(), key);
50+
}
51+
}
52+
Some(AttributeKind::SkipDuringMethodDispatch { array, boxed_slice, span: cx.attr_span })
53+
}
54+
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use crate::attributes::semantics::MayDangleParser;
2626
use crate::attributes::stability::{
2727
BodyStabilityParser, ConstStabilityIndirectParser, ConstStabilityParser, StabilityParser,
2828
};
29+
use crate::attributes::traits::SkipDuringMethodDispatchParser;
2930
use crate::attributes::transparency::TransparencyParser;
3031
use crate::attributes::{AttributeParser as _, Combine, Single};
3132
use crate::parser::{ArgParser, MetaItemParser, PathParser};
@@ -119,6 +120,7 @@ attribute_parsers!(
119120
Single<OptimizeParser>,
120121
Single<PubTransparentParser>,
121122
Single<RustcForceInlineParser>,
123+
Single<SkipDuringMethodDispatchParser>,
122124
Single<TransparencyParser>,
123125
// tidy-alphabetical-end
124126
];
@@ -325,6 +327,16 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
325327
})
326328
}
327329

330+
pub(crate) fn expected_at_least_one_argument(&self, span: Span) -> ErrorGuaranteed {
331+
self.emit_err(AttributeParseError {
332+
span,
333+
attr_span: self.attr_span,
334+
template: self.template.clone(),
335+
attribute: self.attr_path.clone(),
336+
reason: AttributeParseErrorReason::ExpectedAtLeastOneArgument,
337+
})
338+
}
339+
328340
pub(crate) fn expected_specific_argument(
329341
&self,
330342
span: Span,

compiler/rustc_attr_parsing/src/parser.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,15 @@ impl<'a> ArgParser<'a> {
169169
}
170170
}
171171

172-
/// Asserts that there are no arguments
173-
pub fn no_args(&self) -> bool {
174-
matches!(self, Self::NoArgs)
172+
/// Assert that there were no args.
173+
/// If there were, get a span to the arguments
174+
/// (to pass to [`AcceptContext::expected_no_args`](crate::context::AcceptContext::expected_no_args)).
175+
pub fn no_args(&self) -> Result<(), Span> {
176+
match self {
177+
Self::NoArgs => Ok(()),
178+
Self::List(args) => Err(args.span),
179+
Self::NameValue(args) => Err(args.eq_span.to(args.value_span)),
180+
}
175181
}
176182
}
177183

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,7 @@ pub(crate) struct NakedFunctionIncompatibleAttribute {
496496
pub(crate) enum AttributeParseErrorReason {
497497
ExpectedNoArgs,
498498
ExpectedStringLiteral { byte_string: Option<Span> },
499+
ExpectedAtLeastOneArgument,
499500
ExpectedSingleArgument,
500501
ExpectedList,
501502
UnexpectedLiteral,
@@ -539,6 +540,9 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
539540
diag.span_label(self.span, "expected a single argument here");
540541
diag.code(E0805);
541542
}
543+
AttributeParseErrorReason::ExpectedAtLeastOneArgument => {
544+
diag.span_label(self.span, "expected at least 1 argument here");
545+
}
542546
AttributeParseErrorReason::ExpectedList => {
543547
diag.span_label(self.span, "expected this to be a list");
544548
}

compiler/rustc_feature/src/builtin_attrs.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
10831083
"the `#[rustc_main]` attribute is used internally to specify test entry point function",
10841084
),
10851085
rustc_attr!(
1086-
rustc_skip_during_method_dispatch, Normal, template!(List: "array, boxed_slice"), WarnFollowing,
1086+
rustc_skip_during_method_dispatch, Normal, template!(List: "array, boxed_slice"), ErrorFollowing,
10871087
EncodeCrossCrate::No,
10881088
"the `#[rustc_skip_during_method_dispatch]` attribute is used to exclude a trait \
10891089
from method dispatch when the receiver is of the following type, for compatibility in \

compiler/rustc_hir_analysis/src/collect.rs

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use std::ops::Bound;
2121

2222
use rustc_abi::ExternAbi;
2323
use rustc_ast::Recovered;
24+
use rustc_attr_data_structures::{AttributeKind, find_attr};
2425
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
2526
use rustc_data_structures::unord::UnordMap;
2627
use rustc_errors::{
@@ -1151,22 +1152,11 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
11511152
let rustc_coinductive = tcx.has_attr(def_id, sym::rustc_coinductive);
11521153
let is_fundamental = tcx.has_attr(def_id, sym::fundamental);
11531154

1154-
// FIXME: We could probably do way better attribute validation here.
1155-
let mut skip_array_during_method_dispatch = false;
1156-
let mut skip_boxed_slice_during_method_dispatch = false;
1157-
for attr in tcx.get_attrs(def_id, sym::rustc_skip_during_method_dispatch) {
1158-
if let Some(lst) = attr.meta_item_list() {
1159-
for item in lst {
1160-
if let Some(ident) = item.ident() {
1161-
match ident.as_str() {
1162-
"array" => skip_array_during_method_dispatch = true,
1163-
"boxed_slice" => skip_boxed_slice_during_method_dispatch = true,
1164-
_ => (),
1165-
}
1166-
}
1167-
}
1168-
}
1169-
}
1155+
let [skip_array_during_method_dispatch, skip_boxed_slice_during_method_dispatch] = find_attr!(
1156+
tcx.get_all_attrs(def_id),
1157+
AttributeKind::SkipDuringMethodDispatch { array, boxed_slice, span:_ } => [*array, *boxed_slice]
1158+
)
1159+
.unwrap_or([false; 2]);
11701160

11711161
let specialization_kind = if tcx.has_attr(def_id, sym::rustc_unsafe_specialization_marker) {
11721162
ty::trait_def::TraitSpecializationKind::Marker

compiler/rustc_parse/src/validate_attr.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,13 +286,20 @@ fn emit_malformed_attribute(
286286
if matches!(
287287
name,
288288
sym::inline
289+
| sym::may_dangle
290+
| sym::rustc_as_ptr
291+
| sym::rustc_pub_transparent
292+
| sym::rustc_const_stable_indirect
289293
| sym::rustc_force_inline
290294
| sym::rustc_confusables
295+
| sym::rustc_skip_during_method_dispatch
291296
| sym::repr
292297
| sym::align
293298
| sym::deprecated
294299
| sym::optimize
295300
| sym::cold
301+
| sym::naked
302+
| sym::no_mangle
296303
| sym::must_use
297304
) {
298305
return;

compiler/rustc_passes/src/check_attr.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
118118
for attr in attrs {
119119
let mut style = None;
120120
match attr {
121+
Attribute::Parsed(AttributeKind::SkipDuringMethodDispatch {
122+
span: attr_span,
123+
..
124+
}) => {
125+
self.check_must_be_applied_to_trait(*attr_span, span, target);
126+
}
121127
Attribute::Parsed(AttributeKind::Confusables { first_span, .. }) => {
122128
self.check_confusables(*first_span, target);
123129
}
@@ -250,7 +256,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
250256
| [sym::rustc_must_implement_one_of, ..]
251257
| [sym::rustc_deny_explicit_impl, ..]
252258
| [sym::rustc_do_not_implement_via_object, ..]
253-
| [sym::const_trait, ..] => self.check_must_be_applied_to_trait(attr, span, target),
259+
| [sym::const_trait, ..] => self.check_must_be_applied_to_trait(attr.span(), span, target),
254260
[sym::collapse_debuginfo, ..] => self.check_collapse_debuginfo(attr, span, target),
255261
[sym::must_not_suspend, ..] => self.check_must_not_suspend(attr, span, target),
256262
[sym::rustc_pass_by_value, ..] => self.check_pass_by_value(attr, span, target),
@@ -1805,14 +1811,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
18051811
}
18061812

18071813
/// Checks if the attribute is applied to a trait.
1808-
fn check_must_be_applied_to_trait(&self, attr: &Attribute, span: Span, target: Target) {
1814+
fn check_must_be_applied_to_trait(&self, attr_span: Span, defn_span: Span, target: Target) {
18091815
match target {
18101816
Target::Trait => {}
18111817
_ => {
1812-
self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait {
1813-
attr_span: attr.span(),
1814-
defn_span: span,
1815-
});
1818+
self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait { attr_span, defn_span });
18161819
}
18171820
}
18181821
}

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,7 @@ symbols! {
577577
box_new,
578578
box_patterns,
579579
box_syntax,
580+
boxed_slice,
580581
bpf_target_feature,
581582
braced_empty_structs,
582583
branch,
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#![feature(rustc_attrs)]
2+
3+
#[rustc_skip_during_method_dispatch]
4+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input [E0539]
5+
trait NotAList {}
6+
7+
#[rustc_skip_during_method_dispatch = "array"]
8+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input [E0539]
9+
trait AlsoNotAList {}
10+
11+
#[rustc_skip_during_method_dispatch()]
12+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input
13+
trait Argless {}
14+
15+
#[rustc_skip_during_method_dispatch(array, boxed_slice, array)]
16+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input
17+
trait Duplicate {}
18+
19+
#[rustc_skip_during_method_dispatch(slice)]
20+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input
21+
trait Unexpected {}
22+
23+
#[rustc_skip_during_method_dispatch(array = true)]
24+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input
25+
trait KeyValue {}
26+
27+
#[rustc_skip_during_method_dispatch("array")]
28+
//~^ ERROR: malformed `rustc_skip_during_method_dispatch` attribute input
29+
trait String {}
30+
31+
#[rustc_skip_during_method_dispatch(array, boxed_slice)]
32+
trait OK {}
33+
34+
#[rustc_skip_during_method_dispatch(array)]
35+
//~^ ERROR: attribute should be applied to a trait
36+
impl OK for () {}
37+
38+
fn main() {}

0 commit comments

Comments
 (0)