Skip to content

Commit 264f242

Browse files
Make the implementation better
1 parent 1820863 commit 264f242

15 files changed

+325
-35
lines changed

compiler/rustc_middle/src/query/keys.rs

+8
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,14 @@ impl Key for (DefId, SimplifiedType) {
320320
}
321321
}
322322

323+
impl Key for (DefId, Option<DefId>) {
324+
type Cache<V> = DefaultCache<Self, V>;
325+
326+
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
327+
self.0.default_span(tcx)
328+
}
329+
}
330+
323331
impl<'tcx> Key for GenericArgsRef<'tcx> {
324332
type Cache<V> = DefaultCache<Self, V>;
325333

compiler/rustc_middle/src/query/mod.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1370,11 +1370,12 @@ rustc_queries! {
13701370
desc { |tcx| "checking if trait `{}` is dyn-compatible", tcx.def_path_str(trait_id) }
13711371
}
13721372

1373-
query trait_has_impl_which_may_shadow_dyn(trait_def_id: DefId) -> bool {
1373+
query trait_has_impl_which_may_shadow_dyn(key: (DefId, Option<DefId>)) -> bool {
13741374
desc {
13751375
|tcx| "checking if trait `{}` has an impl which may overlap with \
1376-
the built-in impl for trait objects",
1377-
tcx.def_path_str(trait_def_id)
1376+
the built-in impl for `dyn {}`",
1377+
tcx.def_path_str(key.0),
1378+
key.1.map_or(String::from("..."), |def_id| tcx.def_path_str(def_id)),
13781379
}
13791380
}
13801381

compiler/rustc_middle/src/ty/context.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -578,8 +578,12 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
578578
self.trait_def(trait_def_id).implement_via_object
579579
}
580580

581-
fn trait_has_impl_which_may_shadow_dyn(self, trait_def_id: DefId) -> bool {
582-
self.trait_has_impl_which_may_shadow_dyn(trait_def_id)
581+
fn trait_has_impl_which_may_shadow_dyn(
582+
self,
583+
trait_def_id: DefId,
584+
principal_def_id: Option<DefId>,
585+
) -> bool {
586+
self.trait_has_impl_which_may_shadow_dyn((trait_def_id, principal_def_id))
583587
}
584588

585589
fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {

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

+8-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,14 @@ where
8282
goal: Goal<I, Self>,
8383
assumption: I::Clause,
8484
) -> Result<Candidate<I>, NoSolution> {
85-
if ecx.cx().trait_has_impl_which_may_shadow_dyn(goal.predicate.trait_def_id(ecx.cx())) {
85+
let ty::Dynamic(data, _, _) = goal.predicate.self_ty().kind() else {
86+
unreachable!();
87+
};
88+
89+
if ecx.cx().trait_has_impl_which_may_shadow_dyn(
90+
goal.predicate.trait_def_id(ecx.cx()),
91+
data.principal_def_id(),
92+
) {
8693
return Err(NoSolution);
8794
}
8895

compiler/rustc_trait_selection/src/traits/project.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -842,7 +842,12 @@ fn assemble_candidates_from_object_ty<'cx, 'tcx>(
842842
let env_predicates = data
843843
.projection_bounds()
844844
.filter(|bound| bound.item_def_id() == obligation.predicate.def_id)
845-
.filter(|bound| !tcx.trait_has_impl_which_may_shadow_dyn(bound.trait_def_id(tcx)))
845+
.filter(|bound| {
846+
!tcx.trait_has_impl_which_may_shadow_dyn((
847+
bound.trait_def_id(tcx),
848+
data.principal_def_id(),
849+
))
850+
})
846851
.map(|p| p.with_self_ty(tcx, object_ty).upcast(tcx));
847852

848853
assemble_candidates_from_predicates(

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -916,7 +916,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
916916
})
917917
})
918918
.filter(|(_, trait_ref)| {
919-
!tcx.trait_has_impl_which_may_shadow_dyn(trait_ref.def_id())
919+
!tcx.trait_has_impl_which_may_shadow_dyn((
920+
trait_ref.def_id(),
921+
Some(principal_trait_ref.def_id()),
922+
))
920923
})
921924
.map(|(idx, _)| ObjectCandidate(idx));
922925

compiler/rustc_trait_selection/src/traits/specialize/mod.rs

+87-25
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
1212
pub mod specialization_graph;
1313

14-
use rustc_data_structures::fx::FxIndexSet;
14+
use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
1515
use rustc_errors::codes::*;
1616
use rustc_errors::{Diag, EmissionGuarantee};
1717
use rustc_hir::LangItem;
@@ -25,6 +25,8 @@ use rustc_middle::ty::{
2525
};
2626
use rustc_session::lint::builtin::{COHERENCE_LEAK_CHECK, ORDER_DEPENDENT_TRAIT_OBJECTS};
2727
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym};
28+
use rustc_type_ir::elaborate;
29+
use rustc_type_ir::fast_reject::{SimplifiedType, TreatParams, simplify_type};
2830
use specialization_graph::GraphExt;
2931
use tracing::{debug, instrument};
3032

@@ -484,20 +486,62 @@ fn report_conflicting_impls<'tcx>(
484486

485487
pub(super) fn trait_has_impl_which_may_shadow_dyn<'tcx>(
486488
tcx: TyCtxt<'tcx>,
487-
trait_def_id: DefId,
489+
(target_trait_def_id, principal_def_id): (DefId, Option<DefId>),
488490
) -> bool {
489491
// We only care about trait objects which have associated types.
490492
if !tcx
491-
.associated_items(trait_def_id)
493+
.associated_items(target_trait_def_id)
492494
.in_definition_order()
493495
.any(|item| item.kind == ty::AssocKind::Type)
494496
{
495497
return false;
496498
}
497499

498-
let mut has_impl = false;
499-
tcx.for_each_impl(trait_def_id, |impl_def_id| {
500-
if has_impl {
500+
let target_self_ty =
501+
principal_def_id.map_or(SimplifiedType::MarkerTraitObject, SimplifiedType::Trait);
502+
503+
let elaborated_supertraits =
504+
principal_def_id.into_iter().flat_map(|def_id| tcx.supertrait_def_ids(def_id)).collect();
505+
506+
trait_has_impl_inner(
507+
tcx,
508+
target_trait_def_id,
509+
target_self_ty,
510+
&elaborated_supertraits,
511+
&mut Default::default(),
512+
true,
513+
)
514+
}
515+
516+
fn trait_has_impl_inner<'tcx>(
517+
tcx: TyCtxt<'tcx>,
518+
target_trait_def_id: DefId,
519+
target_self_ty: SimplifiedType<DefId>,
520+
elaborated_supertraits: &FxHashSet<DefId>,
521+
seen_traits: &mut FxHashSet<DefId>,
522+
first_generation: bool,
523+
) -> bool {
524+
if tcx.is_lang_item(target_trait_def_id, LangItem::Sized) {
525+
return false;
526+
}
527+
528+
// If we've encountered a trait in a cycle, then let's just
529+
// consider it to be implemented defensively.
530+
if !seen_traits.insert(target_trait_def_id) {
531+
return true;
532+
}
533+
// Since we don't pass in the set of auto traits, and just the principal,
534+
// consider all auto traits implemented.
535+
if tcx.trait_is_auto(target_trait_def_id) {
536+
return true;
537+
}
538+
if !first_generation && elaborated_supertraits.contains(&target_trait_def_id) {
539+
return true;
540+
}
541+
542+
let mut has_offending_impl = false;
543+
tcx.for_each_impl(target_trait_def_id, |impl_def_id| {
544+
if has_offending_impl {
501545
return;
502546
}
503547

@@ -506,33 +550,51 @@ pub(super) fn trait_has_impl_which_may_shadow_dyn<'tcx>(
506550
.expect("impl must have trait ref")
507551
.instantiate_identity()
508552
.self_ty();
509-
if self_ty.is_known_rigid() {
510-
return;
511-
}
512553

513-
let sized_trait = tcx.require_lang_item(LangItem::Sized, None);
514-
if tcx
515-
.param_env(impl_def_id)
516-
.caller_bounds()
517-
.iter()
518-
.filter_map(|clause| clause.as_trait_clause())
519-
.any(|bound| bound.def_id() == sized_trait && bound.self_ty().skip_binder() == self_ty)
554+
if simplify_type(tcx, self_ty, TreatParams::InstantiateWithInfer)
555+
.is_some_and(|simp| simp != target_self_ty)
520556
{
521557
return;
522558
}
523559

524-
if let ty::Alias(ty::Projection, alias_ty) = self_ty.kind()
525-
&& tcx
526-
.item_super_predicates(alias_ty.def_id)
527-
.iter_identity()
528-
.filter_map(|clause| clause.as_trait_clause())
529-
.any(|bound| bound.def_id() == sized_trait)
560+
for (pred, _) in
561+
elaborate::elaborate(tcx, tcx.predicates_of(impl_def_id).instantiate_identity(tcx))
530562
{
531-
return;
563+
if let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
564+
&& trait_pred.self_ty() == self_ty
565+
&& !trait_has_impl_inner(
566+
tcx,
567+
trait_pred.def_id(),
568+
target_self_ty,
569+
elaborated_supertraits,
570+
seen_traits,
571+
false,
572+
)
573+
{
574+
return;
575+
}
576+
}
577+
578+
if let ty::Alias(ty::Projection, alias_ty) = self_ty.kind() {
579+
for pred in tcx.item_super_predicates(alias_ty.def_id).iter_identity() {
580+
if let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
581+
&& trait_pred.self_ty() == self_ty
582+
&& !trait_has_impl_inner(
583+
tcx,
584+
trait_pred.def_id(),
585+
target_self_ty,
586+
elaborated_supertraits,
587+
seen_traits,
588+
false,
589+
)
590+
{
591+
return;
592+
}
593+
}
532594
}
533595

534-
has_impl = true;
596+
has_offending_impl = true;
535597
});
536598

537-
has_impl
599+
has_offending_impl
538600
}

compiler/rustc_type_ir/src/interner.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,11 @@ pub trait Interner:
269269

270270
fn trait_may_be_implemented_via_object(self, trait_def_id: Self::DefId) -> bool;
271271

272-
fn trait_has_impl_which_may_shadow_dyn(self, trait_def_id: Self::DefId) -> bool;
272+
fn trait_has_impl_which_may_shadow_dyn(
273+
self,
274+
trait_def_id: Self::DefId,
275+
principal_def_id: Option<Self::DefId>,
276+
) -> bool;
273277

274278
fn is_impl_trait_in_trait(self, def_id: Self::DefId) -> bool;
275279

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//@ check-pass
2+
3+
// Make sure that if we don't disqualify a built-in object impl
4+
// due to a blanket with a trait bound that will never apply to
5+
// the object.
6+
7+
pub trait SimpleService {
8+
type Resp;
9+
}
10+
11+
trait Service {
12+
type Resp;
13+
}
14+
15+
impl<S> Service for S where S: SimpleService + ?Sized {
16+
type Resp = <S as SimpleService>::Resp;
17+
}
18+
19+
fn implements_service(x: &(impl Service<Resp = ()> + ?Sized)) {}
20+
21+
fn test(x: &dyn Service<Resp = ()>) {
22+
implements_service(x);
23+
}
24+
25+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
trait Trait {
2+
type Assoc;
3+
fn generate(&self) -> Self::Assoc;
4+
}
5+
6+
trait Other {}
7+
8+
impl<S> Trait for S where S: Other + ?Sized {
9+
type Assoc = &'static str;
10+
fn generate(&self) -> Self::Assoc { "hi" }
11+
}
12+
13+
trait Downstream: Trait<Assoc = usize> {}
14+
impl<T> Other for T where T: ?Sized + Downstream + OnlyDyn {}
15+
16+
trait OnlyDyn {}
17+
impl OnlyDyn for dyn Downstream {}
18+
19+
struct Concrete;
20+
impl Trait for Concrete {
21+
type Assoc = usize;
22+
fn generate(&self) -> Self::Assoc { 42 }
23+
}
24+
impl Downstream for Concrete {}
25+
26+
fn test<T: ?Sized + Other>(x: &T) {
27+
let s: &str = x.generate();
28+
println!("{s}");
29+
}
30+
31+
fn impl_downstream<T: ?Sized + Downstream>(x: &T) {}
32+
33+
fn main() {
34+
let x: &dyn Downstream = &Concrete;
35+
36+
test(x); // This call used to segfault.
37+
//~^ ERROR type mismatch resolving
38+
39+
// This no longer holds since `Downstream: Trait<Assoc = usize>`,
40+
// but the `Trait<Assoc = &'static str>` blanket impl now shadows.
41+
impl_downstream(x);
42+
//~^ ERROR type mismatch resolving
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
error[E0271]: type mismatch resolving `<dyn Downstream as Trait>::Assoc == usize`
2+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:36:10
3+
|
4+
LL | test(x); // This call used to segfault.
5+
| ---- ^ type mismatch resolving `<dyn Downstream as Trait>::Assoc == usize`
6+
| |
7+
| required by a bound introduced by this call
8+
|
9+
note: expected this to be `usize`
10+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:9:18
11+
|
12+
LL | type Assoc = &'static str;
13+
| ^^^^^^^^^^^^
14+
note: required for `dyn Downstream` to implement `Other`
15+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:14:9
16+
|
17+
LL | impl<T> Other for T where T: ?Sized + Downstream + OnlyDyn {}
18+
| ^^^^^ ^ ---------- unsatisfied trait bound introduced here
19+
= note: associated types for the current `impl` cannot be restricted in `where` clauses
20+
note: required by a bound in `test`
21+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:26:21
22+
|
23+
LL | fn test<T: ?Sized + Other>(x: &T) {
24+
| ^^^^^ required by this bound in `test`
25+
26+
error[E0271]: type mismatch resolving `<dyn Downstream as Trait>::Assoc == usize`
27+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:41:21
28+
|
29+
LL | impl_downstream(x);
30+
| --------------- ^ type mismatch resolving `<dyn Downstream as Trait>::Assoc == usize`
31+
| |
32+
| required by a bound introduced by this call
33+
|
34+
note: expected this to be `usize`
35+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:9:18
36+
|
37+
LL | type Assoc = &'static str;
38+
| ^^^^^^^^^^^^
39+
note: required by a bound in `impl_downstream`
40+
--> $DIR/indirect-impl-blanket-downstream-trait-2.rs:31:32
41+
|
42+
LL | fn impl_downstream<T: ?Sized + Downstream>(x: &T) {}
43+
| ^^^^^^^^^^ required by this bound in `impl_downstream`
44+
45+
error: aborting due to 2 previous errors
46+
47+
For more information about this error, try `rustc --explain E0271`.

0 commit comments

Comments
 (0)