Skip to content

Commit

Permalink
Rollup merge of rust-lang#134367 - WaffleLapkin:trait_upcasting_as_a_…
Browse files Browse the repository at this point in the history
…treat, r=compiler-errors

Stabilize `feature(trait_upcasting)`

This feature was "done" for a while now, I think it's finally time to stabilize it! Stabilization report: rust-lang#134367 (comment).
cc reference PR: rust-lang/reference#1622.

Closes rust-lang#65991 (tracking issue), closes rust-lang#89460 (the lint is no longer future incompat).

r? compiler-errors
  • Loading branch information
matthiaskrgr authored Feb 7, 2025
2 parents 64e06c0 + 4915995 commit cbd44d7
Show file tree
Hide file tree
Showing 94 changed files with 140 additions and 479 deletions.
3 changes: 3 additions & 0 deletions compiler/rustc_feature/src/accepted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,9 @@ declare_features! (
/// Allows `#[track_caller]` to be used which provides
/// accurate caller location reporting during panic (RFC 2091).
(accepted, track_caller, "1.46.0", Some(47809)),
/// Allows dyn upcasting trait objects via supertraits.
/// Dyn upcasting is casting, e.g., `dyn Foo -> dyn Bar` where `Foo: Bar`.
(accepted, trait_upcasting, "CURRENT_RUSTC_VERSION", Some(65991)),
/// Allows #[repr(transparent)] on univariant enums (RFC 2645).
(accepted, transparent_enums, "1.42.0", Some(60405)),
/// Allows indexing tuples.
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,9 +634,6 @@ declare_features! (
(unstable, thread_local, "1.0.0", Some(29594)),
/// Allows defining `trait X = A + B;` alias items.
(unstable, trait_alias, "1.24.0", Some(41517)),
/// Allows dyn upcasting trait objects via supertraits.
/// Dyn upcasting is casting, e.g., `dyn Foo -> dyn Bar` where `Foo: Bar`.
(unstable, trait_upcasting, "1.56.0", Some(65991)),
/// Allows for transmuting between arrays with sizes that contain generic consts.
(unstable, transmute_generic_consts, "1.70.0", Some(109929)),
/// Allows #[repr(transparent)] on unions (RFC 2645).
Expand Down
23 changes: 0 additions & 23 deletions compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
)];

let mut has_unsized_tuple_coercion = false;
let mut has_trait_upcasting_coercion = None;

// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
// emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
Expand Down Expand Up @@ -690,13 +689,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// these here and emit a feature error if coercion doesn't fail
// due to another reason.
match impl_source {
traits::ImplSource::Builtin(
BuiltinImplSource::TraitUpcasting { .. },
_,
) => {
has_trait_upcasting_coercion =
Some((trait_pred.self_ty(), trait_pred.trait_ref.args.type_at(1)));
}
traits::ImplSource::Builtin(BuiltinImplSource::TupleUnsizing, _) => {
has_unsized_tuple_coercion = true;
}
Expand All @@ -707,21 +699,6 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
}
}

if let Some((sub, sup)) = has_trait_upcasting_coercion
&& !self.tcx().features().trait_upcasting()
{
// Renders better when we erase regions, since they're not really the point here.
let (sub, sup) = self.tcx.erase_regions((sub, sup));
let mut err = feature_err(
&self.tcx.sess,
sym::trait_upcasting,
self.cause.span,
format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
);
err.note(format!("required when coercing `{source}` into `{target}`"));
err.emit();
}

if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion() {
feature_err(
&self.tcx.sess,
Expand Down
25 changes: 12 additions & 13 deletions compiler/rustc_lint/src/deref_into_dyn_supertrait.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use rustc_hir::{self as hir, LangItem};
use rustc_middle::ty;
use rustc_session::lint::FutureIncompatibilityReason;
use rustc_session::{declare_lint, declare_lint_pass};
use rustc_span::sym;
use rustc_trait_selection::traits::supertraits;
Expand All @@ -9,11 +8,12 @@ use crate::lints::{SupertraitAsDerefTarget, SupertraitAsDerefTargetLabel};
use crate::{LateContext, LateLintPass, LintContext};

declare_lint! {
/// The `deref_into_dyn_supertrait` lint is output whenever there is a use of the
/// `Deref` implementation with a `dyn SuperTrait` type as `Output`.
/// The `deref_into_dyn_supertrait` lint is emitted whenever there is a `Deref` implementation
/// for `dyn SubTrait` with a `dyn SuperTrait` type as the `Output` type.
///
/// These implementations will become shadowed when the `trait_upcasting` feature is stabilized.
/// The `deref` functions will no longer be called implicitly, so there might be behavior change.
/// These implementations are "shadowed" by trait upcasting (stabilized since
/// CURRENT_RUSTC_VERSION). The `deref` functions is no longer called implicitly, which might
/// change behavior compared to previous rustc versions.
///
/// ### Example
///
Expand Down Expand Up @@ -43,15 +43,14 @@ declare_lint! {
///
/// ### Explanation
///
/// The dyn upcasting coercion feature adds new coercion rules, taking priority
/// over certain other coercion rules, which will cause some behavior change.
/// The trait upcasting coercion added a new coercion rule, taking priority over certain other
/// coercion rules, which causes some behavior change compared to older `rustc` versions.
///
/// `deref` can be still called explicitly, it just isn't called as part of a deref coercion
/// (since trait upcasting coercion takes priority).
pub DEREF_INTO_DYN_SUPERTRAIT,
Warn,
"`Deref` implementation usage with a supertrait trait object for output might be shadowed in the future",
@future_incompatible = FutureIncompatibleInfo {
reason: FutureIncompatibilityReason::FutureReleaseSemanticsChange,
reference: "issue #89460 <https://github.com/rust-lang/rust/issues/89460>",
};
Allow,
"`Deref` implementation with a supertrait trait object for output is shadowed by trait upcasting",
}

declare_lint_pass!(DerefIntoDynSupertrait => [DEREF_INTO_DYN_SUPERTRAIT]);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
// tidy-alphabetical-start
#![allow(internal_features)]
#![cfg_attr(bootstrap, feature(trait_upcasting))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(array_windows)]
Expand All @@ -32,7 +33,6 @@
#![feature(let_chains)]
#![feature(rustc_attrs)]
#![feature(rustdoc_internals)]
#![feature(trait_upcasting)]
#![warn(unreachable_pub)]
// tidy-alphabetical-end

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::potential_query_instability)]
#![allow(rustc::untranslatable_diagnostic)]
#![cfg_attr(bootstrap, feature(trait_upcasting))]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(allocator_api)]
Expand Down Expand Up @@ -56,7 +57,6 @@
#![feature(ptr_alignment_type)]
#![feature(rustc_attrs)]
#![feature(rustdoc_internals)]
#![feature(trait_upcasting)]
#![feature(trusted_len)]
#![feature(try_blocks)]
#![feature(try_trait_v2)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ use hir::LangItem;
use hir::def_id::DefId;
use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
use rustc_hir as hir;
use rustc_infer::traits::{
Obligation, ObligationCause, PolyTraitObligation, PredicateObligations, SelectionError,
};
use rustc_infer::traits::{Obligation, PolyTraitObligation, SelectionError};
use rustc_middle::ty::fast_reject::DeepRejectCtxt;
use rustc_middle::ty::{self, Ty, TypeVisitableExt, TypingMode};
use rustc_middle::{bug, span_bug};
Expand All @@ -23,8 +21,6 @@ use tracing::{debug, instrument, trace};

use super::SelectionCandidate::*;
use super::{BuiltinImplConditions, SelectionCandidateSet, SelectionContext, TraitObligationStack};
use crate::traits;
use crate::traits::query::evaluate_obligation::InferCtxtExt;
use crate::traits::util;

impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
Expand Down Expand Up @@ -904,54 +900,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
})
}

/// Temporary migration for #89190
fn need_migrate_deref_output_trait_object(
&mut self,
ty: Ty<'tcx>,
param_env: ty::ParamEnv<'tcx>,
cause: &ObligationCause<'tcx>,
) -> Option<ty::PolyExistentialTraitRef<'tcx>> {
// Don't drop any candidates in intercrate mode, as it's incomplete.
// (Not that it matters, since `Unsize` is not a stable trait.)
//
// FIXME(@lcnr): This should probably only trigger during analysis,
// disabling candidates during codegen is also questionable.
if let TypingMode::Coherence = self.infcx.typing_mode() {
return None;
}

let tcx = self.tcx();
if tcx.features().trait_upcasting() {
return None;
}

// <ty as Deref>
let trait_ref = ty::TraitRef::new(tcx, tcx.lang_items().deref_trait()?, [ty]);

let obligation =
traits::Obligation::new(tcx, cause.clone(), param_env, ty::Binder::dummy(trait_ref));
if !self.infcx.predicate_may_hold(&obligation) {
return None;
}

self.infcx.probe(|_| {
let ty = traits::normalize_projection_ty(
self,
param_env,
ty::AliasTy::new_from_args(tcx, tcx.lang_items().deref_target()?, trait_ref.args),
cause.clone(),
0,
// We're *intentionally* throwing these away,
// since we don't actually use them.
&mut PredicateObligations::new(),
)
.as_type()
.unwrap();

if let ty::Dynamic(data, ..) = ty.kind() { data.principal() } else { None }
})
}

/// Searches for unsizing that might apply to `obligation`.
fn assemble_candidates_for_unsizing(
&mut self,
Expand Down Expand Up @@ -1019,15 +967,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let principal_a = a_data.principal().unwrap();
let target_trait_did = principal_def_id_b.unwrap();
let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
if let Some(deref_trait_ref) = self.need_migrate_deref_output_trait_object(
source,
obligation.param_env,
&obligation.cause,
) {
if deref_trait_ref.def_id() == target_trait_did {
return;
}
}

for (idx, upcast_trait_ref) in
util::supertraits(self.tcx(), source_trait_ref).enumerate()
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_type_ir/src/solve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,7 @@ pub enum BuiltinImplSource {
Object(usize),
/// A built-in implementation of `Upcast` for trait objects to other trait objects.
///
/// This can be removed when `feature(dyn_upcasting)` is stabilized, since we only
/// use it to detect when upcasting traits in hir typeck. The index is only used
/// for winnowing.
/// The index is only used for winnowing.
TraitUpcasting(usize),
/// Unsizing a tuple like `(A, B, ..., X)` to `(A, B, ..., Y)` if `X` unsizes to `Y`.
///
Expand Down
1 change: 0 additions & 1 deletion library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@
#![feature(strict_provenance_atomic_ptr)]
#![feature(strict_provenance_lints)]
#![feature(test)]
#![feature(trait_upcasting)]
#![feature(trusted_len)]
#![feature(trusted_random_access)]
#![feature(try_blocks)]
Expand Down
26 changes: 0 additions & 26 deletions src/doc/unstable-book/src/language-features/trait-upcasting.md

This file was deleted.

2 changes: 1 addition & 1 deletion src/tools/miri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg_attr(bootstrap, feature(trait_upcasting))]
#![feature(rustc_private)]
#![feature(cell_update)]
#![feature(float_gamma)]
Expand All @@ -9,7 +10,6 @@
#![feature(yeet_expr)]
#![feature(nonzero_ops)]
#![feature(let_chains)]
#![feature(trait_upcasting)]
#![feature(strict_overflow_ops)]
#![feature(pointer_is_aligned_to)]
#![feature(unqualified_local_imports)]
Expand Down
3 changes: 0 additions & 3 deletions src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Validation stops this too early.
//@compile-flags: -Zmiri-disable-validation

#![feature(trait_upcasting)]
#![allow(incomplete_features)]

trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
#[allow(dead_code)]
fn a(&self) -> i32 {
Expand Down
3 changes: 1 addition & 2 deletions src/tools/miri/tests/pass/box-custom-alloc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//@revisions: stack tree
//@[tree]compile-flags: -Zmiri-tree-borrows
#![allow(incomplete_features)] // for trait upcasting
#![feature(allocator_api, trait_upcasting)]
#![feature(allocator_api)]

use std::alloc::{AllocError, Allocator, Layout};
use std::cell::Cell;
Expand Down
3 changes: 0 additions & 3 deletions src/tools/miri/tests/pass/dyn-upcast.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#![feature(trait_upcasting)]
#![allow(incomplete_features)]

use std::fmt;

fn main() {
Expand Down
1 change: 0 additions & 1 deletion tests/codegen/vtable-upcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
//@ compile-flags: -C no-prepopulate-passes -Copt-level=0

#![crate_type = "lib"]
#![feature(trait_upcasting)]

pub trait Base {
fn base(&self);
Expand Down
2 changes: 1 addition & 1 deletion tests/crashes/131886.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//@ known-bug: #131886
//@ compile-flags: -Zvalidate-mir --crate-type=lib
#![feature(trait_upcasting, type_alias_impl_trait)]
#![feature(type_alias_impl_trait)]

type Tait = impl Sized;

Expand Down
1 change: 0 additions & 1 deletion tests/ui/codegen/issue-99551.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//@ build-pass
#![feature(trait_upcasting)]

pub trait A {}
pub trait B {}
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/dyn-star/no-unsize-coerce-dyn-trait.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![feature(dyn_star, trait_upcasting)]
//~^ WARN the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes
#![expect(incomplete_features)]
#![feature(dyn_star)]

trait A: B {}
trait B {}
Expand Down
11 changes: 1 addition & 10 deletions tests/ui/dyn-star/no-unsize-coerce-dyn-trait.stderr
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes
--> $DIR/no-unsize-coerce-dyn-trait.rs:1:12
|
LL | #![feature(dyn_star, trait_upcasting)]
| ^^^^^^^^
|
= note: see issue #102425 <https://github.com/rust-lang/rust/issues/102425> for more information
= note: `#[warn(incomplete_features)]` on by default

error[E0308]: mismatched types
--> $DIR/no-unsize-coerce-dyn-trait.rs:11:26
|
Expand All @@ -18,6 +9,6 @@ LL | let y: Box<dyn* B> = x;
= note: expected struct `Box<dyn* B>`
found struct `Box<dyn* A>`

error: aborting due to 1 previous error; 1 warning emitted
error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.
2 changes: 1 addition & 1 deletion tests/ui/dyn-star/upcast.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//@ known-bug: #104800

#![feature(dyn_star, trait_upcasting)]
#![feature(dyn_star)]

trait Foo: Bar {
fn hello(&self);
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/dyn-star/upcast.stderr
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes
--> $DIR/upcast.rs:3:12
|
LL | #![feature(dyn_star, trait_upcasting)]
LL | #![feature(dyn_star)]
| ^^^^^^^^
|
= note: see issue #102425 <https://github.com/rust-lang/rust/issues/102425> for more information
Expand Down
Loading

0 comments on commit cbd44d7

Please sign in to comment.