Skip to content

Commit faf8d66

Browse files
authored
Rollup merge of rust-lang#92164 - WaffleLapkin:rustc_must_implement_one_of_attr, r=Aaron1011
Implement `#[rustc_must_implement_one_of]` attribute This PR adds a new attribute — `#[rustc_must_implement_one_of]` that allows changing the "minimal complete definition" of a trait. It's similar to GHC's minimal `{-# MINIMAL #-}` pragma, though `#[rustc_must_implement_one_of]` is weaker atm. Such attribute was long wanted. It can be, for example, used in `Read` trait to make transitions to recently added `read_buf` easier: ```rust #[rustc_must_implement_one_of(read, read_buf)] pub trait Read { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let mut buf = ReadBuf::new(buf); self.read_buf(&mut buf)?; Ok(buf.filled_len()) } fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> { default_read_buf(|b| self.read(b), buf) } } impl Read for Ty0 {} //^ This will fail to compile even though all `Read` methods have default implementations // Both of these will compile just fine impl Read for Ty1 { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { /* ... */ } } impl Read for Ty2 { fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> { /* ... */ } } ``` For now, this is implemented as an internal attribute to start experimenting on the design of this feature. In the future we may want to extend it: - Allow arbitrary requirements like `a | (b & c)` - Allow multiple requirements like - ```rust #[rustc_must_implement_one_of(a, b)] #[rustc_must_implement_one_of(c, d)] ``` - Make it appear in rustdoc documentation - Change the syntax? - Etc Eventually, we should make an RFC and make this (or rather similar) attribute public. --- I'm fairly new to compiler development and not at all sure if the implementation makes sense, but at least it passes tests :)
2 parents 219c5d3 + 4ccfa97 commit faf8d66

File tree

15 files changed

+357
-4
lines changed

15 files changed

+357
-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: "function1, function2, ..."), 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
@@ -1513,6 +1513,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
15131513
is_marker: trait_def.is_marker,
15141514
skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
15151515
specialization_kind: trait_def.specialization_kind,
1516+
must_implement_one_of: trait_def.must_implement_one_of.clone(),
15161517
};
15171518

15181519
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 functions 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: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,10 @@ fn check_impl_items_against_trait<'tcx>(
983983
if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
984984
// Check for missing items from trait
985985
let mut missing_items = Vec::new();
986+
987+
let mut must_implement_one_of: Option<FxHashSet<Ident>> =
988+
trait_def.must_implement_one_of.as_deref().map(|slice| slice.iter().copied().collect());
989+
986990
for &trait_item_id in tcx.associated_item_def_ids(impl_trait_ref.def_id) {
987991
let is_implemented = ancestors
988992
.leaf_def(tcx, trait_item_id)
@@ -991,12 +995,37 @@ fn check_impl_items_against_trait<'tcx>(
991995
if !is_implemented && tcx.impl_defaultness(impl_id).is_final() {
992996
missing_items.push(tcx.associated_item(trait_item_id));
993997
}
998+
999+
if let Some(required_items) = &must_implement_one_of {
1000+
// true if this item is specifically implemented in this impl
1001+
let is_implemented_here = ancestors
1002+
.leaf_def(tcx, trait_item_id)
1003+
.map_or(false, |node_item| !node_item.defining_node.is_from_trait());
1004+
1005+
if is_implemented_here {
1006+
let trait_item = tcx.associated_item(trait_item_id);
1007+
if required_items.contains(&trait_item.ident) {
1008+
must_implement_one_of = None;
1009+
}
1010+
}
1011+
}
9941012
}
9951013

9961014
if !missing_items.is_empty() {
9971015
let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
9981016
missing_items_err(tcx, impl_span, &missing_items, full_impl_span);
9991017
}
1018+
1019+
if let Some(missing_items) = must_implement_one_of {
1020+
let impl_span = tcx.sess.source_map().guess_head_span(full_impl_span);
1021+
let attr_span = tcx
1022+
.get_attrs(impl_trait_ref.def_id)
1023+
.iter()
1024+
.find(|attr| attr.has_name(sym::rustc_must_implement_one_of))
1025+
.map(|attr| attr.span);
1026+
1027+
missing_items_must_implement_one_of_err(tcx, impl_span, &missing_items, attr_span);
1028+
}
10001029
}
10011030
}
10021031

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: 82 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,9 +1197,11 @@ fn super_predicates_that_define_assoc_type(
11971197
fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> ty::TraitDef {
11981198
let item = tcx.hir().expect_item(def_id.expect_local());
11991199

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

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

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() {}

0 commit comments

Comments
 (0)