Skip to content

Commit 5ab40c8

Browse files
committed
Implement #[rustc_must_implement_one_of] attribute
1 parent 02fe61b commit 5ab40c8

File tree

11 files changed

+205
-4
lines changed

11 files changed

+205
-4
lines changed

compiler/rustc_feature/src/builtin_attrs.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,12 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
677677
"the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \
678678
from method dispatch when the receiver is an array, for compatibility in editions < 2021."
679679
),
680+
rustc_attr!(
681+
rustc_must_implement_one_of, Normal, template!(List: "method1, method2, ..."), ErrorFollowing,
682+
"the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \
683+
definition of a trait, it's currently in experimental form and should be changed before \
684+
being exposed outside of the std"
685+
),
680686

681687
// ==========================================================================
682688
// Internal attributes, Testing:

compiler/rustc_metadata/src/rmeta/decoder.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
820820
data.skip_array_during_method_dispatch,
821821
data.specialization_kind,
822822
self.def_path_hash(item_id),
823+
data.must_implement_one_of,
823824
)
824825
}
825826
EntryKind::TraitAlias => ty::TraitDef::new(
@@ -831,6 +832,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
831832
false,
832833
ty::trait_def::TraitSpecializationKind::None,
833834
self.def_path_hash(item_id),
835+
None,
834836
),
835837
_ => bug!("def-index does not refer to trait or trait alias"),
836838
}

compiler/rustc_metadata/src/rmeta/encoder.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1514,6 +1514,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
15141514
is_marker: trait_def.is_marker,
15151515
skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
15161516
specialization_kind: trait_def.specialization_kind,
1517+
must_implement_one_of: trait_def.must_implement_one_of.clone(),
15171518
};
15181519

15191520
EntryKind::Trait(self.lazy(data))

compiler/rustc_metadata/src/rmeta/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ struct TraitData {
378378
is_marker: bool,
379379
skip_array_during_method_dispatch: bool,
380380
specialization_kind: ty::trait_def::TraitSpecializationKind,
381+
must_implement_one_of: Option<Box<[Ident]>>,
381382
}
382383

383384
#[derive(TyEncodable, TyDecodable)]

compiler/rustc_middle/src/ty/trait_def.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::traits::specialization_graph;
22
use crate::ty::fast_reject::{self, SimplifiedType, SimplifyParams, StripReferences};
33
use crate::ty::fold::TypeFoldable;
4-
use crate::ty::{Ty, TyCtxt};
4+
use crate::ty::{Ident, Ty, TyCtxt};
55
use rustc_hir as hir;
66
use rustc_hir::def_id::DefId;
77
use rustc_hir::definitions::DefPathHash;
@@ -44,6 +44,10 @@ pub struct TraitDef {
4444
/// The ICH of this trait's DefPath, cached here so it doesn't have to be
4545
/// recomputed all the time.
4646
pub def_path_hash: DefPathHash,
47+
48+
/// List of methods from `#[rustc_must_implement_one_of]` attribute one of which
49+
/// must be implemented.
50+
pub must_implement_one_of: Option<Box<[Ident]>>,
4751
}
4852

4953
/// Whether this trait is treated specially by the standard library
@@ -87,6 +91,7 @@ impl<'tcx> TraitDef {
8791
skip_array_during_method_dispatch: bool,
8892
specialization_kind: TraitSpecializationKind,
8993
def_path_hash: DefPathHash,
94+
must_implement_one_of: Option<Box<[Ident]>>,
9095
) -> TraitDef {
9196
TraitDef {
9297
def_id,
@@ -97,6 +102,7 @@ impl<'tcx> TraitDef {
97102
skip_array_during_method_dispatch,
98103
specialization_kind,
99104
def_path_hash,
105+
must_implement_one_of,
100106
}
101107
}
102108

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,7 @@ symbols! {
11361136
rustc_macro_transparency,
11371137
rustc_main,
11381138
rustc_mir,
1139+
rustc_must_implement_one_of,
11391140
rustc_nonnull_optimization_guaranteed,
11401141
rustc_object_lifetime_default,
11411142
rustc_on_unimplemented,

compiler/rustc_typeck/src/check/check.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -979,6 +979,10 @@ fn check_impl_items_against_trait<'tcx>(
979979
if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
980980
// Check for missing items from trait
981981
let mut missing_items = Vec::new();
982+
983+
let mut must_implement_one_of: Option<FxHashSet<Ident>> =
984+
trait_def.must_implement_one_of.as_deref().map(|slice| slice.iter().copied().collect());
985+
982986
for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
983987
let is_implemented = ancestors
984988
.leaf_def(tcx, trait_item_id)
@@ -987,12 +991,31 @@ fn check_impl_items_against_trait<'tcx>(
987991
if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
988992
missing_items.push(tcx.associated_item(trait_item_id));
989993
}
994+
995+
if let Some(required_items) = &must_implement_one_of {
996+
let trait_item = tcx.associated_item(trait_item_id);
997+
998+
if is_implemented && required_items.contains(&trait_item.ident) {
999+
must_implement_one_of = None;
1000+
}
1001+
}
9901002
}
9911003

9921004
if !missing_items.is_empty() {
9931005
let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
9941006
missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
9951007
}
1008+
1009+
if let Some(missing_items) = must_implement_one_of {
1010+
let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1011+
let attr_span = tcx
1012+
.get_attrs(impl_trait_ref.def_id)
1013+
.iter()
1014+
.find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1015+
.map(|attr| attr.span);
1016+
1017+
missing_items_must_implement_one_of_err(tcx, impl_span, &missing_items, attr_span);
1018+
}
9961019
}
9971020
}
9981021

compiler/rustc_typeck/src/check/mod.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,31 @@ fn missing_items_err(
641641
err.emit();
642642
}
643643

644+
fn missing_items_must_implement_one_of_err(
645+
tcx: TyCtxt<'_>,
646+
impl_span: Span,
647+
missing_items: &FxHashSet<Ident>,
648+
annotation_span: Option<Span>,
649+
) {
650+
let missing_items_msg =
651+
missing_items.iter().map(Ident::to_string).collect::<Vec<_>>().join("`, `");
652+
653+
let mut err = struct_span_err!(
654+
tcx.sess,
655+
impl_span,
656+
E0046,
657+
"not all trait items implemented, missing one of: `{}`",
658+
missing_items_msg
659+
);
660+
err.span_label(impl_span, format!("missing one of `{}` in implementation", missing_items_msg));
661+
662+
if let Some(annotation_span) = annotation_span {
663+
err.span_note(annotation_span, "required because of this annotation");
664+
}
665+
666+
err.emit();
667+
}
668+
644669
/// Resugar `ty::GenericPredicates` in a way suitable to be used in structured suggestions.
645670
fn bounds_from_generic_predicates<'tcx>(
646671
tcx: TyCtxt<'tcx>,

compiler/rustc_typeck/src/collect.rs

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,9 +1198,11 @@ fn super_predicates_that_define_assoc_type(
11981198
fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
11991199
let item = tcx.hir().expect_item(def_id.expect_local());
12001200

1201-
let (is_auto, unsafety) = match item.kind {
1202-
hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
1203-
hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal),
1201+
let (is_auto, unsafety, items) = match item.kind {
1202+
hir::ItemKind::Trait(is_auto, unsafety, .., items) => {
1203+
(is_auto == hir::IsAuto::Yes, unsafety, items)
1204+
}
1205+
hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]),
12041206
_ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
12051207
};
12061208

@@ -1227,6 +1229,80 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
12271229
ty::trait_def::TraitSpecializationKind::None
12281230
};
12291231
let def_path_hash = tcx.def_path_hash(def_id);
1232+
1233+
let must_implement_one_of = tcx
1234+
.get_attrs(def_id)
1235+
.iter()
1236+
.find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1237+
// Check that there are at least 2 arguments of `#[rustc_must_implement_one_of]`
1238+
// and that they are all identifiers
1239+
.and_then(|attr| match attr.meta_item_list() {
1240+
Some(items) if items.len() < 2 => {
1241+
tcx.sess
1242+
.struct_span_err(
1243+
attr.span,
1244+
"the `#[rustc_must_implement_one_of]` attribute must be \
1245+
used with at least 2 args",
1246+
)
1247+
.emit();
1248+
1249+
None
1250+
}
1251+
Some(items) => items
1252+
.into_iter()
1253+
.map(|item| item.ident().ok_or(item.span()))
1254+
.collect::<Result<Box<[_]>, _>>()
1255+
.map_err(|span| {
1256+
tcx.sess.struct_span_err(span, "must be an identifier of a method").emit();
1257+
})
1258+
.ok()
1259+
.zip(Some(attr.span)),
1260+
// Error is reported by `rustc_attr!`
1261+
None => None,
1262+
})
1263+
// Check that all arguments of `#[rustc_must_implement_one_of]` reference
1264+
// methods in the trait with default implementations
1265+
.and_then(|(list, attr_span)| {
1266+
let errors = list.iter().filter_map(|ident| {
1267+
let item = items.iter().find(|item| item.ident == *ident);
1268+
1269+
match item {
1270+
Some(item) if matches!(item.kind, hir::AssocItemKind::Fn { .. }) => {
1271+
if !item.defaultness.has_value() {
1272+
tcx.sess
1273+
.struct_span_err(
1274+
item.span,
1275+
"This method doesn't have a default implementation",
1276+
)
1277+
.span_note(attr_span, "required by this annotation")
1278+
.emit();
1279+
1280+
return Some(());
1281+
}
1282+
1283+
return None;
1284+
}
1285+
Some(item) => tcx
1286+
.sess
1287+
.struct_span_err(item.span, "Not a method")
1288+
.span_note(attr_span, "required by this annotation")
1289+
.note(
1290+
"All `#[rustc_must_implement_one_of]` arguments \
1291+
must be method identifiers",
1292+
)
1293+
.emit(),
1294+
None => tcx
1295+
.sess
1296+
.struct_span_err(ident.span, "Method not found in this trait")
1297+
.emit(),
1298+
}
1299+
1300+
Some(())
1301+
});
1302+
1303+
(errors.count() == 0).then_some(list)
1304+
});
1305+
12301306
ty::TraitDef::new(
12311307
def_id,
12321308
unsafety,
@@ -1236,6 +1312,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
12361312
skip_array_during_method_dispatch,
12371313
spec_kind,
12381314
def_path_hash,
1315+
must_implement_one_of,
12391316
)
12401317
}
12411318

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#![feature(rustc_attrs)]
2+
3+
#[rustc_must_implement_one_of(eq, neq)]
4+
trait Equal {
5+
fn eq(&self, other: &Self) -> bool {
6+
!self.neq(other)
7+
}
8+
9+
fn neq(&self, other: &Self) -> bool {
10+
!self.eq(other)
11+
}
12+
}
13+
14+
struct T0;
15+
struct T1;
16+
struct T2;
17+
struct T3;
18+
19+
impl Equal for T0 {
20+
fn eq(&self, _other: &Self) -> bool {
21+
true
22+
}
23+
}
24+
25+
impl Equal for T1 {
26+
fn neq(&self, _other: &Self) -> bool {
27+
false
28+
}
29+
}
30+
31+
impl Equal for T2 {
32+
fn eq(&self, _other: &Self) -> bool {
33+
true
34+
}
35+
36+
fn neq(&self, _other: &Self) -> bool {
37+
false
38+
}
39+
}
40+
41+
impl Equal for T3 {}
42+
//~^ not all trait items implemented, missing one of: `neq`, `eq`
43+
44+
fn main() {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0046]: not all trait items implemented, missing one of: `neq`, `eq`
2+
--> $DIR/rustc_must_implement_one_of.rs:41:1
3+
|
4+
LL | impl Equal for T3 {}
5+
| ^^^^^^^^^^^^^^^^^ missing one of `neq`, `eq` in implementation
6+
|
7+
note: required because of this annotation
8+
--> $DIR/rustc_must_implement_one_of.rs:3:1
9+
|
10+
LL | #[rustc_must_implement_one_of(eq, neq)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0046`.

0 commit comments

Comments
 (0)