Skip to content

Commit 6fc0273

Browse files
committed
Auto merge of #112320 - compiler-errors:do-not-impl-via-obj, r=lcnr
Add `implement_via_object` to `rustc_deny_explicit_impl` to control object candidate assembly Some built-in traits are special, since they are used to prove facts about the program that are important for later phases of compilation such as codegen and CTFE. For example, the `Unsize` trait is used to assert to the compiler that we are able to unsize a type into another type. It doesn't have any methods because it doesn't actually *instruct* the compiler how to do this unsizing, but this is later used (alongside an exhaustive match of combinations of unsizeable types) during codegen to generate unsize coercion code. Due to this, these built-in traits are incompatible with the type erasure provided by object types. For example, the existence of `dyn Unsize<T>` does not mean that the compiler is able to unsize `Box<dyn Unsize<T>>` into `Box<T>`, since `Unsize` is a *witness* to the fact that a type can be unsized, and it doesn't actually encode that unsizing operation in its vtable as mentioned above. The old trait solver gets around this fact by having complex control flow that never considers object bounds for certain built-in traits: https://github.com/rust-lang/rust/blob/2f896da247e0ee8f0bef7cd7c54cfbea255b9f68/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs#L61-L132 However, candidate assembly in the new solver is much more lovely, and I'd hate to add this list of opt-out cases into the new solver. Instead of maintaining this complex and hard-coded control flow, instead we can make this a property of the trait via a built-in attribute. We already have such a build attribute that's applied to every single trait that we care about: `rustc_deny_explicit_impl`. This PR adds `implement_via_object` as a meta-item to that attribute that allows us to opt a trait out of object-bound candidate assembly as well. r? `@lcnr`
2 parents b9d608c + ca68cf0 commit 6fc0273

File tree

21 files changed

+175
-60
lines changed

21 files changed

+175
-60
lines changed

compiler/rustc_feature/src/builtin_attrs.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -705,7 +705,11 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
705705
"#[rustc_allow_incoherent_impl] has to be added to all impl items of an incoherent inherent impl."
706706
),
707707
rustc_attr!(
708-
rustc_deny_explicit_impl, AttributeType::Normal, template!(Word), ErrorFollowing, @only_local: false,
708+
rustc_deny_explicit_impl,
709+
AttributeType::Normal,
710+
template!(List: "implement_via_object = (true|false)"),
711+
ErrorFollowing,
712+
@only_local: true,
709713
"#[rustc_deny_explicit_impl] enforces that a trait can have no user-provided impls"
710714
),
711715
rustc_attr!(

compiler/rustc_hir_analysis/src/coherence/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use rustc_errors::{error_code, struct_span_err};
1010
use rustc_hir::def_id::{DefId, LocalDefId};
1111
use rustc_middle::query::Providers;
1212
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
13-
use rustc_span::sym;
1413
use rustc_trait_selection::traits;
1514

1615
mod builtin;
@@ -44,7 +43,7 @@ fn enforce_trait_manually_implementable(
4443
let impl_header_span = tcx.def_span(impl_def_id);
4544

4645
// Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`
47-
if tcx.has_attr(trait_def_id, sym::rustc_deny_explicit_impl) {
46+
if tcx.trait_def(trait_def_id).deny_explicit_impl {
4847
let trait_name = tcx.item_name(trait_def_id);
4948
let mut err = struct_span_err!(
5049
tcx.sess,

compiler/rustc_hir_analysis/src/collect.rs

+46
Original file line numberDiff line numberDiff line change
@@ -991,6 +991,50 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
991991
no_dups.then_some(list)
992992
});
993993

994+
let mut deny_explicit_impl = false;
995+
let mut implement_via_object = true;
996+
if let Some(attr) = tcx.get_attr(def_id, sym::rustc_deny_explicit_impl) {
997+
deny_explicit_impl = true;
998+
let mut seen_attr = false;
999+
for meta in attr.meta_item_list().iter().flatten() {
1000+
if let Some(meta) = meta.meta_item()
1001+
&& meta.name_or_empty() == sym::implement_via_object
1002+
&& let Some(lit) = meta.name_value_literal()
1003+
{
1004+
if seen_attr {
1005+
tcx.sess.span_err(
1006+
meta.span,
1007+
"duplicated `implement_via_object` meta item",
1008+
);
1009+
}
1010+
seen_attr = true;
1011+
1012+
match lit.symbol {
1013+
kw::True => {
1014+
implement_via_object = true;
1015+
}
1016+
kw::False => {
1017+
implement_via_object = false;
1018+
}
1019+
_ => {
1020+
tcx.sess.span_err(
1021+
meta.span,
1022+
format!("unknown literal passed to `implement_via_object` attribute: {}", lit.symbol),
1023+
);
1024+
}
1025+
}
1026+
} else {
1027+
tcx.sess.span_err(
1028+
meta.span(),
1029+
format!("unknown meta item passed to `rustc_deny_explicit_impl` {:?}", meta),
1030+
);
1031+
}
1032+
}
1033+
if !seen_attr {
1034+
tcx.sess.span_err(attr.span, "missing `implement_via_object` meta item");
1035+
}
1036+
}
1037+
9941038
ty::TraitDef {
9951039
def_id: def_id.to_def_id(),
9961040
unsafety,
@@ -1001,6 +1045,8 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
10011045
skip_array_during_method_dispatch,
10021046
specialization_kind,
10031047
must_implement_one_of,
1048+
implement_via_object,
1049+
deny_explicit_impl,
10041050
}
10051051
}
10061052

compiler/rustc_middle/src/ty/trait_def.rs

+10
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ pub struct TraitDef {
5252
/// List of functions from `#[rustc_must_implement_one_of]` attribute one of which
5353
/// must be implemented.
5454
pub must_implement_one_of: Option<Box<[Ident]>>,
55+
56+
/// Whether to add a builtin `dyn Trait: Trait` implementation.
57+
/// This is enabled for all traits except ones marked with
58+
/// `#[rustc_deny_explicit_impl(implement_via_object = false)]`.
59+
pub implement_via_object: bool,
60+
61+
/// Whether a trait is fully built-in, and any implementation is disallowed.
62+
/// This only applies to built-in traits, and is marked via
63+
/// `#[rustc_deny_explicit_impl(implement_via_object = ...)]`.
64+
pub deny_explicit_impl: bool,
5565
}
5666

5767
/// Whether this trait is treated specially by the standard library

compiler/rustc_passes/messages.ftl

-3
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,6 @@ passes_const_impl_const_trait =
102102
const `impl`s must be for traits marked with `#[const_trait]`
103103
.note = this trait must be annotated with `#[const_trait]`
104104
105-
passes_const_trait =
106-
attribute should be applied to a trait
107-
108105
passes_continue_labeled_block =
109106
`continue` pointing to a labeled block
110107
.label = labeled blocks cannot be `continue`'d

compiler/rustc_passes/src/check_attr.rs

+6-37
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,6 @@ impl CheckAttrVisitor<'_> {
110110
sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
111111
sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
112112
sym::marker => self.check_marker(hir_id, attr, span, target),
113-
sym::rustc_must_implement_one_of => {
114-
self.check_rustc_must_implement_one_of(attr, span, target)
115-
}
116113
sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
117114
sym::thread_local => self.check_thread_local(attr, span, target),
118115
sym::track_caller => {
@@ -159,12 +156,14 @@ impl CheckAttrVisitor<'_> {
159156
| sym::rustc_dirty
160157
| sym::rustc_if_this_changed
161158
| sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
162-
sym::rustc_coinductive => self.check_rustc_coinductive(&attr, span, target),
159+
sym::rustc_coinductive
160+
| sym::rustc_must_implement_one_of
161+
| sym::rustc_deny_explicit_impl
162+
| sym::const_trait => self.check_must_be_applied_to_trait(&attr, span, target),
163163
sym::cmse_nonsecure_entry => {
164164
self.check_cmse_nonsecure_entry(hir_id, attr, span, target)
165165
}
166166
sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target),
167-
sym::const_trait => self.check_const_trait(attr, span, target),
168167
sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
169168
sym::must_use => self.check_must_use(hir_id, &attr, target),
170169
sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
@@ -567,25 +566,6 @@ impl CheckAttrVisitor<'_> {
567566
}
568567
}
569568

570-
/// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
571-
fn check_rustc_must_implement_one_of(
572-
&self,
573-
attr: &Attribute,
574-
span: Span,
575-
target: Target,
576-
) -> bool {
577-
match target {
578-
Target::Trait => true,
579-
_ => {
580-
self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
581-
attr_span: attr.span,
582-
defn_span: span,
583-
});
584-
false
585-
}
586-
}
587-
}
588-
589569
/// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
590570
fn check_target_feature(
591571
&self,
@@ -1591,8 +1571,8 @@ impl CheckAttrVisitor<'_> {
15911571
}
15921572
}
15931573

1594-
/// Checks if the `#[rustc_coinductive]` attribute is applied to a trait.
1595-
fn check_rustc_coinductive(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1574+
/// Checks if the attribute is applied to a trait.
1575+
fn check_must_be_applied_to_trait(&self, attr: &Attribute, span: Span, target: Target) -> bool {
15961576
match target {
15971577
Target::Trait => true,
15981578
_ => {
@@ -1986,17 +1966,6 @@ impl CheckAttrVisitor<'_> {
19861966
}
19871967
}
19881968

1989-
/// `#[const_trait]` only applies to traits.
1990-
fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1991-
match target {
1992-
Target::Trait => true,
1993-
_ => {
1994-
self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1995-
false
1996-
}
1997-
}
1998-
}
1999-
20001969
fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
20011970
match target {
20021971
Target::Expression => {

compiler/rustc_passes/src/errors.rs

-7
Original file line numberDiff line numberDiff line change
@@ -610,13 +610,6 @@ pub struct RustcStdInternalSymbol {
610610
pub span: Span,
611611
}
612612

613-
#[derive(Diagnostic)]
614-
#[diag(passes_const_trait)]
615-
pub struct ConstTrait {
616-
#[primary_span]
617-
pub attr_span: Span,
618-
}
619-
620613
#[derive(Diagnostic)]
621614
#[diag(passes_link_ordinal)]
622615
pub struct LinkOrdinal {

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -816,6 +816,7 @@ symbols! {
816816
impl_trait_in_bindings,
817817
impl_trait_in_fn_trait_return,
818818
impl_trait_projections,
819+
implement_via_object,
819820
implied_by,
820821
import,
821822
import_name_type,

compiler/rustc_trait_selection/src/solve/assembly/mod.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,11 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
640640
goal: Goal<'tcx, G>,
641641
candidates: &mut Vec<Candidate<'tcx>>,
642642
) {
643+
let tcx = self.tcx();
644+
if !tcx.trait_def(goal.predicate.trait_def_id(tcx)).implement_via_object {
645+
return;
646+
}
647+
643648
let self_ty = goal.predicate.self_ty();
644649
let bounds = match *self_ty.kind() {
645650
ty::Bool
@@ -672,7 +677,6 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
672677
ty::Dynamic(bounds, ..) => bounds,
673678
};
674679

675-
let tcx = self.tcx();
676680
let own_bounds: FxIndexSet<_> =
677681
bounds.iter().map(|bound| bound.with_self_ty(tcx, self_ty)).collect();
678682
for assumption in elaborate(tcx, own_bounds.iter().copied())

compiler/rustc_trait_selection/src/traits/project.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1607,6 +1607,10 @@ fn assemble_candidates_from_object_ty<'cx, 'tcx>(
16071607

16081608
let tcx = selcx.tcx();
16091609

1610+
if !tcx.trait_def(obligation.predicate.trait_def_id(tcx)).implement_via_object {
1611+
return;
1612+
}
1613+
16101614
let self_ty = obligation.predicate.self_ty();
16111615
let object_ty = selcx.infcx.shallow_resolve(self_ty);
16121616
let data = match object_ty.kind() {

compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

+4
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
552552
"assemble_candidates_from_object_ty",
553553
);
554554

555+
if !self.tcx().trait_def(obligation.predicate.def_id()).implement_via_object {
556+
return;
557+
}
558+
555559
self.infcx.probe(|_snapshot| {
556560
if obligation.has_non_region_late_bound() {
557561
return;

library/core/src/marker.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ unsafe impl<T: Sync + ?Sized> Send for &T {}
140140
)]
141141
#[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
142142
#[rustc_specialization_trait]
143-
#[rustc_deny_explicit_impl]
143+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
144+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
144145
#[rustc_coinductive]
145146
pub trait Sized {
146147
// Empty.
@@ -173,7 +174,8 @@ pub trait Sized {
173174
/// [nomicon-coerce]: ../../nomicon/coercions.html
174175
#[unstable(feature = "unsize", issue = "18598")]
175176
#[lang = "unsize"]
176-
#[rustc_deny_explicit_impl]
177+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
178+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
177179
pub trait Unsize<T: ?Sized> {
178180
// Empty.
179181
}
@@ -854,7 +856,8 @@ impl<T: ?Sized> StructuralEq for PhantomData<T> {}
854856
reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead"
855857
)]
856858
#[lang = "discriminant_kind"]
857-
#[rustc_deny_explicit_impl]
859+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
860+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
858861
pub trait DiscriminantKind {
859862
/// The type of the discriminant, which must satisfy the trait
860863
/// bounds required by `mem::Discriminant`.
@@ -959,7 +962,8 @@ marker_impls! {
959962
#[unstable(feature = "const_trait_impl", issue = "67792")]
960963
#[lang = "destruct"]
961964
#[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)]
962-
#[rustc_deny_explicit_impl]
965+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
966+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
963967
#[const_trait]
964968
pub trait Destruct {}
965969

@@ -970,7 +974,8 @@ pub trait Destruct {}
970974
#[unstable(feature = "tuple_trait", issue = "none")]
971975
#[lang = "tuple_trait"]
972976
#[rustc_on_unimplemented(message = "`{Self}` is not a tuple")]
973-
#[rustc_deny_explicit_impl]
977+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
978+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
974979
pub trait Tuple {}
975980

976981
/// A marker for pointer-like types.
@@ -1025,7 +1030,8 @@ impl ConstParamTy for () {}
10251030
reason = "internal trait for implementing various traits for all function pointers"
10261031
)]
10271032
#[lang = "fn_ptr_trait"]
1028-
#[rustc_deny_explicit_impl]
1033+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
1034+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
10291035
pub trait FnPtr: Copy + Clone {
10301036
/// Returns the address of the function pointer.
10311037
#[lang = "fn_ptr_addr"]

library/core/src/mem/transmutability.rs

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use crate::marker::ConstParamTy;
77
/// notwithstanding whatever safety checks you have asked the compiler to [`Assume`] are satisfied.
88
#[unstable(feature = "transmutability", issue = "99571")]
99
#[lang = "transmute_trait"]
10+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
11+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
1012
pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = { Assume::NOTHING }>
1113
where
1214
Src: ?Sized,

library/core/src/ptr/metadata.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ use crate::hash::{Hash, Hasher};
5050
///
5151
/// [`to_raw_parts`]: *const::to_raw_parts
5252
#[lang = "pointee_trait"]
53-
#[rustc_deny_explicit_impl]
53+
#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))]
54+
#[cfg_attr(bootstrap, rustc_deny_explicit_impl)]
5455
pub trait Pointee {
5556
/// The type for metadata in pointers and references to `Self`.
5657
#[lang = "metadata_type"]

tests/ui/rfcs/rfc-2632-const-trait-impl/attr-misuse.stderr

+4
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,16 @@ error: attribute should be applied to a trait
33
|
44
LL | #[const_trait]
55
| ^^^^^^^^^^^^^^
6+
LL | fn main() {}
7+
| ------------ not a trait
68

79
error: attribute should be applied to a trait
810
--> $DIR/attr-misuse.rs:5:5
911
|
1012
LL | #[const_trait]
1113
| ^^^^^^^^^^^^^^
14+
LL | fn foo(self);
15+
| ------------- not a trait
1216

1317
error: aborting due to 2 previous errors
1418

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `dyn NotObject: NotObject` is not satisfied
2+
--> $DIR/deny-builtin-object-impl.rs:18:23
3+
|
4+
LL | test_not_object::<dyn NotObject>();
5+
| ^^^^^^^^^^^^^ the trait `NotObject` is not implemented for `dyn NotObject`
6+
|
7+
note: required by a bound in `test_not_object`
8+
--> $DIR/deny-builtin-object-impl.rs:14:23
9+
|
10+
LL | fn test_not_object<T: NotObject + ?Sized>() {}
11+
| ^^^^^^^^^ required by this bound in `test_not_object`
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0277`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `dyn NotObject: NotObject` is not satisfied
2+
--> $DIR/deny-builtin-object-impl.rs:18:23
3+
|
4+
LL | test_not_object::<dyn NotObject>();
5+
| ^^^^^^^^^^^^^ the trait `NotObject` is not implemented for `dyn NotObject`
6+
|
7+
note: required by a bound in `test_not_object`
8+
--> $DIR/deny-builtin-object-impl.rs:14:23
9+
|
10+
LL | fn test_not_object<T: NotObject + ?Sized>() {}
11+
| ^^^^^^^^^ required by this bound in `test_not_object`
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)