Skip to content

Commit 48290c7

Browse files
committed
Port #[rustc_skip_during_method_dispatch] to the new attribute system
1 parent ea34650 commit 48290c7

File tree

15 files changed

+228
-39
lines changed

15 files changed

+228
-39
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

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

246+
/// Represents `#[rustc_skip_during_method_dispatch]`.
247+
SkipDuringMethodDispatch { array: bool, boxed_slice: bool, span: Span },
248+
246249
/// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`.
247250
Stability {
248251
stability: Stability,

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,7 @@ impl<S: Stage> SingleAttributeParser<S> for ColdParser {
4848
const TEMPLATE: AttributeTemplate = template!(Word);
4949

5050
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
51-
if !args.no_args() {
52-
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
53-
return None;
54-
};
55-
51+
cx.expect_no_args(args).ok()?;
5652
Some(AttributeKind::Cold(cx.attr_span))
5753
}
5854
}

compiler/rustc_attr_parsing/src/attributes/lint_helpers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ 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+
cx.expect_no_args(args).ok()?;
1919
Some(AttributeKind::AsPtr(cx.attr_span))
2020
}
2121
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ pub(crate) mod deprecation;
3434
pub(crate) mod inline;
3535
pub(crate) mod lint_helpers;
3636
pub(crate) mod repr;
37+
pub(crate) mod resolution;
3738
pub(crate) mod semantics;
3839
pub(crate) mod stability;
3940
pub(crate) mod transparency;
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use core::mem;
2+
3+
use rustc_attr_data_structures::AttributeKind;
4+
use rustc_feature::{AttributeTemplate, template};
5+
use rustc_span::{ErrorGuaranteed, 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+
let _: Result<(), ErrorGuaranteed> = cx.expect_no_args(arg.args());
37+
let path = arg.path();
38+
let (key, skip): (Symbol, &mut bool) = match path.word_sym() {
39+
Some(key @ sym::array) => (key, &mut array),
40+
Some(key @ sym::boxed_slice) => (key, &mut boxed_slice),
41+
_ => {
42+
cx.expected_specific_argument(path.span(), vec!["array", "boxed_slice"]);
43+
continue;
44+
}
45+
};
46+
if mem::replace(skip, true) {
47+
cx.duplicate_key(arg.span(), key);
48+
}
49+
}
50+
Some(AttributeKind::SkipDuringMethodDispatch { array, boxed_slice, span: cx.attr_span })
51+
}
52+
}

compiler/rustc_attr_parsing/src/attributes/stability.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,8 @@ 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+
cx.expect_no_args(args).ok()?;
143144
Some(AttributeKind::ConstStabilityIndirect)
144145
}
145146
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::attributes::deprecation::DeprecationParser;
2121
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
2222
use crate::attributes::lint_helpers::AsPtrParser;
2323
use crate::attributes::repr::{AlignParser, ReprParser};
24+
use crate::attributes::resolution::SkipDuringMethodDispatchParser;
2425
use crate::attributes::semantics::MayDangleParser;
2526
use crate::attributes::stability::{
2627
BodyStabilityParser, ConstStabilityIndirectParser, ConstStabilityParser, StabilityParser,
@@ -114,6 +115,7 @@ attribute_parsers!(
114115
Single<MayDangleParser>,
115116
Single<OptimizeParser>,
116117
Single<RustcForceInlineParser>,
118+
Single<SkipDuringMethodDispatchParser>,
117119
Single<TransparencyParser>,
118120
// tidy-alphabetical-end
119121
];
@@ -237,14 +239,22 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
237239
})
238240
}
239241

240-
pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
241-
self.emit_err(AttributeParseError {
242-
span: args_span,
243-
attr_span: self.attr_span,
244-
template: self.template.clone(),
245-
attribute: self.attr_path.clone(),
246-
reason: AttributeParseErrorReason::ExpectedNoArgs,
247-
})
242+
pub(crate) fn expect_no_args(&self, args: &ArgParser<'_>) -> Result<(), ErrorGuaranteed> {
243+
if let Some(span) = match args {
244+
ArgParser::NoArgs => None,
245+
ArgParser::List(args) => Some(args.span),
246+
ArgParser::NameValue(args) => Some(args.eq_span.to(args.value_span)),
247+
} {
248+
Err(self.emit_err(AttributeParseError {
249+
span,
250+
attr_span: self.attr_span,
251+
template: self.template.clone(),
252+
attribute: self.attr_path.clone(),
253+
reason: AttributeParseErrorReason::ExpectedNoArgs,
254+
}))
255+
} else {
256+
Ok(())
257+
}
248258
}
249259

250260
/// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
@@ -292,6 +302,16 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
292302
})
293303
}
294304

305+
pub(crate) fn expected_at_least_one_argument(&self, span: Span) -> ErrorGuaranteed {
306+
self.emit_err(AttributeParseError {
307+
span,
308+
attr_span: self.attr_span,
309+
template: self.template.clone(),
310+
attribute: self.attr_path.clone(),
311+
reason: AttributeParseErrorReason::ExpectedAtLeastOneArgument,
312+
})
313+
}
314+
295315
pub(crate) fn expected_specific_argument(
296316
&self,
297317
span: Span,

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,7 @@ pub(crate) struct UnrecognizedReprHint {
476476
pub(crate) enum AttributeParseErrorReason {
477477
ExpectedNoArgs,
478478
ExpectedStringLiteral { byte_string: Option<Span> },
479+
ExpectedAtLeastOneArgument,
479480
ExpectedSingleArgument,
480481
ExpectedList,
481482
UnexpectedLiteral,
@@ -519,6 +520,9 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
519520
diag.span_label(self.span, "expected a single argument here");
520521
diag.code(E0805);
521522
}
523+
AttributeParseErrorReason::ExpectedAtLeastOneArgument => {
524+
diag.span_label(self.span, "expected at least 1 argument here");
525+
}
522526
AttributeParseErrorReason::ExpectedList => {
523527
diag.span_label(self.span, "expected this to be a list");
524528
}

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: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,13 +286,17 @@ fn emit_malformed_attribute(
286286
if matches!(
287287
name,
288288
sym::inline
289+
| sym::rustc_as_ptr
290+
| sym::rustc_pub_transparent
291+
| sym::rustc_const_stable_indirect
289292
| sym::rustc_force_inline
290293
| sym::rustc_confusables
291294
| sym::repr
292295
| sym::align
293296
| sym::deprecated
294297
| sym::optimize
295298
| sym::cold
299+
| sym::rustc_skip_during_method_dispatch
296300
) {
297301
return;
298302
}

compiler/rustc_passes/src/check_attr.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
117117
let attrs = self.tcx.hir_attrs(hir_id);
118118
for attr in attrs {
119119
match attr {
120+
Attribute::Parsed(AttributeKind::SkipDuringMethodDispatch {
121+
span: attr_span,
122+
..
123+
}) => {
124+
self.check_must_be_applied_to_trait(*attr_span, span, target);
125+
}
120126
Attribute::Parsed(AttributeKind::Confusables { first_span, .. }) => {
121127
self.check_confusables(*first_span, target);
122128
}
@@ -235,7 +241,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
235241
| [sym::rustc_must_implement_one_of, ..]
236242
| [sym::rustc_deny_explicit_impl, ..]
237243
| [sym::rustc_do_not_implement_via_object, ..]
238-
| [sym::const_trait, ..] => self.check_must_be_applied_to_trait(attr, span, target),
244+
| [sym::const_trait, ..] => self.check_must_be_applied_to_trait(attr.span(), span, target),
239245
[sym::collapse_debuginfo, ..] => self.check_collapse_debuginfo(attr, span, target),
240246
[sym::must_not_suspend, ..] => self.check_must_not_suspend(attr, span, target),
241247
[sym::must_use, ..] => self.check_must_use(hir_id, attr, target),
@@ -1901,14 +1907,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
19011907
}
19021908

19031909
/// Checks if the attribute is applied to a trait.
1904-
fn check_must_be_applied_to_trait(&self, attr: &Attribute, span: Span, target: Target) {
1910+
fn check_must_be_applied_to_trait(&self, attr_span: Span, defn_span: Span, target: Target) {
19051911
match target {
19061912
Target::Trait => {}
19071913
_ => {
1908-
self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait {
1909-
attr_span: attr.span(),
1910-
defn_span: span,
1911-
});
1914+
self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait { attr_span, defn_span });
19121915
}
19131916
}
19141917
}

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)