Skip to content

Commit cee2a0d

Browse files
Rollup merge of #163946 - lsunsi:next-transmute, r=lcnr,ShoyuVanilla
Fix transmutability type mismatch bug Fixes #161251 r? @ShoyuVanilla The change was done as instructed by @ShoyuVanilla and @lcnr on Zulip. There are some leftover questions I'll add as comments (self review). But the original examples are both fixed.
2 parents bd86817 + 13694b6 commit cee2a0d

82 files changed

Lines changed: 1497 additions & 703 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_middle/src/ty/context/impl_interner.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,7 @@ bidirectional_lang_item_map! {
796796
FnMut,
797797
FnOnce,
798798
FnPtrTrait,
799+
Freeze,
799800
FusedIterator,
800801
Future,
801802
Iterator,

‎compiler/rustc_next_trait_solver/src/delegate.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ use std::fmt::Debug;
22
use std::ops::Deref;
33

44
use rustc_type_ir::solve::{
5-
Certainty, ComputeGoalFastPathOutcome, FetchEligibleAssocItemResponse, Goal, NoSolution,
5+
ComputeGoalFastPathOutcome, FetchEligibleAssocItemResponse, Goal, NoSolution,
66
VisibleForLeakCheck,
77
};
8-
use rustc_type_ir::{self as ty, CanonicalizerState, Const, InferCtxtLike, Interner, TypeFoldable};
8+
use rustc_type_ir::transmute::Answer;
9+
use rustc_type_ir::{
10+
self as ty, CanonicalizerState, Const, InferCtxtLike, Interner, Region, TypeFoldable,
11+
};
912

1013
/// `SolverDelegate` is one of the two traits in the `rustc_type_ir` shared abstraction layer
1114
/// between rustc and rust-analyzer abstracting over the [InferCtxt][inferctxt-doc], which had to be
@@ -113,7 +116,7 @@ pub trait SolverDelegate: Deref<Target = Self::Infcx> + Sized {
113116
src: <Self::Interner as Interner>::Ty,
114117
dst: <Self::Interner as Interner>::Ty,
115118
assume: Const<Self::Interner>,
116-
) -> Result<Certainty, NoSolution>;
119+
) -> Result<Answer<Region<Self::Interner>, <Self::Interner as Interner>::Ty>, NoSolution>;
117120

118121
/// Obtain canonicalizer state, either by allocating it afresh (the default) or by reusing
119122
/// previously allocated state.

‎compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use rustc_type_ir::solve::{
1616
NoSolutionOrRerunNonErased, OpaqueTypesJank, QueryResultOrRerunNonErased, RerunCondition,
1717
RerunNonErased, RerunReason, RerunResultExt, SmallCopySet, TyOrConstInferVar,
1818
};
19+
use rustc_type_ir::transmute::Answer;
1920
use rustc_type_ir::{
2021
self as ty, ClauseKind, Const, InferCtxtLike, Interner, MayBeErased, OpaqueTypeKey,
2122
PredicateKind, PredicateProxy, Region, RegionVid, TypeFoldable, TypeSuperVisitable,
@@ -1565,7 +1566,7 @@ where
15651566
src: I::Ty,
15661567
dst: I::Ty,
15671568
assume: Const<I>,
1568-
) -> Result<Certainty, NoSolution> {
1569+
) -> Result<Answer<Region<I>, I::Ty>, NoSolution> {
15691570
self.delegate.is_transmutable(dst, src, assume)
15701571
}
15711572

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

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@ mod trait_goals;
2222

2323
use derive_where::derive_where;
2424
use rustc_type_ir::inherent::*;
25+
use rustc_type_ir::lang_items::SolverTraitLangItem;
2526
pub use rustc_type_ir::solve::*;
26-
use rustc_type_ir::{self as ty, Const, Interner, Region, TypeVisitableExt};
27+
use rustc_type_ir::transmute::Condition;
28+
use rustc_type_ir::{self as ty, Const, Interner, Region, TraitClause, TypeVisitableExt, Upcast};
29+
use thin_vec::{ThinVec, thin_vec};
2730
use tracing::instrument;
2831

2932
pub use self::eval_ctxt::{
@@ -491,3 +494,42 @@ pub struct GoalEvaluation<I: Interner> {
491494
/// before rerunning it.
492495
pub stalled_on: Option<GoalStalledOn<I>>,
493496
}
497+
498+
/// Flatten the `Condition` tree into a conjunction of predicates.
499+
#[instrument(level = "debug", skip(interner, predicate))]
500+
pub fn flatten_answer_tree<I: Interner>(
501+
interner: I,
502+
predicate: TraitClause<I>,
503+
cond: Condition<Region<I>, I::Ty>,
504+
) -> ThinVec<I::Predicate> {
505+
match cond {
506+
// FIXME(bryangarza): Add separate `IfAny` case, instead of treating as `IfAll`
507+
// Not possible until the trait solver supports disjunctions of obligations
508+
Condition::IfAll(conds) | Condition::IfAny(conds) => conds
509+
.into_iter()
510+
.flat_map(|cond| flatten_answer_tree(interner, predicate, cond))
511+
.collect(),
512+
Condition::Immutable { ty } => {
513+
let trait_ref = ty::TraitRef::new(
514+
interner,
515+
interner.require_trait_lang_item(SolverTraitLangItem::Freeze),
516+
[I::GenericArg::from(ty)],
517+
);
518+
thin_vec![trait_ref.upcast(interner)]
519+
}
520+
Condition::Outlives { long, short } => {
521+
let outlives = ty::OutlivesClause(long, short);
522+
thin_vec![outlives.upcast(interner)]
523+
}
524+
Condition::Transmutable { src, dst } => {
525+
let transmute_trait = predicate.def_id();
526+
let assume = predicate.trait_ref.args.const_at(2);
527+
let trait_ref = ty::TraitRef::new(
528+
interner,
529+
transmute_trait,
530+
[I::GenericArg::from(dst), I::GenericArg::from(src), I::GenericArg::from(assume)],
531+
);
532+
thin_vec![trait_ref.upcast(interner)]
533+
}
534+
}
535+
}

‎compiler/rustc_next_trait_solver/src/solve/trait_goals.rs‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use crate::solve::assembly::{
2424
use crate::solve::inspect::ProbeKind;
2525
use crate::solve::{
2626
BuiltinImplSource, CandidateSource, Certainty, EvalCtxt, Goal, GoalSource, MaybeCause,
27-
MergeCandidateInfo, NoSolution, ParamEnvSource, StalledOnCoroutines,
27+
MergeCandidateInfo, NoSolution, ParamEnvSource, StalledOnCoroutines, flatten_answer_tree,
2828
has_only_region_constraints,
2929
};
3030

@@ -659,6 +659,8 @@ where
659659
ecx: &mut EvalCtxt<'_, D>,
660660
goal: Goal<I, Self>,
661661
) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
662+
use rustc_type_ir::transmute::Answer;
663+
662664
if goal.predicate.polarity != ty::ClausePolarity::Positive {
663665
return Err(NoSolution.into());
664666
}
@@ -681,11 +683,28 @@ where
681683
goal.predicate.trait_ref.args.const_at(2),
682684
)?;
683685

684-
let certainty = ecx.is_transmutable(
686+
let answer = ecx.is_transmutable(
685687
goal.predicate.trait_ref.args.type_at(0),
686688
goal.predicate.trait_ref.args.type_at(1),
687689
assume,
688690
)?;
691+
692+
let certainty = match answer {
693+
Answer::No(_) => return Err(NoSolution.into()),
694+
Answer::Yes => Certainty::Yes,
695+
Answer::If(cond) => {
696+
let tcx = ecx.cx();
697+
ecx.add_goals(
698+
GoalSource::Misc,
699+
flatten_answer_tree(tcx, goal.predicate, cond)
700+
.into_iter()
701+
.map(|predicate| Goal::new(tcx, goal.param_env, predicate)),
702+
)?;
703+
704+
Certainty::Yes
705+
}
706+
};
707+
689708
ecx.evaluate_added_goals_and_make_canonical_response(certainty)
690709
},
691710
)

‎compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs‎

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use rustc_middle::ty::print::{
3131
PrintPolyTraitClauseExt, PrintPolyTraitRefExt as _, PrintTraitClauseExt as _,
3232
PrintTraitRefExt as _, with_forced_trimmed_paths,
3333
};
34+
use rustc_middle::ty::transmute::{Answer, Reason};
3435
use rustc_middle::ty::{
3536
self, GenericArgKind, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder,
3637
TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
@@ -3253,7 +3254,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
32533254
trait_ref.args.type_at(0),
32543255
assume,
32553256
),
3256-
rustc_transmute::Answer::Yes,
3257+
Answer::Yes,
32573258
);
32583259

32593260
// If the normalized check unexpectedly passes, fall back to root obligation for reporting.
@@ -3274,7 +3275,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
32743275
trait_pred: ty::PolyTraitClause<'tcx>,
32753276
span: Span,
32763277
) -> GetSafeTransmuteErrorAndReason {
3277-
use rustc_transmute::Answer;
32783278
self.probe(|_| {
32793279
// We don't assemble a transmutability candidate for types that are generic
32803280
// and we should have ambiguity for types that still have non-region infer.
@@ -3311,69 +3311,61 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
33113311
{
33123312
Answer::No(reason) => {
33133313
let safe_transmute_explanation = match reason {
3314-
rustc_transmute::Reason::SrcIsNotYetSupported => {
3314+
Reason::SrcIsNotYetSupported => {
33153315
format!("analyzing the transmutability of `{src}` is not yet supported")
33163316
}
3317-
rustc_transmute::Reason::DstIsNotYetSupported => {
3317+
Reason::DstIsNotYetSupported => {
33183318
format!("analyzing the transmutability of `{dst}` is not yet supported")
33193319
}
3320-
rustc_transmute::Reason::DstIsBitIncompatible => {
3320+
Reason::DstIsBitIncompatible => {
33213321
format!(
33223322
"at least one value of `{src}` isn't a bit-valid value of `{dst}`"
33233323
)
33243324
}
3325-
rustc_transmute::Reason::DstUninhabited => {
3325+
Reason::DstUninhabited => {
33263326
format!("`{dst}` is uninhabited")
33273327
}
3328-
rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3328+
Reason::DstMayHaveSafetyInvariants => {
33293329
format!("`{dst}` may carry safety invariants")
33303330
}
3331-
rustc_transmute::Reason::DstIsTooBig => {
3331+
Reason::DstIsTooBig => {
33323332
format!("the size of `{src}` is smaller than the size of `{dst}`")
33333333
}
3334-
rustc_transmute::Reason::DstRefIsTooBig {
3335-
src,
3336-
src_size,
3337-
dst,
3338-
dst_size,
3339-
} => {
3334+
Reason::DstRefIsTooBig { src, src_size, dst, dst_size } => {
33403335
format!(
33413336
"the size of `{src}` ({src_size} bytes) \
33423337
is smaller than that of `{dst}` ({dst_size} bytes)"
33433338
)
33443339
}
3345-
rustc_transmute::Reason::SrcSizeOverflow => {
3340+
Reason::SrcSizeOverflow => {
33463341
format!(
33473342
"values of the type `{src}` are too big for the target architecture"
33483343
)
33493344
}
3350-
rustc_transmute::Reason::DstSizeOverflow => {
3345+
Reason::DstSizeOverflow => {
33513346
format!(
33523347
"values of the type `{dst}` are too big for the target architecture"
33533348
)
33543349
}
3355-
rustc_transmute::Reason::DstHasStricterAlignment {
3356-
src_min_align,
3357-
dst_min_align,
3358-
} => {
3350+
Reason::DstHasStricterAlignment { src_min_align, dst_min_align } => {
33593351
format!(
33603352
"the minimum alignment of `{src}` ({src_min_align}) should be \
33613353
greater than that of `{dst}` ({dst_min_align})"
33623354
)
33633355
}
3364-
rustc_transmute::Reason::DstIsMoreUnique => {
3356+
Reason::DstIsMoreUnique => {
33653357
format!(
33663358
"`{src}` is a shared reference, but `{dst}` is a unique reference"
33673359
)
33683360
}
33693361
// Already reported by rustc
3370-
rustc_transmute::Reason::TypeError => {
3362+
Reason::TypeError => {
33713363
return GetSafeTransmuteErrorAndReason::Silent;
33723364
}
3373-
rustc_transmute::Reason::SrcLayoutUnknown => {
3365+
Reason::SrcLayoutUnknown => {
33743366
format!("`{src}` has an unknown layout")
33753367
}
3376-
rustc_transmute::Reason::DstLayoutUnknown => {
3368+
Reason::DstLayoutUnknown => {
33773369
format!("`{dst}` has an unknown layout")
33783370
}
33793371
};

‎compiler/rustc_trait_selection/src/solve/delegate.rs‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,17 @@ use rustc_infer::traits::solve::{
1919
};
2020
use rustc_lint_defs::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT;
2121
use rustc_middle::traits::query::NoSolution;
22-
use rustc_middle::traits::solve::{Certainty, MaybeInfo};
22+
use rustc_middle::traits::solve::MaybeInfo;
2323
use rustc_middle::ty::print::{FmtPrinter, Print};
24+
use rustc_middle::ty::transmute::Answer;
2425
use rustc_middle::ty::{
25-
self, CanonicalizerState, MayBeErased, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeSuperVisitable,
26-
TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
26+
self, CanonicalizerState, MayBeErased, Region, Ty, TyCtxt, TypeFlags, TypeFoldable,
27+
TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
2728
};
2829
use rustc_next_trait_solver::solve::{GoalStalledOn, GoalStalledOnOpaques, TyOrConstInferVar};
2930
use rustc_span::{DUMMY_SP, Span};
3031
use rustc_structures::Limit;
32+
use rustc_transmute::TransmuteTypeEnv;
3133
use thin_vec::{ThinVec, thin_vec};
3234

3335
use super::inspect::InferCtxtProofTreeExt;
@@ -491,20 +493,14 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<
491493
src: Ty<'tcx>,
492494
dst: Ty<'tcx>,
493495
assume: ty::Const<'tcx>,
494-
) -> Result<Certainty, NoSolution> {
496+
) -> Result<Answer<Region<'tcx>, Ty<'tcx>>, NoSolution> {
495497
// Erase regions because we compute layouts in `rustc_transmute`,
496498
// which will ICE for region vars.
497499
let (dst, src) = self.tcx.erase_and_anonymize_regions((dst, src));
498500

499-
let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
500-
return Err(NoSolution);
501-
};
502-
503-
// FIXME(transmutability): This really should be returning nested goals for `Answer::If*`
504-
match rustc_transmute::TransmuteTypeEnv::new(self.0.tcx).is_transmutable(src, dst, assume) {
505-
rustc_transmute::Answer::Yes => Ok(Certainty::Yes),
506-
rustc_transmute::Answer::No(_) | rustc_transmute::Answer::If(_) => Err(NoSolution),
507-
}
501+
rustc_transmute::Assume::from_const(self.tcx, assume)
502+
.map(|assume| TransmuteTypeEnv::new(self.0.tcx).is_transmutable(src, dst, assume))
503+
.ok_or(NoSolution)
508504
}
509505

510506
fn obtain_canonicalizer_state(&self) -> CanonicalizerState<Self::Interner> {

0 commit comments

Comments
 (0)