Skip to content

Commit ab276b8

Browse files
Rollup merge of rust-lang#89461 - crlf0710:dyn_upcasting_lint, r=nikomatsakis
Add `deref_into_dyn_supertrait` lint. Initial implementation of rust-lang#89460. Resolves rust-lang#89190. Maybe also worth a beta backport if necessary. r? `@nikomatsakis`
2 parents 1584b6a + 250d126 commit ab276b8

File tree

6 files changed

+168
-1
lines changed

6 files changed

+168
-1
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4454,6 +4454,7 @@ dependencies = [
44544454
"rustc_hir",
44554455
"rustc_index",
44564456
"rustc_infer",
4457+
"rustc_lint_defs",
44574458
"rustc_macros",
44584459
"rustc_middle",
44594460
"rustc_parse_format",

compiler/rustc_lint_defs/src/builtin.rs

+46
Original file line numberDiff line numberDiff line change
@@ -3051,6 +3051,7 @@ declare_lint_pass! {
30513051
BREAK_WITH_LABEL_AND_LOOP,
30523052
UNUSED_ATTRIBUTES,
30533053
NON_EXHAUSTIVE_OMITTED_PATTERNS,
3054+
DEREF_INTO_DYN_SUPERTRAIT,
30543055
]
30553056
}
30563057

@@ -3512,3 +3513,48 @@ declare_lint! {
35123513
Allow,
35133514
"detect when patterns of types marked `non_exhaustive` are missed",
35143515
}
3516+
3517+
declare_lint! {
3518+
/// The `deref_into_dyn_supertrait` lint is output whenever there is a use of the
3519+
/// `Deref` implementation with a `dyn SuperTrait` type as `Output`.
3520+
///
3521+
/// These implementations will become shadowed when the `trait_upcasting` feature is stablized.
3522+
/// The `deref` functions will no longer be called implicitly, so there might be behavior change.
3523+
///
3524+
/// ### Example
3525+
///
3526+
/// ```rust,compile_fail
3527+
/// #![deny(deref_into_dyn_supertrait)]
3528+
/// #![allow(dead_code)]
3529+
///
3530+
/// use core::ops::Deref;
3531+
///
3532+
/// trait A {}
3533+
/// trait B: A {}
3534+
/// impl<'a> Deref for dyn 'a + B {
3535+
/// type Target = dyn A;
3536+
/// fn deref(&self) -> &Self::Target {
3537+
/// todo!()
3538+
/// }
3539+
/// }
3540+
///
3541+
/// fn take_a(_: &dyn A) { }
3542+
///
3543+
/// fn take_b(b: &dyn B) {
3544+
/// take_a(b);
3545+
/// }
3546+
/// ```
3547+
///
3548+
/// {{produces}}
3549+
///
3550+
/// ### Explanation
3551+
///
3552+
/// The dyn upcasting coercion feature adds new coercion rules, taking priority
3553+
/// over certain other coercion rules, which will cause some behavior change.
3554+
pub DEREF_INTO_DYN_SUPERTRAIT,
3555+
Warn,
3556+
"`Deref` implementation usage with a supertrait trait object for output might be shadowed in the future",
3557+
@future_incompatible = FutureIncompatibleInfo {
3558+
reference: "issue #89460 <https://github.com/rust-lang/rust/issues/89460>",
3559+
};
3560+
}

compiler/rustc_trait_selection/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ rustc_errors = { path = "../rustc_errors" }
1717
rustc_hir = { path = "../rustc_hir" }
1818
rustc_index = { path = "../rustc_index" }
1919
rustc_infer = { path = "../rustc_infer" }
20+
rustc_lint_defs = { path = "../rustc_lint_defs" }
2021
rustc_macros = { path = "../rustc_macros" }
2122
rustc_query_system = { path = "../rustc_query_system" }
2223
rustc_session = { path = "../rustc_session" }

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

+79-1
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,17 @@
66
//!
77
//! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
88
use rustc_hir as hir;
9+
use rustc_hir::def_id::DefId;
10+
use rustc_infer::traits::TraitEngine;
911
use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
12+
use rustc_lint_defs::builtin::DEREF_INTO_DYN_SUPERTRAIT;
1013
use rustc_middle::ty::print::with_no_trimmed_paths;
11-
use rustc_middle::ty::{self, Ty, TypeFoldable};
14+
use rustc_middle::ty::{self, ToPredicate, Ty, TypeFoldable, WithConstness};
1215
use rustc_target::spec::abi::Abi;
1316

17+
use crate::traits;
1418
use crate::traits::coherence::Conflict;
19+
use crate::traits::query::evaluate_obligation::InferCtxtExt;
1520
use crate::traits::{util, SelectionResult};
1621
use crate::traits::{Overflow, Unimplemented};
1722

@@ -672,6 +677,55 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
672677
})
673678
}
674679

680+
/// Temporary migration for #89190
681+
fn need_migrate_deref_output_trait_object(
682+
&mut self,
683+
ty: Ty<'tcx>,
684+
cause: &traits::ObligationCause<'tcx>,
685+
param_env: ty::ParamEnv<'tcx>,
686+
) -> Option<(Ty<'tcx>, DefId)> {
687+
let tcx = self.tcx();
688+
if tcx.features().trait_upcasting {
689+
return None;
690+
}
691+
692+
// <ty as Deref>
693+
let trait_ref = ty::TraitRef {
694+
def_id: tcx.lang_items().deref_trait()?,
695+
substs: tcx.mk_substs_trait(ty, &[]),
696+
};
697+
698+
let obligation = traits::Obligation::new(
699+
cause.clone(),
700+
param_env,
701+
ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
702+
);
703+
if !self.infcx.predicate_may_hold(&obligation) {
704+
return None;
705+
}
706+
707+
let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
708+
let normalized_ty = fulfillcx.normalize_projection_type(
709+
&self.infcx,
710+
param_env,
711+
ty::ProjectionTy {
712+
item_def_id: tcx.lang_items().deref_target()?,
713+
substs: trait_ref.substs,
714+
},
715+
cause.clone(),
716+
);
717+
718+
let data = if let ty::Dynamic(ref data, ..) = normalized_ty.kind() {
719+
data
720+
} else {
721+
return None;
722+
};
723+
724+
let def_id = data.principal_def_id()?;
725+
726+
return Some((normalized_ty, def_id));
727+
}
728+
675729
/// Searches for unsizing that might apply to `obligation`.
676730
fn assemble_candidates_for_unsizing(
677731
&mut self,
@@ -732,6 +786,30 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
732786
let principal_a = data_a.principal().unwrap();
733787
let target_trait_did = principal_def_id_b.unwrap();
734788
let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
789+
if let Some((deref_output_ty, deref_output_trait_did)) = self
790+
.need_migrate_deref_output_trait_object(
791+
source,
792+
&obligation.cause,
793+
obligation.param_env,
794+
)
795+
{
796+
if deref_output_trait_did == target_trait_did {
797+
self.tcx().struct_span_lint_hir(
798+
DEREF_INTO_DYN_SUPERTRAIT,
799+
obligation.cause.body_id,
800+
obligation.cause.span,
801+
|lint| {
802+
lint.build(&format!(
803+
"`{}` implements `Deref` with supertrait `{}` as output",
804+
source,
805+
deref_output_ty
806+
)).emit();
807+
},
808+
);
809+
return;
810+
}
811+
}
812+
735813
for (idx, upcast_trait_ref) in
736814
util::supertraits(self.tcx(), source_trait_ref).enumerate()
737815
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#![deny(deref_into_dyn_supertrait)]
2+
3+
extern crate core;
4+
5+
use core::ops::Deref;
6+
7+
// issue 89190
8+
trait A {}
9+
trait B: A {}
10+
impl<'a> Deref for dyn 'a + B {
11+
type Target = dyn A;
12+
fn deref(&self) -> &Self::Target {
13+
todo!()
14+
}
15+
}
16+
17+
fn take_a(_: &dyn A) {}
18+
19+
fn whoops(b: &dyn B) {
20+
take_a(b)
21+
//~^ ERROR `dyn B` implements `Deref` with supertrait `(dyn A + 'static)` as output
22+
//~^^ WARN this was previously accepted by the compiler but is being phased out;
23+
}
24+
25+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: `dyn B` implements `Deref` with supertrait `(dyn A + 'static)` as output
2+
--> $DIR/migrate-lint-deny.rs:20:12
3+
|
4+
LL | take_a(b)
5+
| ^
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/migrate-lint-deny.rs:1:9
9+
|
10+
LL | #![deny(deref_into_dyn_supertrait)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^
12+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
13+
= note: for more information, see issue #89460 <https://github.com/rust-lang/rust/issues/89460>
14+
15+
error: aborting due to previous error
16+

0 commit comments

Comments
 (0)