Skip to content

Commit f46fffc

Browse files
committed
safe transmute: use Assume struct to provide analysis options
This was left as a TODO in #92268, and brings the trait more in line with what was defined in MCP411. `Assume::visibility` has been renamed to `Assume::safety`, as library safety is what's actually being assumed; visibility is just the mechanism by which it is currently checked (this may change). ref: rust-lang/compiler-team#411 ref: #99571
1 parent e0dc8d7 commit f46fffc

File tree

77 files changed

+1320
-720
lines changed

Some content is hidden

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

77 files changed

+1320
-720
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4581,6 +4581,7 @@ version = "0.1.0"
45814581
dependencies = [
45824582
"itertools",
45834583
"rustc_data_structures",
4584+
"rustc_hir",
45844585
"rustc_infer",
45854586
"rustc_macros",
45864587
"rustc_middle",

compiler/rustc_hir/src/lang_items.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,8 @@ language_item_table! {
192192
DispatchFromDyn, sym::dispatch_from_dyn, dispatch_from_dyn_trait, Target::Trait, GenericRequirement::Minimum(1);
193193

194194
// language items relating to transmutability
195-
TransmuteTrait, sym::transmute_trait, transmute_trait, Target::Trait, GenericRequirement::Exact(6);
195+
TransmuteOpts, sym::transmute_opts, transmute_opts, Target::Struct, GenericRequirement::Exact(0);
196+
TransmuteTrait, sym::transmute_trait, transmute_trait, Target::Trait, GenericRequirement::Exact(3);
196197

197198
Add(Op), sym::add, add_trait, Target::Trait, GenericRequirement::Exact(1);
198199
Sub(Op), sym::sub, sub_trait, Target::Trait, GenericRequirement::Exact(1);

compiler/rustc_span/src/symbol.rs

+5
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@ symbols! {
334334
alias,
335335
align,
336336
align_offset,
337+
alignment,
337338
alignstack,
338339
all,
339340
alloc,
@@ -859,6 +860,7 @@ symbols! {
859860
lib,
860861
libc,
861862
lifetime,
863+
lifetimes,
862864
likely,
863865
line,
864866
line_macro,
@@ -1284,6 +1286,7 @@ symbols! {
12841286
rustfmt,
12851287
rvalue_static_promotion,
12861288
s,
1289+
safety,
12871290
sanitize,
12881291
sanitizer_runtime,
12891292
saturating_add,
@@ -1466,6 +1469,7 @@ symbols! {
14661469
trait_alias,
14671470
trait_upcasting,
14681471
transmute,
1472+
transmute_opts,
14691473
transmute_trait,
14701474
transparent,
14711475
transparent_enums,
@@ -1560,6 +1564,7 @@ symbols! {
15601564
va_list,
15611565
va_start,
15621566
val,
1567+
validity,
15631568
values,
15641569
var,
15651570
variant_count,

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

+4-16
Original file line numberDiff line numberDiff line change
@@ -279,29 +279,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
279279
let predicate = obligation.predicate;
280280

281281
let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
282-
let bool_at = |i| {
283-
predicate
284-
.skip_binder()
285-
.trait_ref
286-
.substs
287-
.const_at(i)
288-
.try_eval_bool(self.tcx(), obligation.param_env)
289-
.unwrap_or(true)
290-
};
282+
let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
291283

292284
let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
293-
src: p.trait_ref.substs.type_at(1),
294285
dst: p.trait_ref.substs.type_at(0),
286+
src: p.trait_ref.substs.type_at(1),
295287
});
296288

297289
let scope = type_at(2).skip_binder();
298290

299-
let assume = rustc_transmute::Assume {
300-
alignment: bool_at(3),
301-
lifetimes: bool_at(4),
302-
validity: bool_at(5),
303-
visibility: bool_at(6),
304-
};
291+
let assume =
292+
rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3));
305293

306294
let cause = obligation.cause.clone();
307295

compiler/rustc_transmute/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2021"
88
[dependencies]
99
tracing = "0.1"
1010
rustc_data_structures = { path = "../rustc_data_structures", optional = true}
11+
rustc_hir = { path = "../rustc_hir", optional = true}
1112
rustc_infer = { path = "../rustc_infer", optional = true}
1213
rustc_macros = { path = "../rustc_macros", optional = true}
1314
rustc_middle = { path = "../rustc_middle", optional = true}
@@ -18,6 +19,7 @@ rustc_target = { path = "../rustc_target", optional = true}
1819
rustc = [
1920
"rustc_middle",
2021
"rustc_data_structures",
22+
"rustc_hir",
2123
"rustc_infer",
2224
"rustc_macros",
2325
"rustc_span",

compiler/rustc_transmute/src/lib.rs

+58-1
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ pub(crate) mod maybe_transmutable;
2626
pub struct Assume {
2727
pub alignment: bool,
2828
pub lifetimes: bool,
29+
pub safety: bool,
2930
pub validity: bool,
30-
pub visibility: bool,
3131
}
3232

3333
/// The type encodes answers to the question: "Are these types transmutable?"
@@ -69,11 +69,17 @@ pub enum Reason {
6969

7070
#[cfg(feature = "rustc")]
7171
mod rustc {
72+
use super::*;
73+
74+
use rustc_hir::lang_items::LangItem;
7275
use rustc_infer::infer::InferCtxt;
7376
use rustc_macros::{TypeFoldable, TypeVisitable};
7477
use rustc_middle::traits::ObligationCause;
7578
use rustc_middle::ty::Binder;
79+
use rustc_middle::ty::Const;
80+
use rustc_middle::ty::ParamEnv;
7681
use rustc_middle::ty::Ty;
82+
use rustc_middle::ty::TyCtxt;
7783

7884
/// The source and destination types of a transmutation.
7985
#[derive(TypeFoldable, TypeVisitable, Debug, Clone, Copy)]
@@ -113,6 +119,57 @@ mod rustc {
113119
.answer()
114120
}
115121
}
122+
123+
impl Assume {
124+
/// Constructs an `Assume` from a given const-`Assume`.
125+
pub fn from_const<'tcx>(
126+
tcx: TyCtxt<'tcx>,
127+
param_env: ParamEnv<'tcx>,
128+
c: Const<'tcx>,
129+
) -> Self {
130+
use rustc_middle::ty::DestructuredConst;
131+
use rustc_middle::ty::TypeVisitable;
132+
use rustc_span::symbol::sym;
133+
134+
let c = c.eval(tcx, param_env);
135+
136+
if let Some(err) = c.error_reported() {
137+
return Self { alignment: true, lifetimes: true, safety: true, validity: true };
138+
}
139+
140+
let adt_def = c.ty().ty_adt_def().expect("The given `Const` must be an ADT.");
141+
142+
assert_eq!(
143+
tcx.require_lang_item(LangItem::TransmuteOpts, None),
144+
adt_def.did(),
145+
"The given `Const` was not marked with the `{}` lang item.",
146+
LangItem::TransmuteOpts.name(),
147+
);
148+
149+
let DestructuredConst { variant, fields } = tcx.destructure_const(c);
150+
let variant_idx = variant.expect("The given `Const` must be an ADT.");
151+
let variant = adt_def.variant(variant_idx);
152+
153+
let get_field = |name| {
154+
let (field_idx, _) = variant
155+
.fields
156+
.iter()
157+
.enumerate()
158+
.find(|(_, field_def)| name == field_def.name)
159+
.expect(&format!("There were no fields named `{name}`."));
160+
fields[field_idx].try_eval_bool(tcx, param_env).expect(&format!(
161+
"The field named `{name}` lang item could not be evaluated to a bool."
162+
))
163+
};
164+
165+
Self {
166+
alignment: get_field(sym::alignment),
167+
lifetimes: get_field(sym::lifetimes),
168+
safety: get_field(sym::safety),
169+
validity: get_field(sym::validity),
170+
}
171+
}
172+
}
116173
}
117174

118175
#[cfg(feature = "rustc")]

compiler/rustc_transmute/src/maybe_transmutable/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ where
105105
#[inline(always)]
106106
#[instrument(level = "debug", skip(self), fields(src = ?self.src, dst = ?self.dst))]
107107
pub(crate) fn answer(self) -> Answer<<C as QueryContext>::Ref> {
108-
let assume_visibility = self.assume.visibility;
108+
let assume_visibility = self.assume.safety;
109109
let query_or_answer = self.map_layouts(|src, dst, scope, context| {
110110
// Remove all `Def` nodes from `src`, without checking their visibility.
111111
let src = src.prune(&|def| true);

compiler/rustc_transmute/src/maybe_transmutable/tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ mod bool {
1313
layout::Tree::<Def, !>::bool(),
1414
layout::Tree::<Def, !>::bool(),
1515
(),
16-
crate::Assume { alignment: false, lifetimes: false, validity: true, visibility: false },
16+
crate::Assume { alignment: false, lifetimes: false, validity: true, safety: false },
1717
UltraMinimal,
1818
)
1919
.answer();
@@ -26,7 +26,7 @@ mod bool {
2626
layout::Dfa::<!>::bool(),
2727
layout::Dfa::<!>::bool(),
2828
(),
29-
crate::Assume { alignment: false, lifetimes: false, validity: true, visibility: false },
29+
crate::Assume { alignment: false, lifetimes: false, validity: true, safety: false },
3030
UltraMinimal,
3131
)
3232
.answer();

library/core/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
#![warn(missing_debug_implementations)]
9494
#![warn(missing_docs)]
9595
#![allow(explicit_outlives_requirements)]
96+
#![allow(incomplete_features)]
9697
//
9798
// Library features:
9899
#![feature(const_align_offset)]
@@ -160,6 +161,7 @@
160161
//
161162
// Language features:
162163
#![feature(abi_unadjusted)]
164+
#![feature(adt_const_params)]
163165
#![feature(allow_internal_unsafe)]
164166
#![feature(allow_internal_unstable)]
165167
#![feature(associated_type_bounds)]

library/core/src/mem/transmutability.rs

+76-12
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,20 @@
44
/// any value of type `Self` are safely transmutable into a value of type `Dst`, in a given `Context`,
55
/// notwithstanding whatever safety checks you have asked the compiler to [`Assume`] are satisfied.
66
#[unstable(feature = "transmutability", issue = "99571")]
7-
#[lang = "transmute_trait"]
7+
#[cfg_attr(not(bootstrap), lang = "transmute_trait")]
88
#[rustc_on_unimplemented(
99
message = "`{Src}` cannot be safely transmuted into `{Self}` in the defining scope of `{Context}`.",
1010
label = "`{Src}` cannot be safely transmuted into `{Self}` in the defining scope of `{Context}`."
1111
)]
12-
pub unsafe trait BikeshedIntrinsicFrom<
13-
Src,
14-
Context,
15-
const ASSUME_ALIGNMENT: bool,
16-
const ASSUME_LIFETIMES: bool,
17-
const ASSUME_VALIDITY: bool,
18-
const ASSUME_VISIBILITY: bool,
19-
> where
12+
pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = { Assume::NOTHING }>
13+
where
2014
Src: ?Sized,
2115
{
2216
}
2317

2418
/// What transmutation safety conditions shall the compiler assume that *you* are checking?
2519
#[unstable(feature = "transmutability", issue = "99571")]
20+
#[cfg_attr(not(bootstrap), lang = "transmute_opts")]
2621
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
2722
pub struct Assume {
2823
/// When `true`, the compiler assumes that *you* are ensuring (either dynamically or statically) that
@@ -33,11 +28,80 @@ pub struct Assume {
3328
/// that violates Rust's memory model.
3429
pub lifetimes: bool,
3530

31+
/// When `true`, the compiler assumes that *you* have ensured that it is safe for you to violate the
32+
/// type and field privacy of the destination type (and sometimes of the source type, too).
33+
pub safety: bool,
34+
3635
/// When `true`, the compiler assumes that *you* are ensuring that the source type is actually a valid
3736
/// instance of the destination type.
3837
pub validity: bool,
38+
}
3939

40-
/// When `true`, the compiler assumes that *you* have ensured that it is safe for you to violate the
41-
/// type and field privacy of the destination type (and sometimes of the source type, too).
42-
pub visibility: bool,
40+
impl Assume {
41+
/// Do not assume that *you* have ensured any safety properties are met.
42+
#[unstable(feature = "transmutability", issue = "99571")]
43+
pub const NOTHING: Self =
44+
Self { alignment: false, lifetimes: false, safety: false, validity: false };
45+
46+
/// Assume only that alignment conditions are met.
47+
#[unstable(feature = "transmutability", issue = "99571")]
48+
pub const ALIGNMENT: Self = Self { alignment: true, ..Self::NOTHING };
49+
50+
/// Assume only that lifetime conditions are met.
51+
#[unstable(feature = "transmutability", issue = "99571")]
52+
pub const LIFETIMES: Self = Self { lifetimes: true, ..Self::NOTHING };
53+
54+
/// Assume only that safety conditions are met.
55+
#[unstable(feature = "transmutability", issue = "99571")]
56+
pub const SAFETY: Self = Self { safety: true, ..Self::NOTHING };
57+
58+
/// Assume only that dynamically-satisfiable validity conditions are met.
59+
#[unstable(feature = "transmutability", issue = "99571")]
60+
pub const VALIDITY: Self = Self { validity: true, ..Self::NOTHING };
61+
62+
/// Assume both `self` and `other_assumptions`.
63+
#[unstable(feature = "transmutability", issue = "99571")]
64+
pub const fn and(self, other_assumptions: Self) -> Self {
65+
Self {
66+
alignment: self.alignment || other_assumptions.alignment,
67+
lifetimes: self.lifetimes || other_assumptions.lifetimes,
68+
safety: self.safety || other_assumptions.safety,
69+
validity: self.validity || other_assumptions.validity,
70+
}
71+
}
72+
73+
/// Assume `self`, excepting `other_assumptions`.
74+
#[unstable(feature = "transmutability", issue = "99571")]
75+
pub const fn but_not(self, other_assumptions: Self) -> Self {
76+
Self {
77+
alignment: self.alignment && !other_assumptions.alignment,
78+
lifetimes: self.lifetimes && !other_assumptions.lifetimes,
79+
safety: self.safety && !other_assumptions.safety,
80+
validity: self.validity && !other_assumptions.validity,
81+
}
82+
}
83+
}
84+
85+
// FIXME(jswrenn): This const op is not actually usable. Why?
86+
// https://github.com/rust-lang/rust/pull/100726#issuecomment-1219928926
87+
#[unstable(feature = "transmutability", issue = "99571")]
88+
#[rustc_const_unstable(feature = "transmutability", issue = "99571")]
89+
impl const core::ops::Add for Assume {
90+
type Output = Assume;
91+
92+
fn add(self, other_assumptions: Assume) -> Assume {
93+
self.and(other_assumptions)
94+
}
95+
}
96+
97+
// FIXME(jswrenn): This const op is not actually usable. Why?
98+
// https://github.com/rust-lang/rust/pull/100726#issuecomment-1219928926
99+
#[unstable(feature = "transmutability", issue = "99571")]
100+
#[rustc_const_unstable(feature = "transmutability", issue = "99571")]
101+
impl const core::ops::Sub for Assume {
102+
type Output = Assume;
103+
104+
fn sub(self, other_assumptions: Assume) -> Assume {
105+
self.but_not(other_assumptions)
106+
}
43107
}

0 commit comments

Comments
 (0)