blob: dac8d5751034400a7dd63bdb2c51813416240e1e [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Owned capture data. Metadata and semantic constructors stay separate so that
//! Rust names and paths never become executable Lean source.
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
use sha2::{Digest, Sha256};
// Version 4 widens integer widths to include `i128` (`IntWidth::I128`), encodes
// 128-bit bit-pattern fields (`ConstLit::Scalar.bits`, `EnumTy.discriminants`,
// and `Terminator::SwitchInt.targets`) as canonical base-10 strings so JSON
// consumers without arbitrary-precision numbers round-trip `0..=u128::MAX`
// losslessly, adds `Ty::{Char, Ordering, OverflowPair}`, `UnOp::{Not, Neg}`,
// `CastKind::IntToInt`, `BinOp::{Div, Rem, AddWithOverflow, SubWithOverflow,
// MulWithOverflow, Cmp}`, and `Rvalue::{Unary, Cast}`, and enforces static
// operand and destination typing across binary, unary, cast, discriminant, and
// switch operations. Version 5 adds `Terminator::{Call, SysrootCall}` with
// their `SysrootNumOp` (`SysrootNumKind`) payloads, and
// `BinOp::{AddUnchecked, SubUnchecked, MulUnchecked}`.
pub const SCHEMA_VERSION: u32 = 5;
pub const COMPILER_COMMIT: &str = "f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1";
pub const COMPILER_VERSION: &str = "1.98.0-nightly (f8a08b688 2026-05-30)";
fn serialize_u128_decimal<S: Serializer>(val: &u128, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&val.to_string())
}
fn serialize_u128_slice_decimal<S: Serializer>(
vals: &[u128],
serializer: S,
) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(vals.len()))?;
for val in vals {
seq.serialize_element(&val.to_string())?;
}
seq.end()
}
fn serialize_switch_targets_decimal<S: Serializer>(
targets: &[(u128, u32)],
serializer: S,
) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(targets.len()))?;
for (val, block) in targets {
seq.serialize_element(&(val.to_string(), *block))?;
}
seq.end()
}
/// Admitted integer widths in the 64-bit little-endian capture profile,
/// corresponding 1-to-1 to `Trusted.MirAst.IntWidth`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum IntWidth {
I8,
I16,
I32,
I64,
I128,
Isize,
}
impl IntWidth {
pub const fn bits(self) -> u32 {
match self {
Self::I8 => 8,
Self::I16 => 16,
Self::I32 => 32,
Self::I64 | Self::Isize => 64,
Self::I128 => 128,
}
}
pub const fn mask(self) -> u128 {
let bits = self.bits();
if bits == 128 {
u128::MAX
} else {
(1u128 << bits) - 1
}
}
pub const fn lean_name(self) -> &'static str {
match self {
Self::I8 => "i8",
Self::I16 => "i16",
Self::I32 => "i32",
Self::I64 => "i64",
Self::I128 => "i128",
Self::Isize => "isize",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct IntTy {
pub width: IntWidth,
pub signed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EnumTagRepr {
ZeroSized,
Scalar(IntTy),
}
/// Recover discriminant bits from raw tag bits as `rustc` does for
/// `TagEncoding::Direct`. The tag is read at the integer type of its layout
/// primitive and then cast to the discriminant type ("Cast bits from tag
/// layout to discriminant layout."). That integer cast first makes sure the
/// value "is sign-extended *if* it has a signed type" and then truncates it to
/// the target size.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/discriminant.rs#L95-L96
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/discriminant.rs#L119-L123
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/cast.rs#L266-L286
fn tag_bits_to_discr_bits(tag: IntTy, discr_width: IntWidth, raw_tag: u128) -> u128 {
let masked_tag = raw_tag & tag.width.mask();
let extended = if tag.signed {
let shift = 128 - tag.width.bits();
(((masked_tag << shift) as i128) >> shift) as u128
} else {
masked_tag
};
extended & discr_width.mask()
}
/// Validated fieldless enum descriptor matching `Trusted.MirAst.EnumTy` and
/// `Trusted.MirSemantics.enumAdmitted`.
///
/// Private fields guarantee that every `EnumTy` instance is inhabited, has
/// fewer than `2^32` variants, carries pairwise-distinct discriminants within
/// `discr_width`, and round-trips losslessly through `tag_repr`.
///
/// `id` is the nominal key that Lean compares in enum type equality. Capture
/// derives it with `extract::enum_id` from the enum's semantic path rather
/// than from a compiler index, and refuses any emitted key shared by two local
/// enum definitions in the crate. This constructor does not check how the key
/// was derived.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct EnumTy {
id: u32,
discr_width: IntWidth,
discr_signed: bool,
tag_repr: EnumTagRepr,
#[serde(serialize_with = "serialize_u128_slice_decimal")]
discriminants: Vec<u128>,
}
impl EnumTy {
pub fn try_new(
id: u32,
discr: IntTy,
tag_repr: EnumTagRepr,
discriminants: Vec<u128>,
) -> Result<Self, String> {
if discriminants.is_empty() {
return Err("uninhabited zero-variant enums are unsupported".into());
}
if u64::try_from(discriminants.len()).unwrap_or(u64::MAX) >= (1u64 << 32) {
return Err("enum variant count is at or above 2^32".into());
}
let discr_mask = discr.width.mask();
for &d in &discriminants {
if d > discr_mask {
return Err("enum discriminant exceeds its discriminant width".into());
}
}
let unique: BTreeSet<u128> = discriminants.iter().copied().collect();
if unique.len() != discriminants.len() {
return Err("duplicate enum discriminants are unsupported".into());
}
match tag_repr {
EnumTagRepr::ZeroSized => {
if discriminants.len() != 1 {
return Err("zero-sized enum tag requires a single variant".into());
}
}
EnumTagRepr::Scalar(tag) => {
let tag_mask = tag.width.mask();
for &d in &discriminants {
let recovered = tag_bits_to_discr_bits(tag, discr.width, d & tag_mask);
if recovered != d {
return Err(
"enum discriminant does not round-trip through its tag representation"
.into(),
);
}
}
}
}
Ok(Self {
id,
discr_width: discr.width,
discr_signed: discr.signed,
tag_repr,
discriminants,
})
}
pub fn id(&self) -> u32 {
self.id
}
pub fn discr(&self) -> IntTy {
IntTy {
width: self.discr_width,
signed: self.discr_signed,
}
}
pub fn tag_repr(&self) -> EnumTagRepr {
self.tag_repr
}
pub fn discriminants(&self) -> &[u128] {
&self.discriminants
}
}
/// Validated struct layout descriptor matching `Trusted.MirAst.StructLayout`
/// and the checks of `Trusted.MirSemantics.layoutOfArrayV2` and
/// `structFieldSpansV2`.
///
/// `field_offsets` are indexed in field-declaration (`FieldIdx`) order, not
/// memory order. `id` is the nominal key that `extract::struct_id` derives
/// from the struct's semantic path; `capture.rs` refuses any emitted key
/// shared by two local struct definitions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StructLayout {
id: u32,
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
}
impl StructLayout {
pub fn id(&self) -> u32 {
self.id
}
pub fn size(&self) -> usize {
self.size
}
pub fn align_log2(&self) -> u32 {
self.align_log2
}
pub fn field_offsets(&self) -> &[usize] {
&self.field_offsets
}
}
/// Validated struct type matching `Trusted.MirAst.MirTy.struct_`.
///
/// Private fields guarantee that every `StructTy` satisfies the checks in
/// [`StructTy::try_new`], which mirror `layoutOfArrayV2` and
/// `structFieldSpansV2`: one offset per field, every field a reference- and
/// pointer-free Profile v2 data type placed aligned and in bounds,
/// nonzero-size fields pairwise disjoint, and a size that is a multiple of
/// the alignment and below `2^61`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct StructTy {
layout: StructLayout,
#[serde(serialize_with = "serialize_ty_slice")]
fields: Vec<Ty>,
/// Canonical pre-hash identity key for a synthetic (non-local) struct
/// (`Some(...)`) — such as a tuple lowered to a struct
/// ([`StructTy::try_new_tuple`]) or a monomorphized sysroot struct
/// ([`StructTy::try_new_synthetic`]) — or `None` for a crate-local nominal
/// struct definition. The model sees an ordinary `.struct_` either way;
/// retaining the pre-hash key lets [`check_synthetic_struct_ids`] reject
/// 32-bit digest collisions even between distinct synthetic structs that
/// share a layout and field list.
#[serde(skip)]
synthetic: Option<String>,
}
impl StructTy {
pub fn try_new(
id: u32,
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
fields: Vec<Ty>,
) -> Result<Self, String> {
Self::try_new_with(id, size, align_log2, field_offsets, fields, Ty::is_owned_data)
}
/// A payload enum variant's payload struct, whose fields may also be
/// those of a payload enum with reference fields
/// ([`Ty::is_ref_enum_field_v2`]); [`AdtEnumTy`] then admits the enum only
/// as owned data or as such an enum ([`Ty::is_supported_v2_local`]).
pub fn try_new_variant(
id: u32,
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
fields: Vec<Ty>,
) -> Result<Self, String> {
Self::try_new_with(id, size, align_log2, field_offsets, fields, |f| {
f.is_owned_data() || f.is_ref_enum_field_v2()
})
}
fn try_new_with(
id: u32,
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
fields: Vec<Ty>,
field_ok: impl Fn(&Ty) -> bool,
) -> Result<Self, String> {
if field_offsets.len() != fields.len() {
return Err(format!(
"struct layout has {} offsets for {} fields",
field_offsets.len(),
fields.len()
));
}
let size_u64 = u64::try_from(size).map_err(|_| "struct size overflows u64")?;
// `obj_size_bound` "Returns **exclusive** upper bound on object size
// in bytes", which is `64 => 1 << 61` on the admitted 64-bit targets;
// `Trusted.MirSemantics.structSizeBound` is the same bound.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L597-L615
if size_u64 >= (1u64 << 61) {
return Err(format!("struct size {size} is not below 2^61"));
}
let Some(align) = 1u64.checked_shl(align_log2).filter(|a| *a < (1u64 << 61)) else {
return Err(format!("struct alignment 2^{align_log2} is unsupported"));
};
if !size_u64.is_multiple_of(align) {
return Err(format!("struct size {size} is not a multiple of its alignment {align}"));
}
let mut occupied: Vec<(usize, usize)> = Vec::with_capacity(fields.len());
for (index, (field, &offset)) in fields.iter().zip(&field_offsets).enumerate() {
if !field_ok(field) {
return Err(format!(
"struct field {index} of type {field:?} is outside the Profile v2 owned \
data fragment"
));
}
let Some((field_size, field_align_log2)) = field.v2_layout() else {
return Err(format!("struct field {index} of type {field:?} lacks layout"));
};
if field_align_log2 > align_log2 {
return Err(format!("struct field {index} alignment exceeds the struct alignment"));
}
if !offset.is_multiple_of(1usize << field_align_log2) {
return Err(format!("struct field {index} offset {offset} is misaligned"));
}
let end = offset
.checked_add(field_size)
.filter(|end| *end <= size)
.ok_or_else(|| format!("struct field {index} exceeds the struct size {size}"))?;
if field_size != 0 {
if occupied.iter().any(|&(s, e)| offset < e && s < end) {
return Err(format!("struct field {index} overlaps another field"));
}
occupied.push((offset, end));
}
}
Ok(Self {
layout: StructLayout { id, size, align_log2, field_offsets },
fields,
synthetic: None,
})
}
/// A synthetic (non-local) struct lowered to `MirTy.struct_`, keyed by the
/// canonical pre-hash identity string `key` (via [`synthetic_struct_id`]).
/// Such a struct is not a crate-local nominal definition, so the
/// crate-local struct collision check skips it ([`Ty::collect_struct_ids`])
/// and [`check_synthetic_struct_ids`] checks it instead.
pub fn try_new_synthetic(
key: String,
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
fields: Vec<Ty>,
) -> Result<Self, String> {
if key.is_empty() {
return Err("synthetic struct key must be non-empty".into());
}
let id = synthetic_struct_id(&key);
let sty = Self::try_new(id, size, align_log2, field_offsets, fields)?;
Ok(Self { synthetic: Some(key), ..sty })
}
/// A tuple lowered to a struct: `fields` in source order (so `.k`
/// projections and drop order are unchanged) at `rustc`'s field offsets,
/// keyed by [`tuple_struct_key`], which depends only on the layout and
/// the translated field types as capture serializes them. Such a struct
/// is synthetic, so the crate-local struct collision check skips it
/// ([`Ty::collect_struct_ids`]) and [`check_synthetic_struct_ids`] checks
/// it instead.
pub fn try_new_tuple(
size: usize,
align_log2: u32,
field_offsets: Vec<usize>,
fields: Vec<Ty>,
) -> Result<Self, String> {
let key = tuple_struct_key(size, align_log2, &field_offsets, &fields)?;
Self::try_new_synthetic(key, size, align_log2, field_offsets, fields)
}
/// Whether this is a synthetic (non-local) struct (such as a tuple or
/// monomorphized sysroot struct lowered to `MirTy.struct_`).
pub fn is_synthetic(&self) -> bool {
self.synthetic.is_some()
}
pub fn layout(&self) -> &StructLayout {
&self.layout
}
pub fn fields(&self) -> &[Ty] {
&self.fields
}
}
/// Derive a 32-bit layout id from a canonical pre-hash key string.
pub fn synthetic_struct_id(key: &str) -> u32 {
let digest = Sha256::digest(key);
u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]])
}
/// Canonical pre-hash key for a tuple lowered to a struct: the JSON encoding
/// of the layout and translated field types as capture serializes them
/// (including fields the Lean term omits, such as an enum's `local` flag),
/// with the `anneal:tuple:v1:` prefix, so the same tuple type always gets the
/// same key and two tuples share a key only if their encodings are equal (or
/// the truncated digests collide, which [`check_synthetic_struct_ids`]
/// refuses).
fn tuple_struct_key(
size: usize,
align_log2: u32,
field_offsets: &[usize],
fields: &[Ty],
) -> Result<String, String> {
let encoded = serde_json::to_string(&(size, align_log2, field_offsets, fields))
.map_err(|err| format!("cannot encode tuple layout: {err}"))?;
Ok(format!("anneal:tuple:v1:{encoded}"))
}
/// Refuse a key shared by two different synthetic structs (whether tuples or
/// monomorphized sysroot structs), or by a synthetic struct and a crate-local
/// struct or enum definition, so every struct key that enters the program still
/// names one type.
pub fn check_synthetic_struct_ids<'a>(
synthetics: impl IntoIterator<Item = &'a StructTy>,
local_struct_ids: &BTreeSet<u32>,
local_enum_ids: &BTreeSet<u32>,
) -> Result<(), String> {
let mut seen: BTreeMap<u32, &StructTy> = BTreeMap::new();
for sty in synthetics {
let id = sty.layout().id();
if !sty.is_synthetic() {
return Err(format!(
"non-synthetic struct passed to synthetic identity check: id {id}"
));
}
if local_struct_ids.contains(&id) || local_enum_ids.contains(&id) {
return Err(format!(
"synthetic struct identity collision: a synthetic struct and a local definition \
share id {id}"
));
}
match seen.get(&id) {
Some(prev) if *prev != sty => {
return Err(format!(
"synthetic struct identity collision: two synthetic struct types share id {id}"
));
}
_ => {
seen.insert(id, sty);
}
}
}
Ok(())
}
/// Tag encoding of a payload enum, matching `Trusted.MirAst.AdtTagEncoding`
/// and `rustc_abi::TagEncoding` (plus `Variants::Single` as `Single`).
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L1964-L2000
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AdtTagEncoding {
Single,
Direct,
Niche {
untagged: u32,
first: u32,
last: u32,
#[serde(serialize_with = "serialize_u128_decimal")]
start: u128,
},
}
/// Validated layout of a payload enum, matching `Trusted.MirAst.AdtEnumLayout`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct AdtEnumLayout {
id: u32,
size: usize,
align_log2: u32,
discr: IntTy,
#[serde(serialize_with = "serialize_u128_slice_decimal")]
discriminants: Vec<u128>,
tag_offset: usize,
tag: IntTy,
#[serde(serialize_with = "serialize_u128_decimal")]
tag_valid_start: u128,
#[serde(serialize_with = "serialize_u128_decimal")]
tag_valid_end: u128,
encoding: AdtTagEncoding,
}
impl AdtEnumLayout {
pub fn id(&self) -> u32 {
self.id
}
pub fn size(&self) -> usize {
self.size
}
pub fn align_log2(&self) -> u32 {
self.align_log2
}
pub fn discr(&self) -> IntTy {
self.discr
}
pub fn discriminants(&self) -> &[u128] {
&self.discriminants
}
pub fn tag_offset(&self) -> usize {
self.tag_offset
}
pub fn tag(&self) -> IntTy {
self.tag
}
pub fn tag_valid_range(&self) -> (u128, u128) {
(self.tag_valid_start, self.tag_valid_end)
}
pub fn encoding(&self) -> AdtTagEncoding {
self.encoding
}
/// The tag's byte span `(offset, size)`, empty for `Single`
/// (`Trusted.MirSemantics.adtTagSpanV2`).
fn tag_span(&self) -> (usize, usize) {
match self.encoding {
AdtTagEncoding::Single => (self.tag_offset, 0),
_ => (self.tag_offset, self.tag.width.bits() as usize / 8),
}
}
/// Whether variant `i` writes a tag
/// (`Trusted.MirSemantics.adtVariantTaggedV2`).
fn variant_tagged(&self, i: usize) -> bool {
match self.encoding {
AdtTagEncoding::Single => false,
AdtTagEncoding::Direct => true,
AdtTagEncoding::Niche { untagged, .. } => i != untagged as usize,
}
}
}
/// Validated payload enum matching `Trusted.MirAst.MirTy.adtEnum`.
///
/// Private fields guarantee that every `AdtEnumTy` passes
/// [`AdtEnumTy::try_new`], which mirrors `Trusted.MirSemantics.adtEnumHeadWfV2`
/// and `adtVariantsWfV2`: one discriminant per variant; for `Direct`, every
/// discriminant round-trips through the tag; for `Niche`, the discriminants
/// are the variant indices and the niche parameters fit the tag; each variant
/// is a [`Ty::Struct`] with the enum's size and alignment whose fields (already
/// checked by [`StructTy::try_new`]) do not overlap the tag when the variant is
/// tagged.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct AdtEnumTy {
layout: AdtEnumLayout,
/// Whether this is a crate-local enum, whose `id` is a nominal key checked
/// for collisions ([`Ty::collect_enum_ids`]); `false` for a sysroot
/// `Result`/`Option` instantiation.
local: bool,
#[serde(serialize_with = "serialize_ty_slice")]
variants: Vec<Ty>,
}
impl AdtEnumTy {
#[allow(clippy::too_many_arguments)]
pub fn try_new(
id: u32,
local: bool,
size: usize,
align_log2: u32,
discr: IntTy,
discriminants: Vec<u128>,
tag_offset: usize,
tag: IntTy,
tag_valid_range: (u128, u128),
encoding: AdtTagEncoding,
variants: Vec<Ty>,
) -> Result<Self, String> {
let n = variants.len();
if n == 0 || discriminants.len() != n {
return Err(format!("payload enum has {n} variants and {} discriminants",
discriminants.len()));
}
if discriminants.iter().any(|&d| d > discr.width.mask()) {
return Err("payload enum discriminant exceeds its discriminant width".into());
}
let unique: BTreeSet<u128> = discriminants.iter().copied().collect();
if unique.len() != n {
return Err("duplicate payload enum discriminants are unsupported".into());
}
let size_u64 = u64::try_from(size).map_err(|_| "payload enum size overflows u64")?;
if size_u64 >= (1u64 << 61) {
return Err(format!("payload enum size {size} is not below 2^61"));
}
let Some(align) = 1u64.checked_shl(align_log2).filter(|a| *a < (1u64 << 61)) else {
return Err(format!("payload enum alignment 2^{align_log2} is unsupported"));
};
if !size_u64.is_multiple_of(align) {
return Err(format!("payload enum size {size} is not a multiple of {align}"));
}
let tag_mask = tag.width.mask();
let tag_bytes = tag.width.bits() as usize / 8;
let tag_fits = tag_offset.checked_add(tag_bytes).is_some_and(|end| end <= size)
&& tag_valid_range.0 <= tag_mask
&& tag_valid_range.1 <= tag_mask;
match encoding {
// `Variants::Single { index }` names its one inhabited variant
// in `tag_valid_range` (`Trusted.MirSemantics.adtEnumHeadWfV2`);
// every other variant must be uninhabited (checked below).
AdtTagEncoding::Single => {
if tag_valid_range.0 != tag_valid_range.1 || tag_valid_range.0 >= n as u128 {
return Err("an untagged payload enum must name one inhabited variant".into());
}
}
AdtTagEncoding::Direct => {
if !tag_fits {
return Err("payload enum tag does not fit the enum".into());
}
for &d in &discriminants {
if tag_bits_to_discr_bits(tag, discr.width, d & tag_mask) != d {
return Err("payload enum discriminant does not round-trip through \
its tag"
.into());
}
}
}
AdtTagEncoding::Niche { untagged, first, last, start } => {
let (u, f, l) = (untagged as usize, first as usize, last as usize);
if !tag_fits
|| u >= n
|| f > l
|| l >= n
|| start > tag_mask
|| u128::from(last - first) > tag_mask
{
return Err("payload enum niche does not fit its tag or variants".into());
}
if discriminants.iter().enumerate().any(|(i, &d)| d != i as u128) {
return Err("niche-encoded enum discriminants must be variant indices".into());
}
}
}
let layout = AdtEnumLayout {
id,
size,
align_log2,
discr,
discriminants,
tag_offset,
tag,
tag_valid_start: tag_valid_range.0,
tag_valid_end: tag_valid_range.1,
encoding,
};
let (tag_off, tag_len) = layout.tag_span();
for (i, variant) in variants.iter().enumerate() {
let Ty::Struct(sty) = variant else {
return Err(format!("payload enum variant {i} is not a struct payload"));
};
if sty.layout().size() != size || sty.layout().align_log2() != align_log2 {
return Err(format!("payload enum variant {i} payload layout differs from the enum"));
}
// `Trusted.MirSemantics.adtSingleOtherVariantV2`: an untagged
// enum's other variants have an uninhabited (`!`) field.
if encoding == AdtTagEncoding::Single
&& i as u128 != tag_valid_range.0
&& !sty.fields().iter().any(|f| matches!(f, Ty::Never))
{
return Err(format!(
"payload enum variant {i} is inhabited but not the untagged variant"
));
}
if layout.variant_tagged(i) && tag_len != 0 {
for (field, &off) in sty.fields().iter().zip(sty.layout().field_offsets()) {
let Some((fsize, _)) = field.v2_layout() else {
return Err(format!("payload enum variant {i} field lacks layout"));
};
if fsize != 0 && off < tag_off + tag_len && tag_off < off + fsize {
return Err(format!("payload enum variant {i} field overlaps the tag"));
}
}
}
}
Ok(Self { layout, local, variants })
}
pub fn layout(&self) -> &AdtEnumLayout {
&self.layout
}
pub fn variants(&self) -> &[Ty] {
&self.variants
}
/// The payload struct of variant `i`.
pub fn variant(&self, i: usize) -> Option<&StructTy> {
match self.variants.get(i)? {
Ty::Struct(sty) => Some(sty),
_ => None,
}
}
}
/// Whether `bits` is a Unicode scalar value (`0x0000..=0xD7FF` or
/// `0xE000..=0x10FFFF`), matching the Rust Reference ("A value of type `char`
/// is represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000
/// to 0x10FFFF range. It is immediate [undefined behavior] to create a `char`
/// that falls outside this range.") and `Scalar::to_char`.
/// https://github.com/rust-lang/reference/blob/a286e1ecb8ce193d50056e4bb042eea9b23876ef/src/types/char.md?plain=1#L17-L21
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/interpret/value.rs#L353-L359
pub const fn is_unicode_scalar(bits: u128) -> bool {
bits <= 0x10_FFFF && !(0xD800 <= bits && bits <= 0xDFFF)
}
/// Mutability qualifier matching `Trusted.MirAst.Mutability`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Mutability {
Shared,
Mut,
}
impl Mutability {
pub const fn lean_name(self) -> &'static str {
match self {
Self::Shared => "shared",
Self::Mut => "mut",
}
}
}
fn serialize_boxed_ty<S: Serializer>(val: &Ty, serializer: S) -> Result<S::Ok, S::Error> {
let v = serde_json::to_value(val).map_err(serde::ser::Error::custom)?;
v.serialize(serializer)
}
fn serialize_ty_slice<S: Serializer>(vals: &[Ty], serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(vals.len()))?;
for val in vals {
let v = serde_json::to_value(val).map_err(serde::ser::Error::custom)?;
seq.serialize_element(&v)?;
}
seq.end()
}
/// Size of the model's `Vec<T>` handle (`Trusted.MirSemantics.layoutOfTyV2`).
pub const VEC_SIZE: usize = 24;
/// Alignment (log2) of the model's `Vec<T>` handle.
pub const VEC_ALIGN_LOG2: u32 = 3;
/// Byte offset of a `Vec` handle's capacity word
/// (`Trusted.MirSemantics.vecCapOffsetV2`).
pub const VEC_CAP_OFFSET: u64 = 0;
/// Byte offset of a `Vec` handle's buffer pointer word
/// (`Trusted.MirSemantics.vecPtrOffsetV2`).
pub const VEC_PTR_OFFSET: u64 = 8;
/// Byte offset of a `Vec` handle's length word
/// (`Trusted.MirSemantics.vecLenOffsetV2`).
pub const VEC_LEN_OFFSET: u64 = 16;
/// Check `rustc`'s layout of a `Vec<T>` against the model's handle: size,
/// alignment, and the offsets of the capacity, buffer pointer, and length
/// words (`Trusted.MirSemantics.encodeVecHandleV2`), each of which must be
/// one 8-byte word (`word_sizes`, in the order capacity, pointer, length).
/// Rust leaves the field order unspecified, so a compiler that reorders them
/// is refused here rather than modeled with the wrong order.
pub fn check_vec_layout(
size: u64,
align_log2: u32,
cap: u64,
ptr: u64,
len: u64,
word_sizes: [u64; 3],
) -> Result<(), String> {
let expected =
(VEC_SIZE as u64, VEC_ALIGN_LOG2, VEC_CAP_OFFSET, VEC_PTR_OFFSET, VEC_LEN_OFFSET);
if (size, align_log2, cap, ptr, len) != expected || word_sizes != [8; 3] {
return Err(format!(
"rustc's Vec layout (size {size}, align 2^{align_log2}, cap@{cap}, ptr@{ptr}, \
len@{len}, word sizes {word_sizes:?}) disagrees with the model's {expected:?}"
));
}
Ok(())
}
/// `rustc`'s niche value for `Option<Vec<T>>::None` in `RawVecInner.cap`
/// (`UsizeNoHighBit`, valid range `0..=isize::MAX`; `Niche::reserve` assigns
/// `u64::MAX = 2^64 - 1`, matching `Trusted.MirSemantics.vecNoneNicheV2`).
pub const VEC_NONE_NICHE: u128 = u64::MAX as u128;
/// Kind of owned heap handle whose `Option<H>` uses a niche layout in Profile
/// v2 (`Trusted.MirSemantics.{Layout,Bytes,Step}`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OptionHandleNicheKind {
/// `Option<Box<T>>` or `Option<Box<[T]>>`: null pointer niche
/// (`niche_start == 0`) at byte offset `0`.
Box,
/// `Option<Vec<T>>`: `RawVecInner.cap : UsizeNoHighBit` niche
/// (`niche_start == VEC_NONE_NICHE`) at `VEC_CAP_OFFSET` (`0`).
Vec,
}
/// Cross-check `rustc`'s niche-encoded `Option<Box<...>>` or `Option<Vec<T>>`
/// layout against the Profile v2 model
/// (`Trusted.MirSemantics.{Layout,Bytes,Step}`): `Some` (`variant 1`) is
/// untagged, `None` (`variant 0`) is the sole niche variant, the niche tag is
/// 8 bytes at byte offset `0` (`VEC_CAP_OFFSET` for `Vec`) with
/// `niche_start == 0` for `Box` and `niche_start == VEC_NONE_NICHE` for `Vec`,
/// and the `Some` payload starts at byte offset `0` (`optionSomeOffsetV2`).
#[allow(clippy::too_many_arguments)]
pub fn check_niche_option_handle_layout(
kind: OptionHandleNicheKind,
tag_bytes: u64,
tag_offset: u64,
untagged_variant: usize,
niche_variants: (usize, usize),
niche_start: u128,
some_payload_offset: Option<u64>,
) -> Result<(), String> {
let expected_tag_offset = match kind {
OptionHandleNicheKind::Box => 0,
OptionHandleNicheKind::Vec => VEC_CAP_OFFSET,
};
if untagged_variant != 1 || niche_variants != (0, 0) {
return Err(format!(
"Option<{kind:?}> niche variants (untagged={untagged_variant}, \
niche={niche_variants:?}) disagree with modeled (None=0 niche, Some=1 untagged)"
));
}
if tag_bytes != 8 || tag_offset != expected_tag_offset {
return Err(format!(
"Option<{kind:?}> niche tag (size={tag_bytes}, offset={tag_offset}) \
disagrees with modeled (size=8, offset={expected_tag_offset})"
));
}
let niche_ok = match kind {
OptionHandleNicheKind::Box => niche_start == 0,
OptionHandleNicheKind::Vec => niche_start == VEC_NONE_NICHE,
};
if !niche_ok {
return Err(format!(
"Option<{kind:?}> niche_start ({niche_start:#x}) disagrees with modeled niche range"
));
}
if some_payload_offset != Some(0) {
return Err(format!(
"Option<{kind:?}> Some payload offset ({some_payload_offset:?}) \
disagrees with modeled offset 0"
));
}
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Ty {
Bool,
Char,
Ordering,
Unit,
Never,
Int(IntTy),
Enum(EnumTy),
Struct(StructTy),
OverflowPair(IntTy),
Tuple {
#[serde(serialize_with = "serialize_ty_slice")]
fields: Vec<Ty>,
},
Ref {
mutability: Mutability,
#[serde(serialize_with = "serialize_boxed_ty")]
pointee: Box<Ty>,
},
RawPtr {
mutability: Mutability,
#[serde(serialize_with = "serialize_boxed_ty")]
pointee: Box<Ty>,
},
Slice {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
Str,
Array {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
len: usize,
},
Vec {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
Box {
#[serde(serialize_with = "serialize_boxed_ty")]
pointee: Box<Ty>,
},
RangeTo {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
RangeFrom {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
Range {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
Option {
#[serde(serialize_with = "serialize_boxed_ty")]
elem: Box<Ty>,
},
/// A crate-local, non-generic, self-recursive struct
/// (`Trusted.MirAst.MirTy.recAdt`): the closed term `μ id. defn`, where
/// `defn` is the struct's own [`Self::Struct`] (with
/// [`StructLayout::id`] `id`) and each recursive occurrence of the struct
/// in it is [`Self::RecSelf`] `id`, directly under a `Box` or `Vec`.
RecAdt {
id: u32,
#[serde(serialize_with = "serialize_boxed_ty")]
defn: Box<Ty>,
},
/// The recursive occurrence of the enclosing [`Self::RecAdt`] with the
/// same `id` (`Trusted.MirAst.MirTy.recSelf`).
RecSelf { id: u32 },
/// A payload enum (`Trusted.MirAst.MirTy.adtEnum`): a crate-local
/// non-generic enum with a variant that has fields, `Result<T, E>`, or an
/// `Option<T>` whose payload has no [`Self::Option`] layout.
AdtEnum(Box<AdtEnumTy>),
}
impl Ty {
/// Whether `rustc`'s `WithRetag::Yes` (`pub enum WithRetag { Yes, No }`,
/// where `Rvalue::Use` "yields the operand unchanged, except for a
/// potential retag") is an operational no-op for values of this type.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L497-L511
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1363-L1365
///
/// In Miri (`Miri/Interpreter/Rvalue.lean` and `ValidityVisitor.lean`),
/// `WithRetag::Yes` sets `RetagMode::Default` during `copyOp`, which calls
/// `retagSafePointer` only inside `ValidityVisitor::checkSafe` on safe
/// pointers (`&T`, `&mut T`, `Box<T>`). For reference-free scalar, `char`,
/// `Ordering`, unit, never, fieldless-enum, raw-pointer, range, and `(int,
/// bool)` overflow-pair types, `WithRetag::Yes` and `WithRetag::No` have
/// identical semantics. Any reference-bearing type returns `false` so
/// capture never erases active retags (`Rvalue::UseRetag` instead).
pub fn is_retag_noop(&self) -> bool {
match self {
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_)
| Self::RawPtr { .. }
| Self::Slice { .. }
| Self::Str
| Self::Vec { .. }
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. } => true,
Self::Option { elem } => elem.is_retag_noop(),
Self::Ref { .. } | Self::Box { .. } => false,
// A recursive struct owns a `Box` or `Vec` of itself; `RecSelf`
// only occurs under one.
Self::RecAdt { .. } | Self::RecSelf { .. } => false,
Self::Array { elem, .. } => elem.is_retag_noop(),
Self::Tuple { fields } => fields.iter().all(Self::is_retag_noop),
Self::Struct(sty) => sty.fields().iter().all(Self::is_retag_noop),
Self::AdtEnum(aty) => aty.variants().iter().all(Self::is_retag_noop),
}
}
/// Whether values of this type are always statically `Sized`.
///
/// In `rustc_const_eval`'s `eval_statement` (`"PlaceMention(place) => {
/// let _ = self.eval_place(**place)?; }"`) and `local_to_place` (`"let
/// layout = self.layout_of_local(frame, local, None)?; let place = if
/// layout.is_sized() { Place::Local { local, offset: None, locals_addr:
/// frame.locals_addr() } } else { match frame.locals[local].access()? {
/// Operand::Immediate(_) => bug!(), Operand::Indirect(mplace) =>
/// Place::Ptr(*mplace), } };"`, where `layout_of_local` indexes
/// `&frame.locals[local]` without calling `.access()`), and in
/// `lean-miri`'s `Miri.Interpreter.localToPlace`, evaluating an unprojected
/// `PlaceMention` of a `Sized` local returns `Place::Local` without reading
/// memory or checking liveness (an exact operational no-op), whereas an
/// unsized local accesses its local operand and checks liveness. Unsized
/// [`Ty`] variants ([`Self::Slice`] and [`Self::Str`]) return `false` so
/// capture fails closed rather than rendering `Statement::PlaceMention` as
/// `StatementKind.nop`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/step.rs#L117-L119
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/place.rs#L519-L536
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/stack.rs#L610-L631
pub fn is_sized(&self) -> bool {
match self {
Self::Slice { .. } | Self::Str => false,
Self::Array { elem, .. } => elem.is_sized(),
Self::Tuple { fields } => fields.iter().all(Self::is_sized),
Self::Struct(sty) => sty.fields().iter().all(Self::is_sized),
Self::RecAdt { .. } | Self::RecSelf { .. } | Self::AdtEnum(_) => true,
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_)
| Self::Ref { .. }
| Self::RawPtr { .. }
| Self::Vec { .. }
| Self::Box { .. }
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. }
| Self::Option { .. } => true,
}
}
/// Whether this type belongs to the Profile v1 scalar/unit/enum/pair
/// fragment.
pub fn is_supported_scalar_or_unit(&self) -> bool {
matches!(
self,
Self::Bool
| Self::Int(_)
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Enum(_)
| Self::OverflowPair(_)
)
}
/// Whether this type belongs to the Profile v2 fixed-size data fragment
/// (`Trusted.MirSemantics.isSupportedV2DataTy`): scalars, units, enums,
/// fixed arrays `[T; N]`, and admitted crate-local structs, all without
/// embedded refs, ptrs, or overflow pairs.
pub fn is_supported_v2_data(&self) -> bool {
match self {
Self::Array { elem, .. } => elem.is_supported_v2_data(),
Self::Struct(sty) => sty.fields().iter().all(Self::is_supported_v2_data),
Self::OverflowPair(_) => false,
_ => self.is_supported_scalar_or_unit(),
}
}
/// Whether this type belongs to the Profile v2 structural `PartialEq`
/// fragment (`Trusted.MirSemantics.isArrayEqElemSupported`): primitives,
/// `Ordering`, `()`, and nested fixed-size arrays thereof, excluding enums
/// and structs whose `PartialEq` impl may be non-structural.
pub fn is_array_eq_elem_supported(&self) -> bool {
match self {
Self::Bool | Self::Int(_) | Self::Char | Self::Ordering | Self::Unit => true,
Self::Array { elem, .. } => elem.is_array_eq_elem_supported(),
Self::Never
| Self::Enum(_)
| Self::Struct(_)
| Self::OverflowPair(_)
| Self::Tuple { .. }
| Self::Ref { .. }
| Self::RawPtr { .. }
| Self::Slice { .. }
| Self::Str
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. }
| Self::Option { .. }
| Self::Vec { .. }
| Self::Box { .. }
| Self::RecAdt { .. }
| Self::RecSelf { .. }
| Self::AdtEnum(_) => false,
}
}
/// Layout `(size_bytes, align_log2)` matching
/// `Trusted.MirSemantics.layoutOfTyV2`.
pub fn v2_layout(&self) -> Option<(usize, u32)> {
match self {
Self::Bool | Self::Ordering => Some((1, 0)),
Self::Int(ity) => Some(match ity.width {
IntWidth::I8 => (1, 0),
IntWidth::I16 => (2, 1),
IntWidth::I32 => (4, 2),
IntWidth::I64 | IntWidth::Isize => (8, 3),
IntWidth::I128 => (16, 4),
}),
Self::Char => Some((4, 2)),
Self::Unit | Self::Never => Some((0, 0)),
Self::Enum(ety) => match ety.tag_repr() {
EnumTagRepr::ZeroSized => Some((0, 0)),
EnumTagRepr::Scalar(tag) => Self::Int(tag).v2_layout(),
},
Self::OverflowPair(ity) => {
let (w_bytes, align_log2) = Self::Int(*ity).v2_layout()?;
Some((2 * w_bytes, align_log2))
}
Self::Array { elem, len } => {
let (elem_size, align_log2) = elem.v2_layout()?;
let size = len.checked_mul(elem_size)?;
Some((size, align_log2))
}
Self::Struct(sty) => Some((sty.layout().size(), sty.layout().align_log2())),
// `AdtEnumTy::try_new` checked `adtEnumHeadWfV2` and
// `adtVariantsWfV2`.
Self::AdtEnum(aty) => Some((aty.layout().size(), aty.layout().align_log2())),
Self::RecAdt { defn, .. } => defn.v2_layout(),
// An inline recursive occurrence would have infinite layout.
Self::RecSelf { .. } => None,
Self::Ref { pointee, .. } | Self::RawPtr { pointee, .. } => {
Some(if matches!(&**pointee, Self::Slice { .. } | Self::Str) {
(16, 3)
} else {
(8, 3)
})
}
Self::Box { pointee } => Some(
if matches!(&**pointee, Self::Slice { .. } | Self::Str) { (16, 3) } else { (8, 3) },
),
Self::Vec { .. } => Some((VEC_SIZE, VEC_ALIGN_LOG2)),
Self::RangeTo { elem } | Self::RangeFrom { elem }
if matches!(
&**elem,
Self::Int(IntTy {
width: IntWidth::Isize,
signed: false
})
) =>
{
Some((8, 3))
}
Self::Option { elem } => match &**elem {
// `Option<Box<T>>` and `Option<Vec<T>>` are niche-encoded
// owned handles; other payloads must be sized, reference-free,
// and option-payload-supported.
Self::Box { pointee } => {
Some(if matches!(&**pointee, Self::Slice { .. } | Self::Str) {
(16, 3)
} else {
(8, 3)
})
}
Self::Vec { .. } => Some((24, 3)),
Self::Bool | Self::Unit => Some((1, 0)),
inner => {
if !inner.is_sized_no_ref() || !inner.is_option_payload_supported_v2() {
return None;
}
let (size, align_log2) = inner.v2_layout()?;
let tag_bytes = 1usize.checked_shl(align_log2)?;
Some((tag_bytes.checked_add(size)?, align_log2))
}
},
Self::Tuple { .. }
| Self::Slice { .. }
| Self::Str
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. } => None,
}
}
/// Whether this type is a sized Profile v2 pointee or slice-element type
/// containing no nested references or raw pointers and having a fixed,
/// guaranteed ABI layout (matching
/// `Trusted.MirSemantics.isSizedNoRefV2Ty`).
///
/// Tuples (`OverflowPair` and `Tuple`) and `Range`/`RangeTo`/`RangeFrom`
/// are `#[repr(Rust)]` and subject to `rustc_abi`'s `univariant` field
/// reordering (`compiler/rustc_abi/src/layout.rs:1111` at
/// `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), so they remain local-only
/// (`is_supported_v2_local`) and are refused behind references, pointers,
/// and slices. `Option<T>` additionally requires
/// `is_option_payload_supported_v2` so `&Option<Option<u8>>` fails closed.
/// Structs are admitted as pointees through `is_supported_v2_data`
/// instead.
pub fn is_sized_no_ref(&self) -> bool {
match self {
Self::Bool
| Self::Int(_)
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Enum(_) => true,
Self::Option { elem } => {
elem.is_sized_no_ref() && elem.is_option_payload_supported_v2()
}
Self::OverflowPair(_)
| Self::Tuple { .. }
| Self::Array { .. }
| Self::Vec { .. }
| Self::Box { .. }
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. }
| Self::Ref { .. }
| Self::RawPtr { .. }
| Self::Slice { .. }
| Self::Str
| Self::Struct(_)
| Self::RecAdt { .. }
| Self::RecSelf { .. }
| Self::AdtEnum(_) => false,
}
}
/// Whether `self` is an admitted Profile v2 thin pointee (matching
/// `Trusted.MirSemantics.isSupportedV2PointeeTy`): the union of
/// [`Self::is_sized_no_ref`] and [`Self::is_supported_v2_data`].
pub fn is_supported_v2_pointee(&self) -> bool {
self.is_sized_no_ref() || self.is_supported_v2_data()
}
/// Whether `self` uses `rustc` `TagEncoding::Direct` with fixed layout
/// inside `Option<self>` (scalars and raw pointers; matching
/// `Trusted.MirSemantics.isNicheFreeOptionPayloadV2`). Tuples,
/// `OverflowPair`, and `Range*` are refused due to `#[repr(Rust)]`
/// field reordering and padding-tag optimizations.
pub fn is_niche_free_option_payload(&self) -> bool {
matches!(self, Self::Int(_) | Self::RawPtr { .. })
}
/// Whether `self` has a modeled `Option<self>` layout in Profile v2
/// (matching `Trusted.MirSemantics.isOptionPayloadSupportedV2`). Nested
/// references `&&T` stay excluded from `Option`.
pub fn is_option_payload_supported_v2(&self) -> bool {
match self {
Self::Unit | Self::Bool => true,
Self::Ref { pointee, .. } => !matches!(&**pointee, Self::Ref { .. }),
_ => self.is_niche_free_option_payload(),
}
}
/// Whether this type is owned Profile v2 data
/// (`Trusted.MirSemantics.isOwnedDataTyV2`): a data type
/// ([`Self::is_supported_v2_data`]), a `Vec<T>`, `Box<T>`, or `Box<[T]>`
/// handle whose element is owned data, a struct whose fields are all
/// owned data, or an array of owned data. Owned data may be a `Vec`/`Box`
/// element, a struct field, an array element, a local, or a reference
/// pointee, but never a raw-pointer pointee unless it is plain data, so
/// the model's handle encoding is never observable by reinterpreting
/// bytes.
/// Whether this type may be a field of a payload enum with reference
/// fields (`Trusted.MirSemantics.isRefEnumFieldTyV2`): a shared `&T` that
/// is an admitted 1-level local over a sized pointee that is not a
/// reference or raw pointer (`isNestedRefInnerPointeeV2`), or owned data
/// that owns no heap buffer.
pub fn is_ref_enum_field_v2(&self) -> bool {
match self {
Self::Ref { mutability: Mutability::Shared, pointee } => {
!matches!(
&**pointee,
Self::Slice { .. } | Self::Str | Self::Ref { .. } | Self::RawPtr { .. }
) && self.is_supported_v2_local()
}
_ => self.is_owned_data() && !self.has_heap_handle_v2(),
}
}
/// Whether this type is a payload enum with at least one reference field
/// whose variant fields are all [`Self::is_ref_enum_field_v2`]
/// (`Trusted.MirSemantics.isRefEnumTyV2`), such as `Result<&T, E>`.
pub fn is_ref_enum_v2(&self) -> bool {
let Self::AdtEnum(aty) = self else { return false };
let fields = |v: &Ty| match v {
Self::Struct(sty) => Some(sty.fields().to_vec()),
_ => None,
};
let mut has_ref = false;
for v in aty.variants() {
let Some(fs) = fields(v) else { return false };
for f in &fs {
if !f.is_ref_enum_field_v2() {
return false;
}
has_ref |= matches!(f, Self::Ref { .. });
}
}
has_ref
}
pub fn is_owned_data(&self) -> bool {
match self {
Self::Vec { elem } => match &**elem {
// A back edge of a recursive struct: its pointee is the
// enclosing binder (`Self::rec_ty_wf` binds it).
Self::RecSelf { .. } => true,
other => other.is_owned_data(),
},
Self::Box { pointee } => match &**pointee {
Self::Slice { elem } => elem.is_owned_data(),
Self::RecSelf { .. } => true,
other => other.is_owned_data(),
},
Self::RecAdt { defn, .. } => defn.is_owned_data(),
Self::Struct(sty) => sty.fields().iter().all(Self::is_owned_data),
// An array is owned data when its element is
// (`Trusted.MirSemantics.isOwnedDataTyV2`).
Self::Array { elem, .. } => elem.is_owned_data(),
// A payload enum is owned data when every variant's payload is.
Self::AdtEnum(aty) => aty.variants().iter().all(Self::is_owned_data),
// `Option<Box<T>>` and `Option<Vec<T>>` use the handle's niche
// (`Trusted.MirSemantics.encodeValV2`).
// `Option` of plain sized data has its `rustc` layout, which
// `struct_ty` and `adt_enum_ty` check field by field.
Self::Option { elem } => {
matches!(&**elem, Self::Vec { .. } | Self::Box { .. }) && elem.is_owned_data()
|| self.is_sized_no_ref()
}
_ => self.is_supported_v2_data(),
}
}
/// For a `Vec<T>`, `Box<[T]>`, or `Box<T>`, whether `T` is owned data,
/// mirroring the `.vec`/`.box` arms of
/// `Trusted.MirSemantics.isSupportedV2LocalTy` (unlike `is_owned_data`, a
/// bare back edge `RecSelf` is not); `false` for any other type.
fn handle_payload_is_owned_data(&self) -> bool {
match self {
Self::Vec { elem } => elem.is_owned_data(),
Self::Box { pointee } => match &**pointee {
Self::Slice { elem } => elem.is_owned_data(),
other => other.is_owned_data(),
},
_ => false,
}
}
/// Whether this type is admitted as a Profile v2 local type (matching
/// `Trusted.MirSemantics.isSupportedV2LocalTy`). Forbids nested
/// references/pointers inside pointees (`&&T`, `*mut &T`, `&[&T]`,
/// `[&T; N]`) and unmodeled niche-packed `Option` payloads.
///
/// Also forbids tuple, overflow-pair, and range pointees and overflow-pair
/// array elements (`&(T, bool)`, `*const (T, bool)`, `&Range<usize>`,
/// `[(T, bool); N]`). The Reference says "Tuples are
/// laid out according to the [`Rust` representation][`Rust`]." Beyond
/// field alignment and non-overlap, "There are no other guarantees of
/// data layout made by this representation." Yet
/// `Trusted.MirSemantics.overflowPairLayout` fixes one field order and
/// size without a `layout_of` check. So overflow pairs stay
/// non-addressable locals that hold checked-operator results, and no
/// pointer can reach their bytes (see [`Self::is_sized_no_ref`]).
/// https://github.com/rust-lang/reference/blob/ad35aca481751a06afeb23820a672b0f3b11a476/src/type-layout.md#L94
/// https://github.com/rust-lang/reference/blob/ad35aca481751a06afeb23820a672b0f3b11a476/src/type-layout.md#L184
pub fn is_supported_v2_local(&self) -> bool {
let usize_ty = Self::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
match self {
Self::Bool
| Self::Int(_)
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Enum(_)
| Self::OverflowPair(_) => true,
Self::Array { elem, .. } => elem.is_supported_v2_data() || elem.is_owned_data(),
Self::Struct(_) => self.is_owned_data(),
Self::Tuple { fields } => fields.iter().all(Self::is_supported_v2_local),
// As in Lean, the payload itself must be owned data, so a bare
// back edge (`Box<RecSelf>`) is not a local type.
Self::Vec { .. } | Self::Box { .. } => self.handle_payload_is_owned_data(),
// References to `Vec`/`Box` are admitted, but raw pointers to them
// are not: `Vec`'s layout is unspecified ("The order of these
// fields is completely unspecified",
// `library/alloc/src/vec/mod.rs:312-314`, `rust-lang/rust`
// `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), so a raw pointer
// could reinterpret the handle's bytes in a way the model's
// encoding (`Trusted.MirSemantics.encodeValV2`) does not match.
Self::Ref { mutability, pointee } => match &**pointee {
Self::Slice { elem } => elem.is_sized_no_ref() || elem.is_owned_data(),
Self::Str if *mutability == Mutability::Shared => true,
Self::Vec { .. } | Self::Box { .. } => {
pointee.handle_payload_is_owned_data()
}
// An intra-body `&&T`: the outer shared reference points at a
// slot holding an admitted 1-level shared reference
// (`Trusted.MirSemantics.isNestedRefInnerPointeeV2`).
// A match guard on `&mut self` also views a `&mut T` binding
// through a shared reference (`& &mut T`). Capture only admits
// reads through such a local and through the `&mut T` copied
// out of it (`check_nested_mut_ref_copies` in `extract.rs`).
Self::Ref {
mutability: Mutability::Shared | Mutability::Mut,
pointee: inner_pt,
} if *mutability == Mutability::Shared => {
!matches!(
&**inner_pt,
Self::Slice { .. } | Self::Str | Self::Ref { .. } | Self::RawPtr { .. }
) && pointee.is_supported_v2_local()
}
other => other.is_supported_v2_pointee() || other.is_owned_data(),
},
Self::RawPtr { pointee, .. } => match &**pointee {
Self::Slice { elem } => elem.is_sized_no_ref(),
other => other.is_supported_v2_pointee(),
},
Self::RangeTo { elem } | Self::RangeFrom { elem } | Self::Range { elem } => {
**elem == usize_ty
}
Self::Option { elem } => {
elem.is_supported_v2_local() && elem.is_option_payload_supported_v2()
|| self.is_owned_data()
}
// A recursive struct is owned data
// (`Trusted.MirSemantics.isOwnedDataTyV2`); an inline back edge
// never is.
Self::RecAdt { .. } => self.is_owned_data(),
Self::AdtEnum(_) => self.is_owned_data() || self.is_ref_enum_v2(),
Self::Slice { .. } | Self::RecSelf { .. } | Self::Str => false,
}
}
/// Whether a value of this type has drop glue, mirroring
/// `Trusted.MirSemantics.tyNeedsDropV2`: `Vec` and `Box` always do (they
/// implement `Drop`); tuples, structs, `Option`, ranges, and slices do when
/// a component does; arrays do when their length is nonzero and their
/// element does; every other type does not. Capture compares this with
/// `rustc`'s `Ty::needs_drop` for every `Drop` terminator and refuses on
/// disagreement, so a type with drop glue the model does not see (such as a
/// `Drop` impl on a fieldless enum) fails closed.
pub fn needs_drop_v2(&self) -> bool {
match self {
Self::Vec { .. } | Self::Box { .. } => true,
Self::RecAdt { .. } | Self::RecSelf { .. } => true,
Self::Tuple { fields } => fields.iter().any(Self::needs_drop_v2),
Self::Struct(sty) => sty.fields().iter().any(Self::needs_drop_v2),
Self::AdtEnum(aty) => aty.variants().iter().any(Self::needs_drop_v2),
Self::Array { elem, len } => *len != 0 && elem.needs_drop_v2(),
Self::Slice { elem }
| Self::Option { elem }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem } => elem.needs_drop_v2(),
Self::Bool
| Self::Char
| Self::Str
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_)
| Self::Ref { .. }
| Self::RawPtr { .. } => false,
}
}
/// Whether this type is a reference or a `Box` (which the aliasing models
/// retag like a unique reference), or an `Option`, range, tuple, array,
/// struct (recursive or not), or `Vec` containing one, mirroring
/// `Trusted.MirSemantics.tyHasRefV2`.
pub fn has_ref_v2(&self) -> bool {
match self {
// A `Vec`'s handle bytes are model-internal, so, like a `Box`, it
// counts as a reference and may not share a body with raw
// pointers (`Trusted.MirSemantics.tyHasRefV2`).
Self::Ref { .. } | Self::Box { .. } | Self::Vec { .. } => true,
Self::Array { elem, .. } => elem.has_ref_v2(),
Self::Option { elem }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem } => elem.has_ref_v2(),
Self::Tuple { fields } => fields.iter().any(Self::has_ref_v2),
Self::Struct(sty) => sty.fields().iter().any(Self::has_ref_v2),
Self::AdtEnum(aty) => aty.variants().iter().any(Self::has_ref_v2),
Self::RecAdt { defn, .. } => defn.has_ref_v2(),
// A back edge is under a `Box` or `Vec` of its binder, already
// counted.
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_)
| Self::RawPtr { .. }
| Self::Slice { .. }
| Self::RecSelf { .. }
| Self::Str => false,
}
}
/// Whether this type is a raw pointer or an `Option`, range, tuple, array,
/// struct (recursive or not), `Vec`, or `Box` containing one, mirroring
/// `Trusted.MirSemantics.tyHasRawPtrV2`.
pub fn has_raw_ptr_v2(&self) -> bool {
match self {
Self::RawPtr { .. } => true,
Self::Array { elem, .. } => elem.has_raw_ptr_v2(),
Self::Option { elem }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem } => elem.has_raw_ptr_v2(),
Self::Tuple { fields } => fields.iter().any(Self::has_raw_ptr_v2),
Self::Vec { elem } => elem.has_raw_ptr_v2(),
Self::Box { pointee } => pointee.has_raw_ptr_v2(),
Self::Struct(sty) => sty.fields().iter().any(Self::has_raw_ptr_v2),
Self::AdtEnum(aty) => aty.variants().iter().any(Self::has_raw_ptr_v2),
Self::RecAdt { defn, .. } => defn.has_raw_ptr_v2(),
// A back edge stands for its enclosing binder, whose `defn` is
// scanned by the `RecAdt` arm.
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_)
| Self::Ref { .. }
| Self::Slice { .. }
| Self::RecSelf { .. }
| Self::Str => false,
}
}
/// Whether this type is or contains a two-level `&&T` reference,
/// mirroring `Trusted.MirSemantics.tyHasNestedRefV2`.
pub fn has_nested_ref_v2(&self) -> bool {
match self {
Self::Ref { pointee, .. } => matches!(pointee.as_ref(), Self::Ref { .. }),
Self::Tuple { fields } => fields.iter().any(Self::has_nested_ref_v2),
Self::Option { elem } => elem.has_nested_ref_v2(),
_ => false,
}
}
/// For a payload enum with the shape of `Result<T, E>` (two variants with
/// one field each), `(T, E)` (`Trusted.MirSemantics.adtResultShapeV2`).
pub fn adt_result_payloads(&self) -> Option<(&Ty, &Ty)> {
let Self::AdtEnum(aty) = self else {
return None;
};
match aty.variants() {
[Self::Struct(ok), Self::Struct(err)]
if ok.fields().len() == 1 && err.fields().len() == 1 =>
{
Some((&ok.fields()[0], &err.fields()[0]))
}
_ => None,
}
}
/// For a `ControlFlow<B, C>`-shaped payload enum (two variants with one
/// field each, `Continue(C)` first), `(C, B)`
/// (`Trusted.MirSemantics.adtControlFlowV2`).
pub fn adt_control_flow_payloads(&self) -> Option<(&Ty, &Ty)> {
self.adt_result_payloads()
}
/// For a payload enum with the shape of `Option<T>` (variant 0 without
/// fields, variant 1 with one field), `T`
/// (`Trusted.MirSemantics.adtOptionShapeV2`).
pub fn adt_option_payload(&self) -> Option<&Ty> {
let Self::AdtEnum(aty) = self else {
return None;
};
match aty.variants() {
[Self::Struct(none), Self::Struct(some)]
if none.fields().is_empty() && some.fields().len() == 1 =>
{
some.fields().first()
}
_ => None,
}
}
/// Whether this type is or contains an owned `Vec` or `Box` handle,
/// mirroring `Trusted.MirSemantics.tyHasHeapHandleV2`.
pub fn has_heap_handle_v2(&self) -> bool {
match self {
Self::Vec { .. } | Self::Box { .. } => true,
Self::Array { elem, .. } | Self::Option { elem } => elem.has_heap_handle_v2(),
Self::Tuple { fields } => fields.iter().any(Self::has_heap_handle_v2),
Self::Struct(sty) => sty.fields().iter().any(Self::has_heap_handle_v2),
Self::AdtEnum(aty) => aty.variants().iter().any(Self::has_heap_handle_v2),
Self::RecAdt { defn, .. } => defn.has_heap_handle_v2(),
_ => false,
}
}
/// Whether this type uses Profile v2 extensions.
pub fn is_profile_v2(&self) -> bool {
match self {
Self::Tuple { .. }
| Self::Ref { .. }
| Self::RawPtr { .. }
| Self::Slice { .. }
| Self::Str
| Self::Array { .. }
| Self::Vec { .. }
| Self::Box { .. }
| Self::Struct(_)
| Self::RangeTo { .. }
| Self::RangeFrom { .. }
| Self::Range { .. }
| Self::Option { .. }
| Self::RecAdt { .. }
| Self::RecSelf { .. }
| Self::AdtEnum(_) => true,
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_) => false,
}
}
/// Record every nominal [`EnumTy::id`] embedded in this type.
///
/// Keep the match exhaustive so any future compound type variant must
/// recurse into its constituent types rather than hiding an enum key from
/// collision checks.
pub fn collect_enum_ids(&self, out: &mut BTreeSet<u32>) {
self.for_each_nested(&mut |ty| match ty {
Self::Enum(ety) => {
out.insert(ety.id());
}
Self::AdtEnum(aty) if aty.local => {
out.insert(aty.layout().id());
}
_ => {}
});
}
/// Well-formedness of self-recursive structs, mirroring
/// `Trusted.MirSemantics.recTyWfV2`: `scope` is the id of the innermost
/// enclosing [`Self::RecAdt`]. Every [`Self::RecSelf`] must be the direct
/// pointee of a `Box` or `Vec` (possibly inside `Option`) and name the
/// innermost binder, so each type is closed and a binder's definition
/// mentions no outer binder; a binder must not rebind an enclosing id, and
/// its definition must be the struct or payload enum with layout id equal
/// to its id.
pub fn rec_ty_wf(&self, scope: Option<u32>) -> bool {
match self {
Self::RecSelf { .. } => false,
Self::Box { pointee: inner } | Self::Vec { elem: inner } => match &**inner {
Self::RecSelf { id } => scope == Some(*id),
other => other.rec_ty_wf(scope),
},
Self::RecAdt { id, defn } => {
scope != Some(*id)
&& match &**defn {
Self::Struct(sty) => sty.layout().id() == *id,
Self::AdtEnum(aty) => aty.layout().id() == *id,
_ => false,
}
&& defn.rec_ty_wf(Some(*id))
}
Self::Tuple { fields } => fields.iter().all(|t| t.rec_ty_wf(scope)),
Self::Struct(sty) => sty.fields().iter().all(|t| t.rec_ty_wf(scope)),
Self::AdtEnum(aty) => aty.variants().iter().all(|t| t.rec_ty_wf(scope)),
Self::Ref { pointee, .. } | Self::RawPtr { pointee, .. } => pointee.rec_ty_wf(scope),
Self::Slice { elem }
| Self::Array { elem, .. }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem }
| Self::Option { elem } => elem.rec_ty_wf(scope),
Self::Bool
| Self::Char
| Self::Str
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_) => true,
}
}
/// Replace every [`Self::RecSelf`] `id` by `r`, leaving nested binders
/// unchanged (`Trusted.MirSemantics.substRecSelfV2`).
fn subst_rec_self(&self, id: u32, r: &Ty) -> Ty {
let sub = |t: &Ty| Box::new(t.subst_rec_self(id, r));
match self {
Self::RecSelf { id: j } if *j == id => r.clone(),
Self::Tuple { fields } => Self::Tuple {
fields: fields.iter().map(|t| t.subst_rec_self(id, r)).collect(),
},
Self::Ref { mutability, pointee } => Self::Ref {
mutability: *mutability,
pointee: sub(pointee),
},
Self::RawPtr { mutability, pointee } => Self::RawPtr {
mutability: *mutability,
pointee: sub(pointee),
},
Self::Slice { elem } => Self::Slice { elem: sub(elem) },
Self::Array { elem, len } => Self::Array {
elem: sub(elem),
len: *len,
},
Self::Vec { elem } => Self::Vec { elem: sub(elem) },
Self::Box { pointee } => Self::Box { pointee: sub(pointee) },
Self::RangeTo { elem } => Self::RangeTo { elem: sub(elem) },
Self::RangeFrom { elem } => Self::RangeFrom { elem: sub(elem) },
Self::Range { elem } => Self::Range { elem: sub(elem) },
Self::Option { elem } => Self::Option { elem: sub(elem) },
Self::Struct(sty) => Self::Struct(StructTy {
layout: sty.layout.clone(),
fields: sty.fields.iter().map(|t| t.subst_rec_self(id, r)).collect(),
synthetic: sty.synthetic.clone(),
}),
Self::AdtEnum(aty) => Self::AdtEnum(Box::new(AdtEnumTy {
layout: aty.layout.clone(),
local: aty.local,
variants: aty.variants.iter().map(|t| t.subst_rec_self(id, r)).collect(),
})),
other => other.clone(),
}
}
/// One unfolding of a [`Self::RecAdt`]
/// (`Trusted.MirSemantics.unfoldRecV2`): its definition with each back
/// edge replaced by the closed binder.
pub fn unfold_rec(&self) -> Option<Ty> {
match self {
Self::RecAdt { id, defn } => Some(defn.subst_rec_self(*id, self)),
_ => None,
}
}
/// The payload enum this type is, unfolding a recursive one so that its
/// variants' back edges are the closed binder
/// (`Trusted.MirSemantics.adtVariantsV2`).
pub fn as_adt_enum(&self) -> Option<AdtEnumTy> {
match self {
Self::AdtEnum(aty) => Some((**aty).clone()),
Self::RecAdt { .. } => match self.unfold_rec() {
Some(Self::AdtEnum(aty)) => Some(*aty),
_ => None,
},
_ => None,
}
}
/// Walk this type for [`check_rec_tys`], mirroring
/// `Trusted.MirSemantics.recAdmitWalkV2`: `scope` is the id of the
/// innermost enclosing [`Self::RecAdt`]. Fail when this type is not
/// well-formed ([`Self::rec_ty_wf`]), when a binder id has two different
/// definitions, or when a binder id is also a plain layout id; otherwise
/// record the definition of each binder id in `defs` and the layout ids
/// of the structs and payload enums that do not head a binder's
/// definition in `plain`. A binder's head and definition are checked only
/// when its id is first recorded, in the binder's own scope; a binder
/// whose id already has an equal definition is not walked again. A binder
/// that rebinds the enclosing id is part of the definition being walked
/// for that id, so it differs from it and fails as incoherent.
fn walk_rec_admit<'a>(
&'a self,
scope: Option<u32>,
defs: &mut BTreeMap<u32, &'a Ty>,
plain: &mut BTreeSet<u32>,
) -> Result<(), String> {
let ill_formed = || Err(format!("ill-formed recursive type {self:?}"));
match self {
Self::RecSelf { .. } => ill_formed(),
Self::Box { pointee: inner } | Self::Vec { elem: inner }
if matches!(&**inner, Self::RecSelf { .. }) =>
{
if matches!(&**inner, Self::RecSelf { id } if scope == Some(*id)) {
Ok(())
} else {
ill_formed()
}
}
Self::RecAdt { id, defn } => {
if plain.contains(id) {
return Err(format!(
"recursive type id {id} is reused by a plain struct or payload enum"
));
}
if let Some(first) = defs.get(id) {
if **first != **defn {
return Err(format!("recursive type {id} has two different definitions"));
}
return Ok(());
}
defs.insert(*id, defn);
match &**defn {
Self::Struct(sty) if sty.layout().id() == *id => {
for field in sty.fields() {
field.walk_rec_admit(Some(*id), defs, plain)?;
}
Ok(())
}
Self::AdtEnum(aty) if aty.layout().id() == *id => {
for variant in aty.variants() {
variant.walk_rec_admit(Some(*id), defs, plain)?;
}
Ok(())
}
_ => ill_formed(),
}
}
Self::Struct(sty) => {
Self::record_plain_id(sty.layout().id(), defs, plain)?;
for field in sty.fields() {
field.walk_rec_admit(scope, defs, plain)?;
}
Ok(())
}
Self::Tuple { fields } => {
for field in fields {
field.walk_rec_admit(scope, defs, plain)?;
}
Ok(())
}
Self::AdtEnum(aty) => {
Self::record_plain_id(aty.layout().id(), defs, plain)?;
for variant in aty.variants() {
variant.walk_rec_admit(scope, defs, plain)?;
}
Ok(())
}
Self::Ref { pointee, .. } | Self::RawPtr { pointee, .. } | Self::Box { pointee } => {
pointee.walk_rec_admit(scope, defs, plain)
}
Self::Slice { elem }
| Self::Array { elem, .. }
| Self::Vec { elem }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem }
| Self::Option { elem } => elem.walk_rec_admit(scope, defs, plain),
Self::Bool
| Self::Char
| Self::Str
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_) => Ok(()),
}
}
/// Record the plain layout id `id` for [`Self::walk_rec_admit`],
/// failing when a binder already uses it.
fn record_plain_id(
id: u32,
defs: &BTreeMap<u32, &Ty>,
plain: &mut BTreeSet<u32>,
) -> Result<(), String> {
if defs.contains_key(&id) {
return Err(format!(
"recursive type id {id} is reused by a plain struct or payload enum"
));
}
plain.insert(id);
Ok(())
}
/// Record every nominal [`StructLayout::id`] embedded in this type.
pub fn collect_struct_ids(&self, out: &mut BTreeSet<u32>) {
self.for_each_nested(&mut |ty| {
if let Self::Struct(sty) = ty
&& !sty.is_synthetic()
{
out.insert(sty.layout().id());
}
});
}
/// Collect every synthetic (non-local) struct embedded in this type.
pub fn collect_synthetic_structs(&self, out: &mut Vec<StructTy>) {
self.for_each_nested(&mut |ty| {
if let Self::Struct(sty) = ty
&& sty.is_synthetic()
{
out.push(sty.clone());
}
});
}
/// Visit this type and every type nested inside it, in pre-order.
fn for_each_nested(&self, f: &mut dyn FnMut(&Ty)) {
f(self);
match self {
Self::Tuple { fields } => {
for field in fields {
field.for_each_nested(f);
}
}
Self::Struct(sty) => {
for field in sty.fields() {
field.for_each_nested(f);
}
}
// A variant's payload struct is not a nominal struct, so only its
// fields are visited.
Self::AdtEnum(aty) => {
for variant in aty.variants() {
if let Self::Struct(sty) = variant {
for field in sty.fields() {
field.for_each_nested(f);
}
}
}
}
Self::Ref { pointee, .. }
| Self::RawPtr { pointee, .. }
| Self::Box { pointee } => {
pointee.for_each_nested(f);
}
Self::Slice { elem }
| Self::Array { elem, .. }
| Self::Vec { elem }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem }
| Self::Option { elem } => {
elem.for_each_nested(f);
}
Self::RecAdt { defn, .. } => {
defn.for_each_nested(f);
}
Self::RecSelf { .. } => {}
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Str
| Self::Int(_)
| Self::Enum(_)
| Self::OverflowPair(_) => {}
}
}
pub fn ast_nodes(&self) -> usize {
match self {
Self::Bool
| Self::Char
| Self::Ordering
| Self::Unit
| Self::Never
| Self::Str
| Self::Int(_) => 1,
Self::OverflowPair(_) => 3,
Self::Enum(ety) => 1 + ety.discriminants.len(),
Self::Tuple { fields } => 1 + fields.iter().map(Self::ast_nodes).sum::<usize>(),
Self::Ref { pointee, .. }
| Self::RawPtr { pointee, .. }
| Self::Box { pointee } => 1 + pointee.ast_nodes(),
Self::Slice { elem }
| Self::Array { elem, .. }
| Self::RangeTo { elem }
| Self::RangeFrom { elem }
| Self::Range { elem }
| Self::Option { elem }
| Self::Vec { elem } => 1 + elem.ast_nodes(),
Self::Struct(st) => {
1 + st.fields().len() + st.fields().iter().map(Self::ast_nodes).sum::<usize>()
}
Self::RecAdt { defn, .. } => 2 + defn.ast_nodes(),
Self::RecSelf { .. } => 2,
Self::AdtEnum(aty) => {
1 + aty.layout().discriminants().len()
+ aty.variants().iter().map(Self::ast_nodes).sum::<usize>()
}
}
}
}
/// Byte entry in immutable `.rodata` constant memory
/// (`Trusted.MirAst.RodataByte`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RodataByte {
Uninit,
Init { byte: u8 },
}
/// Constant literal payload matching `Trusted.MirAst.ConstLit` 1-to-1.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConstLit {
ZeroSized,
Scalar {
#[serde(serialize_with = "serialize_u128_decimal")]
bits: u128,
},
RodataBytes {
bytes: Vec<RodataByte>,
},
RodataRef {
bytes: Vec<RodataByte>,
align_log2: u32,
offset_bytes: usize,
slice_len: Option<usize>,
},
}
/// Validate that `with_retag` is admitted for destination type `dst_ty`.
///
/// `lean.rs` renders `Rvalue::Use` without its retag flag, so the flag may be
/// erased only when [`Ty::is_retag_noop`] holds for the destination type
/// (retagging `Use` on reference-bearing types uses [`Rvalue::UseRetag`]).
pub fn check_use_retag(dst_ty: &Ty, with_retag: bool) -> Result<(), String> {
admit_retag(dst_ty.is_retag_noop(), with_retag)
}
/// Refuse erasing a `WithRetag::Yes` that could change the assigned value.
fn admit_retag(retag_noop: bool, with_retag: bool) -> Result<(), String> {
if with_retag && !retag_noop {
return Err("retagging Use rvalues on reference-bearing types are unsupported".into());
}
Ok(())
}
/// Validate that an unprojected `PlaceMention` is an operational no-op for
/// `local_ty`.
///
/// `lean.rs` renders an unprojected [`Statement::PlaceMention`] as
/// `Trusted.MirAst.StatementKind.nop`, which is sound only when the place has
/// no projections (enforced in `extract.rs`) and its local type is `Sized`
/// (`local_to_place` neither loads memory nor checks liveness; unsized
/// [`Ty::Slice`] returns `false` from [`Ty::is_sized`]).
pub fn check_place_mention(local_ty: &Ty) -> Result<(), String> {
admit_place_mention(local_ty.is_sized())
}
/// Refuse rendering a `PlaceMention` of an unsized local as a no-op.
fn admit_place_mention(is_sized: bool) -> Result<(), String> {
if !is_sized {
return Err("PlaceMention on unsized locals is unsupported".into());
}
Ok(())
}
/// The byte size that `Trusted.MirSemantics.layoutOfTyV2` gives each type
/// [`niche_scalar_ranges`] walks through, or `None` for any other type (so the
/// walk refuses where the Lean one might not).
fn niche_walk_size(ty: &Ty) -> Option<usize> {
match ty {
Ty::Bool => Some(1),
Ty::Int(ity) => Some(ity.width.bits() as usize / 8),
Ty::Struct(sty) => Some(sty.layout().size()),
Ty::AdtEnum(aty) => Some(aty.layout().size()),
Ty::Vec { .. } => Some(24),
// A niche-free `Option<int>`: a tag as wide as the integer, then it.
Ty::Option { elem } => match &**elem {
Ty::Int(ity) => Some(2 * (ity.width.bits() as usize / 8)),
_ => None,
},
_ => None,
}
}
/// The values the `w` bytes at offset `off` of any valid value of `ty` can
/// hold, as closed ranges, mirroring
/// `Trusted.MirSemantics.nicheScalarRangesV2`: a `bool`'s byte, the tag of a
/// niche-free `Option<int>`, a `Vec`'s capacity word (at most `isize::MAX`,
/// at offset `0` in the model's word order, [`check_vec_layout`]), or those
/// of the struct field that contains the span. `None` otherwise.
fn niche_scalar_ranges(ty: &Ty, off: usize, w: usize) -> Option<Vec<(u128, u128)>> {
match ty {
Ty::Bool => (off == 0 && w == 1).then(|| vec![(0, 1)]),
Ty::Option { elem } if matches!(&**elem, Ty::Int(_)) => {
let tag = niche_walk_size(elem)?;
(off == 0 && w == tag).then(|| vec![(0, 1)])
}
Ty::Vec { .. } => (off == 0 && w == 8).then(|| vec![(0, (1u128 << 63) - 1)]),
Ty::Struct(sty) => {
for (&o, field) in sty.layout().field_offsets().iter().zip(sty.fields()) {
let size = niche_walk_size(field)?;
if o <= off && off + w <= o + size {
return niche_scalar_ranges(field, off - o, w);
}
if !(off + w <= o || o + size <= off) {
return None;
}
}
None
}
_ => None,
}
}
/// Whether every value in `ranges`, as the tag of the niche enum `layout`
/// with niche variants `first..=last` starting at tag `start`, decodes as
/// the untagged variant: outside the niche values and inside the tag's valid
/// range, both wrapping (`Trusted.MirSemantics.nicheRangesUntaggedV2`).
fn niche_ranges_untagged(
layout: &AdtEnumLayout,
first: u32,
last: u32,
start: u128,
ranges: &[(u128, u128)],
) -> bool {
let bits = layout.tag.width.bits();
if bits >= 128 || last < first {
return false;
}
let m = 1u128 << bits;
let (valid_start, valid_end) = layout.tag_valid_range();
let rel = |base: u128, x: u128| if base <= x { x - base } else { x + m - base };
ranges.iter().all(|&(lo, hi)| {
lo <= hi
&& hi < m
&& start < m
&& valid_start < m
&& valid_end < m
&& u128::from(last - first) < rel(start, lo)
&& rel(start, lo) + (hi - lo) < m
&& rel(valid_start, lo) + (hi - lo) <= rel(valid_start, valid_end)
})
}
/// Whether field `fi` of variant `vi` of the payload enum `aty`, of type
/// `field_ty`, may be borrowed mutably although the enum is niche-encoded,
/// mirroring `Trusted.MirSemantics.adtNicheFieldUntaggedV2`: `vi` is the
/// untagged variant, and the field either lies outside the tag or contains
/// all of it with every value a valid `field_ty` can leave there decoding as
/// that variant.
fn niche_field_untagged(aty: &AdtEnumTy, vi: usize, fi: usize, field_ty: &Ty) -> bool {
let layout = aty.layout();
let AdtTagEncoding::Niche {
untagged,
first,
last,
start,
} = layout.encoding
else {
return false;
};
if vi != untagged as usize {
return false;
}
let Some(payload) = aty.variant(vi) else {
return false;
};
let (Some(&off), Some(field)) =
(payload.layout().field_offsets().get(fi), payload.fields().get(fi))
else {
return false;
};
if field != field_ty {
return false;
}
let Some(size) = niche_walk_size(field_ty) else {
return false;
};
let (tag_off, tag_w) = layout.tag_span();
if size == 0 || tag_w == 0 || off + size <= tag_off || tag_off + tag_w <= off {
return true;
}
off <= tag_off
&& tag_off + tag_w <= off + size
&& niche_scalar_ranges(field_ty, tag_off - off, tag_w)
.is_some_and(|ranges| niche_ranges_untagged(layout, first, last, start, &ranges))
}
/// Check the self-recursive struct and payload enum types in `tys`, mirroring
/// `Trusted.MirSemantics.programRecTysAdmittedV2`: every type is well-formed
/// ([`Ty::rec_ty_wf`]), all binders with the same id have the same
/// definition, and no plain struct or payload enum reuses a binder's layout
/// id.
pub fn check_rec_tys<'a>(tys: impl IntoIterator<Item = &'a Ty>) -> Result<(), String> {
// Each binder is compared with the first one of its id and each distinct
// definition is walked once, so this is near-linear in the total size of
// `tys` with repeated definitions counted once; checking every binder
// occurrence separately does not finish on Starnix eBPF's verifier.
let mut defs = BTreeMap::new();
let mut plain = BTreeSet::new();
for ty in tys {
ty.walk_rec_admit(None, &mut defs, &mut plain)?;
}
Ok(())
}
/// Mirror `Trusted.MirSemantics.rodataAdtVariantDataOkV2`: return `true` when
/// `ty` is an owned payload enum (`Ty::AdtEnum` or `Ty::RecAdt` wrapping
/// `Ty::AdtEnum`) whose active variant decoded from provenance-free `bytes`
/// is heap-free owned data (zero heap handles and zero `RecSelf`, admitting
/// heap-free `Option` and nested payload-enum fields).
fn rodata_adt_variant_is_heap_free_owned(ty: &Ty, bytes: &[RodataByte]) -> bool {
if !ty.is_owned_data() {
return false;
}
let aty = match ty {
Ty::AdtEnum(aty) => aty,
Ty::RecAdt { defn, .. } => match &**defn {
Ty::AdtEnum(aty) => aty,
_ => return false,
},
_ => return false,
};
let layout = aty.layout();
if layout.size() == 0 || bytes.len() != layout.size() {
return false;
}
let variant_idx: Option<usize> = match layout.encoding() {
AdtTagEncoding::Single => usize::try_from(layout.tag_valid_range().0).ok(),
enc => {
let tag_size = (layout.tag().width.bits() / 8) as usize;
let end = match layout.tag_offset().checked_add(tag_size) {
Some(e) if e <= bytes.len() => e,
_ => return false,
};
let mut tag: u128 = 0;
for (idx, b) in bytes[layout.tag_offset()..end].iter().enumerate() {
let RodataByte::Init { byte } = b else {
return false;
};
tag |= (*byte as u128) << (idx * 8);
}
let (start_v, end_v) = layout.tag_valid_range();
let in_range = if start_v <= end_v {
tag >= start_v && tag <= end_v
} else {
tag >= start_v || tag <= end_v
};
match enc {
AdtTagEncoding::Niche { untagged, first, last, start } => {
let mask = layout.tag().width.mask();
let rel = tag.wrapping_sub(start) & mask;
let span = (last as u128).saturating_sub(first as u128);
if rel <= span {
let cand = (first as u128) + rel;
if cand == untagged as u128 {
None
} else {
usize::try_from(cand).ok()
}
} else if in_range {
Some(untagged as usize)
} else {
None
}
}
AdtTagEncoding::Direct => {
if !in_range {
None
} else {
let discr =
tag_bits_to_discr_bits(layout.tag(), layout.discr().width, tag);
layout.discriminants().iter().position(|&d| d == discr)
}
}
AdtTagEncoding::Single => unreachable!(),
}
}
};
variant_idx
.and_then(|idx| aty.variant(idx))
.is_some_and(|sty| {
sty.fields()
.iter()
.all(|f| f.is_owned_data() && !f.has_heap_handle_v2())
})
}
/// Validate a typed constant literal against `evalConstLit` / Profile v2
/// `.rodata` invariants.
pub fn validate_constant(ty: &Ty, lit: &ConstLit) -> Result<(), String> {
match (ty, lit) {
(Ty::Unit, ConstLit::ZeroSized) => Ok(()),
(Ty::Unit, ConstLit::Scalar { .. } | ConstLit::RodataBytes { .. } | ConstLit::RodataRef { .. }) => {
Err("zero-sized constant must use ZeroSized literal".into())
}
(Ty::Never, ConstLit::ZeroSized) => {
Err("ZeroSized constant requires unit or zero-sized enum type".into())
}
(Ty::Never, _) => Err("the never type has no constants".into()),
(Ty::OverflowPair(_), _) => Err("overflow-pair tuple constants are unsupported".into()),
(Ty::Bool, ConstLit::Scalar { bits }) => {
// `Scalar::to_bool` maps `0` and `1` to `false` and `true` and
// raises `InvalidBool` for every other byte.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/interpret/value.rs#L344-L351
if *bits <= 1 {
Ok(())
} else {
Err("invalid Boolean constant".into())
}
}
(Ty::Bool, _) => Err("boolean constant must use Scalar literal".into()),
(Ty::Char, ConstLit::Scalar { bits }) => {
if is_unicode_scalar(*bits) {
Ok(())
} else {
Err(format!(
"invalid char constant {bits:#x}: outside Unicode scalar range"
))
}
}
(Ty::Char, _) => Err("char constant must use Scalar literal".into()),
(Ty::Ordering, ConstLit::Scalar { bits }) => {
// `core::cmp::Ordering` is `#[repr(i8)]` whose "three variants
// `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8`
// respectively" (`0xff`, `0`, `1` as 8-bit unsigned tags).
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/cmp.rs#L400-L415
if matches!(*bits, 0 | 1 | 0xff) {
Ok(())
} else {
Err(format!("invalid Ordering tag constant {bits:#x}"))
}
}
(Ty::Ordering, _) => Err("Ordering constant must use Scalar literal".into()),
(Ty::Int(ity), ConstLit::Scalar { bits }) => {
if *bits > ity.width.mask() {
return Err(format!(
"scalar constant {bits:#x} exceeds {}-bit width",
ity.width.bits()
));
}
Ok(())
}
(Ty::Int(_), _) => Err("integer constant must use Scalar literal".into()),
// A zero-sized struct value is the compiler's `ZeroSized` constant
// ("Only for ZSTs."), and every other struct constant is a by-value
// byte image of its full layout size, padding included.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/consts.rs#L38-L39
(Ty::Struct(sty), ConstLit::ZeroSized) => {
if sty.layout().size() == 0 {
Ok(())
} else {
Err("ZeroSized constant requires a zero-sized struct type".into())
}
}
// A struct owning a `Vec`/`Box` buffer would decode `rustc`'s byte
// image under the model-internal handle encoding, so its constants
// are refused (`Trusted.MirSemantics.evalOperandToSlotV2`).
(Ty::Struct(_), ConstLit::RodataBytes { .. }) if !ty.is_supported_v2_data() => {
Err("constant of a struct owning a heap buffer is unsupported".into())
}
(Ty::Struct(sty), ConstLit::RodataBytes { bytes }) => {
let size = sty.layout().size();
if size == 0 {
return Err("zero-sized struct constant must use ZeroSized literal".into());
}
if bytes.len() != size {
return Err(format!(
"struct constant byte length {} disagrees with layout size {size}",
bytes.len()
));
}
Ok(())
}
(Ty::Struct(_), _) => {
Err("struct constant must use ZeroSized or RodataBytes literal".into())
}
// A zero-sized payload enum constant uses `ZeroSized`; every other
// payload enum constant is its provenance-free byte image, decoded at
// its type (`Trusted.MirSemantics.evalOperandToSlotV2`). A heap-owning
// payload enum or recursive payload enum (`RecAdt(AdtEnum)`) is
// admitted only when its active variant carries no heap handles or
// `RecSelf` (`rodata_adt_variant_is_heap_free_owned`).
(Ty::AdtEnum(aty), ConstLit::ZeroSized) => {
if ty.has_heap_handle_v2() {
return Err("constant of a payload enum owning a heap buffer is unsupported".into());
}
if aty.layout().size() == 0 {
Ok(())
} else {
Err("ZeroSized constant requires a zero-sized payload enum type".into())
}
}
(Ty::AdtEnum(aty), ConstLit::RodataBytes { bytes }) => {
let size = aty.layout().size();
if size == 0 {
return Err(
"zero-sized payload enum constant must use ZeroSized literal".into(),
);
}
if bytes.len() != size {
return Err(format!(
"payload enum constant byte length {} disagrees with layout size {size}",
bytes.len()
));
}
if !rodata_adt_variant_is_heap_free_owned(ty, bytes) {
return Err(
"payload enum constant must select a heap-free owned variant".into(),
);
}
Ok(())
}
(Ty::AdtEnum(_), _) => {
Err("payload enum constant must use ZeroSized or RodataBytes literal".into())
}
(Ty::RecAdt { defn, .. }, ConstLit::RodataBytes { bytes })
if matches!(&**defn, Ty::AdtEnum(_)) =>
{
if !rodata_adt_variant_is_heap_free_owned(ty, bytes) {
return Err(
"recursive payload enum constant must select a heap-free variant".into(),
);
}
Ok(())
}
(Ty::RecAdt { .. } | Ty::RecSelf { .. }, _) => {
Err("recursive struct constants are unsupported".into())
}
(Ty::Array { elem, .. }, ConstLit::RodataBytes { bytes }) => {
if !elem.is_supported_v2_data() {
return Err(format!(
"unsupported element type {elem:?} in array constant"
));
}
let Some((expected_size, _)) = ty.v2_layout() else {
return Err(format!("array constant type {ty:?} lacks layout"));
};
if bytes.len() != expected_size {
return Err(format!(
"array constant byte length {} disagrees with layout size {expected_size}",
bytes.len()
));
}
Ok(())
}
(
Ty::Ref {
mutability: Mutability::Shared,
pointee,
}
| Ty::RawPtr {
mutability: Mutability::Shared,
pointee,
},
ConstLit::RodataRef {
bytes,
align_log2,
offset_bytes,
slice_len,
},
) => match (&**pointee, slice_len) {
(Ty::Slice { elem }, Some(len)) if matches!(&**elem, Ty::Int(_)) => {
let Some((elem_size, elem_align_log2)) = elem.v2_layout() else {
return Err(format!("slice element type {elem:?} lacks layout"));
};
let slice_bytes = len
.checked_mul(elem_size)
.ok_or_else(|| "rodata slice byte size overflow".to_string())?;
let end = offset_bytes
.checked_add(slice_bytes)
.ok_or_else(|| "rodata slice offset overflow".to_string())?;
if end > bytes.len() {
return Err(format!(
"rodata slice range [{offset_bytes}..{end}) exceeds rodata size {}",
bytes.len()
));
}
let align_bytes = 1usize.checked_shl(elem_align_log2).unwrap_or(usize::MAX);
if *align_log2 < elem_align_log2 || *offset_bytes % align_bytes != 0 {
return Err("rodata slice reference is misaligned".into());
}
Ok(())
}
(Ty::Str, Some(len))
if matches!(
ty,
Ty::Ref {
mutability: Mutability::Shared,
..
}
) =>
{
let max_bytes = 1usize << 63;
if bytes.len() >= max_bytes || *align_log2 > 29 || *len >= max_bytes {
return Err(
"rodata str allocation or length exceeds size or alignment limit".into(),
);
}
let end = offset_bytes
.checked_add(*len)
.ok_or_else(|| "rodata str offset overflow".to_string())?;
if end > bytes.len() {
return Err(format!(
"rodata str range [{offset_bytes}..{end}) exceeds rodata size {}",
bytes.len()
));
}
let mut raw_bytes = Vec::with_capacity(*len);
for byte in &bytes[*offset_bytes..end] {
match byte {
RodataByte::Init { byte } => raw_bytes.push(*byte),
RodataByte::Uninit => {
return Err("uninitialized byte in rodata &str constant".into());
}
}
}
std::str::from_utf8(&raw_bytes)
.map_err(|_| "non-UTF-8 rodata &str constant is unsupported".to_string())?;
Ok(())
}
(pt, None) => {
let Some((pt_size, pt_align_log2)) = pt.v2_layout() else {
return Err(format!("rodata pointee type {pt:?} lacks layout"));
};
let end = offset_bytes
.checked_add(pt_size)
.ok_or_else(|| "rodata pointer offset overflow".to_string())?;
if end > bytes.len() {
return Err(format!(
"rodata pointer range [{offset_bytes}..{end}) exceeds rodata size {}",
bytes.len()
));
}
let is_ref = matches!(ty, Ty::Ref { .. });
let ok_adt = is_ref
&& rodata_adt_variant_is_heap_free_owned(pt, &bytes[*offset_bytes..end]);
if !pt.is_supported_v2_data() && !ok_adt {
return Err(format!(
"unsupported rodata reference pointee {pointee:?} \
/ slice_len {slice_len:?}"
));
}
let align_bytes = 1usize.checked_shl(pt_align_log2).unwrap_or(usize::MAX);
if *align_log2 < pt_align_log2 || *offset_bytes % align_bytes != 0 {
return Err("rodata pointer is misaligned".into());
}
Ok(())
}
_ => Err(format!(
"unsupported rodata reference pointee {pointee:?} / slice_len {slice_len:?}"
)),
},
(
Ty::Array { .. }
| Ty::Tuple { .. }
| Ty::Ref { .. }
| Ty::RawPtr { .. }
| Ty::Slice { .. }
| Ty::Str
| Ty::Vec { .. }
| Ty::Box { .. }
| Ty::RangeTo { .. }
| Ty::RangeFrom { .. }
| Ty::Range { .. }
| Ty::Option { .. },
_,
) => Err(format!("constants of compound/pointer type {ty:?} are unsupported")),
(Ty::Enum(ety), lit) => match (ety.tag_repr, lit) {
(EnumTagRepr::ZeroSized, ConstLit::ZeroSized) => Ok(()),
(EnumTagRepr::ZeroSized, _) => {
Err("zero-sized constant must use ZeroSized literal".into())
}
(EnumTagRepr::Scalar(_), ConstLit::ZeroSized) => {
Err("ZeroSized constant requires unit or zero-sized enum type".into())
}
(EnumTagRepr::Scalar(tag), ConstLit::Scalar { bits }) => {
if *bits > tag.width.mask() {
return Err(format!(
"enum tag constant {bits:#x} exceeds {}-bit tag width",
tag.width.bits()
));
}
let discr = tag_bits_to_discr_bits(tag, ety.discr().width, *bits);
if !ety.discriminants.contains(&discr) {
return Err(format!(
"enum tag constant {bits:#x} does not match any declared variant"
));
}
Ok(())
}
(EnumTagRepr::Scalar(_), _) => Err("scalar enum constant must use Scalar literal".into()),
},
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PlaceElem {
Deref,
Field {
index: usize,
ty: Ty,
},
ConstantIndex {
offset: usize,
min_length: usize,
from_end: bool,
},
Downcast { variant_idx: usize },
Index {
local: u32,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Place {
pub local: u32,
pub projection: Vec<PlaceElem>,
}
impl Place {
fn for_each_ty(&self, f: &mut dyn FnMut(&Ty)) {
for elem in &self.projection {
if let PlaceElem::Field { ty, .. } = elem {
f(ty);
}
}
}
fn ast_nodes(&self) -> usize {
1 + self
.projection
.iter()
.map(|elem| match elem {
PlaceElem::Deref
| PlaceElem::ConstantIndex { .. }
| PlaceElem::Downcast { .. }
| PlaceElem::Index { .. } => 1,
PlaceElem::Field { ty, .. } => 1 + ty.ast_nodes(),
})
.sum::<usize>()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Operand {
Copy { local: u32 },
Move { local: u32 },
CopyPlace { place: Place },
MovePlace { place: Place },
Constant { ty: Ty, lit: ConstLit },
}
impl Operand {
fn for_each_ty(&self, f: &mut dyn FnMut(&Ty)) {
match self {
Self::Copy { .. } | Self::Move { .. } => {}
Self::CopyPlace { place } | Self::MovePlace { place } => place.for_each_ty(f),
Self::Constant { ty, .. } => f(ty),
}
}
pub fn is_profile_v2(&self) -> bool {
match self {
Self::CopyPlace { .. } | Self::MovePlace { .. } => true,
Self::Copy { .. } | Self::Move { .. } => false,
Self::Constant { ty, lit } => {
ty.is_profile_v2() || !matches!(lit, ConstLit::ZeroSized | ConstLit::Scalar { .. })
}
}
}
fn ast_nodes(&self) -> usize {
match self {
Self::Copy { .. } | Self::Move { .. } => 1,
Self::CopyPlace { place } | Self::MovePlace { place } => 1 + place.ast_nodes(),
Self::Constant { ty, .. } => 1 + ty.ast_nodes(),
}
}
}
/// Admitted MIR unary operators (`rustc_middle::mir::UnOp`): "The `!`
/// operator for logical inversion", "The `-` operator for negation", and
/// `PtrMetadata`, which "Gets the metadata `M` from a
/// `*const`/`*mut`/`&`/`&mut` to `impl Pointee<Metadata = M>`" ("a `()`
/// from `*const i32`, a `usize` from `&mut [u8]`"), matching
/// `Trusted.MirAst.UnOp`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1603-L1617
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UnOp {
Not,
Neg,
PtrMetadata,
}
/// Admitted MIR cast kinds (`rustc_middle::mir::CastKind::{IntToInt,
/// PtrToPtr}` and `PointerWithExposedProvenance`, "An address-to-pointer cast
/// that picks up an exposed provenance", as `IntToPtr`), matching
/// `Trusted.MirAst.CastKind`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1491-L1532
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CastKind {
IntToInt,
PtrToPtr,
IntToPtr,
Unsize,
/// The `*const P` that `ElaborateBoxDerefs` builds for a `*b` dereference
/// (`extract::try_peel_box_raw_ptr_transmute`). Internal to capture:
/// `extract::promote_box_as_ref` rewrites the admitted uses to `BoxAsRef`,
/// and `check_cast_types` refuses any that remain, because a body with a
/// `Box` and a raw-pointer local mixes references and raw pointers. It is
/// never rendered to Lean.
// RUSTC-WORKAROUND(#4367): exists only for rustc 1.98's `Box` deref
// lowering.
BoxAsRawPtr,
BoxAsRef,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BinOp {
BitAnd,
BitOr,
BitXor,
Shl,
Shr,
Add,
Sub,
Mul,
AddUnchecked,
SubUnchecked,
MulUnchecked,
Div,
Rem,
AddWithOverflow,
SubWithOverflow,
MulWithOverflow,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
Cmp,
Offset,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Rvalue {
Use {
operand: Operand,
with_retag: bool,
},
UseRetag {
operand: Operand,
},
Binary {
op: BinOp,
left: Operand,
right: Operand,
},
Unary {
op: UnOp,
operand: Operand,
},
Cast {
cast_kind: CastKind,
operand: Operand,
ty: Ty,
},
Discriminant {
place: Place,
},
Ref {
mutability: Mutability,
place: Place,
},
AddressOf {
mutability: Mutability,
place: Place,
},
FakeAddressOf {
place: Place,
},
AggregateTuple {
fields: Vec<Operand>,
},
AggregateArray {
elem_ty: Ty,
elems: Vec<Operand>,
},
AggregateStruct {
ty: Ty,
fields: Vec<Operand>,
},
Repeat {
operand: Operand,
elem_ty: Ty,
count: usize,
},
AggregateRangeTo {
elem_ty: Ty,
end: Operand,
},
AggregateRangeFrom {
elem_ty: Ty,
start: Operand,
},
AggregateRange {
elem_ty: Ty,
start: Operand,
end: Operand,
},
AggregateOption {
variant_idx: usize,
inner_ty: Ty,
payload: Option<Box<Operand>>,
},
AggregateOrdering {
tag_bits: u8,
},
/// Variant `variant_idx` of the payload enum `ty`
/// (`Trusted.MirAst.Rvalue.aggregateAdtEnum`), with its fields in
/// `FieldIdx` order, or of the fieldless enum `ty` (`Ty::Enum`), with no
/// fields.
AggregateAdtEnum {
ty: Ty,
variant_idx: usize,
fields: Vec<Operand>,
},
}
impl Rvalue {
fn ast_nodes(&self) -> usize {
match self {
Self::Use { operand, .. }
| Self::UseRetag { operand }
| Self::Unary { operand, .. } => 1 + operand.ast_nodes(),
Self::Binary { left, right, .. } => 1 + left.ast_nodes() + right.ast_nodes(),
Self::Cast { operand, ty, .. } => 1 + operand.ast_nodes() + ty.ast_nodes(),
Self::Discriminant { place } => 1 + place.ast_nodes(),
Self::Ref { place, .. }
| Self::AddressOf { place, .. }
| Self::FakeAddressOf { place } => 1 + place.ast_nodes(),
Self::AggregateTuple { fields } => {
1 + fields.iter().map(Operand::ast_nodes).sum::<usize>()
}
Self::AggregateArray { elem_ty, elems } => {
1 + elem_ty.ast_nodes() + elems.iter().map(Operand::ast_nodes).sum::<usize>()
}
Self::Repeat { elem_ty, operand, .. } => 1 + elem_ty.ast_nodes() + operand.ast_nodes(),
Self::AggregateRangeTo { elem_ty, end } => 1 + elem_ty.ast_nodes() + end.ast_nodes(),
Self::AggregateRangeFrom { elem_ty, start } => {
1 + elem_ty.ast_nodes() + start.ast_nodes()
}
Self::AggregateRange { elem_ty, start, end } => {
1 + elem_ty.ast_nodes() + start.ast_nodes() + end.ast_nodes()
}
Self::AggregateOrdering { .. } => 1,
Self::AggregateStruct { ty, fields } => {
1 + ty.ast_nodes() + fields.iter().map(Operand::ast_nodes).sum::<usize>()
}
Self::AggregateOption { inner_ty, payload, .. } => {
1 + inner_ty.ast_nodes() + payload.as_ref().map_or(0, |op| op.ast_nodes())
}
Self::AggregateAdtEnum { ty, fields, .. } => {
1 + ty.ast_nodes() + fields.iter().map(Operand::ast_nodes).sum::<usize>()
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Statement {
Assign { local: u32, value: Rvalue },
AssignPlace { place: Place, value: Rvalue },
StorageLive { local: u32 },
StorageDead { local: u32 },
PlaceMention { local: u32 },
/// A `PlaceMention` of a place with at least one projection
/// (`Trusted.MirAst.StatementKind.placeMention`), such as the
/// `PlaceMention((*_2).3)` that `let _ = (*p).f;` or `match (*p).f { .. }`
/// emits. Computing the place reads every dereferenced pointer and
/// index local and must stay in bounds, so it is not a no-op;
/// `Trusted.MirSemantics.evalStatementV2` evaluates it as a non-moving
/// read and discards the value. [`Body::try_new`] checks the place as a
/// read operand.
PlaceMentionPlace { place: Place },
Nop,
}
impl Statement {
fn ast_nodes(&self) -> usize {
match self {
Self::Assign { value, .. } => 1 + value.ast_nodes(),
Self::AssignPlace { place, value } => 1 + place.ast_nodes() + value.ast_nodes(),
Self::PlaceMentionPlace { place } => 1 + place.ast_nodes(),
Self::StorageLive { .. }
| Self::StorageDead { .. }
| Self::PlaceMention { .. }
| Self::Nop => 1,
}
}
}
/// Compilation crate type explicitly authorized for capture.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CrateType {
#[default]
Lib,
Bin,
}
impl CrateType {
pub const fn as_str(self) -> &'static str {
match self {
Self::Lib => "lib",
Self::Bin => "bin",
}
}
}
/// Panic unwinding strategy explicitly configured for capture.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PanicStrategy {
#[default]
Unwind,
Abort,
}
impl PanicStrategy {
pub const fn as_str(self) -> &'static str {
match self {
Self::Unwind => "unwind",
Self::Abort => "abort",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AssertKind {
Overflow { op: BinOp },
OverflowNeg,
DivByZero,
RemByZero,
BoundsCheck,
MisalignedPtrDeref,
NullPtrDeref,
}
/// Reason a MIR `UnwindAction::Terminate` edge aborts execution, matching
/// `rustc_middle::mir::UnwindTerminateReason` in
/// `compiler/rustc_middle/src/mir/syntax.rs` (`rust-lang/rust` commit
/// `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UnwindTerminateReason {
Abi,
InCleanup,
}
/// Unwind action of a captured `Assert` or returning call, matching the
/// non-cleanup constructors of `Trusted.MirAst.UnwindAction` 1:1 while
/// preserving rustc's `UnwindTerminateReason` in the capture IR/JSON.
///
/// Upstream `UnwindAction::Continue` is "No action is to be taken. Continue
/// unwinding.", `Unreachable` "Triggers undefined behavior if unwind
/// happens.", and `Terminate(UnwindTerminateReason)` "Terminates the
/// execution if unwind happens." `Cleanup(BasicBlock)` is refused at capture
/// time and has no variant here.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1027-L1055
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnwindAction {
Continue,
Unreachable,
Terminate { reason: UnwindTerminateReason },
}
impl Serialize for UnwindAction {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
match self {
Self::Continue => serializer.serialize_str("continue"),
Self::Unreachable => serializer.serialize_str("unreachable"),
Self::Terminate { reason } => {
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("kind", "terminate")?;
map.serialize_entry("reason", reason)?;
map.end()
}
}
}
}
impl UnwindAction {
/// The `Trusted.MirAst.UnwindAction` constructor name.
pub const fn lean_name(self) -> &'static str {
match self {
Self::Continue => "continue_",
Self::Unreachable => "unreachable",
Self::Terminate { .. } => "terminate",
}
}
}
/// Function calling-convention ABI tag matching `Trusted.MirAst.AbiKind`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AbiKind {
#[default]
Rust,
C {
unwind: bool,
},
System {
unwind: bool,
},
}
impl AbiKind {
pub const fn is_rust(&self) -> bool {
matches!(self, Self::Rust)
}
pub const fn lean_expr(self) -> &'static str {
match self {
Self::Rust => "Trusted.MirAst.AbiKind.rust",
Self::C { unwind: false } => "(Trusted.MirAst.AbiKind.c false)",
Self::C { unwind: true } => "(Trusted.MirAst.AbiKind.c true)",
Self::System { unwind: false } => "(Trusted.MirAst.AbiKind.system false)",
Self::System { unwind: true } => "(Trusted.MirAst.AbiKind.system true)",
}
}
}
/// The closed table of sysroot `core` calls that Profile v2 executes,
/// matching `Trusted.MirAst.CoreCallOp` 1:1. `extract::core_call_op` maps
/// returning entries and `extract::terminator` maps diverging
/// [`Self::PanicAbort`] from pinned `library/core` definitions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CoreCallOp {
SliceLen,
SliceGetUncheckedRangeTo,
SliceGetUncheckedRangeFrom,
SliceGetUncheckedRange,
SliceGetUncheckedIndex,
SliceIndexRange {
mutability: Mutability,
elem: Ty,
},
SliceIndexRangeFrom {
mutability: Mutability,
elem: Ty,
},
SliceIsEmpty {
elem: Ty,
},
SliceSplitAt {
mutability: Mutability,
elem: Ty,
},
NumIsMultipleOf(IntTy),
NumNextMultipleOf(IntTy),
NumDivCeil(IntTy),
NumCheckedAdd(IntTy),
NumCheckedMul(IntTy),
NumCheckedSub(IntTy),
NumCheckedShl(IntTy),
NumSaturatingAdd(IntTy),
NumWrappingShl(IntTy),
NumWrappingShr(IntTy),
NumLeadingZeros(IntTy),
NumCountOnes(IntTy),
NumTrailingZeros(IntTy),
NumNextPowerOfTwo(IntTy),
NumOverflowingAdd(IntTy),
NumOverflowingSub(IntTy),
NumOverflowingMul(IntTy),
CmpMin(IntTy),
CmpMax(IntTy),
MemReplace {
ty: Ty,
},
MemSizeOf {
ty: Ty,
},
OptionIsSome {
inner: Ty,
},
OptionIsNone {
inner: Ty,
},
OptionTake {
inner: Ty,
},
OptionUnwrap {
inner: Ty,
},
/// `<Result<ok, err> as Try>::branch`.
TryBranchResult {
ok: Ty,
err: Ty,
},
/// `<Option<inner> as Try>::branch`.
TryBranchOption {
inner: Ty,
},
/// `FromResidual<Result<Infallible, err>>::from_residual` for
/// `Result<ok, err>` (the identity `From` on `err`).
FromResidualResult {
ok: Ty,
err: Ty,
},
/// `<Option<inner> as FromResidual<Option<Infallible>>>::from_residual`.
FromResidualOption {
inner: Ty,
},
DefaultVal {
ty: Ty,
},
RefIntPartialEq {
int_ty: IntTy,
is_ne: bool,
},
UnitPartialEq {
is_ne: bool,
},
/// `<T as core::clone::Clone>::clone(&self) -> Self` for primitive `Copy`
/// scalars (`bool`, `char`, and integer widths).
ScalarClone {
ty: Ty,
},
PtrAdd {
mutability: Mutability,
pointee: Ty,
},
UsizeUncheckedSub,
IntToLeBytes { int_ty: IntTy },
IntFromLeBytes { int_ty: IntTy },
ArrayEq { elem: Ty, len: usize },
VecNew { elem: Ty },
VecWithCapacity { elem: Ty },
VecLen,
VecPush,
VecResize,
VecExtendFromSlice,
VecIndex,
VecIndexMut,
VecDeref,
VecDerefMut,
VecReserve,
BoxFromVec,
BoxDeref,
BoxDerefMut,
BoxClone,
BoxNew {
pointee: Ty,
},
PanicAbort,
PartialEqNe {
ty: Ty,
},
}
/// A `core::num` arithmetic method that Profile v1 calls through its pinned
/// sysroot body (`Trusted.MirAst.SysrootNumKind`). Profile v2 instead models
/// its `core` calls atomically through [`CoreCallOp`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SysrootNumKind {
UncheckedAdd,
UncheckedSub,
UncheckedMul,
WrappingAdd,
WrappingSub,
WrappingMul,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct SysrootNumOp {
pub kind: SysrootNumKind,
pub ty: IntTy,
}
/// How a [`Terminator::CallVia`] reaches its captured callee
/// (`Trusted.MirAst.CallVia`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallVia {
/// `<&A as PartialEq<&B>>::{eq, ne}`, calling `A::eq` (or an overriding
/// `A::ne`) with the two dereferenced arguments; `negate` negates the
/// result for the provided `ne`.
RefPartialEq { negate: bool },
/// `<Box<T> as Clone>::clone` for a crate-local `T = pointee` that is not
/// `TrivialClone`, calling `T::clone` with `&**self` between allocating
/// the box and writing the result into it.
BoxClone { pointee: Ty },
/// `PartialOrd`'s provided `lt` (`greater = false`, `or_equal = false`),
/// `le` (`false`, `true`), `gt` (`true`, `false`), or `ge` (`true`, `true`)
/// for `Self = Rhs = A` with a crate-local `A`, calling `A::partial_cmp`
/// with the two arguments unchanged and mapping its `Option<Ordering>` to
/// a `bool`.
PartialOrd { greater: bool, or_equal: bool },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Terminator {
Goto {
block: u32,
},
SwitchInt {
operand: Operand,
#[serde(serialize_with = "serialize_switch_targets_decimal")]
targets: Vec<(u128, u32)>,
otherwise: u32,
},
Assert {
cond: Operand,
expected: bool,
msg: AssertKind,
target: u32,
unwind: UnwindAction,
},
CoreCall {
op: CoreCallOp,
args: Vec<Operand>,
dst: Place,
target: Option<u32>,
unwind: UnwindAction,
},
Call {
callee: usize,
args: Vec<Operand>,
dst: u32,
target: Option<u32>,
unwind: UnwindAction,
},
SysrootCall {
op: SysrootNumOp,
args: Vec<Operand>,
dst: u32,
target: Option<u32>,
unwind: UnwindAction,
},
/// Call to `core::cmp::PartialEq::ne`'s default body on a crate-local
/// type whose `PartialEq` impl does not override `ne`, executed as a call
/// to that impl's `eq` (`Program::bodies[eq_callee]`) whose result is
/// negated. Like [`Terminator::Call`], it is resolved from a crate-local
/// callee when the program is assembled.
CallNe {
eq_callee: usize,
args: Vec<Operand>,
dst: u32,
target: Option<u32>,
unwind: UnwindAction,
},
/// Call of the sysroot function that `via` names, executed as the call
/// of `Program::bodies[callee]` that its body makes. Like
/// [`Terminator::Call`], it is resolved from a crate-local callee when the
/// program is assembled.
CallVia {
via: CallVia,
callee: usize,
args: Vec<Operand>,
dst: u32,
target: Option<u32>,
unwind: UnwindAction,
},
/// `Drop` of an unprojected local or `*r` dereference (`r: &mut Vec<T>` or
/// `&mut Box<P>`) whose drop glue is admitted in Profile v2.
Drop {
place: Place,
target: u32,
unwind: UnwindAction,
},
Ret,
Unreachable,
Unsupported,
}
/// Pairwise local-disjointness of `.move` call operands and `dst`, matching
/// `Trusted.MirSemantics.moveDefinitelyDisjoint`.
fn check_move_disjoint(args: &[Operand], dst: u32) -> Result<(), String> {
let mut seen = BTreeSet::new();
for arg in args {
match arg {
Operand::Move { local } if !seen.insert(*local) => {
return Err(format!("duplicate Move operand local _{local} in call"));
}
Operand::CopyPlace { .. } | Operand::MovePlace { .. } => {
return Err("call operands must be unprojected locals or constants".into());
}
_ => {}
}
}
if !seen.insert(dst) {
return Err(format!("call destination _{dst} aliases a Move operand"));
}
Ok(())
}
/// Check a [`Terminator::CallVia`] against its resolved callee, mirroring
/// the static checks of `Trusted.MirSemantics.evalCallViaV2`.
fn check_call_via_callee(
local_tys: &[Ty],
via: &CallVia,
args: &[Operand],
dst: u32,
callee_body: &Body,
) -> Result<(), String> {
let arg_ty = |op: &Operand| match op {
Operand::Copy { local } | Operand::Move { local } => {
local_tys.get(*local as usize).cloned()
}
Operand::Constant { ty, .. } => Some(ty.clone()),
Operand::CopyPlace { .. } | Operand::MovePlace { .. } => None,
};
let params = callee_body.local_tys.iter().skip(1).take(callee_body.arg_count);
match via {
// `A::eq(&A, &A) -> bool` (or an overriding `A::ne`), called with the
// `&A`s that the two `&&A` arguments point to.
CallVia::RefPartialEq { .. } => {
let derefed: Vec<Option<Ty>> = args
.iter()
.map(|op| match arg_ty(op) {
Some(Ty::Ref {
mutability: Mutability::Shared,
pointee,
}) => Some(*pointee),
_ => None,
})
.collect();
let params: Vec<Option<Ty>> = params.cloned().map(Some).collect();
if derefed != params
|| callee_body.local_tys[0] != Ty::Bool
|| local_tys.get(dst as usize) != Some(&Ty::Bool)
{
return Err(format!(
"reference PartialEq call of {} with {derefed:?} disagrees with its \
signature",
callee_body.identity
));
}
}
// `A::partial_cmp(&A, &A) -> Option<Ordering>`, called with the two
// `&A` arguments unchanged.
CallVia::PartialOrd { .. } => {
let arg_tys: Vec<Option<Ty>> = args.iter().map(arg_ty).collect();
let params: Vec<Option<Ty>> = params.cloned().map(Some).collect();
if arg_tys != params
|| callee_body.local_tys[0].adt_option_payload() != Some(&Ty::Ordering)
|| local_tys.get(dst as usize) != Some(&Ty::Bool)
{
return Err(format!(
"PartialOrd comparison call of {} with {arg_tys:?} disagrees with its \
signature",
callee_body.identity
));
}
}
// `T::clone(&T) -> T`, called with `&**self`.
CallVia::BoxClone { pointee } => {
let param = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(pointee.clone()),
};
let params: Vec<&Ty> = params.collect();
if params != [&param] || callee_body.local_tys[0] != *pointee {
return Err(format!(
"Box::clone call of {} disagrees with its signature",
callee_body.identity
));
}
}
}
Ok(())
}
impl Terminator {
fn ast_nodes(&self) -> usize {
match self {
Self::Goto { .. } | Self::Ret | Self::Unreachable | Self::Unsupported => 1,
Self::SwitchInt { operand, targets, .. } => 2 + operand.ast_nodes() + targets.len(),
Self::Assert { cond, .. } => 2 + cond.ast_nodes(),
Self::CoreCall { op, args, dst, .. } => {
let op_nodes = match op {
CoreCallOp::PtrAdd { pointee, .. }
| CoreCallOp::BoxNew { pointee } => 1 + pointee.ast_nodes(),
CoreCallOp::SliceIndexRange { elem, .. }
| CoreCallOp::SliceIndexRangeFrom { elem, .. }
| CoreCallOp::SliceIsEmpty { elem }
| CoreCallOp::SliceSplitAt { elem, .. }
| CoreCallOp::ArrayEq { elem, .. }
| CoreCallOp::VecNew { elem }
| CoreCallOp::VecWithCapacity { elem } => 1 + elem.ast_nodes(),
CoreCallOp::MemReplace { ty }
| CoreCallOp::MemSizeOf { ty }
| CoreCallOp::PartialEqNe { ty }
| CoreCallOp::DefaultVal { ty }
| CoreCallOp::ScalarClone { ty } => 1 + ty.ast_nodes(),
CoreCallOp::OptionIsSome { inner }
| CoreCallOp::OptionIsNone { inner }
| CoreCallOp::OptionTake { inner }
| CoreCallOp::OptionUnwrap { inner }
| CoreCallOp::TryBranchOption { inner }
| CoreCallOp::FromResidualOption { inner } => 1 + inner.ast_nodes(),
CoreCallOp::TryBranchResult { ok, err }
| CoreCallOp::FromResidualResult { ok, err } => {
1 + ok.ast_nodes() + err.ast_nodes()
}
CoreCallOp::SliceLen
| CoreCallOp::SliceGetUncheckedRangeTo
| CoreCallOp::SliceGetUncheckedRangeFrom
| CoreCallOp::SliceGetUncheckedRange
| CoreCallOp::SliceGetUncheckedIndex
| CoreCallOp::NumIsMultipleOf(_)
| CoreCallOp::NumNextMultipleOf(_)
| CoreCallOp::NumDivCeil(_)
| CoreCallOp::NumCheckedAdd(_)
| CoreCallOp::NumCheckedMul(_)
| CoreCallOp::NumCheckedSub(_)
| CoreCallOp::NumCheckedShl(_)
| CoreCallOp::NumSaturatingAdd(_)
| CoreCallOp::NumWrappingShl(_)
| CoreCallOp::NumWrappingShr(_)
| CoreCallOp::NumLeadingZeros(_)
| CoreCallOp::NumCountOnes(_)
| CoreCallOp::NumTrailingZeros(_)
| CoreCallOp::NumNextPowerOfTwo(_)
| CoreCallOp::NumOverflowingAdd(_)
| CoreCallOp::NumOverflowingSub(_)
| CoreCallOp::NumOverflowingMul(_)
| CoreCallOp::CmpMin(_)
| CoreCallOp::CmpMax(_)
| CoreCallOp::UsizeUncheckedSub
| CoreCallOp::IntToLeBytes { .. }
| CoreCallOp::IntFromLeBytes { .. }
| CoreCallOp::PanicAbort
| CoreCallOp::VecLen
| CoreCallOp::VecPush
| CoreCallOp::VecResize
| CoreCallOp::VecExtendFromSlice
| CoreCallOp::VecIndex
| CoreCallOp::VecIndexMut
| CoreCallOp::VecDeref
| CoreCallOp::VecDerefMut
| CoreCallOp::VecReserve
| CoreCallOp::BoxFromVec
| CoreCallOp::BoxDeref
| CoreCallOp::BoxDerefMut
| CoreCallOp::BoxClone
| CoreCallOp::RefIntPartialEq { .. }
| CoreCallOp::UnitPartialEq { .. } => 1,
};
1 + op_nodes + args.iter().map(Operand::ast_nodes).sum::<usize>() + dst.ast_nodes()
}
Self::Call { args, .. } | Self::SysrootCall { args, .. } | Self::CallNe { args, .. } => {
2 + args.iter().map(Operand::ast_nodes).sum::<usize>()
}
Self::CallVia { args, .. } => 3 + args.iter().map(Operand::ast_nodes).sum::<usize>(),
Self::Drop { place, .. } => 2 + place.ast_nodes(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Block {
pub statements: Vec<Statement>,
pub terminator: Terminator,
}
impl Block {
fn ast_nodes(&self) -> usize {
1 + self.statements.iter().map(Statement::ast_nodes).sum::<usize>()
+ self.terminator.ast_nodes()
}
}
/// Check static operand and destination typing for [`Rvalue::Binary`], matching
/// `Trusted.MirSemantics.evalBinOp` and `writePlace`.
fn check_binary_types(op: BinOp, l_ty: &Ty, r_ty: &Ty, dst_ty: &Ty) -> Result<(), String> {
match op {
BinOp::Shl | BinOp::Shr => match (l_ty, r_ty) {
(Ty::Int(l_ity), Ty::Int(_)) if *dst_ty == Ty::Int(*l_ity) => Ok(()),
_ => Err(format!(
"invalid shift operand or destination types: ({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
)),
},
BinOp::Add
| BinOp::Sub
| BinOp::Mul
| BinOp::AddUnchecked
| BinOp::SubUnchecked
| BinOp::MulUnchecked
| BinOp::Div
| BinOp::Rem => match (l_ty, r_ty) {
(Ty::Int(l_ity), Ty::Int(r_ity)) if l_ity == r_ity && *dst_ty == Ty::Int(*l_ity) => {
Ok(())
}
_ => Err(format!(
"invalid arithmetic operand or destination types for {op:?}: \
({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
)),
},
BinOp::AddWithOverflow | BinOp::SubWithOverflow | BinOp::MulWithOverflow => {
match (l_ty, r_ty) {
(Ty::Int(l_ity), Ty::Int(r_ity))
if l_ity == r_ity && *dst_ty == Ty::OverflowPair(*l_ity) =>
{
Ok(())
}
_ => Err(format!(
"invalid overflowing arithmetic types for {op:?}: \
({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
)),
}
}
BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => match (l_ty, r_ty) {
(Ty::Int(l_ity), Ty::Int(r_ity)) if l_ity == r_ity && *dst_ty == Ty::Int(*l_ity) => {
Ok(())
}
(Ty::Bool, Ty::Bool) if *dst_ty == Ty::Bool => Ok(()),
_ => Err(format!(
"invalid bitwise operand or destination types for {op:?}: \
({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
)),
},
BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
if l_ty == r_ty
&& matches!(l_ty, Ty::Int(_) | Ty::Bool | Ty::Char)
&& *dst_ty == Ty::Bool
{
Ok(())
} else {
Err(format!(
"invalid comparison operand or destination types for {op:?}: \
({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
))
}
}
// `BinOp::Cmp` "is supported only on the integer types and `char`,
// always returning [`rustc_hir::LangItem::OrderingEnum`]".
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1697-L1706
BinOp::Cmp => {
if l_ty == r_ty && matches!(l_ty, Ty::Int(_) | Ty::Char) && *dst_ty == Ty::Ordering {
Ok(())
} else {
Err(format!(
"invalid three-way comparison types: ({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
))
}
}
BinOp::Offset => match (l_ty, r_ty) {
(Ty::RawPtr { pointee, .. }, Ty::Int(IntTy { width: IntWidth::Isize, signed: true }))
if pointee.is_sized() && dst_ty == l_ty =>
{
Ok(())
}
_ => Err(format!(
"invalid pointer offset types: ({l_ty:?}, {r_ty:?}) -> {dst_ty:?}"
)),
},
}
}
/// Check static operand and destination typing for [`Rvalue::Unary`], matching
/// `Trusted.MirSemantics.evalUnOp` and `UnOp.ptrMetadata`.
fn check_unary_types(op: UnOp, op_ty: &Ty, dst_ty: &Ty) -> Result<(), String> {
if op == UnOp::PtrMetadata {
return match op_ty {
Ty::Ref {
mutability,
pointee,
} => match (&**pointee, mutability) {
(Ty::Slice { .. }, _) | (Ty::Str, Mutability::Shared)
if *dst_ty
== Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
}) =>
{
Ok(())
}
(pt, _) if pt.is_sized() && *dst_ty == Ty::Unit => Ok(()),
_ => Err(format!(
"invalid PtrMetadata destination {dst_ty:?} for {op_ty:?}"
)),
},
Ty::RawPtr { pointee, .. } => match &**pointee {
Ty::Slice { .. }
if *dst_ty
== Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
}) =>
{
Ok(())
}
pt if pt.is_sized() && *dst_ty == Ty::Unit => Ok(()),
_ => Err(format!(
"invalid PtrMetadata destination {dst_ty:?} for {op_ty:?}"
)),
},
_ => Err(format!("invalid PtrMetadata operand type {op_ty:?}")),
};
}
if op_ty != dst_ty {
return Err("unary rvalue operand type disagrees with destination local".into());
}
match (op, op_ty) {
(UnOp::Not, Ty::Bool | Ty::Int(_)) => Ok(()),
(UnOp::Neg, Ty::Int(IntTy { signed: true, .. })) => Ok(()),
_ => Err(format!("invalid unary operator {op:?} for type {op_ty:?}")),
}
}
/// Refuse a pointer to an overflow pair `(T, bool)`, which must stay a
/// non-addressable local (see [`Ty::is_supported_v2_local`]).
/// [`validate_local_tys`] already refuses every local typed as such a
/// pointer; this check names the cause at the rvalue or cast.
fn refuse_overflow_pair_pointee(pointee: &Ty, what: &str) -> Result<(), String> {
if matches!(pointee, Ty::OverflowPair(_)) {
return Err(format!(
"{what} to an overflow pair `(T, bool)` is unsupported: its \
`#[repr(Rust)]` tuple layout is unchecked, so overflow pairs are not addressable"
));
}
Ok(())
}
/// Check static source, target, and destination typing for [`Rvalue::Cast`].
///
/// `IntToInt` matches `cast_from_int_like` ("can take 'int-like' input type
/// (basically everything with a scalar layout) to int/float/char types",
/// where `ty::Char` executes `u8::try_from(v).unwrap().into()`) and
/// `Trusted.MirSemantics.castTypesValid` / `evalIntToIntCast`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/cast.rs#L258-L312
///
/// `PtrToPtr` matches `ptr_to_ptr` ("Thin or wide pointer that just has the
/// ptr kind of target type changed"), admitting only raw-pointer sources
/// with both pointees sized or both the same slice, and never a `*const T`
/// to `*mut T` cast, mirroring `Trusted.MirSemantics.evalPtrToPtrCastV2`:
/// Profile v2 models no aliasing rules, and that cast is how a body could
/// write to an immutable binding. Reference sources stay
/// refused: upstream says "reference-to-raw-ptr casts are translated into
/// `&raw mut/const *r`, i.e., they are not actually casts", and such a body
/// would mix reference and non-fake raw-pointer locals, which
/// [`validate_local_tys_with_exemptions`] refuses. `IntToPtr`
/// (`PointerWithExposedProvenance`) admits only a `usize` source and a sized
/// raw-pointer target, matching `pointer_with_exposed_provenance_cast`
/// ("First cast to usize.").
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/cast.rs#L189-L218
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/cast.rs#L240-L256
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/syntax.rs#L1499-L1500
fn check_cast_types(kind: CastKind, src_ty: &Ty, cast_ty: &Ty, dst_ty: &Ty) -> Result<(), String> {
if cast_ty != dst_ty {
return Err("cast target type disagrees with destination local".into());
}
match (kind, src_ty, cast_ty) {
(CastKind::IntToInt, Ty::Int(_) | Ty::Bool | Ty::Char, Ty::Int(_)) => Ok(()),
(
CastKind::IntToInt,
Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
}),
Ty::Char,
) => Ok(()),
(CastKind::PtrToPtr, Ty::Ref { .. }, _) => Err(format!(
"PtrToPtr cast from reference {src_ty:?} is unsupported: runtime MIR \
expresses reference-to-raw-pointer conversion as `&raw (*r)`, \
and Profile v2 refuses bodies mixing references and raw pointers"
)),
(
CastKind::PtrToPtr,
Ty::RawPtr {
mutability: Mutability::Shared,
..
},
Ty::RawPtr {
mutability: Mutability::Mut,
..
},
) => Err(format!(
"PtrToPtr cast from {src_ty:?} to {cast_ty:?} is unsupported: \
Profile v2 models no aliasing rules, so it refuses `*const T` to \
`*mut T` casts, which could write to an immutable binding"
)),
(
CastKind::PtrToPtr,
Ty::RawPtr { pointee: src_pt, .. },
Ty::RawPtr { pointee: dst_pt, .. },
) => match (&**src_pt, &**dst_pt) {
(pt @ Ty::OverflowPair(_), _) | (_, pt @ Ty::OverflowPair(_)) => {
refuse_overflow_pair_pointee(pt, "PtrToPtr cast")
}
(Ty::Slice { elem: e1 }, Ty::Slice { elem: e2 }) if e1 == e2 => Ok(()),
(s, d) if s.is_sized() && d.is_sized() => Ok(()),
_ => Err(format!(
"unsupported PtrToPtr cast from {src_ty:?} to {cast_ty:?}"
)),
},
(
CastKind::IntToPtr,
Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
}),
Ty::RawPtr { pointee, .. },
) if pointee.is_sized() => Ok(()),
(CastKind::Unsize, src_ptr, dst_ptr) => match (src_ptr, dst_ptr) {
(
Ty::Ref {
mutability: src_mut,
pointee: src_pt,
},
Ty::Ref {
mutability: dst_mut,
pointee: dst_pt,
},
)
| (
Ty::RawPtr {
mutability: src_mut,
pointee: src_pt,
},
Ty::RawPtr {
mutability: dst_mut,
pointee: dst_pt,
},
) => match (&**src_pt, &**dst_pt) {
(Ty::Array { elem: e1, .. }, Ty::Slice { elem: e2 })
if e1 == e2
&& e1.is_sized()
&& !(*src_mut == Mutability::Shared && *dst_mut == Mutability::Mut) =>
{
Ok(())
}
_ => Err(format!(
"unsupported Unsize cast from {src_ty:?} to {cast_ty:?}"
)),
},
_ => Err(format!(
"unsupported Unsize cast from {src_ty:?} to {cast_ty:?}"
)),
},
(CastKind::BoxAsRawPtr, _, _) => Err(format!(
"raw pointer {cast_ty:?} from a `Box` dereference mixes a `Box` with a \
raw-pointer local, which Profile v2 refuses"
)),
(
CastKind::BoxAsRef,
Ty::Box { pointee: src_pt },
Ty::Ref {
mutability: Mutability::Shared,
pointee: dst_pt,
},
) if src_pt == dst_pt => Ok(()),
_ => Err(format!(
"unsupported cast {kind:?} from {src_ty:?} to {cast_ty:?}"
)),
}
}
/// Check static operand and case-value typing for [`Terminator::SwitchInt`],
/// matching `Trusted.MirSemantics.evalTerminator`.
fn check_switch_targets(discr_ty: &Ty, targets: &[(u128, u32)]) -> Result<(), String> {
match discr_ty {
Ty::Int(ity) => {
let mask = ity.width.mask();
for &(val, _) in targets {
if val > mask {
return Err(format!(
"SwitchInt case {val:#x} exceeds {}-bit operand width",
ity.width.bits()
));
}
}
Ok(())
}
Ty::Bool => {
for &(val, _) in targets {
if val > 1 {
return Err(format!("invalid Boolean SwitchInt case {val:#x}"));
}
}
Ok(())
}
Ty::Char => {
for &(val, _) in targets {
if !is_unicode_scalar(val) {
return Err(format!(
"invalid char SwitchInt case {val:#x}: outside Unicode scalar range"
));
}
}
Ok(())
}
Ty::OverflowPair(_) => {
if targets.is_empty() {
Ok(())
} else {
Err("non-empty SwitchInt branches on overflow-pair tuple are unsupported".into())
}
}
Ty::Unit
| Ty::Never
| Ty::Ordering
| Ty::Enum(_)
| Ty::Struct(_)
| Ty::Array { .. }
| Ty::Tuple { .. }
| Ty::Ref { .. }
| Ty::RawPtr { .. }
| Ty::Slice { .. }
| Ty::Str
| Ty::Vec { .. }
| Ty::Box { .. }
| Ty::RangeTo { .. }
| Ty::RangeFrom { .. }
| Ty::Range { .. }
| Ty::Option { .. }
| Ty::RecAdt { .. }
| Ty::RecSelf { .. }
| Ty::AdtEnum(_) => Err(format!(
"SwitchInt operand type {discr_ty:?} is not primitive-switchable"
)),
}
}
fn place_mentions_local_v2(place: &Place, lid: u32) -> bool {
place.local == lid
|| place.projection.iter().any(|elem| match elem {
PlaceElem::Index { local } => *local == lid,
PlaceElem::Deref
| PlaceElem::Field { .. }
| PlaceElem::ConstantIndex { .. }
| PlaceElem::Downcast { .. } => false,
})
}
fn operand_mentions_local_v2(op: &Operand, lid: u32) -> bool {
match op {
Operand::Copy { local } | Operand::Move { local } => *local == lid,
Operand::CopyPlace { place } | Operand::MovePlace { place } => {
place_mentions_local_v2(place, lid)
}
Operand::Constant { .. } => false,
}
}
fn rvalue_mentions_local_v2(rv: &Rvalue, lid: u32) -> bool {
match rv {
Rvalue::Use { operand, .. }
| Rvalue::UseRetag { operand }
| Rvalue::Unary { operand, .. }
| Rvalue::Cast { operand, .. }
| Rvalue::Repeat { operand, .. }
| Rvalue::AggregateRangeTo { end: operand, .. }
| Rvalue::AggregateRangeFrom { start: operand, .. } => {
operand_mentions_local_v2(operand, lid)
}
Rvalue::Binary { left, right, .. }
| Rvalue::AggregateRange { start: left, end: right, .. } => {
operand_mentions_local_v2(left, lid) || operand_mentions_local_v2(right, lid)
}
Rvalue::AggregateOption { payload, .. } => {
payload.as_deref().is_some_and(|op| operand_mentions_local_v2(op, lid))
}
Rvalue::AggregateOrdering { .. } => false,
Rvalue::Discriminant { place }
| Rvalue::Ref { place, .. }
| Rvalue::AddressOf { place, .. }
| Rvalue::FakeAddressOf { place } => place_mentions_local_v2(place, lid),
Rvalue::AggregateTuple { fields: ops }
| Rvalue::AggregateArray { elems: ops, .. }
| Rvalue::AggregateStruct { fields: ops, .. }
| Rvalue::AggregateAdtEnum { fields: ops, .. } => {
ops.iter().any(|op| operand_mentions_local_v2(op, lid))
}
}
}
fn terminator_mentions_local_v2(term: &Terminator, lid: u32) -> bool {
match term {
Terminator::Goto { .. }
| Terminator::Ret
| Terminator::Unreachable
| Terminator::Unsupported => false,
Terminator::SwitchInt { operand, .. } => operand_mentions_local_v2(operand, lid),
Terminator::Assert { cond, .. } => operand_mentions_local_v2(cond, lid),
Terminator::CoreCall { args, dst, .. } => {
args.iter().any(|op| operand_mentions_local_v2(op, lid))
|| place_mentions_local_v2(dst, lid)
}
Terminator::Call { args, dst, .. }
| Terminator::SysrootCall { args, dst, .. }
| Terminator::CallNe { args, dst, .. }
| Terminator::CallVia { args, dst, .. } => {
args.iter().any(|op| operand_mentions_local_v2(op, lid)) || *dst == lid
}
Terminator::Drop { place, .. } => place_mentions_local_v2(place, lid),
}
}
fn fake_address_of_types_match_v2(local_tys: &[Ty], dst_id: u32, src: &Place) -> bool {
if src.local == dst_id || src.projection.as_slice() != [PlaceElem::Deref] {
return false;
}
let (Some(base_ty), Some(dst_ty)) = (
local_tys.get(src.local as usize),
local_tys.get(dst_id as usize),
) else {
return false;
};
let (Ty::Ref { pointee, .. } | Ty::RawPtr { pointee, .. }) = base_ty else {
return false;
};
!matches!(&**pointee, Ty::OverflowPair(_))
&& *dst_ty
== Ty::RawPtr {
mutability: Mutability::Shared,
pointee: pointee.clone(),
}
}
/// Mirror `Trusted.MirSemantics.isFakePtrMetadataLocalV2`: `lid > arg_count`,
/// `local_tys[lid]` is a top-level `*const` raw pointer, at least one
/// unprojected `FakeAddressOf` writes to `lid`, and every statement/terminator
/// in `blocks` uses `lid` strictly as an unprojected `FakeAddressOf (*base)`
/// destination (`base != lid`) or an unprojected `UnOp::PtrMetadata` operand.
fn is_fake_ptr_metadata_local_v2(
arg_count: usize,
local_tys: &[Ty],
blocks: &[Block],
lid: usize,
) -> bool {
if lid <= arg_count {
return false;
}
let Ok(lid_u32) = u32::try_from(lid) else {
return false;
};
if !matches!(
local_tys.get(lid),
Some(Ty::RawPtr {
mutability: Mutability::Shared,
..
})
) {
return false;
}
let mut saw_fake_assign = false;
for bb in blocks {
for stmt in &bb.statements {
match stmt {
Statement::Assign { local, value } => {
if *local == lid_u32 {
let Rvalue::FakeAddressOf { place } = value else {
return false;
};
if !fake_address_of_types_match_v2(local_tys, lid_u32, place) {
return false;
}
saw_fake_assign = true;
} else if rvalue_mentions_local_v2(value, lid_u32) {
let ok = match value {
Rvalue::Unary {
op: UnOp::PtrMetadata,
operand,
} => match operand {
Operand::Copy { local } | Operand::Move { local } => {
*local == lid_u32
}
Operand::CopyPlace { place } | Operand::MovePlace { place } => {
place.local == lid_u32 && place.projection.is_empty()
}
Operand::Constant { .. } => false,
},
_ => false,
};
if !ok {
return false;
}
}
}
Statement::AssignPlace { place, value } => {
if place_mentions_local_v2(place, lid_u32) {
return false;
}
if rvalue_mentions_local_v2(value, lid_u32) {
let ok = match value {
Rvalue::Unary {
op: UnOp::PtrMetadata,
operand,
} => match operand {
Operand::Copy { local } | Operand::Move { local } => {
*local == lid_u32
}
Operand::CopyPlace { place } | Operand::MovePlace { place } => {
place.local == lid_u32 && place.projection.is_empty()
}
Operand::Constant { .. } => false,
},
_ => false,
};
if !ok {
return false;
}
}
}
Statement::StorageLive { .. } | Statement::StorageDead { .. } | Statement::Nop => {
}
// Intentionally stricter (fail-closed) than Lean/eval, which
// lower `PlaceMention` to `.nop` (`lean.rs`): rustc does not
// emit `PlaceMention` on synthetic `FakeForPtrMetadata` temps.
Statement::PlaceMention { local } => {
if *local == lid_u32 {
return false;
}
}
// A projected `PlaceMention` evaluates its place, as in Lean's
// `stmtRespectsFakePtrMetadataLocalV2`.
Statement::PlaceMentionPlace { place } => {
if place_mentions_local_v2(place, lid_u32) {
return false;
}
}
}
}
if terminator_mentions_local_v2(&bb.terminator, lid_u32) {
return false;
}
}
saw_fake_assign
}
fn collect_fake_ptr_metadata_locals_v2(
arg_count: usize,
local_tys: &[Ty],
blocks: &[Block],
) -> BTreeSet<usize> {
(0..local_tys.len())
.filter(|&idx| is_fake_ptr_metadata_local_v2(arg_count, local_tys, blocks, idx))
.collect()
}
/// The type capture gives local `_idx` of a body with `arg_count` arguments,
/// whose `rustc` type translates to `translated`. A dead local, one that is
/// neither the return place nor an argument and that no statement,
/// terminator, or debuginfo entry mentions (not even a storage marker or a
/// `PlaceMention`), is never read, written, borrowed, allocated, or dropped,
/// so its type is unobservable. Such a local whose type is outside the
/// Profile v2 local fragment, or does not translate, gets `()` instead of
/// failing the body; `rustc` leaves such locals behind when it removes the
/// fake borrows of a match guard. Every other local keeps its translation,
/// so this depends only on the body.
pub(crate) fn dead_local_ty(
idx: usize,
arg_count: usize,
mentioned: bool,
translated: Result<Ty, String>,
) -> Result<Ty, String> {
if idx <= arg_count || mentioned {
return translated;
}
match translated {
Ok(t) if t.is_sized() && t.is_supported_v2_local() => Ok(t),
_ => Ok(Ty::Unit),
}
}
/// Validates that every local in a MIR body is `Sized` and belongs to the
/// Profile v2 local type fragment
/// (`Trusted.MirSemantics.isSupportedV2LocalTy`), prior to aliasing-mix checks
/// (which run after single-purpose `BoxAsRef` deref-temporary promotion in
/// `extract`).
pub(crate) fn validate_local_ty_fragment(local_tys: &[Ty]) -> Result<(), String> {
for (idx, lty) in local_tys.iter().enumerate() {
if !lty.is_sized() {
return Err(format!("unsized local _{idx} of type {lty:?} is unsupported"));
}
if !lty.is_supported_v2_local() {
return Err(format!(
"local _{idx} of type {lty:?} is outside the Profile v2 type fragment"
));
}
}
Ok(())
}
/// Validates that every local in a MIR body belongs to the Profile v2 local
/// type fragment and does not mix reference and raw-pointer locals
/// (`Trusted.MirSemantics.bodyMixesRefsAndRawPtrsV2`), exempting
/// `fake_meta_locals` from the mixing check.
pub(crate) fn validate_local_tys_with_exemptions(
local_tys: &[Ty],
fake_meta_locals: &BTreeSet<usize>,
) -> Result<(), String> {
validate_local_ty_fragment(local_tys)?;
// Mirrors `Trusted.MirSemantics.bodyMixesRefsAndRawPtrsV2`: Profile v2 has
// no aliasing model, so it admits no body that could derive references
// from raw pointers or access referenced memory through them; metadata-only
// `FakeForPtrMetadata` temporaries (`isFakePtrMetadataLocalV2`) never incur
// a retag and are read solely by `UnOp::PtrMetadata`.
let has_non_fake_raw_ptr = local_tys
.iter()
.enumerate()
.any(|(idx, ty)| ty.has_raw_ptr_v2() && !fake_meta_locals.contains(&idx));
if local_tys.iter().any(Ty::has_ref_v2) && has_non_fake_raw_ptr {
return Err("body mixes reference and raw-pointer locals, which Profile v2 \
refuses because it does not model Rust's pointer aliasing rules"
.to_string());
}
Ok(())
}
#[cfg(test)]
pub(crate) fn validate_local_tys(local_tys: &[Ty]) -> Result<(), String> {
validate_local_tys_with_exemptions(local_tys, &BTreeSet::new())
}
/// Validated MIR function body enforcing
/// `Trusted.MirSemantics.BodyStaticAdmitted`, constant/retag/storage
/// invariants, static rvalue/terminator typing, and in-bounds local/block
/// references by construction.
///
/// Most checks in [`Body::try_new`] (static `BodyStaticAdmitted` conditions,
/// constant/index/storage bounds, and operand/destination typing for
/// `Rvalue` and `Terminator::SwitchInt`) mirror `BodyStaticAdmitted` and
/// `WellFormed` in `Trusted.MirSemantics` for fail-fast defense in depth; full
/// runtime safety (such as division-by-zero and initialized-local checks) is
/// enforced by `WellFormed`. By contrast, [`check_use_retag`] is the sole
/// soundness guard for erasing `WithRetag::Yes` in `lean.rs`, because
/// `Trusted.MirAst.Rvalue.use` carries no retag field (load-bearing for
/// reference-bearing types such as [`Ty::Ref`], whose retagging `Use`
/// rvalues are captured as [`Rvalue::UseRetag`] instead).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Body {
arg_count: usize,
is_unsafe: bool,
local_tys: Vec<Ty>,
blocks: Vec<Block>,
/// Source contract key, attached to the same body produced for its DefId.
/// Inventory indices remain navigation metadata; this value enters the
/// theorem subject and selects the reviewed unsafe caller requirements.
identity: String,
/// Whether this body is an external stub (`isExternal := true`,
/// `basicBlocks := []`) whose signature is captured without translating
/// its body. Omitted from `capture.json` when `false` so existing Schema
/// v5 captures keep their exact serialized bytes.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
is_external: bool,
/// Calling convention of this body (`Trusted.MirAst.Body.abi`). Omitted
/// from `capture.json` when `AbiKind::Rust` so existing Schema v5 captures
/// keep their exact serialized bytes; emitted explicitly in `Captured.lean`
/// on every body.
#[serde(default, skip_serializing_if = "AbiKind::is_rust")]
abi: AbiKind,
/// Intra-crate static `ty::FnDef` callee identities extracted from MIR
/// assign-rvalue operands and call/branch/assert terminators for Tarjan SCC
/// `.olean` sharding. Omitted from `capture.json` and projected into
/// `capture_shards.json`.
#[serde(skip)]
callees: BTreeSet<String>,
}
impl Body {
/// Validate and construct a signature-only external stub body
/// (`is_external = true`, `blocks = []`), mirroring
/// `Trusted.MirSemantics.StubBodyStaticAdmittedV2`.
pub fn try_new_external_stub(
arg_count: usize,
is_unsafe: bool,
local_tys: Vec<Ty>,
identity: String,
) -> Result<Self, String> {
if identity.is_empty() {
return Err("captured function identity must not be empty".into());
}
if local_tys.len() != arg_count + 1 {
return Err(format!(
"external stub has {} locals for argument count {arg_count} (expected {})",
local_tys.len(),
arg_count + 1
));
}
validate_local_tys_with_exemptions(&local_tys, &BTreeSet::new())?;
if let Some((idx, ty)) = local_tys
.iter()
.enumerate()
.find(|(_, ty)| ty.has_nested_ref_v2())
{
return Err(format!(
"signature local _{idx} of type {ty:?} contains a nested `&&T` reference, \
which Profile v2 admits only as an intra-body local"
));
}
Ok(Self {
arg_count,
is_unsafe,
local_tys,
blocks: Vec::new(),
identity,
is_external: true,
abi: AbiKind::Rust,
callees: BTreeSet::new(),
})
}
#[cfg(test)]
pub fn try_new(
arg_count: usize,
is_unsafe: bool,
local_tys: Vec<Ty>,
blocks: Vec<Block>,
identity: String,
) -> Result<Self, String> {
Self::try_new_with_callees_and_abi(
arg_count,
is_unsafe,
local_tys,
blocks,
identity,
BTreeSet::new(),
AbiKind::Rust,
)
}
#[cfg(test)]
pub fn try_new_with_callees(
arg_count: usize,
is_unsafe: bool,
local_tys: Vec<Ty>,
blocks: Vec<Block>,
identity: String,
callees: BTreeSet<String>,
) -> Result<Self, String> {
Self::try_new_with_callees_and_abi(
arg_count,
is_unsafe,
local_tys,
blocks,
identity,
callees,
AbiKind::Rust,
)
}
pub fn try_new_with_callees_and_abi(
arg_count: usize,
is_unsafe: bool,
local_tys: Vec<Ty>,
blocks: Vec<Block>,
identity: String,
callees: BTreeSet<String>,
abi: AbiKind,
) -> Result<Self, String> {
if identity.is_empty() {
return Err("captured function identity must not be empty".into());
}
if blocks.is_empty() {
return Err("MIR body contains no basic blocks".into());
}
if arg_count >= local_tys.len() {
return Err(format!(
"argument count {arg_count} out of bounds for {} locals",
local_tys.len()
));
}
let fake_meta_locals =
collect_fake_ptr_metadata_locals_v2(arg_count, &local_tys, &blocks);
validate_local_tys_with_exemptions(&local_tys, &fake_meta_locals)?;
// Locals that may be moved into stack memory (`promoteLocalToMemory` in
// `Step.lean`), covering all four callers:
// 1. `Rvalue::Ref` / `Rvalue::AddressOf` on a non-deref place.
// 2. `moveLocalPlaceV2` (`Operand::MovePlace` on a field chain of a
// non-tuple, non-overflow-pair local with a Profile v2 layout).
// 3. `dropLocalPlaceV2` (`Terminator::Drop` on a non-deref projection
// of a local other than a tuple field chain).
// Because a promoted local remains `.indirect` for the rest of the
// body, immediate-only `Option`/payload-enum downcast moves
// (`allowDowncastMove`) and unmodeled in-memory `Option` payload
// downcasts (`Option<bool>`, `Option<()>`, `Option<Vec<ZST>>`) stay
// refused on any local in `promoted_locals`.
let mut promoted_locals = BTreeSet::new();
let record_move_operand = |op: &Operand, promoted: &mut BTreeSet<u32>| {
if let Operand::MovePlace { place } = op
&& matches!(place.projection.first(), Some(PlaceElem::Field { .. }))
&& local_tys
.get(place.local as usize)
.is_some_and(|t| {
!matches!(t, Ty::Tuple { .. } | Ty::OverflowPair(_))
&& t.v2_layout().is_some()
})
{
promoted.insert(place.local);
}
};
let record_rvalue = |value: &Rvalue, promoted: &mut BTreeSet<u32>| match value {
Rvalue::Ref { place, .. } | Rvalue::AddressOf { place, .. } => {
if !matches!(place.projection.first(), Some(PlaceElem::Deref)) {
promoted.insert(place.local);
}
}
Rvalue::Use { operand, .. }
| Rvalue::UseRetag { operand }
| Rvalue::Unary { operand, .. }
| Rvalue::Cast { operand, .. }
| Rvalue::Repeat { operand, .. }
| Rvalue::AggregateRangeTo { end: operand, .. }
| Rvalue::AggregateRangeFrom { start: operand, .. } => {
record_move_operand(operand, promoted);
}
Rvalue::Binary { left, right, .. }
| Rvalue::AggregateRange {
start: left,
end: right,
..
} => {
record_move_operand(left, promoted);
record_move_operand(right, promoted);
}
Rvalue::AggregateTuple { fields }
| Rvalue::AggregateArray { elems: fields, .. }
| Rvalue::AggregateStruct { fields, .. }
| Rvalue::AggregateAdtEnum { fields, .. } => {
for op in fields {
record_move_operand(op, promoted);
}
}
Rvalue::AggregateOption { payload, .. } => {
if let Some(op) = payload {
record_move_operand(op, promoted);
}
}
Rvalue::Discriminant { .. }
| Rvalue::FakeAddressOf { .. }
| Rvalue::AggregateOrdering { .. } => {}
};
for block in &blocks {
for stmt in &block.statements {
if let Statement::Assign { value, .. } | Statement::AssignPlace { value, .. } = stmt
{
record_rvalue(value, &mut promoted_locals);
}
}
match &block.terminator {
Terminator::SwitchInt { operand, .. } | Terminator::Assert { cond: operand, .. } => {
record_move_operand(operand, &mut promoted_locals);
}
Terminator::CoreCall { args, .. }
| Terminator::Call { args, .. }
| Terminator::SysrootCall { args, .. }
| Terminator::CallNe { args, .. }
| Terminator::CallVia { args, .. } => {
for op in args {
record_move_operand(op, &mut promoted_locals);
}
}
Terminator::Drop { place, .. } => {
if !place.projection.is_empty()
&& !matches!(place.projection.first(), Some(PlaceElem::Deref))
&& !(matches!(place.projection.first(), Some(PlaceElem::Field { .. }))
&& matches!(
local_tys.get(place.local as usize),
Some(Ty::Tuple { .. })
))
{
promoted_locals.insert(place.local);
}
}
Terminator::Goto { .. }
| Terminator::Ret
| Terminator::Unreachable
| Terminator::Unsupported => {}
}
}
// Mirrors `Trusted.MirSemantics.bodyHasNestedRefSignatureV2`: two-level
// `&&T` references are admitted only as intra-body locals, never in
// return or parameter signatures.
if let Some((idx, ty)) = local_tys[..=arg_count]
.iter()
.enumerate()
.find(|(_, ty)| ty.has_nested_ref_v2())
{
return Err(format!(
"signature local _{idx} of type {ty:?} contains a nested `&&T` reference, \
which Profile v2 admits only as an intra-body local"
));
}
fn check_local<'a>(local_tys: &'a [Ty], local: u32, role: &str) -> Result<&'a Ty, String> {
local_tys
.get(local as usize)
.ok_or_else(|| format!("{role} local {local} out of bounds"))
}
fn check_place(
local_tys: &[Ty],
place: &Place,
role: &str,
allow_unsized_deref: bool,
require_mut_deref: bool,
in_memory_local: bool,
) -> Result<Ty, String> {
let base = check_local(local_tys, place.local, role)?;
let mut cur = base.clone();
let mut saw_deref = false;
let mut saw_slice_deref = false;
let mut downcast_variant: Option<usize> = None;
for (step, elem) in place.projection.iter().enumerate() {
match elem {
PlaceElem::Deref => {
if saw_deref || step != 0 || downcast_variant.is_some() {
return Err("nested or post-field deref projections are unsupported".into());
}
saw_deref = true;
match &cur {
Ty::Ref { mutability, pointee } | Ty::RawPtr { mutability, pointee } => {
if require_mut_deref && *mutability != Mutability::Mut {
return Err("cannot write through shared pointer/reference".into());
}
// An unsized slice pointee is admitted only
// as the base of a following `Index`
// projection, which yields a sized element
// place.
let indexed = matches!(
place.projection.get(step + 1),
Some(PlaceElem::Index { .. })
);
if !allow_unsized_deref && !indexed && !pointee.is_sized() {
return Err(format!(
"unsized deref of {pointee:?} is unsupported here"
));
}
saw_slice_deref = !pointee.is_sized();
cur = (**pointee).clone();
}
_ => return Err(format!("cannot deref non-pointer local type {cur:?}")),
}
}
PlaceElem::Downcast { variant_idx } => {
// A downcast reads an `Option` or payload enum variant
// (`Trusted.MirSemantics.projectValFieldV2` /
// `projectMemoryPlaceV2`), which Profile v2 models for
// reads and supported borrows but never for writes
// (`resolvePlaceDestV2` has no `.downcast` arm).
if role == "assignment"
|| (saw_deref && require_mut_deref)
|| downcast_variant.is_some()
{
return Err("nested downcast projections, or a write through a \
downcast, are unsupported"
.into());
}
// A payload enum variant's fields are read through
// `Trusted.MirSemantics.projectValFieldV2` or
// `projectMemoryPlaceV2`. Writing one, or borrowing it
// mutably, could store bytes at the tag of a niche
// enum without `adtFinishEncodeV2`'s check, so both
// are refused, except a mutable borrow of a field of
// a `Direct` enum, whose every variant's fields lie
// outside the tag, or of a field of a niche enum's
// untagged variant through which no valid store can
// change the variant ([`niche_field_untagged`])
// (`Trusted.MirSemantics.projsDowncastMutUnsafeV2`).
// A recursive payload enum's variants are those of
// its one-step unfolding
// (`Trusted.MirSemantics.adtVariantsV2`).
if let Some(aty) = cur.as_adt_enum() {
let direct_ref_mut = role == "ref_mut"
&& matches!(aty.layout.encoding, AdtTagEncoding::Direct);
let niche_ref_mut = role == "ref_mut"
&& match place.projection.get(step + 1) {
Some(PlaceElem::Field { index, ty }) => {
niche_field_untagged(&aty, *variant_idx, *index, ty)
}
_ => false,
};
if require_mut_deref
|| role == "assignment"
|| (role == "ref_mut" && !direct_ref_mut && !niche_ref_mut)
{
return Err(format!(
"a write or mutable borrow through a downcast of {cur:?} is \
unsupported"
));
}
if aty.variant(*variant_idx).is_none() {
return Err(format!(
"downcast variant {variant_idx} out of range on {cur:?}"
));
}
if saw_slice_deref {
return Err(format!("in-memory downcast of {cur:?} is unsupported"));
}
cur = Ty::AdtEnum(Box::new(aty));
downcast_variant = Some(*variant_idx);
continue;
}
if !matches!(cur, Ty::Option { .. }) || *variant_idx != 1 {
return Err(format!("unsupported downcast variant {variant_idx} on {cur:?}"));
}
// In memory, the payload of `Option<bool>`,
// `Option<()>`, and `Option<Vec<ZST>>` has no modeled
// offset (`Trusted.MirSemantics.optionSomeOffsetV2`),
// and a slice element place is resolved without
// downcasts (`Trusted.MirSemantics.sliceElemAddrV2`).
let in_memory =
saw_deref || in_memory_local || role == "ref" || role == "ref_mut";
let unmodeled_payload = matches!(&cur, Ty::Option { elem } if match &**elem {
Ty::Bool | Ty::Unit => true,
Ty::Vec { elem } => elem.v2_layout().is_none_or(|(size, _)| size == 0),
_ => false,
});
if in_memory && (unmodeled_payload || saw_slice_deref) {
return Err(format!("in-memory downcast of {cur:?} is unsupported"));
}
downcast_variant = Some(*variant_idx);
}
PlaceElem::Field { index, ty } => {
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
if let Some(variant) = downcast_variant.take() {
if let Ty::AdtEnum(aty) = &cur {
let expected = aty
.variant(variant)
.and_then(|sty| sty.fields().get(*index).cloned());
let Some(expected) = expected else {
return Err(format!(
"unsupported downcast field {index} for variant {variant}"
));
};
if expected != *ty {
return Err(format!(
"variant field type {ty:?} disagrees with {expected:?}"
));
}
cur = expected;
continue;
}
if variant != 1 || *index != 0 {
return Err(format!("unsupported downcast field {index} for variant {variant}"));
}
let Ty::Option { elem: inner } = &cur else {
return Err("downcast field requires Option".into());
};
if *ty != **inner {
return Err(format!(
"Option downcast field type {ty:?} disagrees with {inner:?}"
));
}
cur = (**inner).clone();
continue;
}
let expected_field = match &cur {
Ty::Tuple { fields } => fields.get(*index).cloned(),
Ty::Struct(sty) => sty.fields().get(*index).cloned(),
// `Trusted.MirSemantics.stepProjectedTyV2`: a
// recursive struct's fields are those of its
// one-step unfolding.
Ty::RecAdt { .. } => match cur.unfold_rec() {
Some(Ty::Struct(sty)) => sty.fields().get(*index).cloned(),
_ => None,
},
Ty::OverflowPair(ity) if *index == 0 => Some(Ty::Int(*ity)),
Ty::OverflowPair(_) if *index == 1 => Some(Ty::Bool),
Ty::RangeTo { elem: e } | Ty::RangeFrom { elem: e }
if *index == 0 && **e == usize_ty =>
{
Some(usize_ty)
}
Ty::Range { elem: e }
if (*index == 0 || *index == 1) && **e == usize_ty =>
{
Some(usize_ty)
}
_ => None,
};
let Some(expected) = expected_field else {
return Err(format!("unsupported field {index} projection on {cur:?}"));
};
if expected != *ty {
return Err(format!(
"field {index} projection type {ty:?} disagrees with {expected:?}"
));
}
cur = expected;
}
PlaceElem::ConstantIndex {
offset,
min_length,
from_end,
} => {
let Ty::Array { elem, len } = &cur else {
return Err(format!(
"ConstantIndex projection requires fixed-size array type, got {cur:?}"
));
};
// Match `Trusted.MirSemantics.constantIndexOffset`:
// `from_end` is a 1-based offset from `len`
// (`1 <= offset <= len`), otherwise 0-based
// (`offset < len`), with `len >= min_length`.
let out_of_bounds = if *from_end {
*offset == 0 || *offset > *len
} else {
*offset >= *len
};
if *len < *min_length || out_of_bounds {
return Err(format!(
"ConstantIndex [{offset} of min {min_length}, from_end={from_end}] out of bounds for array length {len}"
));
}
cur = (**elem).clone();
}
PlaceElem::Index { local } => {
if downcast_variant.is_some() {
return Err("downcast projection must be followed by field projection".into());
}
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let index_ty = check_local(local_tys, *local, "index")?;
if *index_ty != usize_ty {
return Err(format!(
"Index projection local {local} has type {index_ty:?}, not usize"
));
}
let (Ty::Array { elem, .. } | Ty::Slice { elem }) = &cur else {
return Err(format!(
"Index projection requires an array or dereferenced slice, got {cur:?}"
));
};
if matches!(cur, Ty::Slice { .. }) && !saw_deref {
return Err("Index projection on an unsized slice requires a deref".into());
}
cur = (**elem).clone();
}
}
}
if downcast_variant.is_some() {
return Err("downcast projection must be followed by field projection".into());
}
Ok(cur)
}
let check_operand = |local_tys: &[Ty], op: &Operand| -> Result<Ty, String> {
match op {
Operand::Copy { local } | Operand::Move { local } => {
Ok(check_local(local_tys, *local, "operand")?.clone())
}
Operand::CopyPlace { place } => check_place(
local_tys,
place,
"operand",
false,
false,
promoted_locals.contains(&place.local),
),
// `Trusted.MirSemantics.readPlaceV2` models a move out of one
// field of a tuple local (`move (_t.1)`, which rustc emits for
// overflow checks) by deinitializing just that field, and a
// move out of `(x as Some).0` on an immediate `Option` local
// (`allowDowncastMove`) by deinitializing the whole local. A
// projected move through a dereference (`move (*p)`) or out of
// an in-memory `Option` local stays `.unsupported`:
// moving out of `*p` may deinitialize caller memory, which
// MIR leaves unspecified, and moving out of an `.indirect`
// `Option` would leave a live copy in memory. Refuse those
// here so capture fails instead of emitting an obligation no
// execution can discharge.
Operand::MovePlace { place }
if matches!(place.projection.as_slice(), [PlaceElem::Field { .. }])
&& matches!(
local_tys.get(place.local as usize),
Some(Ty::Tuple { .. } | Ty::OverflowPair(_))
) =>
{
check_place(local_tys, place, "operand", false, false, false)
}
// A move out of a nested variant field chain of a tuple local
// (`move ((_t.1 as Some).0)`) projects the leaf from the
// tuple's value (`moveTuplePathV2`): a tuple has no layout for
// `moveLocalPlaceV2` to move it in, and a non-downcast nested
// tuple move fails closed because `partialTuple` tracks only
// top-level field initialization.
Operand::MovePlace { place }
if place.projection.len() >= 2
&& matches!(place.projection.first(), Some(PlaceElem::Field { .. }))
&& place.projection.iter().all(|e| {
matches!(e, PlaceElem::Field { .. } | PlaceElem::Downcast { .. })
})
&& place.projection[1..]
.iter()
.any(|e| matches!(e, PlaceElem::Downcast { .. }))
&& matches!(
local_tys.get(place.local as usize),
Some(Ty::Tuple { .. })
) =>
{
check_place(local_tys, place, "operand", false, false, false)
}
// A move out of `(x as Some).0` on an immediate `Option` local
// or `(x as V).0` on a single-field variant of an immediate
// payload-enum local (including heap-owning and recursive
// enums) is modeled by recording `.movedEnumDiscr`
// (`allowDowncastMove`), while multi-field variants and
// address-taken locals stay refused here.
Operand::MovePlace { place }
if local_tys.get(place.local as usize).is_some_and(|t| {
match (t, place.projection.as_slice()) {
(
Ty::Option { .. },
[
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, .. },
],
) => true,
(
Ty::AdtEnum(aty),
[
PlaceElem::Downcast { variant_idx },
PlaceElem::Field { index: 0, .. },
],
) => aty
.variant(*variant_idx)
.is_some_and(|v| v.fields().len() == 1),
(
Ty::RecAdt { defn, .. },
[
PlaceElem::Downcast { variant_idx },
PlaceElem::Field { index: 0, .. },
],
) => matches!(
&**defn,
Ty::AdtEnum(aty)
if aty
.variant(*variant_idx)
.is_some_and(|v| v.fields().len() == 1)
),
_ => false,
}
}) && !promoted_locals.contains(&place.local) =>
{
check_place(local_tys, place, "operand", false, false, false)
}
// A move out of any other field chain of a local
// (`move (_s.f)`, `move ((_s.f).g)`, `move ((_s.f as V).i)`)
// runs in the local's stack allocation (`moveLocalPlaceV2`),
// which needs a layout, and deinitializes the moved field
// there unless it is reached through a variant.
Operand::MovePlace { place }
if matches!(place.projection.first(), Some(PlaceElem::Field { .. }))
&& place.projection.iter().all(|e| {
matches!(e, PlaceElem::Field { .. } | PlaceElem::Downcast { .. })
})
&& local_tys
.get(place.local as usize)
.is_some_and(|t| t.v2_layout().is_some()) =>
{
check_place(local_tys, place, "operand", false, false, true)
}
Operand::MovePlace { .. } => Err(
"projected move operands other than a field chain of a local \
with a layout (`move (*p)`, indices) are unsupported: \
Profile v2 models partial deinitialization by a move only for locals"
.into(),
),
Operand::Constant { ty, lit } => {
validate_constant(ty, lit)?;
Ok(ty.clone())
}
}
};
let check_rvalue = |local_tys: &[Ty], dst_ty: &Ty, value: &Rvalue| -> Result<(), String> {
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
match value {
Rvalue::Use {
operand,
with_retag,
} => {
check_use_retag(dst_ty, *with_retag)?;
let op_ty = check_operand(local_tys, operand)?;
if &op_ty != dst_ty {
return Err(
"use rvalue operand type disagrees with destination local".into()
);
}
}
Rvalue::UseRetag { operand } => {
if dst_ty.is_retag_noop() {
return Err("UseRetag requires a reference-bearing destination type".into());
}
let op_ty = check_operand(local_tys, operand)?;
if &op_ty != dst_ty {
return Err(
"retag use operand type disagrees with destination local".into()
);
}
}
Rvalue::Binary { op, left, right } => {
let l_ty = check_operand(local_tys, left)?;
let r_ty = check_operand(local_tys, right)?;
check_binary_types(*op, &l_ty, &r_ty, dst_ty)?;
}
Rvalue::Unary { op, operand } => {
let op_ty = check_operand(local_tys, operand)?;
check_unary_types(*op, &op_ty, dst_ty)?;
}
Rvalue::Cast {
cast_kind,
operand,
ty,
} => {
let src_ty = check_operand(local_tys, operand)?;
check_cast_types(*cast_kind, &src_ty, ty, dst_ty)?;
}
Rvalue::Discriminant { place } => {
let src_ty = check_place(
local_tys,
place,
"discriminant",
false,
false,
promoted_locals.contains(&place.local),
)?;
let expected_discr = match &src_ty {
Ty::Enum(ety) => ety.discr(),
Ty::Ordering => IntTy {
width: IntWidth::I8,
signed: true,
},
Ty::Option { .. } => IntTy {
width: IntWidth::Isize,
signed: true,
},
// `Trusted.MirSemantics.evalAdtDiscriminantOfVal`, on a
// payload enum or a recursive one.
Ty::AdtEnum(aty) => aty.layout().discr(),
Ty::RecAdt { defn, .. } if matches!(&**defn, Ty::AdtEnum(_)) => {
let Ty::AdtEnum(aty) = &**defn else { unreachable!() };
aty.layout().discr()
}
_ => {
return Err(
"discriminant rvalue requires an enum, Ordering, or Option place"
.into(),
);
}
};
if *dst_ty != Ty::Int(expected_discr) {
return Err(
"discriminant rvalue destination type disagrees with enum discriminant"
.into(),
);
}
}
Rvalue::Ref { mutability, place } => {
// `check_place` admits a deref only as the first
// projection, so a borrow through a deref reborrows the
// base local.
if matches!(place.projection.first(), Some(PlaceElem::Deref)) {
let base = check_local(local_tys, place.local, "ref")?;
// `&(*p)` for a raw pointer `p` would derive a
// reference from a raw pointer, which needs the
// aliasing model that Profile v2 lacks. Such a body
// mixes reference and non-fake raw-pointer locals and
// is already refused by
// `validate_local_tys_with_exemptions`; refuse it here
// too rather than keep an unreachable rule.
if matches!(base, Ty::RawPtr { .. }) {
return Err(
"Rvalue::Ref through a raw pointer is unsupported: \
Profile v2 does not derive references from raw pointers"
.into(),
);
}
if *mutability == Mutability::Mut
&& matches!(
base,
Ty::Ref {
mutability: Mutability::Shared,
..
}
)
{
return Err("cannot reborrow &mut from shared & reference".into());
}
}
let role = if *mutability == Mutability::Mut { "ref_mut" } else { "ref" };
let pointee = check_place(local_tys, place, role, true, false, true)?;
refuse_overflow_pair_pointee(&pointee, "Rvalue::Ref")?;
let expected = Ty::Ref {
mutability: *mutability,
pointee: Box::new(pointee),
};
if *dst_ty != expected {
return Err(format!(
"Rvalue::Ref type {expected:?} disagrees with destination {dst_ty:?}"
));
}
}
Rvalue::AddressOf { mutability, place } => {
if place.projection.iter().any(|e| matches!(e, PlaceElem::Downcast { .. })) {
return Err("unsupported projection in Rvalue::AddressOf".into());
}
// `check_place` admits a deref only as the first
// projection, so a borrow through a deref reborrows the
// base local.
if matches!(place.projection.first(), Some(PlaceElem::Deref)) {
let base = check_local(local_tys, place.local, "addressOf")?;
// `&raw (*r)` for a reference `r` is how runtime MIR
// converts a reference to a raw pointer. Such a body
// mixes reference and non-fake raw-pointer locals and
// is already refused by
// `validate_local_tys_with_exemptions`; refuse it here
// too rather than keep an unreachable rule.
if matches!(base, Ty::Ref { .. }) {
return Err(
"Rvalue::AddressOf through a reference is unsupported: \
Profile v2 does not derive raw pointers from references"
.into(),
);
}
// `&raw mut *p` through a `*const T` is a borrow-check
// error, so this is unreachable. Refusing it keeps a
// `*const T` from yielding a `*mut T`, matching the
// `PtrToPtr` refusal in [`check_cast_types`].
if *mutability == Mutability::Mut
&& matches!(
base,
Ty::RawPtr {
mutability: Mutability::Shared,
..
}
)
{
return Err(
"cannot take `&raw mut` through a `*const` raw pointer".into()
);
}
}
let pointee = check_place(local_tys, place, "addressOf", true, false, true)?;
refuse_overflow_pair_pointee(&pointee, "Rvalue::AddressOf")?;
let expected = Ty::RawPtr {
mutability: *mutability,
pointee: Box::new(pointee),
};
if *dst_ty != expected {
return Err(format!(
"Rvalue::AddressOf type {expected:?} disagrees with destination {dst_ty:?}"
));
}
}
Rvalue::FakeAddressOf { place } => {
if place.projection.as_slice() != [PlaceElem::Deref] {
return Err(
"Rvalue::FakeAddressOf requires a single Deref projection".into(),
);
}
let base = check_local(local_tys, place.local, "fakeAddressOf")?;
if !matches!(base, Ty::Ref { .. } | Ty::RawPtr { .. }) {
return Err(
"Rvalue::FakeAddressOf base local must be a reference or raw pointer"
.into(),
);
}
let pointee =
check_place(local_tys, place, "fakeAddressOf", true, false, true)?;
refuse_overflow_pair_pointee(&pointee, "Rvalue::FakeAddressOf")?;
let expected = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(pointee),
};
if *dst_ty != expected {
return Err(format!(
"Rvalue::FakeAddressOf type {expected:?} disagrees with destination {dst_ty:?}"
));
}
}
Rvalue::AggregateTuple { fields } => {
let overflow_fields;
let dst_fields: &[Ty] = match dst_ty {
Ty::Unit => &[],
Ty::Tuple { fields } => fields.as_slice(),
Ty::OverflowPair(ity) => {
overflow_fields = [Ty::Int(*ity), Ty::Bool];
&overflow_fields
}
_ => {
return Err(format!(
"AggregateTuple requires Tuple or Unit destination type, got {dst_ty:?}"
));
}
};
if fields.len() != dst_fields.len() {
return Err("AggregateTuple arity disagrees with destination tuple".into());
}
for (field_op, expected_ty) in fields.iter().zip(dst_fields.iter()) {
let got = check_operand(local_tys, field_op)?;
if &got != expected_ty {
return Err(format!(
"AggregateTuple field type {got:?} disagrees with {expected_ty:?}"
));
}
}
}
Rvalue::AggregateArray { elem_ty, elems } => {
let Ty::Array {
elem: dst_elem,
len: dst_len,
} = dst_ty
else {
return Err(format!(
"AggregateArray requires Array destination type, got {dst_ty:?}"
));
};
if elem_ty != &**dst_elem || elems.len() != *dst_len || !elem_ty.is_sized() {
return Err("AggregateArray element type or length disagrees with destination array".into());
}
for op in elems {
let got = check_operand(local_tys, op)?;
if &got != elem_ty {
return Err(format!(
"AggregateArray element operand type {got:?} disagrees with {elem_ty:?}"
));
}
}
}
Rvalue::AggregateStruct { ty, fields } => {
// A recursive struct's fields are those of its one-step
// unfolding (`Trusted.MirSemantics.evalRvalueV2`), whose
// back edges are the closed `RecAdt`.
let unfolded = ty.unfold_rec();
let sty = match (ty, &unfolded) {
(Ty::Struct(sty), _) | (Ty::RecAdt { .. }, Some(Ty::Struct(sty))) => sty,
_ => {
return Err(format!("AggregateStruct requires a struct type, got {ty:?}"));
}
};
if ty != dst_ty {
return Err(format!(
"AggregateStruct type {ty:?} disagrees with destination {dst_ty:?}"
));
}
if fields.len() != sty.fields().len() {
return Err("AggregateStruct arity disagrees with the struct field count".into());
}
for (field_op, expected_ty) in fields.iter().zip(sty.fields()) {
let got = check_operand(local_tys, field_op)?;
if &got != expected_ty {
return Err(format!(
"AggregateStruct field type {got:?} disagrees with {expected_ty:?}"
));
}
}
}
Rvalue::Repeat {
operand,
elem_ty,
count,
} => {
let Ty::Array {
elem: dst_elem,
len: dst_len,
} = dst_ty
else {
return Err(format!(
"Repeat requires Array destination type, got {dst_ty:?}"
));
};
if elem_ty != &**dst_elem || *count != *dst_len || !elem_ty.is_sized() {
return Err("Repeat element type or length disagrees with destination array".into());
}
let got = check_operand(local_tys, operand)?;
if &got != elem_ty {
return Err(format!(
"Repeat operand type {got:?} disagrees with {elem_ty:?}"
));
}
}
Rvalue::AggregateRangeTo { elem_ty, end } => {
if *elem_ty != usize_ty
|| *dst_ty
!= (Ty::RangeTo {
elem: Box::new(usize_ty.clone()),
})
{
return Err("AggregateRangeTo requires RangeTo<usize>".into());
}
let got = check_operand(local_tys, end)?;
if got != usize_ty {
return Err("AggregateRangeTo end operand must be usize".into());
}
}
Rvalue::AggregateRangeFrom { elem_ty, start } => {
if *elem_ty != usize_ty
|| *dst_ty
!= (Ty::RangeFrom {
elem: Box::new(usize_ty.clone()),
})
{
return Err("AggregateRangeFrom requires RangeFrom<usize>".into());
}
let got = check_operand(local_tys, start)?;
if got != usize_ty {
return Err("AggregateRangeFrom start operand must be usize".into());
}
}
Rvalue::AggregateRange { elem_ty, start, end } => {
if *elem_ty != usize_ty
|| *dst_ty
!= (Ty::Range {
elem: Box::new(usize_ty.clone()),
})
{
return Err("AggregateRange requires Range<usize>".into());
}
let got_start = check_operand(local_tys, start)?;
let got_end = check_operand(local_tys, end)?;
if got_start != usize_ty || got_end != usize_ty {
return Err("AggregateRange bounds must be usize".into());
}
}
Rvalue::AggregateOption {
variant_idx,
inner_ty,
payload,
} => {
if *dst_ty
!= (Ty::Option {
elem: Box::new(inner_ty.clone()),
})
{
return Err("AggregateOption requires Option<inner_ty> destination".into());
}
match (variant_idx, payload) {
(0, None) => {}
(1, Some(op)) => {
let got = check_operand(local_tys, op)?;
if got != *inner_ty {
return Err("AggregateOption Some payload type mismatch".into());
}
}
_ => return Err("invalid AggregateOption variant/payload".into()),
}
}
Rvalue::AggregateAdtEnum { ty, variant_idx, fields } => {
// A fieldless enum's variant is payload-free
// (`Trusted.MirSemantics.evalFieldlessEnumAggregateV2`).
if let Ty::Enum(ety) = ty {
if ty != dst_ty {
return Err(format!(
"AggregateAdtEnum type {ty:?} disagrees with destination {dst_ty:?}"
));
}
if *variant_idx >= ety.discriminants().len() {
return Err(format!(
"AggregateAdtEnum variant {variant_idx} is out of range"
));
}
if !fields.is_empty() {
return Err("AggregateAdtEnum of a fieldless enum has fields".into());
}
return Ok(());
}
// A recursive payload enum's variants are those of its
// unfolding (`Trusted.MirSemantics.adtVariantsV2`).
let Some(aty) = ty.as_adt_enum() else {
return Err(format!("AggregateAdtEnum requires an enum, got {ty:?}"));
};
if ty != dst_ty {
return Err(format!(
"AggregateAdtEnum type {ty:?} disagrees with destination {dst_ty:?}"
));
}
let Some(sty) = aty.variant(*variant_idx) else {
return Err(format!("AggregateAdtEnum variant {variant_idx} is out of range"));
};
if fields.len() != sty.fields().len() {
return Err("AggregateAdtEnum arity disagrees with the variant".into());
}
for (field_op, expected_ty) in fields.iter().zip(sty.fields()) {
let got = check_operand(local_tys, field_op)?;
if &got != expected_ty {
return Err(format!(
"AggregateAdtEnum field type {got:?} disagrees with {expected_ty:?}"
));
}
}
}
Rvalue::AggregateOrdering { tag_bits } => {
if *dst_ty != Ty::Ordering {
return Err(format!(
"AggregateOrdering requires Ordering destination, got {dst_ty:?}"
));
}
if !matches!(*tag_bits, 0 | 1 | 0xff) {
return Err(format!(
"invalid AggregateOrdering tag bits {tag_bits:#x}"
));
}
}
}
Ok(())
};
let num_blocks = blocks.len();
let check_block = |target: u32| -> Result<(), String> {
if (target as usize) >= num_blocks {
return Err(format!(
"target basic block {target} out of bounds for {num_blocks} blocks"
));
}
Ok(())
};
for block in &blocks {
for stmt in &block.statements {
match stmt {
Statement::Assign { local, value } => {
let dst_ty = check_local(&local_tys, *local, "assignment")?.clone();
check_rvalue(&local_tys, &dst_ty, value)?;
if matches!(value, Rvalue::FakeAddressOf { .. })
&& !fake_meta_locals.contains(&(*local as usize))
{
return Err(format!(
"Rvalue::FakeAddressOf destination _{local} must be a non-argument \
*const temporary read exclusively by UnOp::PtrMetadata"
));
}
}
Statement::AssignPlace { place, value } => {
if matches!(value, Rvalue::FakeAddressOf { .. }) {
return Err(
"Rvalue::FakeAddressOf destination must be an unprojected local"
.into(),
);
}
let require_mut_deref =
matches!(place.projection.first(), Some(PlaceElem::Deref));
let dst_ty = check_place(
&local_tys,
place,
"assignment",
false,
require_mut_deref,
true,
)?;
check_rvalue(&local_tys, &dst_ty, value)?;
}
Statement::StorageLive { local } => {
check_local(&local_tys, *local, "storage annotation")?;
}
Statement::StorageDead { local } => {
// `rustc_const_eval`'s `storage_dead` asserts
// `local != mir::RETURN_PLACE` ("Cannot make return
// place dead"), and `Trusted.MirSemantics` faults with
// `.unsupported` on `StorageDead(0)` in
// `evalStatement`.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/stack.rs#L582-L590
if *local == 0 {
return Err("StorageDead on return place _0 is unsupported".into());
}
check_local(&local_tys, *local, "storage annotation")?;
}
Statement::PlaceMention { local } => {
let local_ty = check_local(&local_tys, *local, "place mention")?;
check_place_mention(local_ty)?;
}
// `Trusted.MirSemantics.evalStatementV2` reads the place
// without moving, so admit exactly the places a copy
// operand may read. An unprojected mention is
// `Statement::PlaceMention` instead.
Statement::PlaceMentionPlace { place } => {
if place.projection.is_empty() {
return Err("PlaceMentionPlace requires a projected place".into());
}
check_place(
&local_tys,
place,
"operand",
false,
false,
promoted_locals.contains(&place.local),
)?;
}
Statement::Nop => {}
}
}
match &block.terminator {
Terminator::Goto { block } => check_block(*block)?,
Terminator::SwitchInt {
operand,
targets,
otherwise,
} => {
let discr_ty = check_operand(&local_tys, operand)?;
check_switch_targets(&discr_ty, targets)?;
for &(_, target) in targets {
check_block(target)?;
}
check_block(*otherwise)?;
}
Terminator::Assert {
cond,
target,
..
} => {
let cond_ty = check_operand(&local_tys, cond)?;
if cond_ty != Ty::Bool {
return Err(format!("Assert condition must be bool, got {cond_ty:?}"));
}
check_block(*target)?;
}
Terminator::CoreCall {
op,
args,
dst,
target,
unwind: _,
} => {
if !dst.projection.is_empty() {
return Err("CoreCall destination must be an unprojected local".into());
}
let dst_ty = check_local(&local_tys, dst.local, "core call destination")?.clone();
let arg_tys = args
.iter()
.map(|op| check_operand(&local_tys, op))
.collect::<Result<Vec<_>, _>>()?;
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
// `get_unchecked(&self, index: I) -> &I::Output` takes and
// returns shared integer slices; a `&mut [Int]` receiver
// reaches the call through a shared reborrow.
match (op, arg_tys.as_slice()) {
(
CoreCallOp::SliceLen,
[Ty::Ref { pointee, .. }],
) if matches!(
&**pointee,
Ty::Slice { elem: e } if e.is_sized_no_ref() || e.is_owned_data()
) && dst_ty == usize_ty => {}
(
CoreCallOp::SliceGetUncheckedRangeTo,
[Ty::Ref {
mutability: in_mut,
pointee,
}, Ty::RangeTo { elem: idx_ty }],
) if **idx_ty == usize_ty
&& matches!(&**pointee, Ty::Slice { elem: e } if matches!(&**e, Ty::Int(_)))
&& *in_mut == Mutability::Shared
&& matches!(&dst_ty, Ty::Ref { mutability: Mutability::Shared, pointee: dst_pt } if dst_pt == pointee) => {}
(
CoreCallOp::SliceGetUncheckedRangeFrom,
[Ty::Ref {
mutability: in_mut,
pointee,
}, Ty::RangeFrom { elem: idx_ty }],
) if **idx_ty == usize_ty
&& matches!(&**pointee, Ty::Slice { elem: e } if matches!(&**e, Ty::Int(_)))
&& *in_mut == Mutability::Shared
&& matches!(&dst_ty, Ty::Ref { mutability: Mutability::Shared, pointee: dst_pt } if dst_pt == pointee) => {}
(
CoreCallOp::SliceGetUncheckedRange,
[Ty::Ref {
mutability: in_mut,
pointee,
}, Ty::Range { elem: idx_ty }],
) if **idx_ty == usize_ty
&& matches!(&**pointee, Ty::Slice { elem: e } if matches!(&**e, Ty::Int(_)))
&& *in_mut == Mutability::Shared
&& matches!(&dst_ty, Ty::Ref { mutability: Mutability::Shared, pointee: dst_pt } if dst_pt == pointee) => {}
(
CoreCallOp::SliceGetUncheckedIndex,
[Ty::Ref {
mutability: in_mut,
pointee,
}, idx_ty],
) if *idx_ty == usize_ty
&& matches!(&**pointee, Ty::Slice { elem: e } if e.is_sized_no_ref())
&& *in_mut == Mutability::Shared
&& matches!(
&**pointee,
Ty::Slice { elem: e }
if dst_ty
== Ty::Ref {
mutability: Mutability::Shared,
pointee: e.clone(),
}
) => {}
(
CoreCallOp::PtrAdd {
mutability,
pointee,
},
[Ty::RawPtr {
mutability: arg_mut,
pointee: arg_pt,
}, count_ty],
) if arg_mut == mutability
&& **arg_pt == *pointee
&& pointee.is_sized()
&& *count_ty == usize_ty
&& dst_ty
== Ty::RawPtr {
mutability: *mutability,
pointee: Box::new(pointee.clone()),
} => {}
(CoreCallOp::UsizeUncheckedSub, [l_ty, r_ty])
if *l_ty == usize_ty && *r_ty == usize_ty && dst_ty == usize_ty => {}
(CoreCallOp::IntToLeBytes { int_ty }, [arg_ty])
if *arg_ty == Ty::Int(*int_ty)
&& dst_ty
== Ty::Array {
elem: Box::new(Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
})),
len: (int_ty.width.bits() / 8) as usize,
} => {}
(CoreCallOp::IntFromLeBytes { int_ty }, [arg_ty])
if *arg_ty
== Ty::Array {
elem: Box::new(Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
})),
len: (int_ty.width.bits() / 8) as usize,
}
&& dst_ty == Ty::Int(*int_ty) => {}
(
CoreCallOp::ArrayEq { elem, len },
[
Ty::Ref {
pointee: pt1,
..
},
Ty::Ref {
pointee: pt2,
..
},
],
) if elem.is_array_eq_elem_supported()
&& **pt1
== (Ty::Array {
elem: Box::new(elem.clone()),
len: *len,
})
&& **pt2
== (Ty::Array {
elem: Box::new(elem.clone()),
len: *len,
})
&& dst_ty == Ty::Bool => {}
(
CoreCallOp::SliceIndexRange { mutability, elem },
[Ty::Ref {
mutability: in_mut,
pointee,
}, Ty::Range { elem: idx_ty }],
) if **idx_ty == usize_ty
&& elem.is_sized_no_ref()
&& (matches!(&**pointee, Ty::Slice { elem: e } if **e == *elem)
|| matches!(
&**pointee,
Ty::Array { elem: e, .. }
if **e == *elem
&& pointee.is_supported_v2_pointee()
&& pointee
.v2_layout()
.is_some_and(|(sz, _)| sz <= isize::MAX as usize)
))
&& *in_mut == *mutability
&& dst_ty
== Ty::Ref {
mutability: *mutability,
pointee: Box::new(Ty::Slice {
elem: Box::new(elem.clone()),
}),
} => {}
(
CoreCallOp::SliceIndexRangeFrom { mutability, elem },
[Ty::Ref {
mutability: in_mut,
pointee,
}, Ty::RangeFrom { elem: idx_ty }],
) if **idx_ty == usize_ty
&& elem.is_sized_no_ref()
&& (matches!(&**pointee, Ty::Slice { elem: e } if **e == *elem)
|| matches!(
&**pointee,
Ty::Array { elem: e, .. }
if **e == *elem
&& pointee.is_supported_v2_pointee()
&& pointee
.v2_layout()
.is_some_and(|(sz, _)| sz <= isize::MAX as usize)
))
&& *in_mut == *mutability
&& dst_ty
== Ty::Ref {
mutability: *mutability,
pointee: Box::new(Ty::Slice {
elem: Box::new(elem.clone()),
}),
} => {}
(
CoreCallOp::SliceIsEmpty { elem },
[Ty::Ref { pointee, .. }],
) if elem.is_sized_no_ref()
&& matches!(&**pointee, Ty::Slice { elem: e } if **e == *elem)
&& dst_ty == Ty::Bool => {}
(
CoreCallOp::SliceSplitAt { mutability, elem },
[Ty::Ref {
mutability: in_mut,
pointee,
}, mid_ty],
) if *mid_ty == usize_ty
&& elem.is_sized_no_ref()
&& matches!(&**pointee, Ty::Slice { elem: e } if **e == *elem)
&& *in_mut == *mutability
&& dst_ty
== Ty::Tuple {
fields: vec![
Ty::Ref {
mutability: *mutability,
pointee: Box::new(Ty::Slice {
elem: Box::new(elem.clone()),
}),
},
Ty::Ref {
mutability: *mutability,
pointee: Box::new(Ty::Slice {
elem: Box::new(elem.clone()),
}),
},
],
} => {}
(
CoreCallOp::NumIsMultipleOf(ity)
| CoreCallOp::NumNextMultipleOf(ity)
| CoreCallOp::NumDivCeil(ity),
[l_ty, r_ty],
) if !ity.signed
&& *l_ty == Ty::Int(*ity)
&& *r_ty == Ty::Int(*ity)
&& dst_ty
== if matches!(op, CoreCallOp::NumIsMultipleOf(_)) {
Ty::Bool
} else {
Ty::Int(*ity)
} => {}
(
CoreCallOp::NumCheckedAdd(ity)
| CoreCallOp::NumCheckedMul(ity)
| CoreCallOp::NumCheckedSub(ity),
[l_ty, r_ty],
) if *l_ty == Ty::Int(*ity)
&& *r_ty == Ty::Int(*ity)
&& dst_ty
== Ty::Option {
elem: Box::new(Ty::Int(*ity)),
} => {}
(CoreCallOp::NumCheckedShl(ity), [l_ty, r_ty])
if *l_ty == Ty::Int(*ity)
&& *r_ty
== Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
})
&& dst_ty
== Ty::Option {
elem: Box::new(Ty::Int(*ity)),
} => {}
(CoreCallOp::NumSaturatingAdd(ity), [l_ty, r_ty])
if *l_ty == Ty::Int(*ity)
&& *r_ty == Ty::Int(*ity)
&& dst_ty == Ty::Int(*ity) => {}
(
CoreCallOp::NumWrappingShl(ity) | CoreCallOp::NumWrappingShr(ity),
[l_ty, r_ty],
) if *l_ty == Ty::Int(*ity)
&& *r_ty
== Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
})
&& dst_ty == Ty::Int(*ity) => {}
(
CoreCallOp::NumLeadingZeros(ity)
| CoreCallOp::NumCountOnes(ity)
| CoreCallOp::NumTrailingZeros(ity),
[l_ty],
) if *l_ty == Ty::Int(*ity)
&& dst_ty
== Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
}) => {}
(CoreCallOp::NumNextPowerOfTwo(ity), [l_ty])
if !ity.signed
&& *l_ty == Ty::Int(*ity)
&& dst_ty == Ty::Int(*ity) => {}
(
CoreCallOp::NumOverflowingAdd(ity)
| CoreCallOp::NumOverflowingSub(ity)
| CoreCallOp::NumOverflowingMul(ity),
[l_ty, r_ty],
) if *l_ty == Ty::Int(*ity)
&& *r_ty == Ty::Int(*ity)
&& dst_ty == Ty::OverflowPair(*ity) => {}
(
CoreCallOp::CmpMin(ity) | CoreCallOp::CmpMax(ity),
[l_ty, r_ty],
) if *l_ty == Ty::Int(*ity)
&& *r_ty == Ty::Int(*ity)
&& dst_ty == Ty::Int(*ity) => {}
// `mem::replace` of plain sized data or of owned
// data, such as a payload enum or an `Option` that
// owns `Vec`/`Box` buffers
// (`Trusted.MirSemantics.execMemReplace`); its
// operands are checked below.
(
CoreCallOp::MemReplace { ty },
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, src_ty],
) if (ty.is_sized_no_ref() || ty.is_owned_data())
&& **pointee == *ty
&& *src_ty == *ty
&& dst_ty == *ty => {}
(CoreCallOp::MemSizeOf { ty }, [])
if ty.is_sized()
&& ty.is_supported_v2_local()
&& ty.v2_layout().is_some()
&& dst_ty == usize_ty => {}
(
CoreCallOp::OptionIsSome { inner } | CoreCallOp::OptionIsNone { inner },
[Ty::Ref { pointee, .. }],
) if inner.is_sized_no_ref()
&& inner.is_option_payload_supported_v2()
&& matches!(&**pointee, Ty::Option { elem } if **elem == *inner)
&& dst_ty == Ty::Bool => {}
// An `Option<inner>` that is a payload enum
// (`Trusted.MirSemantics.adtOptionShapeV2`).
(
CoreCallOp::OptionIsSome { inner } | CoreCallOp::OptionIsNone { inner },
[Ty::Ref { pointee, .. }],
) if pointee.adt_option_payload() == Some(inner)
&& dst_ty == Ty::Bool => {}
(
CoreCallOp::OptionTake { inner },
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}],
) if inner.is_sized_no_ref()
&& inner.is_option_payload_supported_v2()
&& matches!(&**pointee, Ty::Option { elem } if **elem == *inner)
&& dst_ty
== Ty::Option {
elem: Box::new(inner.clone()),
} => {}
(CoreCallOp::OptionUnwrap { inner }, [opt_ty])
if *opt_ty
== Ty::Option {
elem: Box::new(inner.clone()),
}
&& dst_ty == *inner => {}
(
CoreCallOp::PanicAbort,
[Ty::Ref {
mutability: Mutability::Shared,
pointee,
}],
) if **pointee == Ty::Str && dst_ty == Ty::Never => {}
// `?` (`Trusted.MirSemantics.adtResultShapeV2`,
// `adtResultResidualV2`, `adtOptionResidualV2`, and
// `adtControlFlowV2`): `branch` maps a `Result` or
// `Option` to `ControlFlow<residual, T>`, and
// `from_residual` maps the residual back, with the
// same error type on both sides.
(CoreCallOp::TryBranchResult { ok, err }, [src_ty])
if src_ty.adt_result_payloads() == Some((ok, err))
&& dst_ty.adt_control_flow_payloads().is_some_and(|(c, b)| {
c == ok && b.adt_result_payloads() == Some((&Ty::Never, err))
}) => {}
(CoreCallOp::TryBranchOption { inner }, [src_ty])
if (*src_ty == Ty::Option { elem: Box::new(inner.clone()) }
|| src_ty.adt_option_payload() == Some(inner))
&& dst_ty.adt_control_flow_payloads().is_some_and(|(c, b)| {
c == inner && b.adt_option_payload() == Some(&Ty::Never)
}) => {}
(CoreCallOp::FromResidualResult { ok, err }, [src_ty])
if src_ty.adt_result_payloads() == Some((&Ty::Never, err))
&& dst_ty.adt_result_payloads() == Some((ok, err)) => {}
(CoreCallOp::FromResidualOption { inner }, [src_ty])
if src_ty.adt_option_payload() == Some(&Ty::Never)
&& (dst_ty == Ty::Option { elem: Box::new(inner.clone()) }
|| dst_ty.adt_option_payload() == Some(inner)) => {}
(CoreCallOp::DefaultVal { ty }, [])
if matches!(ty, Ty::Int(_) | Ty::Bool) && dst_ty == *ty => {}
(
CoreCallOp::RefIntPartialEq { int_ty, .. },
[
Ty::Ref {
mutability: Mutability::Shared,
pointee: pt1,
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: pt2,
},
],
) if matches!(
(&**pt1, &**pt2),
(
Ty::Ref {
mutability: Mutability::Shared,
pointee: inner1,
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: inner2,
},
) if **inner1 == Ty::Int(*int_ty) && **inner2 == Ty::Int(*int_ty)
) && dst_ty == Ty::Bool => {}
(
CoreCallOp::UnitPartialEq { .. },
[
Ty::Ref { pointee: pt1, .. },
Ty::Ref { pointee: pt2, .. },
],
) if **pt1 == Ty::Unit && **pt2 == Ty::Unit && dst_ty == Ty::Bool => {}
(
CoreCallOp::ScalarClone { ty },
[Ty::Ref { mutability: Mutability::Shared, pointee }],
) if matches!(ty, Ty::Bool | Ty::Char | Ty::Int(_))
&& **pointee == *ty
&& dst_ty == *ty => {}
(CoreCallOp::VecNew { elem }, [])
if elem.is_owned_data()
&& dst_ty == Ty::Vec { elem: Box::new(elem.clone()) } => {}
(CoreCallOp::VecWithCapacity { elem }, [cap_ty])
if elem.is_owned_data()
&& *cap_ty == usize_ty
&& dst_ty == Ty::Vec { elem: Box::new(elem.clone()) } => {}
(CoreCallOp::VecLen, [Ty::Ref { pointee, .. }])
if matches!(&**pointee, Ty::Vec { .. }) && dst_ty == usize_ty => {}
(
CoreCallOp::VecPush,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, val_ty],
) if matches!(&**pointee, Ty::Vec { elem } if **elem == *val_ty)
&& dst_ty == Ty::Unit => {}
(
CoreCallOp::VecResize,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, len_ty, val_ty],
) if matches!(&**pointee, Ty::Vec { elem } if **elem == *val_ty)
&& *len_ty == usize_ty
&& dst_ty == Ty::Unit => {}
(
CoreCallOp::VecExtendFromSlice,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, Ty::Ref {
pointee: slice_pt,
..
}],
) if matches!(
(&**pointee, &**slice_pt),
(Ty::Vec { elem: ve }, Ty::Slice { elem: se }) if ve == se
) && dst_ty == Ty::Unit => {}
(CoreCallOp::VecIndex, [Ty::Ref { pointee, .. }, idx_ty])
if *idx_ty == usize_ty
&& matches!(
(&**pointee, &dst_ty),
(
Ty::Vec { elem },
Ty::Ref {
mutability: Mutability::Shared,
pointee: dpt,
}
) if elem == dpt
) => {}
(
CoreCallOp::VecIndexMut,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, idx_ty],
) if *idx_ty == usize_ty
&& matches!(
(&**pointee, &dst_ty),
(
Ty::Vec { elem },
Ty::Ref {
mutability: Mutability::Mut,
pointee: dpt,
}
) if elem == dpt
) => {}
(CoreCallOp::VecDeref, [Ty::Ref { pointee, .. }])
if matches!(
(&**pointee, &dst_ty),
(
Ty::Vec { elem },
Ty::Ref {
mutability: Mutability::Shared,
pointee: dpt,
}
) if matches!(&**dpt, Ty::Slice { elem: se } if se == elem)
) => {}
(
CoreCallOp::VecDerefMut,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}],
) if matches!(
(&**pointee, &dst_ty),
(
Ty::Vec { elem },
Ty::Ref {
mutability: Mutability::Mut,
pointee: dpt,
}
) if matches!(&**dpt, Ty::Slice { elem: se } if se == elem)
) => {}
(
CoreCallOp::VecReserve,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}, add_ty],
) if matches!(&**pointee, Ty::Vec { .. })
&& *add_ty == usize_ty
&& dst_ty == Ty::Unit => {}
(CoreCallOp::BoxFromVec, [Ty::Vec { elem }])
if matches!(
&dst_ty,
Ty::Box { pointee }
if matches!(&**pointee, Ty::Slice { elem: se } if se == elem)
) => {}
(CoreCallOp::BoxDeref, [Ty::Ref { pointee, .. }])
if matches!(
(&**pointee, &dst_ty),
(
Ty::Box { pointee: inner },
Ty::Ref {
mutability: Mutability::Shared,
pointee: dpt,
}
) if inner == dpt
) => {}
(
CoreCallOp::BoxDerefMut,
[Ty::Ref {
mutability: Mutability::Mut,
pointee,
}],
) if matches!(
(&**pointee, &dst_ty),
(
Ty::Box { pointee: inner },
Ty::Ref {
mutability: Mutability::Mut,
pointee: dpt,
}
) if inner == dpt
) => {}
(CoreCallOp::BoxClone, [Ty::Ref { pointee, .. }])
if matches!(&**pointee, Ty::Box { .. }) && **pointee == dst_ty => {}
(CoreCallOp::BoxNew { pointee }, [val_ty])
if *val_ty == *pointee
&& pointee.is_owned_data()
&& dst_ty
== Ty::Box {
pointee: Box::new(pointee.clone()),
} => {}
(
CoreCallOp::PartialEqNe { ty },
[Ty::Ref { pointee: pt1, .. }, Ty::Ref { pointee: pt2, .. }],
) if ty.is_array_eq_elem_supported()
&& **pt1 == *ty
&& **pt2 == *ty
&& dst_ty == Ty::Bool => {}
_ => {
return Err(format!(
"invalid CoreCall {op:?} arguments {arg_tys:?} -> {dst_ty:?}"
));
}
}
// `mem::replace` and `Option::take` overwrite `*dest` and
// return the old value, mirroring
// `Trusted.MirSemantics.coreCallOperandsAdmittedV2`. The
// moved operands and the destination must be distinct
// unprojected locals, and a value that owns heap buffers
// must be moved in or passed as a heap-free constant, never
// copied, so no buffer gets two owners. Note that Lean's
// `coreCallOperandsAdmittedV2` additionally requires the
// destination local not to be indirect at runtime.
match op {
CoreCallOp::MemReplace { ty } => {
check_move_disjoint(args, dst.local)?;
if ty.has_heap_handle_v2()
&& !matches!(
args.get(1),
Some(Operand::Move { .. } | Operand::Constant { .. })
)
{
return Err(format!(
"mem::replace of {ty:?}, which owns heap buffers, \
requires a moved or constant source operand"
));
}
}
CoreCallOp::OptionTake { .. } => check_move_disjoint(args, dst.local)?,
_ => {}
}
let is_diverging_panic = matches!(op, CoreCallOp::PanicAbort);
match (is_diverging_panic, target) {
(true, None) => {}
(false, Some(target_block)) => check_block(*target_block)?,
(true, Some(_)) => {
return Err(format!(
"diverging panic CoreCall {op:?} must not have a return target"
));
}
(false, None) => {
return Err(format!(
"returning CoreCall {op:?} must have a return target"
));
}
}
}
Terminator::Call {
args, dst, target, ..
}
| Terminator::CallNe {
args, dst, target, ..
} => {
let arg_tys = args
.iter()
.map(|op| check_operand(&local_tys, op))
.collect::<Result<Vec<_>, _>>()?;
let dst_ty = check_local(&local_tys, *dst, "call destination")?;
check_move_disjoint(args, *dst)?;
if let Terminator::CallNe { .. } = &block.terminator {
// The provided `ne` compares two `&Self` of one
// admitted crate-local type and returns `bool`.
let comparable = match arg_tys.as_slice() {
[Ty::Ref { pointee: l, .. }, Ty::Ref { pointee: r, .. }] => {
l == r
&& matches!(
&**l,
Ty::Enum(_)
| Ty::Struct(_)
| Ty::AdtEnum(_)
| Ty::RecAdt { .. }
)
}
_ => false,
};
if !comparable || *dst_ty != Ty::Bool || target.is_none() {
return Err(format!(
"invalid PartialEq::ne call {arg_tys:?} -> {dst_ty:?}"
));
}
}
if let Some(target_block) = target {
check_block(*target_block)?;
}
}
Terminator::CallVia {
via,
args,
dst,
target,
..
} => {
let arg_tys = args
.iter()
.map(|op| check_operand(&local_tys, op))
.collect::<Result<Vec<_>, _>>()?;
let dst_ty = check_local(&local_tys, *dst, "call destination")?;
check_move_disjoint(args, *dst)?;
match via {
// `<&A as PartialEq<&A>>::{eq, ne}` compares two
// `&&A` of one admitted crate-local type and returns
// `bool`.
CallVia::RefPartialEq { .. } => {
let shared_ref_pointee = |t: &Ty| match t {
Ty::Ref {
mutability: Mutability::Shared,
pointee,
} => match &**pointee {
Ty::Ref {
mutability: Mutability::Shared,
pointee,
} => Some((**pointee).clone()),
_ => None,
},
_ => None,
};
let comparable = match arg_tys.as_slice() {
[l, r] => match (shared_ref_pointee(l), shared_ref_pointee(r)) {
(Some(l), Some(r)) => {
l == r
&& matches!(
l,
Ty::Enum(_)
| Ty::Struct(_)
| Ty::AdtEnum(_)
| Ty::RecAdt { .. }
)
}
_ => false,
},
_ => false,
};
if !comparable || *dst_ty != Ty::Bool || target.is_none() {
return Err(format!(
"invalid reference PartialEq call {arg_tys:?} -> {dst_ty:?}"
));
}
}
// `PartialOrd::{lt, le, gt, ge}` compares two `&A`
// of one admitted crate-local type and returns
// `bool`.
CallVia::PartialOrd { .. } => {
let comparable = match arg_tys.as_slice() {
[
Ty::Ref {
mutability: Mutability::Shared,
pointee: l,
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: r,
},
] => {
l == r
&& matches!(
**l,
Ty::Enum(_)
| Ty::Struct(_)
| Ty::AdtEnum(_)
| Ty::RecAdt { .. }
)
}
_ => false,
};
if !comparable || *dst_ty != Ty::Bool || target.is_none() {
return Err(format!(
"invalid PartialOrd comparison call {arg_tys:?} -> {dst_ty:?}"
));
}
}
// `Box::clone` takes `&Box<T>` and returns `Box<T>`.
CallVia::BoxClone { pointee } => {
let boxed = Ty::Box {
pointee: Box::new(pointee.clone()),
};
let self_ty = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(boxed.clone()),
};
if arg_tys != [self_ty] || *dst_ty != boxed || target.is_none() {
return Err(format!(
"invalid Box::clone call {arg_tys:?} -> {dst_ty:?}"
));
}
}
}
if let Some(target_block) = target {
check_block(*target_block)?;
}
}
Terminator::SysrootCall {
op,
args,
dst,
target,
..
} => {
if args.len() != 2 {
return Err(format!(
"sysroot numeric call expects 2 arguments, got {}",
args.len()
));
}
let expected_ty = Ty::Int(op.ty);
for (idx, arg) in args.iter().enumerate() {
let arg_ty = check_operand(&local_tys, arg)?;
if arg_ty != expected_ty {
return Err(format!(
"sysroot numeric call argument {idx} type {arg_ty:?} \
disagrees with {expected_ty:?}"
));
}
}
let dst_ty = check_local(&local_tys, *dst, "sysroot call destination")?;
if *dst_ty != expected_ty {
return Err(format!(
"sysroot numeric call destination type {dst_ty:?} \
disagrees with {expected_ty:?}"
));
}
check_move_disjoint(args, *dst)?;
if let Some(target_block) = target {
check_block(*target_block)?;
}
}
Terminator::Drop { place, target, .. } => {
// `Trusted.MirSemantics.evalTerminatorV2` executes a
// `Drop` of an unprojected local; of `*r` or `*r` followed
// by field and (constant) index projections with
// `r: &mut T` (the drop half of `*r = new`,
// `(*r).f = new`, and `(*r).f[i] = new`): through the
// handle readers for a `Vec` or `Box` pointee and
// `dropDerefPlaceV2` otherwise, which requires a supported
// leaf type with drop glue; of a field `t.i` of a tuple
// local, moved out as by `Operand.move`; and of field and
// (constant) index projections of a local (`s.f[i]`),
// dropped in its stack allocation (`dropLocalPlaceV2`).
// It faults on every other place.
let base = check_local(&local_tys, place.local, "drop")?;
match place.projection.as_slice() {
[] => {}
[PlaceElem::Deref] if matches!(
base,
Ty::Ref { mutability: Mutability::Mut, pointee }
if matches!(**pointee, Ty::Vec { .. } | Ty::Box { .. })
) => {}
[PlaceElem::Deref, rest @ ..]
if rest.iter().all(|e| {
matches!(
e,
PlaceElem::Field { .. }
| PlaceElem::Index { .. }
| PlaceElem::ConstantIndex { .. }
)
}) =>
{
if !matches!(
base,
Ty::Ref { mutability: Mutability::Mut, pointee }
if pointee.is_sized()
) {
return Err(format!(
"Drop through a dereference of {base:?} is unsupported; \
only `&mut T` with a sized `T` is admitted"
));
}
let leaf = check_place(&local_tys, place, "drop", false, true, true)?;
if !leaf.is_supported_v2_local() || !leaf.needs_drop_v2() {
return Err(format!(
"Drop through a dereference to {leaf:?} is unsupported; \
the dropped type must be a supported local type \
with drop glue"
));
}
}
rest if rest.iter().all(|e| {
matches!(
e,
PlaceElem::Field { .. }
| PlaceElem::Index { .. }
| PlaceElem::ConstantIndex { .. }
| PlaceElem::Downcast { .. }
)
}) =>
{
// A field chain of a tuple held directly in its
// slot (fields and variants only) is moved out
// (`moveTuplePathV2` when nested) and its glue run;
// every other such place is dropped in the local's
// stack allocation (`dropLocalPlaceV2`), which
// needs a layout. A variant field (`(l.f as V).i`)
// has its glue run in place.
let tuple_path = matches!(base, Ty::Tuple { .. })
&& matches!(rest.first(), Some(PlaceElem::Field { .. }))
&& rest.iter().all(|e| {
matches!(
e,
PlaceElem::Field { .. } | PlaceElem::Downcast { .. }
)
})
&& (rest.len() == 1
|| rest[1..]
.iter()
.any(|e| matches!(e, PlaceElem::Downcast { .. })));
if !tuple_path && base.v2_layout().is_none() {
return Err(format!(
"Drop of a projection of {base:?} is unsupported; \
the local must have a Profile v2 layout"
));
}
let leaf =
check_place(&local_tys, place, "drop", false, false, !tuple_path)?;
if !leaf.is_supported_v2_local() || !leaf.needs_drop_v2() {
return Err(format!(
"Drop of a projection of type {leaf:?} is unsupported; \
the dropped type must be a supported local type \
with drop glue"
));
}
}
_ => {
return Err("Drop place must be an unprojected local, a local \
or a dereference of `&mut T` followed by field \
and index projections"
.into());
}
}
check_block(*target)?;
}
Terminator::Ret | Terminator::Unreachable | Terminator::Unsupported => {}
}
}
Ok(Self {
arg_count,
is_unsafe,
local_tys,
blocks,
identity,
is_external: false,
abi,
callees,
})
}
pub fn arg_count(&self) -> usize {
self.arg_count
}
pub fn is_unsafe(&self) -> bool {
self.is_unsafe
}
pub fn is_external(&self) -> bool {
self.is_external
}
pub const fn abi(&self) -> AbiKind {
self.abi
}
pub fn local_tys(&self) -> &[Ty] {
&self.local_tys
}
pub fn blocks(&self) -> &[Block] {
&self.blocks
}
pub fn identity(&self) -> &str {
&self.identity
}
/// Whether this body requires Profile v2 execution rules
/// (`mir_profile_version = 2`).
#[cfg(test)]
pub fn uses_profile_v2(&self) -> bool {
self.profile_v2_trigger().is_some()
}
/// The first construct in this body that requires Profile v2 execution
/// rules, described for diagnostics, or `None` if the body stays in
/// Profile v1.
///
/// [`Program::try_new_with_options`] names this construct when it refuses
/// a Profile v1 call, so users can find which body selected Profile v2.
pub fn profile_v2_trigger(&self) -> Option<String> {
if self.is_external {
return Some("external stub declaration".into());
}
let v2_local = self.local_tys.iter().enumerate().find(|(_, ty)| ty.is_profile_v2());
if let Some((idx, ty)) = v2_local {
return Some(format!("local _{idx} has Profile v2 type {ty:?}"));
}
for (bb, block) in self.blocks.iter().enumerate() {
for (idx, stmt) in block.statements.iter().enumerate() {
match stmt {
Statement::AssignPlace { .. } => {
return Some(format!("bb{bb}[{idx}]: assignment to a projected place"));
}
// Profile v1 faults on a projected `PlaceMention`.
Statement::PlaceMentionPlace { .. } => {
return Some(format!("bb{bb}[{idx}]: projected `PlaceMention`"));
}
Statement::Assign { value, .. } => match value {
Rvalue::Use { operand, .. } => {
if operand.is_profile_v2() {
return Some(format!("bb{bb}[{idx}]: `Use` of {operand:?}"));
}
}
Rvalue::Binary { op, left, right } => {
if *op == BinOp::Offset || left.is_profile_v2() || right.is_profile_v2()
{
return Some(format!(
"bb{bb}[{idx}]: binary `{op:?}` of {left:?}, {right:?}"
));
}
}
Rvalue::Unary { op, operand } => {
if *op == UnOp::PtrMetadata || operand.is_profile_v2() {
return Some(format!(
"bb{bb}[{idx}]: unary `{op:?}` of {operand:?}"
));
}
}
Rvalue::Cast {
cast_kind,
operand,
ty,
} => {
if *cast_kind != CastKind::IntToInt
|| operand.is_profile_v2()
|| ty.is_profile_v2()
{
return Some(format!(
"bb{bb}[{idx}]: `{cast_kind:?}` cast of {operand:?} to {ty:?}"
));
}
}
Rvalue::Discriminant { place } => {
if !place.projection.is_empty() {
return Some(format!(
"bb{bb}[{idx}]: `Discriminant` of projected {place:?}"
));
}
}
Rvalue::UseRetag { .. }
| Rvalue::Ref { .. }
| Rvalue::AddressOf { .. }
| Rvalue::FakeAddressOf { .. }
| Rvalue::AggregateTuple { .. }
| Rvalue::AggregateArray { .. }
| Rvalue::AggregateStruct { .. }
| Rvalue::Repeat { .. }
| Rvalue::AggregateRangeTo { .. }
| Rvalue::AggregateRangeFrom { .. }
| Rvalue::AggregateRange { .. }
| Rvalue::AggregateOption { .. }
| Rvalue::AggregateAdtEnum { .. }
| Rvalue::AggregateOrdering { .. } => {
return Some(format!("bb{bb}[{idx}]: rvalue {value:?}"));
}
},
Statement::StorageLive { .. }
| Statement::StorageDead { .. }
| Statement::PlaceMention { .. }
| Statement::Nop => {}
}
}
match &block.terminator {
Terminator::SwitchInt { operand, .. } => {
if operand.is_profile_v2() {
return Some(format!("bb{bb} terminator: `SwitchInt` on {operand:?}"));
}
}
// Profile v1 `evalTerminator` already models `Assert` for
// primitive conditions with `lean-miri` correspondence
// (`CanaryD17AssertPanicAbortClaim`); route to Profile v2 only
// when `cond` requires Profile v2 or `msg` is an optional
// arithmetic overflow assert outside Profile v1's domain.
Terminator::Assert { cond, msg, .. }
=> {
if cond.is_profile_v2()
|| !matches!(
msg,
AssertKind::DivByZero
| AssertKind::RemByZero
| AssertKind::Overflow {
op: BinOp::Div | BinOp::Rem
}
| AssertKind::BoundsCheck
| AssertKind::MisalignedPtrDeref
| AssertKind::NullPtrDeref
)
{
return Some(format!("bb{bb} terminator: `Assert` ({msg:?}) on {cond:?}"));
}
}
Terminator::CoreCall { op, .. } => {
return Some(format!("bb{bb} terminator: core call {op:?}"));
}
Terminator::CallNe { eq_callee, .. } => {
return Some(format!("bb{bb} terminator: `PartialEq::ne` via body {eq_callee}"));
}
Terminator::CallVia { via, callee, .. } => {
return Some(format!("bb{bb} terminator: `{via:?}` via body {callee}"));
}
Terminator::Drop { place, .. } => {
return Some(format!("bb{bb} terminator: `Drop` of {place:?}"));
}
// Intra-crate calls and `core::num` sysroot calls are admitted
// in both profiles.
Terminator::Call { .. }
| Terminator::SysrootCall { .. }
| Terminator::Goto { .. }
| Terminator::Ret
| Terminator::Unreachable
| Terminator::Unsupported => {}
}
}
None
}
pub fn callees(&self) -> &BTreeSet<String> {
&self.callees
}
/// Deterministic AST-node weight used for sharding budgets, counting local
/// types, basic blocks, and exact `_root_.String.ofList` and
/// `_root_.Char.ofNat` identity chunk nodes matching `lean.rs`.
pub fn ast_nodes(&self) -> usize {
self.identity_ast_nodes()
+ self.local_tys.iter().map(Ty::ast_nodes).sum::<usize>()
+ self.blocks.iter().map(Block::ast_nodes).sum::<usize>()
}
fn identity_ast_nodes(&self) -> usize {
let id_chars = self.identity.chars().count();
if id_chars == 0 {
return 1;
}
// Matches `lean::identity_at`: 16-char `_root_.String.ofList` chunks
// joined by `Trusted.MirAst.stringAppend`, with one
// `(_root_.Char.ofNat n)` term per Unicode scalar character.
let chunks = id_chars.div_ceil(16);
1 + (2 * chunks - 1) + 2 * id_chars
}
/// Record every nominal [`EnumTy::id`] referenced anywhere in this body.
///
/// Exhaustive matching guarantees that any future statement, rvalue,
/// operand, or terminator variant carrying a [`Ty`] must update this
/// traversal so emitted enum keys cannot bypass collision checks.
pub fn collect_enum_ids(&self, out: &mut BTreeSet<u32>) {
self.for_each_ty(&mut |ty| ty.collect_enum_ids(out));
}
/// Record every nominal [`StructLayout::id`] referenced anywhere in this
/// body.
pub fn collect_struct_ids(&self, out: &mut BTreeSet<u32>) {
self.for_each_ty(&mut |ty| ty.collect_struct_ids(out));
}
/// Collect every synthetic (non-local) struct in this body.
pub fn collect_synthetic_structs(&self, out: &mut Vec<StructTy>) {
self.for_each_ty(&mut |ty| ty.collect_synthetic_structs(out));
}
/// Visit every type written in this body: local types, projection field
/// types, constant types, and the types carried by rvalues and core calls.
fn for_each_ty(&self, f: &mut dyn FnMut(&Ty)) {
for ty in &self.local_tys {
f(ty);
}
for block in &self.blocks {
for stmt in &block.statements {
let (place_opt, value_opt) = match stmt {
Statement::Assign { value, .. } => (None, Some(value)),
Statement::AssignPlace { place, value } => (Some(place), Some(value)),
Statement::PlaceMentionPlace { place } => (Some(place), None),
Statement::StorageLive { .. }
| Statement::StorageDead { .. }
| Statement::PlaceMention { .. }
| Statement::Nop => (None, None),
};
if let Some(p) = place_opt {
p.for_each_ty(f);
}
if let Some(value) = value_opt {
match value {
Rvalue::Use { operand, .. }
| Rvalue::UseRetag { operand }
| Rvalue::Unary { operand, .. } => operand.for_each_ty(f),
Rvalue::Binary { left, right, .. } => {
left.for_each_ty(f);
right.for_each_ty(f);
}
Rvalue::Cast { operand, ty, .. } => {
operand.for_each_ty(f);
f(ty);
}
Rvalue::Ref { place, .. }
| Rvalue::AddressOf { place, .. }
| Rvalue::FakeAddressOf { place }
| Rvalue::Discriminant { place } => place.for_each_ty(f),
Rvalue::AggregateTuple { fields } => {
for op in fields {
op.for_each_ty(f);
}
}
Rvalue::AggregateArray { elem_ty: ty, elems: ops }
| Rvalue::AggregateStruct { ty, fields: ops }
| Rvalue::AggregateAdtEnum { ty, fields: ops, .. } => {
f(ty);
for op in ops {
op.for_each_ty(f);
}
}
Rvalue::Repeat {
operand, elem_ty, ..
}
| Rvalue::AggregateRangeTo {
elem_ty,
end: operand,
}
| Rvalue::AggregateRangeFrom {
elem_ty,
start: operand,
} => {
f(elem_ty);
operand.for_each_ty(f);
}
Rvalue::AggregateRange { elem_ty, start, end } => {
f(elem_ty);
start.for_each_ty(f);
end.for_each_ty(f);
}
Rvalue::AggregateOption {
inner_ty, payload, ..
} => {
f(inner_ty);
if let Some(op) = payload {
op.for_each_ty(f);
}
}
Rvalue::AggregateOrdering { .. } => {}
}
}
}
match &block.terminator {
Terminator::SwitchInt { operand, .. } => operand.for_each_ty(f),
Terminator::Assert { cond, .. } => cond.for_each_ty(f),
Terminator::CoreCall { op, args, dst, .. } => {
match op {
CoreCallOp::PtrAdd { pointee: ty, .. }
| CoreCallOp::MemReplace { ty }
| CoreCallOp::DefaultVal { ty }
| CoreCallOp::MemSizeOf { ty }
| CoreCallOp::BoxNew { pointee: ty }
| CoreCallOp::ArrayEq { elem: ty, .. }
| CoreCallOp::SliceIndexRange { elem: ty, .. }
| CoreCallOp::SliceIndexRangeFrom { elem: ty, .. }
| CoreCallOp::SliceIsEmpty { elem: ty }
| CoreCallOp::SliceSplitAt { elem: ty, .. }
| CoreCallOp::OptionIsSome { inner: ty }
| CoreCallOp::OptionIsNone { inner: ty }
| CoreCallOp::OptionTake { inner: ty }
| CoreCallOp::OptionUnwrap { inner: ty }
| CoreCallOp::TryBranchOption { inner: ty }
| CoreCallOp::FromResidualOption { inner: ty }
| CoreCallOp::VecNew { elem: ty }
| CoreCallOp::VecWithCapacity { elem: ty }
| CoreCallOp::PartialEqNe { ty }
| CoreCallOp::ScalarClone { ty } => f(ty),
CoreCallOp::TryBranchResult { ok, err }
| CoreCallOp::FromResidualResult { ok, err } => {
f(ok);
f(err);
}
CoreCallOp::SliceLen
| CoreCallOp::SliceGetUncheckedRangeTo
| CoreCallOp::SliceGetUncheckedRangeFrom
| CoreCallOp::SliceGetUncheckedRange
| CoreCallOp::SliceGetUncheckedIndex
| CoreCallOp::NumIsMultipleOf(_)
| CoreCallOp::NumNextMultipleOf(_)
| CoreCallOp::NumDivCeil(_)
| CoreCallOp::NumCheckedAdd(_)
| CoreCallOp::NumCheckedMul(_)
| CoreCallOp::NumCheckedSub(_)
| CoreCallOp::NumCheckedShl(_)
| CoreCallOp::NumSaturatingAdd(_)
| CoreCallOp::NumWrappingShl(_)
| CoreCallOp::NumWrappingShr(_)
| CoreCallOp::NumLeadingZeros(_)
| CoreCallOp::NumCountOnes(_)
| CoreCallOp::NumTrailingZeros(_)
| CoreCallOp::NumNextPowerOfTwo(_)
| CoreCallOp::NumOverflowingAdd(_)
| CoreCallOp::NumOverflowingSub(_)
| CoreCallOp::NumOverflowingMul(_)
| CoreCallOp::CmpMin(_)
| CoreCallOp::CmpMax(_)
| CoreCallOp::UsizeUncheckedSub
| CoreCallOp::IntToLeBytes { .. }
| CoreCallOp::IntFromLeBytes { .. }
| CoreCallOp::VecLen
| CoreCallOp::VecPush
| CoreCallOp::VecResize
| CoreCallOp::VecExtendFromSlice
| CoreCallOp::VecIndex
| CoreCallOp::VecIndexMut
| CoreCallOp::VecDeref
| CoreCallOp::VecDerefMut
| CoreCallOp::VecReserve
| CoreCallOp::BoxFromVec
| CoreCallOp::BoxDeref
| CoreCallOp::BoxDerefMut
| CoreCallOp::BoxClone
| CoreCallOp::PanicAbort
| CoreCallOp::RefIntPartialEq { .. }
| CoreCallOp::UnitPartialEq { .. } => {}
}
for a in args {
a.for_each_ty(f);
}
dst.for_each_ty(f);
}
Terminator::Call { args, .. }
| Terminator::CallNe { args, .. }
| Terminator::SysrootCall { args, .. } => {
for a in args {
a.for_each_ty(f);
}
}
Terminator::CallVia { via, args, .. } => {
match via {
CallVia::RefPartialEq { .. } | CallVia::PartialOrd { .. } => {}
CallVia::BoxClone { pointee } => f(pointee),
}
for a in args {
a.for_each_ty(f);
}
}
Terminator::Drop { place, .. } => place.for_each_ty(f),
Terminator::Goto { .. }
| Terminator::Ret
| Terminator::Unreachable
| Terminator::Unsupported => {}
}
}
}
}
/// Single authoritative capture scope recorded on [`Program`] and matching
/// the `scope` schema of `cargo-anneal verify`.
///
/// `lean::render` inspects only the enum variant (`SelectedUnit` vs `Crate`)
/// when emitting `Trusted.MirAst.VerificationScope`, so raw selector strings
/// never enter the emitted Lean subject while remaining available in
/// `capture.json` for receipt authentication.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Instantiation {
pub path: String,
pub args: Vec<String>,
}
/// Closed allowlist of formatting and diagnostic traits whose crate-local
/// impls may be excluded from `--scope crate` capture once proven unreachable
/// from every verified body.
///
/// Variant order matches lexicographical canonical path order so
/// `BTreeSet<ExcludedTrait>` serializes deterministically.
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Deserialize, serde::Serialize,
)]
pub enum ExcludedTrait {
#[serde(rename = "core::error::Error")]
Error,
#[serde(rename = "core::fmt::Debug")]
Debug,
#[serde(rename = "core::fmt::Display")]
Display,
}
impl ExcludedTrait {
pub const fn as_str(self) -> &'static str {
match self {
Self::Error => "core::error::Error",
Self::Debug => "core::fmt::Debug",
Self::Display => "core::fmt::Display",
}
}
pub fn parse_canonical(raw: &str) -> Result<Self, String> {
match raw {
"core::error::Error" => Ok(Self::Error),
"core::fmt::Debug" => Ok(Self::Debug),
"core::fmt::Display" => Ok(Self::Display),
_ => Err(format!(
"trait `{raw}` is not in the closed --exclude-trait allowlist \
(allowed: core::error::Error, core::fmt::Debug, core::fmt::Display)"
)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Scope {
SelectedUnit {
roots: BTreeSet<String>,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
instantiations: BTreeSet<Instantiation>,
},
Crate {
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
excluded_traits: BTreeSet<ExcludedTrait>,
},
}
/// Validated captured program enforcing non-empty selected-unit targets,
/// non-empty bodies, and pairwise-distinct function identities
/// (`Trusted.MirSemantics.bodiesHaveUniqueIdentities`).
#[derive(Debug, Serialize)]
pub struct Program {
scope: Scope,
overflow_checks: bool,
panic: PanicStrategy,
has_local_panic_handler: bool,
mir_profile_version: u32,
bodies: Vec<Body>,
}
impl Program {
#[cfg(test)]
pub fn try_new(scope: Scope, bodies: Vec<Body>) -> Result<Self, String> {
Self::try_new_with_options(scope, false, PanicStrategy::Unwind, false, bodies)
}
pub fn try_new_with_options(
scope: Scope,
overflow_checks: bool,
panic: PanicStrategy,
has_local_panic_handler: bool,
bodies: Vec<Body>,
) -> Result<Self, String> {
if let Scope::SelectedUnit { roots, instantiations } = &scope
&& roots.is_empty()
&& instantiations.is_empty()
{
return Err("selected-unit scope must contain at least one root or instantiation".into());
}
if bodies.is_empty() {
return Err("captured program contains no executable bodies".into());
}
let mut identities = BTreeSet::new();
for body in &bodies {
if !identities.insert(body.identity.as_str()) {
return Err(format!(
"ambiguous captured function identity: {}",
body.identity
));
}
}
check_rec_tys(bodies.iter().flat_map(|b| b.local_tys.iter()))?;
for body in &bodies {
for block in &body.blocks {
if let Terminator::CallVia {
via,
callee,
args,
dst,
..
} = &block.terminator
{
let callee_body = bodies.get(*callee).ok_or_else(|| {
format!(
"call target body index {callee} out of bounds for {} bodies",
bodies.len()
)
})?;
check_call_via_callee(&body.local_tys, via, args, *dst, callee_body)?;
}
if let Terminator::Call {
callee, args, dst, ..
}
| Terminator::CallNe {
eq_callee: callee,
args,
dst,
..
} = &block.terminator
{
let callee_body = bodies.get(*callee).ok_or_else(|| {
format!(
"call target body index {callee} out of bounds for {} bodies",
bodies.len()
)
})?;
if args.len() != callee_body.arg_count {
return Err(format!(
"call argument count {} disagrees with callee {} arity {}",
args.len(),
callee_body.identity,
callee_body.arg_count
));
}
let dst_ty = &body.local_tys[*dst as usize];
if *dst_ty != callee_body.local_tys[0] {
return Err(format!(
"call destination type {dst_ty:?} disagrees with callee {} return type {:?}",
callee_body.identity,
callee_body.local_tys[0]
));
}
for (idx, arg) in args.iter().enumerate() {
let arg_ty = match arg {
Operand::Copy { local } | Operand::Move { local } => {
&body.local_tys[*local as usize]
}
Operand::Constant { ty, .. } => ty,
Operand::CopyPlace { .. } | Operand::MovePlace { .. } => {
return Err(format!(
"call argument {idx} must be an unprojected local or constant"
));
}
};
let param_ty = &callee_body.local_tys[1 + idx];
if arg_ty != param_ty {
return Err(format!(
"call argument {idx} type {arg_ty:?} disagrees with callee {} parameter type {param_ty:?}",
callee_body.identity
));
}
}
}
}
}
let uses_profile_v2 = bodies.iter().any(|body| body.profile_v2_trigger().is_some());
let mir_profile_version = if uses_profile_v2 { 2 } else { 1 };
Ok(Self {
scope,
overflow_checks,
panic,
has_local_panic_handler,
mir_profile_version,
bodies,
})
}
pub fn scope(&self) -> &Scope {
&self.scope
}
pub fn overflow_checks(&self) -> bool {
self.overflow_checks
}
pub fn panic(&self) -> PanicStrategy {
self.panic
}
pub fn has_local_panic_handler(&self) -> bool {
self.has_local_panic_handler
}
pub fn mir_profile_version(&self) -> u32 {
self.mir_profile_version
}
pub fn bodies(&self) -> &[Body] {
&self.bodies
}
}
/// Linkage mode observed for `rustc_driver::run_compiler` in the live process.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DriverLinkage {
/// `rustc_driver::run_compiler` lives in a dynamically loaded
/// `librustc_driver-*.so` verified against the sysroot.
DynamicDso,
/// `rustc_driver::run_compiler` is statically linked into the capture
/// executable itself (zero `librustc_driver-*.so` mapped).
StaticExe,
}
/// Authenticated compiler driver identity returned by Linux residency checks
/// and recorded in the capture manifest.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct DriverIdentity {
pub linkage: DriverLinkage,
pub driver_sha256: String,
pub dso_digests: BTreeMap<String, String>,
}
#[derive(Debug, Serialize)]
pub struct Compiler {
pub commit: &'static str,
pub version: &'static str,
pub sysroot: PathBuf,
pub rustc_sha256: String,
pub driver: DriverIdentity,
}
/// Standard-library crate admitted by the explicit `--stdlib-crate`
/// capability. Only `core` is modeled: it links no other crate, so all of its
/// language items are its own definitions. `alloc` and `std` additionally
/// need hashed `--extern` admission and are not representable here yet.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StdlibCrate {
Core,
}
impl StdlibCrate {
pub const fn crate_name(self) -> &'static str {
match self {
Self::Core => "core",
}
}
}
#[derive(Debug, Serialize)]
pub struct Configuration {
pub crate_root: PathBuf,
pub crate_name: String,
pub crate_type: CrateType,
pub panic: PanicStrategy,
pub edition: String,
pub target: String,
pub cfg: Vec<String>,
pub env: BTreeMap<String, String>,
pub opt_level: u8,
pub debug_assertions: bool,
pub overflow_checks: bool,
pub mir_preserve_ub: bool,
pub pointer_bits: u64,
pub endian: &'static str,
pub declared_source_files: Vec<PathBuf>,
/// Present only under the explicit `--stdlib-crate` capability, which
/// admits crate-local language items and selection-only metadata
/// emission (see `capture::check_stdlib_capability`). Omitted otherwise
/// so default captures keep their exact manifest bytes, and so a receipt
/// that embeds this configuration discloses every relaxation in effect.
#[serde(skip_serializing_if = "Option::is_none")]
pub stdlib_crate: Option<StdlibCrate>,
/// Unstable features the operator admitted on a normal crate with
/// `--allow-unstable-feature` (sorted). This and the following feature
/// lists are omitted when empty, so default captures keep their exact
/// manifest bytes.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub allowed_unstable_features: Vec<String>,
/// Unstable features that `tcx.features()` reports the crate enabled
/// (sorted), each a member of `allowed_unstable_features`.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub observed_unstable_features: Vec<String>,
/// The subset of `observed_unstable_features` that `rustc` marks
/// incomplete (sorted).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub incomplete_observed_unstable_features: Vec<String>,
/// Language features the crate enables with `#![feature(...)]` that the
/// pinned compiler has already stabilized (sorted). They activate no
/// unstable behavior and do not taint.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub stabilized_features_present: Vec<String>,
/// Canonical paths explicitly stubbed via `--assume-stub` or
/// `#[anneal::assume_stub(reason = "...")]` (sorted and deduplicated).
/// Omitted when empty so default captures keep their exact manifest bytes.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub assumed_stubs: Vec<String>,
/// True only when `--allow-foreign-exports` was explicitly passed to
/// `anneal-rustc-capture` to admit non-variadic, non-unwinding foreign-ABI
/// export definitions and emit `ffi_exports.json`. Omitted when false so
/// default Rust-only captures keep their exact manifest bytes.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub allow_foreign_exports: bool,
}
#[derive(Clone, Debug, Serialize)]
pub struct SourceFile {
pub path: PathBuf,
pub sha256: String,
pub read_kind: &'static str,
}
/// Inventory every compiler definition independently of successful translation.
/// Separate required/selected flags expose unsupported unselected items without
/// implying that a selected-unit proof covers them.
#[derive(Debug, Serialize)]
pub struct CensusItem {
pub def_id: u32,
pub path: String,
pub kind: String,
pub has_body: bool,
pub selected: bool,
pub required: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub excluded_by: Option<ExcludedTrait>,
#[serde(skip_serializing_if = "Option::is_none")]
pub assumed_stub_reason: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct SelectedBody {
pub def_id: u32,
pub path: String,
pub body_index: usize,
}
#[derive(Debug, Serialize)]
pub struct Unsupported {
pub def_id: u32,
pub path: String,
pub reason: String,
}
/// Bind the proof subject to the compilation and observed input evidence.
/// JSON metadata supports host authentication and coverage checks, with
/// `program.scope` serving as the single authoritative scope for both receipt
/// authentication and `lean::render`; only the owned `program` constructors
/// are rendered into the Lean subject.
#[derive(Debug, Serialize)]
pub struct Manifest {
pub schema_version: u32,
pub compiler: Compiler,
pub configuration: Configuration,
pub source_files: Vec<SourceFile>,
pub census: Vec<CensusItem>,
pub selected: Vec<SelectedBody>,
pub unsupported: Vec<Unsupported>,
pub program: Program,
}
impl Manifest {
/// Permute `program.bodies` into canonical callee-first shard order
/// (`new_bodies[new_idx] = old_bodies[permutation[new_idx]]`) while
/// remapping every `selected[i].body_index` to its new `DefId`.
pub fn reorder_bodies(&mut self, permutation: &[usize]) -> Result<(), String> {
let n = self.program.bodies.len();
if permutation.len() != n {
return Err(format!(
"body permutation length {} disagrees with body count {n}",
permutation.len()
));
}
let mut old_to_new = vec![None; n];
for (new_idx, &old_idx) in permutation.iter().enumerate() {
let Some(slot) = old_to_new.get_mut(old_idx) else {
return Err(format!("body permutation index {old_idx} out of bounds for {n}"));
};
if slot.is_some() {
return Err(format!("duplicate body index {old_idx} in permutation"));
}
*slot = Some(new_idx);
}
let mut old_opts: Vec<Option<Body>> =
std::mem::take(&mut self.program.bodies).into_iter().map(Some).collect();
let mut new_bodies = Vec::with_capacity(n);
for &old_idx in permutation {
let mut body = old_opts[old_idx]
.take()
.ok_or_else(|| format!("missing body at {old_idx}"))?;
// Remap every intra-crate callee body index into the new
// canonical callee-first body numbering so call targets stay bound
// to the exact same `Body` after sharding. The match is exhaustive
// so that a new terminator with a body index cannot be missed.
for block in &mut body.blocks {
let callee = match &mut block.terminator {
Terminator::Call { callee, .. }
| Terminator::CallNe {
eq_callee: callee, ..
}
| Terminator::CallVia { callee, .. } => callee,
Terminator::Goto { .. }
| Terminator::SwitchInt { .. }
| Terminator::Assert { .. }
| Terminator::CoreCall { .. }
| Terminator::SysrootCall { .. }
| Terminator::Drop { .. }
| Terminator::Ret
| Terminator::Unreachable
| Terminator::Unsupported => continue,
};
*callee = old_to_new
.get(*callee)
.and_then(|opt| *opt)
.ok_or_else(|| format!("call callee index {} out of bounds", *callee))?;
}
new_bodies.push(body);
}
self.program = Program::try_new_with_options(
self.program.scope.clone(),
self.program.overflow_checks,
self.program.panic,
self.program.has_local_panic_handler,
new_bodies,
)?;
for sel in &mut self.selected {
sel.body_index = old_to_new
.get(sel.body_index)
.and_then(|opt| *opt)
.ok_or_else(|| format!("selected body_index {} out of bounds", sel.body_index))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `AdtEnumTy::try_new` mirrors `Trusted.MirSemantics.adtEnumHeadWfV2`
/// and `adtVariantsWfV2`.
#[test]
fn adt_enum_try_new_mirrors_lean_well_formedness() {
let u16_ty = IntTy { width: IntWidth::I16, signed: false };
let isize_ty = IntTy { width: IntWidth::Isize, signed: true };
let u32_field = |off: usize| {
Ty::Struct(
StructTy::try_new(9, 8, 2, vec![off], vec![Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
})])
.unwrap(),
)
};
let unit_variant = || Ty::Struct(StructTy::try_new(8, 8, 2, vec![], vec![]).unwrap());
// `enum { A(u32), B }` with a direct `u16` tag at 0.
let direct = |variants: Vec<Ty>, discrs: Vec<u128>, tag_offset: usize| {
AdtEnumTy::try_new(
1,
true,
8,
2,
isize_ty,
discrs,
tag_offset,
u16_ty,
(0, 1),
AdtTagEncoding::Direct,
variants,
)
};
assert!(direct(vec![u32_field(4), unit_variant()], vec![0, 1], 0).is_ok());
// A tagged variant's field may not overlap the tag.
assert!(direct(vec![u32_field(0), unit_variant()], vec![0, 1], 0).is_err());
// The tag must lie inside the enum.
assert!(direct(vec![u32_field(0), unit_variant()], vec![0, 1], 7).is_err());
// One discriminant per variant, pairwise distinct.
assert!(direct(vec![u32_field(4), unit_variant()], vec![0], 0).is_err());
assert!(direct(vec![u32_field(4), unit_variant()], vec![1, 1], 0).is_err());
// A direct discriminant must survive truncation to the tag.
assert!(direct(vec![u32_field(4), unit_variant()], vec![0, 1 << 16], 0).is_err());
// Variants must be struct payloads with the enum's layout.
assert!(direct(vec![Ty::Bool, unit_variant()], vec![0, 1], 0).is_err());
let niche = |discrs: Vec<u128>, untagged: u32| {
AdtEnumTy::try_new(
2,
false,
8,
2,
isize_ty,
discrs,
0,
u16_ty,
(65535, 2),
AdtTagEncoding::Niche { untagged, first: 0, last: 0, start: 65535 },
vec![unit_variant(), u32_field(4)],
)
};
assert!(niche(vec![0, 1], 1).is_ok());
// Niche discriminants are the variant indices.
assert!(niche(vec![0, 7], 1).is_err());
// The untagged variant must exist.
assert!(niche(vec![0, 1], 2).is_err());
}
#[test]
fn vec_layout_check_accepts_only_the_model_word_order() {
assert!(check_vec_layout(24, 3, 0, 8, 16, [8; 3]).is_ok());
assert!(check_vec_layout(24, 3, 0, 8, 16, [8, 4, 8]).is_err());
// The model's former `{ptr, cap, len}` order.
assert!(check_vec_layout(24, 3, 8, 0, 16, [8; 3]).is_err());
assert!(check_vec_layout(24, 3, 0, 16, 8, [8; 3]).is_err());
assert!(check_vec_layout(32, 3, 0, 8, 16, [8; 3]).is_err());
assert!(check_vec_layout(24, 2, 0, 8, 16, [8; 3]).is_err());
}
/// Mirrors of `recAdtHeadOkV2`, `adtVariantsV2`, and `recAdmitWalkV2` on
/// `enum T { Leaf(u8), Node(Box<T>) }`.
#[test]
fn recursive_payload_enum_mirrors_lean() {
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let defn = |layout_id: u32, back: u32| {
Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
layout_id,
true,
16,
3,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I8, signed: false },
(0, 1),
AdtTagEncoding::Direct,
vec![
Ty::Struct(StructTy::try_new(51, 16, 3, vec![1], vec![u8_ty.clone()]).unwrap()),
Ty::Struct(
StructTy::try_new(
52,
16,
3,
vec![8],
vec![Ty::Box { pointee: Box::new(Ty::RecSelf { id: back }) }],
)
.unwrap(),
),
],
)
.unwrap(),
))
};
let t = Ty::RecAdt { id: 5, defn: Box::new(defn(5, 5)) };
assert!(t.rec_ty_wf(None));
// The binder id must be the enum's layout id.
assert!(!Ty::RecAdt { id: 6, defn: Box::new(defn(5, 6)) }.rec_ty_wf(None));
// The variants are those of the unfolding: the back edge is closed.
let aty = t.as_adt_enum().unwrap();
let node = aty.variant(1).unwrap();
assert_eq!(node.fields()[0], Ty::Box { pointee: Box::new(t.clone()) });
assert!(defn(5, 5).as_adt_enum().is_some());
assert!(u8_ty.as_adt_enum().is_none());
assert!(check_rec_tys([&t]).is_ok());
// A plain payload enum reusing the binder's id is incoherent.
let plain = Ty::AdtEnum(Box::new(AdtEnumTy {
layout: aty.layout().clone(),
local: true,
variants: vec![aty.variants()[0].clone(), aty.variants()[0].clone()],
}));
assert!(check_rec_tys([&t, &plain]).is_err());
}
#[test]
fn niche_option_handle_layout_check_enforces_tag_niche_and_payload_offset() {
// Valid Box<T>/Box<[T]> (null niche at offset 0) and Vec<T>
// (exact VEC_NONE_NICHE = u64::MAX).
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Box,
8,
0,
1,
(0, 0),
0,
Some(0),
)
.is_ok()
);
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
8,
0,
1,
(0, 0),
VEC_NONE_NICHE,
Some(0),
)
.is_ok()
);
// Any other high-bit value (such as 2^63) disagrees with
// vecNoneNicheV2 = u64::MAX and must be rejected.
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
8,
0,
1,
(0, 0),
1u128 << 63,
Some(0),
)
.is_err()
);
// Wrong untagged/niche variants.
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Box,
8,
0,
0,
(1, 1),
0,
Some(0),
)
.is_err()
);
// Wrong tag size or offset.
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
4,
0,
1,
(0, 0),
u64::MAX as u128,
Some(0),
)
.is_err()
);
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
8,
8,
1,
(0, 0),
u64::MAX as u128,
Some(0),
)
.is_err()
);
// Wrong niche_start (non-zero for Box; <= isize::MAX for Vec).
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Box,
8,
0,
1,
(0, 0),
1,
Some(0),
)
.is_err()
);
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
8,
0,
1,
(0, 0),
(1u128 << 63) - 1,
Some(0),
)
.is_err()
);
// Wrong Some payload offset (must be 0 to match optionSomeOffsetV2).
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Box,
8,
0,
1,
(0, 0),
0,
Some(8),
)
.is_err()
);
assert!(
check_niche_option_handle_layout(
OptionHandleNicheKind::Vec,
8,
0,
1,
(0, 0),
u64::MAX as u128,
None,
)
.is_err()
);
}
#[test]
fn validate_local_tys_rejects_mixed_refs_and_raw_ptrs() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let shared_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
};
let raw_ptr = Ty::RawPtr {
mutability: Mutability::Mut,
pointee: Box::new(u8_ty.clone()),
};
assert!(validate_local_tys(&[Ty::Unit, shared_ref.clone()]).is_ok());
assert!(validate_local_tys(&[Ty::Unit, raw_ptr.clone()]).is_ok());
let mixed = validate_local_tys(&[Ty::Unit, shared_ref.clone(), raw_ptr.clone()]);
assert!(mixed.unwrap_err().contains("body mixes reference and raw-pointer locals"));
let nested_array_ref = Ty::Array {
elem: Box::new(shared_ref.clone()),
len: 2,
};
let nested_array_raw = Ty::Array {
elem: Box::new(raw_ptr.clone()),
len: 2,
};
assert!(nested_array_ref.has_ref_v2());
assert!(!nested_array_ref.has_raw_ptr_v2());
assert!(nested_array_raw.has_raw_ptr_v2());
assert!(!nested_array_raw.has_ref_v2());
let nested = validate_local_tys(&[
Ty::Tuple {
fields: vec![shared_ref.clone(), u8_ty.clone()],
},
raw_ptr.clone(),
]);
assert!(nested.unwrap_err().contains("body mixes reference and raw-pointer locals"));
let opt_raw = validate_local_tys(&[
shared_ref.clone(),
Ty::Option {
elem: Box::new(raw_ptr.clone()),
},
]);
assert!(opt_raw.unwrap_err().contains("body mixes reference and raw-pointer locals"));
let opt_ref = validate_local_tys(&[
Ty::Option { elem: Box::new(shared_ref.clone()) },
raw_ptr.clone(),
]);
assert!(opt_ref.unwrap_err().contains("body mixes reference and raw-pointer locals"));
assert!(Ty::Vec { elem: Box::new(shared_ref.clone()) }.has_ref_v2());
assert!(Ty::Box { pointee: Box::new(shared_ref) }.has_ref_v2());
assert!(Ty::Vec { elem: Box::new(raw_ptr.clone()) }.has_raw_ptr_v2());
assert!(Ty::Box { pointee: Box::new(raw_ptr.clone()) }.has_raw_ptr_v2());
assert!(!Ty::Box { pointee: Box::new(u8_ty.clone()) }.has_raw_ptr_v2());
// A `Vec` of scalars counts as a reference, like a `Box`.
let scalar_vec = Ty::Vec { elem: Box::new(u8_ty) };
assert!(scalar_vec.has_ref_v2());
let vec_raw = validate_local_tys(&[scalar_vec, raw_ptr]);
assert!(vec_raw.unwrap_err().contains("body mixes reference and raw-pointer locals"));
}
#[test]
fn body_try_new_checks_box_as_ref_cast_mutability() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let box_u8 = Ty::Box {
pointee: Box::new(u8_ty.clone()),
};
let shared_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
};
let mut_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(u8_ty),
};
assert!(
Body::try_new(
1,
false,
vec![shared_ref.clone(), box_u8.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Cast {
cast_kind: CastKind::BoxAsRef,
operand: Operand::Copy { local: 1 },
ty: shared_ref,
},
}],
terminator: Terminator::Ret,
}],
"box_as_ref_ok".into(),
)
.is_ok()
);
assert!(
Body::try_new(
1,
false,
vec![mut_ref.clone(), box_u8],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Cast {
cast_kind: CastKind::BoxAsRef,
operand: Operand::Copy { local: 1 },
ty: mut_ref,
},
}],
terminator: Terminator::Ret,
}],
"box_as_ref_mut_err".into(),
)
.is_err()
);
}
#[test]
fn ptr_to_ptr_casts_admit_raw_sources_and_refuse_reference_and_const_to_mut() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let raw = |mutability, pointee: &Ty| Ty::RawPtr {
mutability,
pointee: Box::new(pointee.clone()),
};
let const_u8 = raw(Mutability::Shared, &u8_ty);
let mut_u8 = raw(Mutability::Mut, &u8_ty);
check_cast_types(CastKind::PtrToPtr, &mut_u8, &const_u8, &const_u8).unwrap();
check_cast_types(CastKind::PtrToPtr, &mut_u8, &mut_u8, &mut_u8).unwrap();
check_cast_types(CastKind::PtrToPtr, &const_u8, &const_u8, &const_u8).unwrap();
let err = check_cast_types(CastKind::PtrToPtr, &const_u8, &mut_u8, &mut_u8).unwrap_err();
assert!(err.contains("`*const T` to `*mut T`"), "{err}");
let u8_slice = Ty::Slice {
elem: Box::new(u8_ty.clone()),
};
let slice = |mutability| raw(mutability, &u8_slice);
for (src, dst) in [
(Mutability::Mut, Mutability::Shared),
(Mutability::Mut, Mutability::Mut),
(Mutability::Shared, Mutability::Shared),
] {
check_cast_types(CastKind::PtrToPtr, &slice(src), &slice(dst), &slice(dst)).unwrap();
}
let err = check_cast_types(
CastKind::PtrToPtr,
&slice(Mutability::Shared),
&slice(Mutability::Mut),
&slice(Mutability::Mut),
)
.unwrap_err();
assert!(err.contains("`*const T` to `*mut T`"), "{err}");
for mutability in [Mutability::Shared, Mutability::Mut] {
let reference = Ty::Ref {
mutability,
pointee: Box::new(u8_ty.clone()),
};
let err =
check_cast_types(CastKind::PtrToPtr, &reference, &const_u8, &const_u8).unwrap_err();
assert!(err.contains("PtrToPtr cast from reference"), "{err}");
}
}
#[test]
fn body_try_new_rejects_mismatched_use_and_discriminant_destination_types() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let unit_into_u8 = Body::try_new(
0,
false,
vec![u8_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Constant {
ty: Ty::Unit,
lit: ConstLit::ZeroSized,
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unit_into_u8".into(),
)
.unwrap_err();
assert!(unit_into_u8.contains("disagrees with destination local"));
let copy_mismatch = Body::try_new(
1,
false,
vec![Ty::Unit, u8_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Copy { local: 1 },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::copy_mismatch".into(),
)
.unwrap_err();
assert!(copy_mismatch.contains("disagrees with destination local"));
assert!(
Body::try_new(
0,
false,
vec![Ty::Unit],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Constant {
ty: Ty::Unit,
lit: ConstLit::ZeroSized,
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unit_into_unit".into(),
)
.is_ok()
);
let ety = EnumTy::try_new(
1,
IntTy {
width: IntWidth::Isize,
signed: true,
},
EnumTagRepr::ZeroSized,
vec![42],
)
.unwrap();
let discr_mismatch = Body::try_new(
1,
false,
vec![u8_ty, Ty::Enum(ety.clone())],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Discriminant {
place: Place {
local: 1,
projection: vec![],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::discr_mismatch".into(),
)
.unwrap_err();
assert!(discr_mismatch.contains("disagrees with enum discriminant"));
assert!(
Body::try_new(
0,
false,
vec![Ty::Enum(ety.clone())],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Constant {
ty: Ty::Enum(ety),
lit: ConstLit::ZeroSized,
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::zst_enum_ok".into(),
)
.is_ok()
);
}
/// A fieldless enum variant aggregate mirrors
/// `Trusted.MirSemantics.evalFieldlessEnumAggregateV2`: no operands, the
/// enum as destination, and an in-range variant.
#[test]
fn body_try_new_checks_fieldless_enum_aggregates() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let ety = EnumTy::try_new(
1,
IntTy {
width: IntWidth::I8,
signed: false,
},
EnumTagRepr::Scalar(IntTy {
width: IntWidth::I8,
signed: false,
}),
vec![3, 7],
)
.unwrap();
let body = |dst: Ty, variant_idx: usize, fields: Vec<Operand>| {
Body::try_new(
0,
false,
vec![dst],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateAdtEnum {
ty: Ty::Enum(ety.clone()),
variant_idx,
fields,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::make".into(),
)
};
assert!(body(Ty::Enum(ety.clone()), 1, vec![]).is_ok());
let dst = body(u8_ty.clone(), 1, vec![]).unwrap_err();
assert!(dst.contains("disagrees with destination"), "{dst}");
let range = body(Ty::Enum(ety.clone()), 2, vec![]).unwrap_err();
assert!(range.contains("out of range"), "{range}");
let field = Operand::Constant {
ty: u8_ty,
lit: ConstLit::Scalar { bits: 0 },
};
let fields = body(Ty::Enum(ety.clone()), 1, vec![field]).unwrap_err();
assert!(fields.contains("has fields"), "{fields}");
}
#[test]
fn body_try_new_refuses_raw_borrow_mut_through_const_pointer() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let raw = |mutability| Ty::RawPtr {
mutability,
pointee: Box::new(u8_ty.clone()),
};
let body = |mutability: Mutability, dst: Ty| {
Body::try_new(
1,
true,
vec![dst, raw(Mutability::Shared)],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AddressOf {
mutability,
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::raw_borrow_through_const".into(),
)
};
let err = body(Mutability::Mut, raw(Mutability::Mut)).unwrap_err();
assert!(err.contains("`&raw mut` through a `*const`"), "{err}");
body(Mutability::Shared, raw(Mutability::Shared)).unwrap();
}
#[test]
fn body_try_new_admits_only_local_field_chain_moves() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let range_from = Ty::RangeFrom {
elem: Box::new(usize_ty.clone()),
};
let body = |locals: Vec<Ty>, operand: Operand| {
Body::try_new(
1,
true,
locals,
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand,
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::projected_move".into(),
)
};
// `move (_1.0)` out of a `(RangeFrom<usize>, usize)` tuple local is
// admitted: Profile v2 deinitializes just that field.
let tuple_locals = vec![
range_from.clone(),
Ty::Tuple {
fields: vec![range_from.clone(), usize_ty.clone()],
},
];
let field = Place {
local: 1,
projection: vec![PlaceElem::Field {
index: 0,
ty: range_from.clone(),
}],
};
body(tuple_locals.clone(), Operand::MovePlace { place: field.clone() }).unwrap();
// `move ((_1 as Some).0)` out of an immediate `Option<Box<u8>>` local
// is admitted, while the same move on an `Option` local whose address
// is taken in the body is refused.
let box_u8 = Ty::Box {
pointee: Box::new(u8_ty.clone()),
};
let opt_box_u8 = Ty::Option {
elem: Box::new(box_u8.clone()),
};
let opt_downcast = Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field {
index: 0,
ty: box_u8.clone(),
},
],
};
body(
vec![box_u8.clone(), opt_box_u8.clone()],
Operand::MovePlace {
place: opt_downcast.clone(),
},
)
.unwrap();
let promoted_opt_err = Body::try_new(
1,
false,
vec![
box_u8,
opt_box_u8.clone(),
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(opt_box_u8),
},
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::Ref {
mutability: Mutability::Shared,
place: Place {
local: 1,
projection: vec![],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::MovePlace { place: opt_downcast },
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::promoted_opt_move".into(),
)
.unwrap_err();
assert!(
promoted_opt_err.contains("projected move operands"),
"{promoted_opt_err}"
);
// `move ((_1.1).0)` out of a struct local nested in a struct local is
// admitted: it runs in the local's stack allocation.
let inner_struct =
Ty::Struct(StructTy::try_new(81, 8, 3, vec![0], vec![usize_ty.clone()]).unwrap());
let outer_struct = Ty::Struct(
StructTy::try_new(82, 16, 3, vec![8, 0], vec![u8_ty.clone(), inner_struct.clone()])
.unwrap(),
);
let struct_field = Place {
local: 1,
projection: vec![
PlaceElem::Field { index: 1, ty: inner_struct },
PlaceElem::Field { index: 0, ty: usize_ty.clone() },
],
};
body(
vec![usize_ty.clone(), outer_struct],
Operand::MovePlace { place: struct_field },
)
.unwrap();
// Refused: `move (*_1)` through a `*const u8`, a nested non-downcast
// field move `move ((_1.0).0)` out of a tuple, and a nested move
// `move ((_1.0)[0])` out of a tuple through a constant index, which
// `moveTuplePathV2` does not model. Admitted: a nested variant field
// move `move ((_1.1 as Some).0)` out of a tuple (`moveTuplePathV2`),
// and a field move out of a non-tuple `RangeFrom<usize>` local, which
// runs in its stack allocation.
let ptr_locals = vec![
u8_ty.clone(),
Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
},
];
let deref = Place {
local: 1,
projection: vec![PlaceElem::Deref],
};
let inner = Ty::Tuple {
fields: vec![usize_ty.clone(), usize_ty.clone()],
};
let nested_locals = vec![
usize_ty.clone(),
Ty::Tuple {
fields: vec![inner.clone(), usize_ty.clone()],
},
];
let nested = Place {
local: 1,
projection: vec![
PlaceElem::Field {
index: 0,
ty: inner,
},
PlaceElem::Field {
index: 0,
ty: usize_ty.clone(),
},
],
};
let range_locals = vec![usize_ty.clone(), range_from.clone()];
let range_field = Place {
local: 1,
projection: vec![PlaceElem::Field {
index: 0,
ty: usize_ty.clone(),
}],
};
let err =
body(ptr_locals.clone(), Operand::MovePlace { place: deref.clone() }).unwrap_err();
assert!(err.contains("projected move operands"), "{err}");
let err =
body(nested_locals.clone(), Operand::MovePlace { place: nested.clone() }).unwrap_err();
assert!(err.contains("projected move operands"), "{err}");
// `move ((_1.1 as Some).0)` out of a `(usize, Option<usize>)` tuple,
// the shape of a `match` on a tuple temporary, is admitted too.
let opt_usize = Ty::Option {
elem: Box::new(usize_ty.clone()),
};
let opt_locals = vec![
usize_ty.clone(),
Ty::Tuple {
fields: vec![usize_ty.clone(), opt_usize.clone()],
},
];
let payload = Place {
local: 1,
projection: vec![
PlaceElem::Field { index: 1, ty: opt_usize },
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: usize_ty.clone() },
],
};
body(opt_locals, Operand::MovePlace { place: payload }).unwrap();
let arr = Ty::Array {
elem: Box::new(usize_ty.clone()),
len: 2,
};
let arr_locals = vec![
usize_ty.clone(),
Ty::Tuple {
fields: vec![arr.clone(), usize_ty.clone()],
},
];
let arr_elem = Place {
local: 1,
projection: vec![
PlaceElem::Field { index: 0, ty: arr },
PlaceElem::ConstantIndex {
offset: 0,
min_length: 2,
from_end: false,
},
],
};
let err = body(arr_locals, Operand::MovePlace { place: arr_elem }).unwrap_err();
assert!(err.contains("projected move operands"), "{err}");
body(range_locals.clone(), Operand::MovePlace { place: range_field.clone() }).unwrap();
// Copying the same places stays admitted.
body(tuple_locals, Operand::CopyPlace { place: field }).unwrap();
body(ptr_locals, Operand::CopyPlace { place: deref }).unwrap();
body(nested_locals, Operand::CopyPlace { place: nested }).unwrap();
body(range_locals, Operand::CopyPlace { place: range_field }).unwrap();
}
#[test]
fn validate_constant_checks_all_ty_and_lit_combinations() {
let zst_enum = Ty::Enum(
EnumTy::try_new(
1,
IntTy {
width: IntWidth::Isize,
signed: true,
},
EnumTagRepr::ZeroSized,
vec![0],
)
.unwrap(),
);
let scalar_enum = Ty::Enum(
EnumTy::try_new(
2,
IntTy {
width: IntWidth::Isize,
signed: true,
},
EnumTagRepr::Scalar(IntTy {
width: IntWidth::I8,
signed: true,
}),
vec![u128::from(u64::MAX), 1],
)
.unwrap(),
);
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u128_ty = Ty::Int(IntTy {
width: IntWidth::I128,
signed: false,
});
let ovf_u8 = Ty::OverflowPair(IntTy {
width: IntWidth::I8,
signed: false,
});
assert_eq!(IntWidth::I128.bits(), 128);
assert_eq!(IntWidth::I128.mask(), u128::MAX);
assert_eq!(IntWidth::I128.lean_name(), "i128");
assert!(validate_constant(&Ty::Unit, &ConstLit::ZeroSized).is_ok());
assert!(validate_constant(&Ty::Unit, &ConstLit::Scalar { bits: 0 }).is_err());
assert!(validate_constant(&Ty::Never, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&Ty::Never, &ConstLit::Scalar { bits: 0 }).is_err());
assert!(validate_constant(&ovf_u8, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&ovf_u8, &ConstLit::Scalar { bits: 0 }).is_err());
assert!(validate_constant(&Ty::Bool, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&Ty::Bool, &ConstLit::Scalar { bits: 0 }).is_ok());
assert!(validate_constant(&Ty::Bool, &ConstLit::Scalar { bits: 1 }).is_ok());
assert!(validate_constant(&Ty::Bool, &ConstLit::Scalar { bits: 2 }).is_err());
assert!(validate_constant(&Ty::Char, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0 }).is_ok());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0xD7FF }).is_ok());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0xD800 }).is_err());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0xDFFF }).is_err());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0xE000 }).is_ok());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0x10_FFFF }).is_ok());
assert!(validate_constant(&Ty::Char, &ConstLit::Scalar { bits: 0x11_0000 }).is_err());
assert!(validate_constant(&Ty::Ordering, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&Ty::Ordering, &ConstLit::Scalar { bits: 0 }).is_ok());
assert!(validate_constant(&Ty::Ordering, &ConstLit::Scalar { bits: 1 }).is_ok());
assert!(validate_constant(&Ty::Ordering, &ConstLit::Scalar { bits: 0xff }).is_ok());
assert!(validate_constant(&Ty::Ordering, &ConstLit::Scalar { bits: 2 }).is_err());
assert!(validate_constant(&Ty::Ordering, &ConstLit::Scalar { bits: 0x1ff }).is_err());
assert!(validate_constant(&u8_ty, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&u8_ty, &ConstLit::Scalar { bits: 255 }).is_ok());
assert!(validate_constant(&u8_ty, &ConstLit::Scalar { bits: 256 }).is_err());
assert!(validate_constant(&u128_ty, &ConstLit::Scalar { bits: u128::MAX }).is_ok());
assert!(validate_constant(&zst_enum, &ConstLit::ZeroSized).is_ok());
assert!(validate_constant(&zst_enum, &ConstLit::Scalar { bits: 0 }).is_err());
assert!(validate_constant(&scalar_enum, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&scalar_enum, &ConstLit::Scalar { bits: 0xff }).is_ok());
assert!(validate_constant(&scalar_enum, &ConstLit::Scalar { bits: 1 }).is_ok());
assert!(validate_constant(&scalar_enum, &ConstLit::Scalar { bits: 2 }).is_err());
// `Ty::AdtEnum`: non-ZST accepts `RodataBytes` of exact size, ZST
// accepts `ZeroSized`, and heap-owning payload enums stay refused.
let isize_ty = IntTy { width: IntWidth::Isize, signed: true };
let u16_ty = IntTy { width: IntWidth::I16, signed: false };
let u32_ty = Ty::Int(IntTy { width: IntWidth::I32, signed: false });
let plain_adt = Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
10,
true,
8,
2,
isize_ty,
vec![0, 1],
0,
u16_ty,
(0, 1),
AdtTagEncoding::Direct,
vec![
Ty::Struct(StructTy::try_new(11, 8, 2, vec![4], vec![u32_ty.clone()]).unwrap()),
Ty::Struct(StructTy::try_new(12, 8, 2, vec![], vec![]).unwrap()),
],
)
.unwrap(),
));
let zst_adt = Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
13,
true,
0,
0,
isize_ty,
vec![0],
0,
IntTy { width: IntWidth::I8, signed: false },
(0, 0),
AdtTagEncoding::Single,
vec![Ty::Struct(StructTy::try_new(14, 0, 0, vec![0], vec![Ty::Unit]).unwrap())],
)
.unwrap(),
));
let heap_adt = Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
15,
true,
16,
3,
isize_ty,
vec![0, 1],
0,
u16_ty,
(0, 1),
AdtTagEncoding::Direct,
vec![
Ty::Struct(
StructTy::try_new(
16,
16,
3,
vec![8],
vec![Ty::Box { pointee: Box::new(u32_ty.clone()) }],
)
.unwrap(),
),
Ty::Struct(StructTy::try_new(17, 16, 3, vec![], vec![]).unwrap()),
],
)
.unwrap(),
));
assert!(
validate_constant(
&plain_adt,
&ConstLit::RodataBytes {
bytes: vec![RodataByte::Init { byte: 0 }; 8],
},
)
.is_ok()
);
assert!(
validate_constant(
&plain_adt,
&ConstLit::RodataBytes {
bytes: vec![RodataByte::Init { byte: 0 }; 4],
},
)
.is_err()
);
assert!(validate_constant(&plain_adt, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&plain_adt, &ConstLit::Scalar { bits: 0 }).is_err());
assert!(validate_constant(&zst_adt, &ConstLit::ZeroSized).is_ok());
assert!(validate_constant(&zst_adt, &ConstLit::RodataBytes { bytes: vec![] }).is_err());
assert!(
validate_constant(
&heap_adt,
&ConstLit::RodataBytes {
bytes: vec![RodataByte::Init { byte: 0 }; 16],
},
)
.is_err()
);
// `Body::try_new` refuses direct-local `AssignPlace` through a downcast
// on `Ty::AdtEnum` and `Ty::Option` (matching `resolvePlaceDestV2`).
for (label, local_ty, variant_idx) in [
("adt_enum_direct_downcast_assign", plain_adt, 0usize),
(
"option_direct_downcast_assign",
Ty::Option { elem: Box::new(u32_ty.clone()) },
1usize,
),
] {
let err = Body::try_new(
1,
false,
vec![Ty::Unit, local_ty],
vec![Block {
statements: vec![Statement::AssignPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx },
PlaceElem::Field {
index: 0,
ty: u32_ty.clone(),
},
],
},
value: Rvalue::Use {
operand: Operand::Constant {
ty: u32_ty.clone(),
lit: ConstLit::Scalar { bits: 1 },
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::direct_downcast_assign".into(),
)
.unwrap_err();
assert!(err.contains("write through a downcast"), "{label}: {err}");
}
}
#[test]
fn retag_guard_refuses_erasing_an_effective_retag() {
let refusal = admit_retag(false, true).unwrap_err();
assert!(
refusal.contains("retagging Use rvalues on reference-bearing types are unsupported"),
"{refusal}"
);
assert!(admit_retag(false, false).is_ok());
assert!(admit_retag(true, true).is_ok());
assert!(admit_retag(true, false).is_ok());
for ref_ty in [
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Bool),
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
},
Ty::Tuple {
fields: vec![
Ty::Bool,
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
},
],
},
] {
assert!(!ref_ty.is_retag_noop(), "{ref_ty:?}");
assert!(check_use_retag(&ref_ty, true).is_err(), "{ref_ty:?}");
assert!(check_use_retag(&ref_ty, false).is_ok(), "{ref_ty:?}");
}
for ty in [
Ty::Bool,
Ty::Char,
Ty::Str,
Ty::Ordering,
Ty::Unit,
Ty::Never,
Ty::Int(IntTy {
width: IntWidth::Isize,
signed: true,
}),
Ty::Int(IntTy {
width: IntWidth::I128,
signed: false,
}),
Ty::OverflowPair(IntTy {
width: IntWidth::I64,
signed: false,
}),
] {
assert!(ty.is_retag_noop(), "{ty:?}");
assert!(check_use_retag(&ty, true).is_ok(), "{ty:?}");
}
}
#[test]
fn body_try_new_enforces_operator_cast_discriminant_and_switch_typing() {
let u8_ity = IntTy {
width: IntWidth::I8,
signed: false,
};
let i8_ity = IntTy {
width: IntWidth::I8,
signed: true,
};
let u32_ity = IntTy {
width: IntWidth::I32,
signed: false,
};
let i128_ity = IntTy {
width: IntWidth::I128,
signed: true,
};
let u8_ty = Ty::Int(u8_ity);
let i8_ty = Ty::Int(i8_ity);
let u32_ty = Ty::Int(u32_ity);
let i128_ty = Ty::Int(i128_ity);
let ovf_u32 = Ty::OverflowPair(u32_ity);
let one_stmt_body = |locals: Vec<Ty>, value: Rvalue| {
Body::try_new(
locals.len() - 1,
false,
locals,
vec![Block {
statements: vec![Statement::Assign { local: 0, value }],
terminator: Terminator::Ret,
}],
"rust-path-v1::stmt_check".into(),
)
};
// Overflowing arithmetic requires matching `Int` operands and
// `OverflowPair(ity)` destination.
assert!(
one_stmt_body(
vec![ovf_u32.clone(), u32_ty.clone(), u32_ty.clone()],
Rvalue::Binary {
op: BinOp::AddWithOverflow,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_ok()
);
assert!(
one_stmt_body(
vec![u32_ty.clone(), u32_ty.clone(), u32_ty.clone()],
Rvalue::Binary {
op: BinOp::AddWithOverflow,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_err()
);
// `Cmp` admits `Int` and `Char` -> `Ordering`, rejecting `Bool` and
// `Ordering`; relational ops admit `Char` and reject `Ordering`.
assert!(
one_stmt_body(
vec![Ty::Ordering, Ty::Char, Ty::Char],
Rvalue::Binary {
op: BinOp::Cmp,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_ok()
);
assert!(
one_stmt_body(
vec![Ty::Ordering, Ty::Bool, Ty::Bool],
Rvalue::Binary {
op: BinOp::Cmp,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_err()
);
assert!(
one_stmt_body(
vec![Ty::Bool, Ty::Char, Ty::Char],
Rvalue::Binary {
op: BinOp::Lt,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_ok()
);
assert!(
one_stmt_body(
vec![Ty::Bool, Ty::Ordering, Ty::Ordering],
Rvalue::Binary {
op: BinOp::Eq,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
)
.is_err()
);
// `Unary`: `Not` admits `Bool` and `Int` (rejects `Char`), `Neg` admits
// signed `Int` (rejects unsigned `Int` and `Bool`).
assert!(
one_stmt_body(
vec![i128_ty.clone(), i128_ty.clone()],
Rvalue::Unary {
op: UnOp::Neg,
operand: Operand::Copy { local: 1 },
},
)
.is_ok()
);
assert!(
one_stmt_body(
vec![u32_ty.clone(), u32_ty.clone()],
Rvalue::Unary {
op: UnOp::Neg,
operand: Operand::Copy { local: 1 },
},
)
.is_err()
);
assert!(
one_stmt_body(
vec![Ty::Char, Ty::Char],
Rvalue::Unary {
op: UnOp::Not,
operand: Operand::Copy { local: 1 },
},
)
.is_err()
);
// `Cast(IntToInt)`: `{int, bool, char} -> int` and `u8 -> char` only,
// with `cast_ty == dst_ty`.
assert!(
one_stmt_body(
vec![Ty::Char, u8_ty.clone()],
Rvalue::Cast {
cast_kind: CastKind::IntToInt,
operand: Operand::Copy { local: 1 },
ty: Ty::Char,
},
)
.is_ok()
);
for bad_src in [i8_ty.clone(), u32_ty.clone(), Ty::Bool, Ty::Char] {
assert!(
one_stmt_body(
vec![Ty::Char, bad_src],
Rvalue::Cast {
cast_kind: CastKind::IntToInt,
operand: Operand::Copy { local: 1 },
ty: Ty::Char,
},
)
.is_err()
);
}
assert!(
one_stmt_body(
vec![u32_ty.clone(), Ty::Char],
Rvalue::Cast {
cast_kind: CastKind::IntToInt,
operand: Operand::Copy { local: 1 },
ty: u8_ty.clone(),
},
)
.is_err()
);
assert!(
one_stmt_body(
vec![Ty::Bool, u8_ty.clone()],
Rvalue::Cast {
cast_kind: CastKind::IntToInt,
operand: Operand::Copy { local: 1 },
ty: Ty::Bool,
},
)
.is_err()
);
// `Discriminant` on `Ordering` requires `i8` destination.
assert!(
one_stmt_body(
vec![i8_ty.clone(), Ty::Ordering],
Rvalue::Discriminant {
place: Place {
local: 1,
projection: vec![],
},
},
)
.is_ok()
);
assert!(
one_stmt_body(
vec![u8_ty.clone(), Ty::Ordering],
Rvalue::Discriminant {
place: Place {
local: 1,
projection: vec![],
},
},
)
.is_err()
);
// `SwitchInt` checks operand switchability and case bounds.
let switch_body = |discr_ty: Ty, targets: Vec<(u128, u32)>| {
Body::try_new(
1,
false,
vec![Ty::Unit, discr_ty],
vec![Block {
statements: vec![],
terminator: Terminator::SwitchInt {
operand: Operand::Copy { local: 1 },
targets,
otherwise: 0,
},
}],
"rust-path-v1::switch_check".into(),
)
};
assert!(switch_body(i128_ty, vec![(u128::MAX, 0)]).is_ok());
assert!(switch_body(u8_ty, vec![(256, 0)]).is_err());
assert!(switch_body(Ty::Bool, vec![(0, 0), (1, 0)]).is_ok());
assert!(switch_body(Ty::Bool, vec![(2, 0)]).is_err());
assert!(switch_body(Ty::Char, vec![(0x1F600, 0)]).is_ok());
assert!(switch_body(Ty::Char, vec![(0xD800, 0)]).is_err());
assert!(switch_body(ovf_u32.clone(), vec![]).is_ok());
assert!(switch_body(ovf_u32, vec![(0, 0)]).is_err());
assert!(switch_body(Ty::Ordering, vec![]).is_err());
// Decimal string serialization for 128-bit values round-trips via
// standard `serde_json::Value` without `arbitrary_precision`.
let i128_enum = EnumTy::try_new(
9,
i128_ity,
EnumTagRepr::Scalar(i128_ity),
vec![u128::MAX, 0, 1],
)
.unwrap();
let json_val = serde_json::to_value(&i128_enum).unwrap();
assert_eq!(
json_val["discriminants"],
serde_json::json!(["340282366920938463463374607431768211455", "0", "1"])
);
}
#[test]
fn place_mention_guard_checks_local_bounds_and_sizedness() {
assert!(admit_place_mention(true).is_ok());
assert!(
admit_place_mention(false)
.unwrap_err()
.contains("PlaceMention on unsized locals is unsupported")
);
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
assert!(check_place_mention(&u64_ty).is_ok());
assert!(check_place_mention(&Ty::Unit).is_ok());
let valid = Body::try_new(
1,
false,
vec![Ty::Unit, u64_ty.clone()],
vec![Block {
statements: vec![Statement::PlaceMention { local: 1 }],
terminator: Terminator::Ret,
}],
"rust-path-v1::place_mention_ok".into(),
)
.unwrap();
let json = serde_json::to_value(&valid).unwrap();
assert_eq!(
json["blocks"][0]["statements"][0],
serde_json::json!({ "kind": "place_mention", "local": 1 })
);
let oob = Body::try_new(
1,
false,
vec![Ty::Unit, u64_ty],
vec![Block {
statements: vec![Statement::PlaceMention { local: 9 }],
terminator: Terminator::Ret,
}],
"rust-path-v1::place_mention_oob".into(),
)
.unwrap_err();
assert!(oob.contains("place mention local 9 out of bounds"), "{oob}");
}
#[test]
fn projected_place_mention_is_checked_as_a_read() {
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
let mention = |local_ty: Ty, projection: Vec<PlaceElem>| {
Body::try_new(
1,
false,
vec![Ty::Unit, local_ty],
vec![Block {
statements: vec![Statement::PlaceMentionPlace {
place: Place { local: 1, projection },
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::place_mention_place".into(),
)
};
let shared_ref = |pointee: Ty| Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(pointee),
};
let valid = mention(shared_ref(u64_ty.clone()), vec![PlaceElem::Deref]).unwrap();
assert!(valid.uses_profile_v2());
let json = serde_json::to_value(&valid).unwrap();
assert_eq!(json["blocks"][0]["statements"][0]["kind"], "place_mention_place");
let unprojected = mention(u64_ty.clone(), vec![]).unwrap_err();
assert!(unprojected.contains("requires a projected place"), "{unprojected}");
let unsized_deref = mention(
shared_ref(Ty::Slice { elem: Box::new(u64_ty.clone()) }),
vec![PlaceElem::Deref],
)
.unwrap_err();
assert!(unsized_deref.contains("unsized deref"), "{unsized_deref}");
let non_pointer = mention(u64_ty, vec![PlaceElem::Deref]).unwrap_err();
assert!(non_pointer.contains("cannot deref non-pointer"), "{non_pointer}");
}
#[test]
fn body_collect_enum_ids_visits_locals_and_constant_operands() {
let isize_discr = IntTy {
width: IntWidth::Isize,
signed: true,
};
let enum_a = EnumTy::try_new(101, isize_discr, EnumTagRepr::ZeroSized, vec![0]).unwrap();
let enum_b = EnumTy::try_new(
202,
isize_discr,
EnumTagRepr::Scalar(IntTy {
width: IntWidth::I8,
signed: false,
}),
vec![0, 1],
)
.unwrap();
let body = Body::try_new(
0,
false,
vec![Ty::Enum(enum_a.clone()), Ty::Enum(enum_b.clone())],
vec![Block {
statements: vec![
Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Constant {
ty: Ty::Enum(enum_a),
lit: ConstLit::ZeroSized,
},
with_retag: false,
},
},
Statement::Assign {
local: 1,
value: Rvalue::Use {
operand: Operand::Constant {
ty: Ty::Enum(enum_b),
lit: ConstLit::Scalar { bits: 1 },
},
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::enum_ids_body".into(),
)
.unwrap();
let mut ids = BTreeSet::new();
body.collect_enum_ids(&mut ids);
assert_eq!(ids, BTreeSet::from([101, 202]));
// `size_of::<E>()` lowers to a `CoreCall` with no local or constant
// of type `E`, so the `MemSizeOf` type operand must register `E`'s id.
let enum_c = EnumTy::try_new(303, isize_discr, EnumTagRepr::ZeroSized, vec![0]).unwrap();
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let size_of_body = Body::try_new(
0,
false,
vec![usize_ty],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::MemSizeOf {
ty: Ty::Enum(enum_c),
},
args: vec![],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::size_of_enum_ids_body".into(),
)
.unwrap();
let mut size_of_ids = BTreeSet::new();
size_of_body.collect_enum_ids(&mut size_of_ids);
assert_eq!(size_of_ids, BTreeSet::from([303]));
let unsupported_term = Body::try_new(
0,
false,
vec![Ty::Never],
vec![Block {
statements: vec![],
terminator: Terminator::Unsupported,
}],
"rust-path-v1::diverging_call".into(),
)
.unwrap();
let term_json = serde_json::to_value(&unsupported_term).unwrap();
assert_eq!(
term_json["blocks"][0]["terminator"],
serde_json::json!({ "kind": "unsupported" })
);
}
#[test]
fn call_sysroot_call_and_unchecked_arith_validation() {
let u16_ty = Ty::Int(IntTy {
width: IntWidth::I16,
signed: false,
});
let u32_ty = Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
});
let isize_discr = IntTy {
width: IntWidth::Isize,
signed: true,
};
let enum_a = EnumTy::try_new(303, isize_discr, EnumTagRepr::ZeroSized, vec![0]).unwrap();
let enum_ty = Ty::Enum(enum_a);
// Unchecked integer arithmetic admits matching IntTy
// operands/destination.
for op in [
BinOp::AddUnchecked,
BinOp::SubUnchecked,
BinOp::MulUnchecked,
] {
assert!(Body::try_new(
2,
false,
vec![u16_ty.clone(), u16_ty.clone(), u16_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Binary {
op,
left: Operand::Copy { local: 1 },
right: Operand::Copy { local: 2 },
},
}],
terminator: Terminator::Ret,
}],
format!("rust-path-v1::unchecked_{op:?}"),
)
.is_ok());
}
// Duplicate Move operand or Move aliasing dst fails closed.
let dup_move = Body::try_new(
1,
false,
vec![u16_ty.clone(), u16_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::SysrootCall {
op: SysrootNumOp {
kind: SysrootNumKind::UncheckedAdd,
ty: IntTy {
width: IntWidth::I16,
signed: false,
},
},
args: vec![Operand::Move { local: 1 }, Operand::Move { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::dup_move".into(),
)
.unwrap_err();
assert!(dup_move.contains("duplicate Move operand"), "{dup_move}");
let alias_dst = Body::try_new(
1,
false,
vec![u16_ty.clone(), u16_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::Call {
callee: 0,
args: vec![Operand::Move { local: 0 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::alias_dst".into(),
)
.unwrap_err();
assert!(alias_dst.contains("aliases a Move operand"), "{alias_dst}");
// Cross-body Program::try_new rejects oob callee, arity mismatch, and
// argument/return type mismatch, while admitting matching signatures.
let callee_body = Body::try_new(
1,
false,
vec![enum_ty.clone(), enum_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Move { local: 1 },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::callee_enum".into(),
)
.unwrap();
let caller_ok = Body::try_new(
1,
false,
vec![enum_ty.clone(), enum_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::Call {
callee: 1,
args: vec![Operand::Copy { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::caller_ok".into(),
)
.unwrap();
let prog_ok = Program::try_new(
Scope::Crate {
excluded_traits: BTreeSet::new(),
},
vec![caller_ok, callee_body.clone()],
)
.unwrap();
let mut ids = BTreeSet::new();
prog_ok.bodies()[0].collect_enum_ids(&mut ids);
assert!(ids.contains(&303));
let caller_bad_type = Body::try_new(
1,
false,
vec![u32_ty.clone(), u32_ty],
vec![
Block {
statements: vec![],
terminator: Terminator::Call {
callee: 1,
args: vec![Operand::Copy { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::caller_bad_type".into(),
)
.unwrap();
let mismatch = Program::try_new(
Scope::Crate {
excluded_traits: BTreeSet::new(),
},
vec![caller_bad_type, callee_body],
)
.unwrap_err();
assert!(mismatch.contains("disagrees with callee"), "{mismatch}");
}
#[test]
fn array_eq_rejects_enum_elements() {
let enum_ty = EnumTy::try_new(
303,
IntTy {
width: IntWidth::I8,
signed: false,
},
EnumTagRepr::Scalar(IntTy {
width: IntWidth::I8,
signed: false,
}),
vec![0, 1],
)
.unwrap();
let arr_ty = Ty::Array {
elem: Box::new(Ty::Enum(enum_ty.clone())),
len: 2,
};
let ref_arr_ty = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(arr_ty),
};
let err = Body::try_new(
2,
false,
vec![Ty::Bool, ref_arr_ty.clone(), ref_arr_ty],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::ArrayEq {
elem: Ty::Enum(enum_ty),
len: 2,
},
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::enum_array_eq".into(),
)
.unwrap_err();
assert!(err.contains("invalid CoreCall ArrayEq"), "{err}");
}
#[test]
fn constant_index_honors_from_end_matching_lean_semantics() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
for len in 0..=4usize {
let arr_ty = Ty::Array {
elem: Box::new(u8_ty.clone()),
len,
};
for min_length in 0..=5usize {
for offset in 0..=5usize {
for from_end in [false, true] {
let expected_ok = len >= min_length
&& if from_end {
offset >= 1 && offset <= len
} else {
offset < len
};
let res = Body::try_new(
1,
false,
vec![u8_ty.clone(), arr_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::ConstantIndex {
offset,
min_length,
from_end,
}],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::const_idx_bounds".into(),
);
assert_eq!(
res.is_ok(),
expected_ok,
"len={len} min_length={min_length} offset={offset} from_end={from_end}: {res:?}"
);
}
}
}
}
}
#[test]
fn fake_address_of_enforces_metadata_only_temporary_invariants() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let slice_u8 = Ty::Slice {
elem: Box::new(u8_ty.clone()),
};
let mut_slice_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(slice_u8.clone()),
};
let const_slice_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(slice_u8.clone()),
};
let mut_slice_ptr = Ty::RawPtr {
mutability: Mutability::Mut,
pointee: Box::new(slice_u8),
};
let const_u8_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
};
let mut_u8_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(u8_ty.clone()),
};
// 1. Valid metadata-only temporary on `&mut [u8]` succeeds and selects
// Profile v2.
let valid = Body::try_new(
1,
false,
vec![
usize_ty.clone(),
mut_slice_ref.clone(),
const_slice_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::Move { local: 2 },
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::valid_fake_ptr_metadata".into(),
)
.expect("valid FakeAddressOf + PtrMetadata body must pass");
assert!(valid.uses_profile_v2());
// 2. Adding an unrelated real `*const u8` local alongside `&mut [u8]`
// is still rejected by `validate_local_tys_with_exemptions`.
let mixed_err = Body::try_new(
1,
false,
vec![
usize_ty.clone(),
mut_slice_ref.clone(),
const_slice_ptr.clone(),
const_u8_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::Move { local: 2 },
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::mixed_fake_and_real_raw".into(),
)
.unwrap_err();
assert!(
mixed_err.contains("body mixes reference and raw-pointer locals"),
"{mixed_err}"
);
// 3. Parameter local (`lid <= arg_count`) cannot be exempted as a fake
// metadata temporary.
let arg_err = Body::try_new(
2,
false,
vec![
usize_ty.clone(),
mut_slice_ref.clone(),
const_slice_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::Move { local: 2 },
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::fake_meta_param".into(),
)
.unwrap_err();
assert!(
arg_err.contains("body mixes reference and raw-pointer locals"),
"{arg_err}"
);
// Return place (`_0`, `lid < arg_count`) cannot be exempted either
// (kills `lid <= arg_count -> lid == arg_count`).
let ret_err = Body::try_new(
1,
false,
vec![const_slice_ptr.clone(), mut_slice_ref.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::fake_meta_return_place".into(),
)
.unwrap_err();
assert!(
ret_err.contains("body mixes reference and raw-pointer locals"),
"{ret_err}"
);
// 4. `*mut [u8]` destination is rejected.
let mut_dst_err = Body::try_new(
1,
false,
vec![usize_ty, mut_slice_ref, mut_slice_ptr],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::fake_meta_mut_dst".into(),
)
.unwrap_err();
assert!(
mut_dst_err.contains("body mixes reference and raw-pointer locals"),
"{mut_dst_err}"
);
// 5. Dereferencing the fake temporary (`*_2`) in a ref body fails the
// mixed-locals guard, and copying `_2` in a raw-pointer-only body
// fails the unconditional `FakeAddressOf` discipline check.
let deref_err = Body::try_new(
1,
false,
vec![u8_ty, mut_u8_ref, const_u8_ptr.clone()],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
},
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::deref_fake_meta".into(),
)
.unwrap_err();
assert!(
deref_err.contains("body mixes reference and raw-pointer locals"),
"{deref_err}"
);
let raw_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Copy { local: 2 },
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::raw_only_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
raw_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{raw_escape_err}"
);
// 6. Passing a fake-metadata local as a `Terminator::CoreCall` argument
// (without mentioning it in `dst`) or overwriting it as a `CoreCall`
// destination (without mentioning it in `args`) must both fail
// closed (kills `|| -> &&` in `terminator_mentions_local_v2`).
let core_call_arg_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![
Block {
statements: vec![Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::CoreCall {
op: CoreCallOp::PtrAdd {
mutability: Mutability::Shared,
pointee: Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
}),
},
args: vec![
Operand::Copy { local: 2 },
Operand::Constant {
ty: Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
}),
lit: ConstLit::Scalar { bits: 0 },
},
],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::core_call_arg_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
core_call_arg_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{core_call_arg_escape_err}"
);
let core_call_dst_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![
Block {
statements: vec![Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::CoreCall {
op: CoreCallOp::PtrAdd {
mutability: Mutability::Shared,
pointee: Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
}),
},
args: vec![
Operand::Copy { local: 1 },
Operand::Constant {
ty: Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
}),
lit: ConstLit::Scalar { bits: 0 },
},
],
dst: Place {
local: 2,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::core_call_dst_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
core_call_dst_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{core_call_dst_escape_err}"
);
// 7. Self-referential `_2 = FakeAddressOf(*_2)` must fail closed
// (kills `fake_address_of_types_match_v2 -> true`).
let self_assign_err = Body::try_new(
1,
true,
vec![
Ty::Unit,
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![Block {
statements: vec![Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::self_assign_fake_meta".into(),
)
.unwrap_err();
assert!(
self_assign_err.contains("read exclusively by UnOp::PtrMetadata"),
"{self_assign_err}"
);
// 8. `Statement::AssignPlace` reading `PtrMetadata(move _3)` into a
// projected destination (`*_2`) is admitted, while copying `_3` into
// a projected destination is rejected.
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let mut_usize_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(usize_ty.clone()),
};
let mut_slice_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice {
elem: Box::new(Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
})),
}),
};
let assign_place_ok = Body::try_new(
2,
false,
vec![
Ty::Unit,
mut_slice_ref.clone(),
mut_usize_ref.clone(),
const_slice_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 3,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::AssignPlace {
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::Move { local: 3 },
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::assign_place_ptr_metadata_ok".into(),
)
.expect("AssignPlace reading PtrMetadata of fake temp must pass");
assert!(assign_place_ok.uses_profile_v2());
let assign_place_bad_err = Body::try_new(
2,
false,
vec![
Ty::Unit,
mut_slice_ref,
mut_usize_ref,
const_slice_ptr,
],
vec![Block {
statements: vec![
Statement::Assign {
local: 3,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::AssignPlace {
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
value: Rvalue::Use {
operand: Operand::Copy { local: 3 },
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::assign_place_copy_fake_meta_bad".into(),
)
.unwrap_err();
assert!(
assign_place_bad_err.contains("body mixes reference and raw-pointer locals"),
"{assign_place_bad_err}"
);
// 9. Escaping a fake-metadata temporary through `Rvalue::Binary`
// (`BinOp::Offset`) in a raw-pointer-only body must fail closed
// (kills `|| -> &&` in `rvalue_mentions_local_v2`).
let isize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: true,
});
let binary_offset_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![Block {
statements: vec![
Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
},
Statement::Assign {
local: 0,
value: Rvalue::Binary {
op: BinOp::Offset,
left: Operand::Move { local: 2 },
right: Operand::Constant {
ty: isize_ty.clone(),
lit: ConstLit::Scalar { bits: 0 },
},
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::binary_offset_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
binary_offset_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{binary_offset_escape_err}"
);
// 10. Passing a fake-metadata local as a `Terminator::Call` argument
// or overwriting it as a `Terminator::Call` destination must both
// fail closed (kills `|| -> &&` and each disjunct in
// `terminator_mentions_local_v2` for `Terminator::Call`).
let call_arg_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![
Block {
statements: vec![Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::Call {
callee: 0,
args: vec![Operand::Copy { local: 2 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::call_arg_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
call_arg_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{call_arg_escape_err}"
);
let call_dst_escape_err = Body::try_new(
1,
true,
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
vec![
Block {
statements: vec![Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
}],
terminator: Terminator::Call {
callee: 0,
args: vec![Operand::Copy { local: 1 }],
dst: 2,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::call_dst_escape_fake_meta".into(),
)
.unwrap_err();
assert!(
call_dst_escape_err.contains("read exclusively by UnOp::PtrMetadata"),
"{call_dst_escape_err}"
);
// 11. Other well-typed escapes (`Cast`, `AggregateTuple`, `AddressOf`,
// distinct-dst `FakeAddressOf`, non-`FakeAddressOf` second
// assignment, and `PlaceMention`) must all fail closed. (`Repeat`
// and `AggregateArray` cannot hold raw-pointer elements in the
// Profile v2 type fragment and are covered directly in
// `fake_ptr_metadata_predicates_cover_every_arm`.)
let fake_assign_2 = Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
};
let ptr_pair_ty = Ty::Tuple {
fields: vec![const_u8_ptr.clone(), const_u8_ptr.clone()],
};
let escape_cases: Vec<(&str, Vec<Ty>, Statement)> = vec![
(
"cast_escape",
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
Statement::Assign {
local: 0,
value: Rvalue::Cast {
cast_kind: CastKind::PtrToPtr,
operand: Operand::Move { local: 2 },
ty: const_u8_ptr.clone(),
},
},
),
(
"tuple_escape",
vec![ptr_pair_ty, const_u8_ptr.clone(), const_u8_ptr.clone()],
Statement::Assign {
local: 0,
value: Rvalue::AggregateTuple {
fields: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
},
},
),
(
"address_of_escape",
vec![
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
Statement::Assign {
local: 0,
value: Rvalue::AddressOf {
mutability: Mutability::Shared,
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
},
},
),
(
"chained_fake_address_of_escape",
vec![
Ty::Unit,
const_u8_ptr.clone(),
const_u8_ptr.clone(),
const_u8_ptr.clone(),
],
Statement::Assign {
local: 3,
value: Rvalue::FakeAddressOf {
place: Place {
local: 2,
projection: vec![PlaceElem::Deref],
},
},
},
),
(
"second_non_fake_assign",
vec![Ty::Unit, const_u8_ptr.clone(), const_u8_ptr.clone()],
Statement::Assign {
local: 2,
value: Rvalue::Use {
operand: Operand::Copy { local: 1 },
with_retag: false,
},
},
),
(
"place_mention_escape",
vec![Ty::Unit, const_u8_ptr.clone(), const_u8_ptr.clone()],
Statement::PlaceMention { local: 2 },
),
];
for (name, locals, stmt) in escape_cases {
let err = Body::try_new(
1,
true,
locals,
vec![Block {
statements: vec![fake_assign_2.clone(), stmt],
terminator: Terminator::Ret,
}],
format!("rust-path-v1::{name}"),
)
.unwrap_err();
assert!(
err.contains("read exclusively by UnOp::PtrMetadata"),
"{name}: {err}"
);
}
// 12. Unprojected `CopyPlace` read by `UnOp::PtrMetadata` is admitted.
let slice_u8 = Ty::Slice {
elem: Box::new(Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
})),
};
let mut_slice_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(slice_u8.clone()),
};
let const_slice_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(slice_u8),
};
let ok = Body::try_new(
1,
false,
vec![usize_ty, mut_slice_ref, const_slice_ptr],
vec![Block {
statements: vec![
fake_assign_2,
Statement::Assign {
local: 0,
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::CopyPlace {
place: Place {
local: 2,
projection: vec![],
},
},
},
},
],
terminator: Terminator::Ret,
}],
"rust-path-v1::ptr_metadata_unprojected_copy_place_ok".into(),
)
.expect("unprojected CopyPlace PtrMetadata must pass");
assert!(ok.uses_profile_v2());
}
#[test]
fn fake_ptr_metadata_predicates_cover_every_arm() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let const_u8_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
};
let mut_u8_ptr = Ty::RawPtr {
mutability: Mutability::Mut,
pointee: Box::new(u8_ty.clone()),
};
let const_usize_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(usize_ty.clone()),
};
let overflow_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::OverflowPair(IntTy {
width: IntWidth::I8,
signed: false,
})),
};
let overflow_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(Ty::OverflowPair(IntTy {
width: IntWidth::I8,
signed: false,
})),
};
let p2 = Place {
local: 2,
projection: vec![],
};
let p2_deref = Place {
local: 2,
projection: vec![PlaceElem::Deref],
};
let p1 = Place {
local: 1,
projection: vec![],
};
let c0 = Operand::Constant {
ty: usize_ty.clone(),
lit: ConstLit::Scalar { bits: 0 },
};
// `operand_mentions_local_v2`
assert!(operand_mentions_local_v2(&Operand::Copy { local: 2 }, 2));
assert!(!operand_mentions_local_v2(&Operand::Copy { local: 1 }, 2));
assert!(operand_mentions_local_v2(&Operand::Move { local: 2 }, 2));
assert!(!operand_mentions_local_v2(&Operand::Move { local: 1 }, 2));
assert!(operand_mentions_local_v2(
&Operand::CopyPlace { place: p2.clone() },
2
));
assert!(!operand_mentions_local_v2(
&Operand::CopyPlace { place: p1.clone() },
2
));
assert!(operand_mentions_local_v2(
&Operand::MovePlace { place: p2.clone() },
2
));
assert!(!operand_mentions_local_v2(
&Operand::MovePlace { place: p1.clone() },
2
));
assert!(!operand_mentions_local_v2(&c0, 2));
// `rvalue_mentions_local_v2` across every Rvalue arm (including both
// sides of Binary).
let rv_true = [
Rvalue::Use {
operand: Operand::Copy { local: 2 },
with_retag: false,
},
Rvalue::UseRetag {
operand: Operand::Move { local: 2 },
},
Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::Copy { local: 2 },
},
Rvalue::Cast {
cast_kind: CastKind::PtrToPtr,
operand: Operand::Copy { local: 2 },
ty: const_u8_ptr.clone(),
},
Rvalue::Repeat {
operand: Operand::Copy { local: 2 },
elem_ty: const_u8_ptr.clone(),
count: 2,
},
Rvalue::AggregateRangeTo {
elem_ty: usize_ty.clone(),
end: Operand::Copy { local: 2 },
},
Rvalue::AggregateRangeFrom {
elem_ty: usize_ty.clone(),
start: Operand::Copy { local: 2 },
},
Rvalue::Binary {
op: BinOp::Offset,
left: Operand::Copy { local: 2 },
right: c0.clone(),
},
Rvalue::Binary {
op: BinOp::Add,
left: c0.clone(),
right: Operand::Copy { local: 2 },
},
Rvalue::Discriminant { place: p2.clone() },
Rvalue::Ref {
mutability: Mutability::Shared,
place: p2.clone(),
},
Rvalue::AddressOf {
mutability: Mutability::Shared,
place: p2_deref.clone(),
},
Rvalue::FakeAddressOf {
place: p2_deref.clone(),
},
Rvalue::AggregateTuple {
fields: vec![c0.clone(), Operand::Copy { local: 2 }],
},
Rvalue::AggregateArray {
elem_ty: const_u8_ptr.clone(),
elems: vec![c0.clone(), Operand::Copy { local: 2 }],
},
Rvalue::AggregateAdtEnum {
ty: Ty::Unit,
variant_idx: 0,
fields: vec![c0.clone(), Operand::Copy { local: 2 }],
},
];
for rv in &rv_true {
assert!(rvalue_mentions_local_v2(rv, 2), "expected mention: {rv:?}");
assert!(
!rvalue_mentions_local_v2(rv, 3),
"unexpected mention of 3: {rv:?}"
);
}
// `terminator_mentions_local_v2` across every Terminator arm
let sys_op = SysrootNumOp {
kind: SysrootNumKind::WrappingAdd,
ty: IntTy {
width: IntWidth::Isize,
signed: false,
},
};
let term_false = [
Terminator::Goto { block: 0 },
Terminator::Ret,
Terminator::Unreachable,
Terminator::Unsupported,
Terminator::SwitchInt {
operand: Operand::Copy { local: 1 },
targets: vec![],
otherwise: 0,
},
Terminator::Assert {
cond: Operand::Copy { local: 1 },
expected: true,
msg: AssertKind::BoundsCheck,
target: 0,
unwind: UnwindAction::Continue,
},
Terminator::SysrootCall {
op: sys_op,
args: vec![Operand::Copy { local: 1 }, c0.clone()],
dst: 0,
target: Some(0),
unwind: UnwindAction::Continue,
},
];
for term in &term_false {
assert!(
!terminator_mentions_local_v2(term, 2),
"unexpected mention: {term:?}"
);
}
let term_true = [
Terminator::SwitchInt {
operand: Operand::Copy { local: 2 },
targets: vec![],
otherwise: 0,
},
Terminator::Assert {
cond: Operand::Copy { local: 2 },
expected: true,
msg: AssertKind::BoundsCheck,
target: 0,
unwind: UnwindAction::Continue,
},
Terminator::CoreCall {
op: CoreCallOp::SliceLen,
args: vec![Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(0),
unwind: UnwindAction::Continue,
},
Terminator::CoreCall {
op: CoreCallOp::SliceLen,
args: vec![Operand::Copy { local: 1 }],
dst: p2.clone(),
target: Some(0),
unwind: UnwindAction::Continue,
},
Terminator::Call {
callee: 0,
args: vec![Operand::Copy { local: 2 }],
dst: 0,
target: Some(0),
unwind: UnwindAction::Continue,
},
Terminator::Call {
callee: 0,
args: vec![Operand::Copy { local: 1 }],
dst: 2,
target: Some(0),
unwind: UnwindAction::Continue,
},
Terminator::SysrootCall {
op: sys_op,
args: vec![Operand::Copy { local: 2 }, c0.clone()],
dst: 0,
target: Some(0),
unwind: UnwindAction::Continue,
},
Terminator::SysrootCall {
op: sys_op,
args: vec![Operand::Copy { local: 1 }, c0.clone()],
dst: 2,
target: Some(0),
unwind: UnwindAction::Continue,
},
];
for term in &term_true {
assert!(
terminator_mentions_local_v2(term, 2),
"expected mention: {term:?}"
);
}
// `fake_address_of_types_match_v2` rejection branches
let base_locals = vec![Ty::Unit, const_u8_ptr.clone(), const_u8_ptr.clone()];
assert!(fake_address_of_types_match_v2(
&base_locals,
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref],
}
));
assert!(!fake_address_of_types_match_v2(&base_locals, 2, &p2_deref));
assert!(!fake_address_of_types_match_v2(&base_locals, 2, &p1));
assert!(!fake_address_of_types_match_v2(
&base_locals,
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref, PlaceElem::Deref],
}
));
assert!(!fake_address_of_types_match_v2(
&[Ty::Unit, u8_ty.clone(), const_u8_ptr.clone()],
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref],
}
));
assert!(!fake_address_of_types_match_v2(
&[Ty::Unit, overflow_ref, overflow_ptr],
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref],
}
));
assert!(!fake_address_of_types_match_v2(
&[Ty::Unit, const_u8_ptr.clone(), mut_u8_ptr],
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref],
}
));
assert!(!fake_address_of_types_match_v2(
&[Ty::Unit, const_u8_ptr.clone(), const_usize_ptr],
2,
&Place {
local: 1,
projection: vec![PlaceElem::Deref],
}
));
// `is_fake_ptr_metadata_local_v2` structural rejections unreachable via
// MIR typing rules alone (projected `PtrMetadata` operand,
// `AssignPlace` writing through `*_2`, and `SysrootCall` mention).
let fake_assign = Statement::Assign {
local: 2,
value: Rvalue::FakeAddressOf {
place: Place {
local: 1,
projection: vec![PlaceElem::Deref],
},
},
};
let proj_ptr_meta = Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::CopyPlace {
place: p2_deref.clone(),
},
};
assert!(is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::Assign {
local: 0,
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::MovePlace { place: p2.clone() },
},
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::AssignPlace {
place: Place {
local: 0,
projection: vec![PlaceElem::Deref],
},
value: Rvalue::Unary {
op: UnOp::PtrMetadata,
operand: Operand::MovePlace { place: p2 },
},
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::Assign {
local: 0,
value: proj_ptr_meta.clone(),
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::AssignPlace {
place: Place {
local: 0,
projection: vec![PlaceElem::Deref],
},
value: proj_ptr_meta,
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::AssignPlace {
place: p2_deref.clone(),
value: Rvalue::Use {
operand: c0.clone(),
with_retag: false,
},
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::Assign {
local: 0,
value: Rvalue::Repeat {
operand: Operand::Copy { local: 2 },
elem_ty: const_u8_ptr.clone(),
count: 2,
},
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::Assign {
local: 0,
value: Rvalue::AggregateArray {
elem_ty: const_u8_ptr,
elems: vec![c0.clone(), Operand::Copy { local: 2 }],
},
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![
fake_assign.clone(),
Statement::PlaceMentionPlace {
place: p2_deref,
},
],
terminator: Terminator::Ret,
}],
2,
));
assert!(!is_fake_ptr_metadata_local_v2(
1,
&base_locals,
&[Block {
statements: vec![fake_assign],
terminator: Terminator::SysrootCall {
op: sys_op,
args: vec![Operand::Copy { local: 2 }, c0],
dst: 0,
target: Some(0),
unwind: UnwindAction::Continue,
},
}],
2,
));
}
#[test]
fn profile_v2_option_range_and_core_call_type_guards() {
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
let range_ty = Ty::Range {
elem: Box::new(usize_ty.clone()),
};
let opt_u64 = Ty::Option {
elem: Box::new(u64_ty.clone()),
};
let opt_ref = Ty::Option {
elem: Box::new(Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u64_ty.clone()),
}),
};
let opt_opt = Ty::Option {
elem: Box::new(opt_u64.clone()),
};
assert!(range_ty.is_supported_v2_local());
assert!(opt_u64.is_supported_v2_local());
assert!(opt_u64.is_retag_noop());
assert!(opt_ref.is_supported_v2_local());
assert!(!opt_ref.is_retag_noop());
assert!(!opt_opt.is_supported_v2_local());
// Local tuples and `Range*` are supported, whereas pointee/slice
// elements and `Option` payloads reject `#[repr(Rust)]` tuples (and
// `OverflowPair`), `Range*`, and nested `Option<Option<_>>`.
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u32_ty = Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
});
let reordered_tuple = Ty::Tuple {
fields: vec![u8_ty.clone(), u32_ty.clone(), u8_ty.clone()],
};
let overflow_pair = Ty::OverflowPair(IntTy {
width: IntWidth::I8,
signed: false,
});
assert!(reordered_tuple.is_supported_v2_local());
assert!(overflow_pair.is_supported_v2_local());
assert!(!reordered_tuple.is_sized_no_ref());
assert!(!overflow_pair.is_sized_no_ref());
assert!(!range_ty.is_sized_no_ref());
let mut_opt_u64 = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(opt_u64.clone()),
};
assert!(mut_opt_u64.is_supported_v2_local());
assert!(!Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(reordered_tuple.clone()),
}
.is_supported_v2_local());
assert!(!Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(overflow_pair.clone()),
}
.is_supported_v2_local());
assert!(!Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(Ty::Tuple {
fields: vec![u8_ty.clone(), u32_ty],
}),
}),
}
.is_supported_v2_local());
assert!(!Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(range_ty.clone()),
}
.is_supported_v2_local());
assert!(!Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Option {
elem: Box::new(Ty::Option {
elem: Box::new(u8_ty),
}),
}),
}
.is_supported_v2_local());
assert!(!Ty::Option {
elem: Box::new(reordered_tuple),
}
.is_supported_v2_local());
assert!(!Ty::Option {
elem: Box::new(overflow_pair),
}
.is_supported_v2_local());
assert!(!Ty::Option {
elem: Box::new(range_ty),
}
.is_supported_v2_local());
assert!(!Ty::Option {
elem: Box::new(Ty::RangeFrom {
elem: Box::new(usize_ty.clone()),
}),
}
.is_supported_v2_local());
assert!(!Ty::Option {
elem: Box::new(Ty::RangeTo {
elem: Box::new(usize_ty),
}),
}
.is_supported_v2_local());
// Downcast on Option must be variant 1 -> field 0 of inner type.
let ok_body = Body::try_new(
1,
false,
vec![u64_ty.clone(), opt_u64.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field {
index: 0,
ty: u64_ty.clone(),
},
],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::option_downcast".into(),
);
assert!(ok_body.is_ok(), "{ok_body:?}");
let dangling_downcast = Body::try_new(
1,
false,
vec![opt_u64.clone(), opt_u64],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::Downcast { variant_idx: 1 }],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::dangling_downcast".into(),
)
.unwrap_err();
assert!(dangling_downcast.contains("must be followed by field projection"));
// Through a reference, a downcast may be read
// (`Trusted.MirSemantics.projectMemoryPlaceV2`) but not written.
let u32_int = IntTy { width: IntWidth::I32, signed: false };
let u32_ty = Ty::Int(u32_int);
let opt_u32 = Ty::Option { elem: Box::new(u32_ty.clone()) };
let payload = Place {
local: 1,
projection: vec![
PlaceElem::Deref,
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: u32_ty.clone() },
],
};
let ref_to = |mutability| Ty::Ref { mutability, pointee: Box::new(opt_u32.clone()) };
let read = Body::try_new(
1,
false,
vec![u32_ty.clone(), ref_to(Mutability::Shared)],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace { place: payload.clone() },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::option_downcast_through_ref".into(),
);
assert!(read.is_ok(), "{read:?}");
let write = Body::try_new(
1,
false,
vec![Ty::Unit, ref_to(Mutability::Mut)],
vec![Block {
statements: vec![Statement::AssignPlace {
place: payload,
value: Rvalue::Use {
operand: Operand::Constant { ty: u32_ty.clone(), lit: ConstLit::Scalar { bits: 1 } },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::option_downcast_write_through_ref".into(),
)
.unwrap_err();
assert!(write.contains("write through a downcast"), "{write}");
// A downcast within a slice element is refused: `sliceElemAddrV2`
// resolves element places without downcasts.
let usize_ty = Ty::Int(IntTy { width: IntWidth::Isize, signed: false });
let slice_elem = Body::try_new(
2,
false,
vec![
u32_ty.clone(),
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice { elem: Box::new(opt_u32.clone()) }),
},
usize_ty,
],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Deref,
PlaceElem::Index { local: 2 },
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: u32_ty.clone() },
],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::option_downcast_in_slice_element".into(),
)
.unwrap_err();
assert!(slice_elem.contains("in-memory downcast"), "{slice_elem}");
}
#[test]
fn is_sized_and_place_projection_guards_cover_unsized_downcast_and_range() {
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let u32_ty = Ty::Int(IntTy { width: IntWidth::I32, signed: false });
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
let usize_ty = Ty::Int(IntTy { width: IntWidth::Isize, signed: false });
let slice_u8 = Ty::Slice { elem: Box::new(u8_ty.clone()) };
let ref_slice_u8 = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(slice_u8.clone()),
};
let ptr_slice_u8 = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(slice_u8.clone()),
};
let opt_u64 = Ty::Option { elem: Box::new(u64_ty.clone()) };
let range_usize = Ty::Range { elem: Box::new(usize_ty.clone()) };
let range_u32 = Ty::Range { elem: Box::new(u32_ty.clone()) };
// Ty::is_sized must return false on unsized slices and unsized
// composite tuples, and true on sized references/pointers.
assert!(!slice_u8.is_sized());
assert!(!Ty::Tuple { fields: vec![u8_ty.clone(), slice_u8.clone()] }.is_sized());
assert!(u8_ty.is_sized());
assert!(ref_slice_u8.is_sized());
assert!(ptr_slice_u8.is_sized());
assert!(opt_u64.is_sized());
assert!(range_usize.is_sized());
// Unsized deref in a non-PtrMetadata place must fail closed via
// is_sized.
let unsized_deref = Body::try_new(
1,
false,
vec![u8_ty.clone(), ref_slice_u8.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place { local: 1, projection: vec![PlaceElem::Deref] },
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unsized_deref".into(),
)
.unwrap_err();
assert!(unsized_deref.contains("unsized deref"), "{unsized_deref}");
// PtrAdd on an unsized slice pointee must fail closed via is_sized.
let unsized_ptr_add = Body::try_new(
2,
false,
vec![ptr_slice_u8.clone(), ptr_slice_u8.clone(), usize_ty.clone()],
vec![Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::PtrAdd {
mutability: Mutability::Shared,
pointee: slice_u8.clone(),
},
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place { local: 0, projection: vec![] },
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
}],
"rust-path-v1::unsized_ptr_add".into(),
)
.unwrap_err();
assert!(unsized_ptr_add.contains("invalid CoreCall PtrAdd"), "{unsized_ptr_add}");
// Downcast(1) on a non-Option type must fail closed.
let non_opt_downcast = Body::try_new(
1,
false,
vec![u64_ty.clone(), u64_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: u64_ty.clone() },
],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::non_opt_downcast".into(),
)
.unwrap_err();
assert!(non_opt_downcast.contains("unsupported downcast variant"), "{non_opt_downcast}");
// Downcast(0) (None) on Option must fail closed.
let none_downcast = Body::try_new(
1,
false,
vec![u64_ty.clone(), opt_u64.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx: 0 },
PlaceElem::Field { index: 0, ty: u64_ty.clone() },
],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::none_downcast".into(),
)
.unwrap_err();
assert!(none_downcast.contains("unsupported downcast variant"), "{none_downcast}");
// [Downcast(1), Field(1)] on Option must fail closed.
let bad_downcast_field = Body::try_new(
1,
false,
vec![u64_ty.clone(), opt_u64.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 1, ty: u64_ty.clone() },
],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::bad_downcast_field".into(),
)
.unwrap_err();
assert!(bad_downcast_field.contains("unsupported downcast field"), "{bad_downcast_field}");
// Positive Range<usize> .start (0) and .end (1) projections.
for field_idx in [0usize, 1usize] {
let ok_range = Body::try_new(
1,
false,
vec![usize_ty.clone(), range_usize.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::Field {
index: field_idx,
ty: usize_ty.clone(),
}],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
format!("rust-path-v1::range_field_{field_idx}"),
);
assert!(ok_range.is_ok(), "field {field_idx}: {ok_range:?}");
}
// Out-of-bounds field 2 on Range<usize> must fail closed.
let bad_range_idx = Body::try_new(
1,
false,
vec![usize_ty.clone(), range_usize],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::Field {
index: 2,
ty: usize_ty.clone(),
}],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::bad_range_idx".into(),
)
.unwrap_err();
assert!(bad_range_idx.contains("unsupported field 2"), "{bad_range_idx}");
// Field 0 on non-usize Range<u32> must fail closed.
let bad_range_elem = Body::try_new(
1,
false,
vec![u32_ty.clone(), range_u32],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::Field {
index: 0,
ty: u32_ty.clone(),
}],
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::bad_range_elem".into(),
)
.unwrap_err();
assert!(
bad_range_elem.contains("outside the Profile v2 type fragment"),
"{bad_range_elem}"
);
}
#[test]
fn v2_layout_covers_all_variants_and_rejects_non_zst_as_zero() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u16_ty = Ty::Int(IntTy {
width: IntWidth::I16,
signed: false,
});
let u32_ty = Ty::Int(IntTy {
width: IntWidth::I32,
signed: false,
});
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
let u128_ty = Ty::Int(IntTy {
width: IntWidth::I128,
signed: false,
});
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let isize_ty = IntTy {
width: IntWidth::Isize,
signed: true,
};
let zst_enum = Ty::Enum(
EnumTy::try_new(11, isize_ty, EnumTagRepr::ZeroSized, vec![0]).unwrap(),
);
let u16_enum = Ty::Enum(
EnumTy::try_new(
12,
isize_ty,
EnumTagRepr::Scalar(IntTy {
width: IntWidth::I16,
signed: false,
}),
vec![0, 1],
)
.unwrap(),
);
assert_eq!(Ty::Bool.v2_layout(), Some((1, 0)));
assert_eq!(Ty::Ordering.v2_layout(), Some((1, 0)));
assert_eq!(u8_ty.v2_layout(), Some((1, 0)));
assert_eq!(u16_ty.v2_layout(), Some((2, 1)));
assert_eq!(u32_ty.v2_layout(), Some((4, 2)));
assert_eq!(u64_ty.v2_layout(), Some((8, 3)));
assert_eq!(usize_ty.v2_layout(), Some((8, 3)));
assert_eq!(u128_ty.v2_layout(), Some((16, 4)));
assert_eq!(Ty::Char.v2_layout(), Some((4, 2)));
assert_eq!(Ty::Unit.v2_layout(), Some((0, 0)));
assert_eq!(Ty::Never.v2_layout(), Some((0, 0)));
assert_eq!(zst_enum.v2_layout(), Some((0, 0)));
assert_eq!(u16_enum.v2_layout(), Some((2, 1)));
assert_eq!(
Ty::OverflowPair(IntTy {
width: IntWidth::I32,
signed: false
})
.v2_layout(),
Some((8, 2))
);
assert_eq!(
Ty::Array {
elem: Box::new(u32_ty.clone()),
len: 3
}
.v2_layout(),
Some((12, 2))
);
assert_eq!(
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u64_ty.clone())
}
.v2_layout(),
Some((8, 3))
);
assert_eq!(
Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone())
})
}
.v2_layout(),
Some((16, 3))
);
assert_eq!(
Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u64_ty.clone())
}
.v2_layout(),
Some((8, 3))
);
assert_eq!(
Ty::RawPtr {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone())
})
}
.v2_layout(),
Some((16, 3))
);
assert_eq!(
Ty::RangeTo {
elem: Box::new(usize_ty.clone())
}
.v2_layout(),
Some((8, 3))
);
assert_eq!(
Ty::RangeFrom {
elem: Box::new(usize_ty.clone())
}
.v2_layout(),
Some((8, 3))
);
assert_eq!(
Ty::Range {
elem: Box::new(usize_ty)
}
.v2_layout(),
None
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::Bool)
}
.v2_layout(),
Some((1, 0))
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::Unit)
}
.v2_layout(),
Some((1, 0))
);
assert_eq!(
Ty::Option {
elem: Box::new(u64_ty.clone())
}
.v2_layout(),
Some((16, 3))
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone())
})
}
.v2_layout(),
None
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone())
})
})
}
.v2_layout(),
None
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone())
})
}
.v2_layout(),
None
);
assert_eq!(
Ty::Option {
elem: Box::new(Ty::Option {
elem: Box::new(u8_ty.clone())
})
}
.v2_layout(),
None
);
assert_eq!(
Ty::Tuple {
fields: vec![u8_ty.clone(), u64_ty]
}
.v2_layout(),
None
);
assert_eq!(
Ty::Slice {
elem: Box::new(u8_ty)
}
.v2_layout(),
None
);
}
#[test]
fn profile_v2_validators_and_gating_reject_malformed_ir() {
let u8_ity = IntTy {
width: IntWidth::I8,
signed: false,
};
let u64_ity = IntTy {
width: IntWidth::I64,
signed: false,
};
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let isize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: true,
});
let u8_ty = Ty::Int(u8_ity);
let u64_ty = Ty::Int(u64_ity);
let range_usize = Ty::Range {
elem: Box::new(usize_ty.clone()),
};
let opt_u64 = Ty::Option {
elem: Box::new(u64_ty.clone()),
};
let mut_ref_u64 = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(u64_ty.clone()),
};
let enum_ty = Ty::Enum(
EnumTy::try_new(
404,
IntTy {
width: IntWidth::Isize,
signed: true,
},
EnumTagRepr::ZeroSized,
vec![0],
)
.unwrap(),
);
// Positive and negative is_array_eq_elem_supported coverage.
assert!(u8_ty.is_array_eq_elem_supported());
assert!(Ty::Bool.is_array_eq_elem_supported());
assert!(Ty::Char.is_array_eq_elem_supported());
assert!(Ty::Ordering.is_array_eq_elem_supported());
assert!(Ty::Unit.is_array_eq_elem_supported());
assert!(Ty::Array {
elem: Box::new(u8_ty.clone()),
len: 2,
}
.is_array_eq_elem_supported());
assert!(!Ty::Never.is_array_eq_elem_supported());
assert!(!enum_ty.is_array_eq_elem_supported());
assert!(!opt_u64.is_array_eq_elem_supported());
assert!(!range_usize.is_array_eq_elem_supported());
assert!(!mut_ref_u64.is_array_eq_elem_supported());
// Ty::is_profile_v2 gates Range and Option.
assert!(range_usize.is_profile_v2());
assert!(opt_u64.is_profile_v2());
assert!(!u64_ty.is_profile_v2());
// AggregateRange: positive, wrong dst_ty, and half-ill-typed bounds.
let agg_range_ok = Body::try_new(
2,
false,
vec![range_usize.clone(), usize_ty.clone(), usize_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateRange {
elem_ty: usize_ty.clone(),
start: Operand::Copy { local: 1 },
end: Operand::Copy { local: 2 },
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::agg_range_ok".into(),
)
.unwrap();
assert!(agg_range_ok.uses_profile_v2());
let agg_range_bad_dst = Body::try_new(
2,
false,
vec![usize_ty.clone(), usize_ty.clone(), usize_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateRange {
elem_ty: usize_ty.clone(),
start: Operand::Copy { local: 1 },
end: Operand::Copy { local: 2 },
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::agg_range_bad_dst".into(),
)
.unwrap_err();
assert!(
agg_range_bad_dst.contains("AggregateRange"),
"{agg_range_bad_dst}"
);
let agg_range_bad_end = Body::try_new(
2,
false,
vec![range_usize.clone(), usize_ty.clone(), u8_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateRange {
elem_ty: usize_ty.clone(),
start: Operand::Copy { local: 1 },
end: Operand::Copy { local: 2 },
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::agg_range_bad_end".into(),
)
.unwrap_err();
assert!(
agg_range_bad_end.contains("AggregateRange"),
"{agg_range_bad_end}"
);
let agg_range_bad_start = Body::try_new(
2,
false,
vec![range_usize.clone(), u8_ty.clone(), usize_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateRange {
elem_ty: usize_ty.clone(),
start: Operand::Copy { local: 1 },
end: Operand::Copy { local: 2 },
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::agg_range_bad_start".into(),
)
.unwrap_err();
assert!(
agg_range_bad_start.contains("AggregateRange"),
"{agg_range_bad_start}"
);
// Option Discriminant: positive isize dst, negative non-isize dst.
let opt_discr_ok = Body::try_new(
1,
false,
vec![isize_ty.clone(), opt_u64.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Discriminant {
place: Place {
local: 1,
projection: vec![],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::opt_discr_ok".into(),
)
.unwrap();
assert!(opt_discr_ok.uses_profile_v2());
let opt_discr_bad = Body::try_new(
1,
false,
vec![u8_ty.clone(), opt_u64.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Discriminant {
place: Place {
local: 1,
projection: vec![],
},
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::opt_discr_bad".into(),
)
.unwrap_err();
assert!(opt_discr_bad.contains("discriminant"), "{opt_discr_bad}");
// NumOverflowingAdd/Sub: positive + negative r_ty/dst_ty/l_ty checks.
for op in [
CoreCallOp::NumOverflowingAdd(u64_ity),
CoreCallOp::NumOverflowingSub(u64_ity),
] {
let ovf_ok = Body::try_new(
2,
false,
vec![Ty::OverflowPair(u64_ity), u64_ty.clone(), u64_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: op.clone(),
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::ovf_ok".into(),
)
.unwrap();
assert!(ovf_ok.uses_profile_v2());
// Valid l_ty + mismatched r_ty must still fail closed.
let ovf_bad_rhs = Body::try_new(
2,
false,
vec![Ty::OverflowPair(u64_ity), u64_ty.clone(), u8_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: op.clone(),
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::ovf_bad_rhs".into(),
)
.unwrap_err();
assert!(ovf_bad_rhs.contains("invalid CoreCall"), "{ovf_bad_rhs}");
// Valid l_ty + valid r_ty + wrong dst_ty must still fail closed.
let ovf_bad_dst = Body::try_new(
2,
false,
vec![u64_ty.clone(), u64_ty.clone(), u64_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op,
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::ovf_bad_dst".into(),
)
.unwrap_err();
assert!(ovf_bad_dst.contains("invalid CoreCall"), "{ovf_bad_dst}");
}
// CoreCallOp::MemReplace: positive and mismatched src_ty rejection.
let mem_replace_ok = Body::try_new(
2,
false,
vec![u64_ty.clone(), mut_ref_u64.clone(), u64_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::MemReplace { ty: u64_ty.clone() },
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::mem_replace_ok".into(),
)
.unwrap();
assert!(mem_replace_ok.uses_profile_v2());
let mem_replace_bad_src = Body::try_new(
2,
false,
vec![u64_ty.clone(), mut_ref_u64, u8_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::MemReplace { ty: u64_ty.clone() },
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::mem_replace_bad_src".into(),
)
.unwrap_err();
assert!(
mem_replace_bad_src.contains("invalid CoreCall"),
"{mem_replace_bad_src}"
);
// CoreCallOp::MemReplace of a `Vec<u8>`, which owns a heap buffer:
// the source must be moved, and the moved operands and destination
// must be distinct locals.
let vec_u8 = Ty::Vec {
elem: Box::new(u8_ty.clone()),
};
let mut_ref_vec = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(vec_u8.clone()),
};
let mem_replace_vec = |args: Vec<Operand>, dst: u32| {
Body::try_new(
2,
false,
vec![vec_u8.clone(), mut_ref_vec.clone(), vec_u8.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::MemReplace { ty: vec_u8.clone() },
args,
dst: Place {
local: dst,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::mem_replace_vec".into(),
)
};
mem_replace_vec(vec![Operand::Move { local: 1 }, Operand::Move { local: 2 }], 0).unwrap();
let copied =
mem_replace_vec(vec![Operand::Move { local: 1 }, Operand::Copy { local: 2 }], 0)
.unwrap_err();
assert!(copied.contains("requires a moved or constant source operand"), "{copied}");
let aliased =
mem_replace_vec(vec![Operand::Move { local: 1 }, Operand::Move { local: 2 }], 2)
.unwrap_err();
assert!(aliased.contains("aliases a Move operand"), "{aliased}");
// Program::try_new admits intra-crate `Call`s and `core::num`
// `SysrootCall`s in a Profile v2 program.
let v1_callee = Body::try_new(
1,
false,
vec![u64_ty.clone(), u64_ty.clone()],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::Copy { local: 1 },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::v1_callee".into(),
)
.unwrap();
let v1_caller = Body::try_new(
1,
false,
vec![u64_ty.clone(), u64_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::Call {
callee: 0,
args: vec![Operand::Copy { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::v1_caller".into(),
)
.unwrap();
let sysroot_caller = Body::try_new(
1,
false,
vec![u64_ty.clone(), u64_ty.clone()],
vec![
Block {
statements: vec![],
terminator: Terminator::SysrootCall {
op: SysrootNumOp {
kind: SysrootNumKind::WrappingAdd,
ty: IntTy { width: IntWidth::I64, signed: false },
},
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::sysroot_caller".into(),
)
.unwrap();
// Profile v2 admits intra-crate `Call`s.
let with_call = Program::try_new(
Scope::Crate { excluded_traits: BTreeSet::new() },
vec![v1_callee.clone(), v1_caller, agg_range_ok.clone()],
)
.unwrap();
assert_eq!(with_call.mir_profile_version(), 2);
// It admits `core::num` sysroot calls too.
let with_sysroot_call = Program::try_new(
Scope::Crate { excluded_traits: BTreeSet::new() },
vec![v1_callee, sysroot_caller, agg_range_ok],
)
.unwrap();
assert_eq!(with_sysroot_call.mir_profile_version(), 2);
// `Rvalue::AggregateOption` validation: valid None/Some, bad dst,
// mismatched Some payload, and invalid variant/payload combinations.
let opt_u64_ty = Ty::Option {
elem: Box::new(u64_ty.clone()),
};
let opt_u8_ty = Ty::Option {
elem: Box::new(u8_ty.clone()),
};
let u32_ity = IntTy {
width: IntWidth::I32,
signed: false,
};
let u32_ty = Ty::Int(u32_ity);
let i32_ty = Ty::Int(IntTy {
width: IntWidth::I32,
signed: true,
});
let i64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: true,
});
let check_agg_opt = |locals: Vec<Ty>, arg_count: usize, value: Rvalue| {
Body::try_new(
arg_count,
false,
locals,
vec![Block {
statements: vec![Statement::Assign { local: 0, value }],
terminator: Terminator::Ret,
}],
"rust-path-v1::agg_opt_check".into(),
)
};
assert!(
check_agg_opt(
vec![opt_u64_ty.clone()],
0,
Rvalue::AggregateOption {
variant_idx: 0,
inner_ty: u64_ty.clone(),
payload: None,
},
)
.is_ok()
);
assert!(
check_agg_opt(
vec![opt_u64_ty.clone(), u64_ty.clone()],
1,
Rvalue::AggregateOption {
variant_idx: 1,
inner_ty: u64_ty.clone(),
payload: Some(Box::new(Operand::Copy { local: 1 })),
},
)
.is_ok()
);
let agg_opt_bad_dst = check_agg_opt(
vec![opt_u8_ty],
0,
Rvalue::AggregateOption {
variant_idx: 0,
inner_ty: u64_ty.clone(),
payload: None,
},
)
.unwrap_err();
assert!(
agg_opt_bad_dst.contains("AggregateOption requires Option<inner_ty> destination"),
"{agg_opt_bad_dst}"
);
let agg_opt_bad_some_ty = check_agg_opt(
vec![opt_u64_ty.clone(), u8_ty.clone()],
1,
Rvalue::AggregateOption {
variant_idx: 1,
inner_ty: u64_ty.clone(),
payload: Some(Box::new(Operand::Copy { local: 1 })),
},
)
.unwrap_err();
assert!(
agg_opt_bad_some_ty.contains("AggregateOption Some payload type mismatch"),
"{agg_opt_bad_some_ty}"
);
for (variant_idx, payload) in [
(0, Some(Box::new(Operand::Copy { local: 1 }))),
(1, None),
(2, None),
] {
let err = check_agg_opt(
vec![opt_u64_ty.clone(), u64_ty.clone()],
1,
Rvalue::AggregateOption {
variant_idx,
inner_ty: u64_ty.clone(),
payload,
},
)
.unwrap_err();
assert!(
err.contains("invalid AggregateOption variant/payload"),
"variant={variant_idx}: {err}"
);
}
// `NumWrappingShl`, `NumWrappingShr`, and `NumLeadingZeros` operand and
// destination type guards (positive + every individual mismatch).
let check_core_call = |locals: Vec<Ty>, arg_count: usize, op: CoreCallOp, args: Vec<Operand>| {
Body::try_new(
arg_count,
false,
locals,
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op,
args,
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::core_call_check".into(),
)
};
for op in [
CoreCallOp::NumWrappingShl(u64_ity),
CoreCallOp::NumWrappingShr(u64_ity),
] {
assert!(
check_core_call(
vec![u64_ty.clone(), u64_ty.clone(), u32_ty.clone()],
2,
op.clone(),
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok()
);
for (label, locals) in [
("bad_l_ty", vec![u64_ty.clone(), u8_ty.clone(), u32_ty.clone()]),
("bad_r_ty_width", vec![u64_ty.clone(), u64_ty.clone(), u64_ty.clone()]),
("bad_r_ty_sign", vec![u64_ty.clone(), u64_ty.clone(), i32_ty.clone()]),
("bad_dst_width", vec![u32_ty.clone(), u64_ty.clone(), u32_ty.clone()]),
("bad_dst_sign", vec![i64_ty.clone(), u64_ty.clone(), u32_ty.clone()]),
] {
let err = check_core_call(
locals,
2,
op.clone(),
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
}
assert!(
check_core_call(
vec![u32_ty.clone(), u64_ty.clone()],
1,
CoreCallOp::NumLeadingZeros(u64_ity),
vec![Operand::Copy { local: 1 }],
)
.is_ok()
);
for (label, locals) in [
("lz_bad_l_ty", vec![u32_ty.clone(), u8_ty.clone()]),
("lz_bad_dst_width", vec![u64_ty.clone(), u64_ty.clone()]),
("lz_bad_dst_sign", vec![i32_ty, u64_ty.clone()]),
] {
let err = check_core_call(
locals,
1,
CoreCallOp::NumLeadingZeros(u64_ity),
vec![Operand::Copy { local: 1 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
// `CoreCallOp::{SliceSplitAt, NumIsMultipleOf, OptionIsSome, OptionIsNone}`
// signature checks (positive + negative cases).
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let slice_u8_shared = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone()),
}),
};
let slice_u8_mut = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone()),
}),
};
let slice_u32_shared = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u32_ty.clone()),
}),
};
let split_shared_dst = Ty::Tuple {
fields: vec![slice_u8_shared.clone(), slice_u8_shared.clone()],
};
let split_mut_dst = Ty::Tuple {
fields: vec![slice_u8_mut.clone(), slice_u8_mut.clone()],
};
assert!(
check_core_call(
vec![
split_shared_dst.clone(),
slice_u8_shared.clone(),
usize_ty.clone(),
],
2,
CoreCallOp::SliceSplitAt {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok()
);
assert!(
check_core_call(
vec![split_mut_dst.clone(), slice_u8_mut.clone(), usize_ty.clone()],
2,
CoreCallOp::SliceSplitAt {
mutability: Mutability::Mut,
elem: u8_ty.clone(),
},
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok()
);
for (label, locals, op) in [
(
"split_at_bad_mid_ty_with_valid_dst",
vec![
split_shared_dst.clone(),
slice_u8_shared.clone(),
u32_ty.clone(),
],
CoreCallOp::SliceSplitAt {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
),
(
"split_at_bad_elem_with_valid_dst",
vec![
split_shared_dst.clone(),
slice_u32_shared.clone(),
usize_ty.clone(),
],
CoreCallOp::SliceSplitAt {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
),
(
"split_at_bad_mut_with_valid_dst",
vec![
split_shared_dst.clone(),
slice_u8_mut.clone(),
usize_ty.clone(),
],
CoreCallOp::SliceSplitAt {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
),
(
"split_at_bad_dst_ty",
vec![
split_mut_dst,
slice_u8_shared.clone(),
usize_ty.clone(),
],
CoreCallOp::SliceSplitAt {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
),
] {
let err = check_core_call(
locals,
2,
op,
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
// `CoreCallOp::SliceIndexRangeFrom` checks the input mutability and
// element against the destination, not just the destination.
let range_from_usize = Ty::RangeFrom {
elem: Box::new(usize_ty.clone()),
};
let u16_ty = Ty::Int(IntTy {
width: IntWidth::I16,
signed: false,
});
let slice_u16_shared = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u16_ty.clone()),
}),
};
assert!(
check_core_call(
vec![
slice_u8_shared.clone(),
slice_u8_shared.clone(),
range_from_usize.clone(),
],
2,
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok()
);
for (label, locals, op) in [
(
"range_from_shared_to_mut",
vec![
slice_u8_mut.clone(),
slice_u8_shared.clone(),
range_from_usize.clone(),
],
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Mut,
elem: u8_ty.clone(),
},
),
(
"range_from_elem_mismatch",
vec![
slice_u16_shared.clone(),
slice_u8_shared.clone(),
range_from_usize.clone(),
],
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: u16_ty.clone(),
},
),
] {
let err = check_core_call(
locals,
2,
op,
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
// `CoreCallOp::{NumCheckedAdd, NumCheckedMul, NumCheckedSub}` admit
// `Option<T>` results over matching operands only.
let u8_ity = IntTy {
width: IntWidth::I8,
signed: false,
};
let opt_u8_ty = Ty::Option {
elem: Box::new(u8_ty.clone()),
};
for op in [
CoreCallOp::NumCheckedAdd(u8_ity),
CoreCallOp::NumCheckedMul(u8_ity),
CoreCallOp::NumCheckedSub(u8_ity),
] {
assert!(
check_core_call(
vec![opt_u8_ty.clone(), u8_ty.clone(), u8_ty.clone()],
2,
op.clone(),
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok(),
"{op:?}"
);
for (label, locals) in [
(
"checked_bad_dst",
vec![u8_ty.clone(), u8_ty.clone(), u8_ty.clone()],
),
(
"checked_bad_rhs",
vec![opt_u8_ty.clone(), u8_ty.clone(), u32_ty.clone()],
),
] {
let err = check_core_call(
locals,
2,
op.clone(),
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label} {op:?}: {err}");
}
}
let i64_ity = IntTy {
width: IntWidth::I64,
signed: true,
};
let i64_ty = Ty::Int(i64_ity);
assert!(
check_core_call(
vec![Ty::Bool, u64_ty.clone(), u64_ty.clone()],
2,
CoreCallOp::NumIsMultipleOf(u64_ity),
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.is_ok()
);
for (label, locals, op) in [
(
"is_multiple_of_bad_r_ty_width",
vec![Ty::Bool, u64_ty.clone(), u32_ty.clone()],
CoreCallOp::NumIsMultipleOf(u64_ity),
),
(
"is_multiple_of_bad_r_ty_sign",
vec![Ty::Bool, u64_ty.clone(), i64_ty.clone()],
CoreCallOp::NumIsMultipleOf(u64_ity),
),
(
"is_multiple_of_bad_l_ty",
vec![Ty::Bool, u32_ty.clone(), u64_ty.clone()],
CoreCallOp::NumIsMultipleOf(u64_ity),
),
(
"is_multiple_of_signed_rejected",
vec![Ty::Bool, i64_ty.clone(), i64_ty],
CoreCallOp::NumIsMultipleOf(i64_ity),
),
(
"is_multiple_of_bad_dst_ty",
vec![u64_ty.clone(), u64_ty.clone(), u64_ty.clone()],
CoreCallOp::NumIsMultipleOf(u64_ity),
),
] {
let err = check_core_call(
locals,
2,
op,
vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
)
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
let ref_opt_u32 = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Option {
elem: Box::new(u32_ty.clone()),
}),
};
let ref_opt_u64 = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Option {
elem: Box::new(u64_ty.clone()),
}),
};
let ref_u32 = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u32_ty.clone()),
};
for op_ctor in [
|t| CoreCallOp::OptionIsSome { inner: t },
|t| CoreCallOp::OptionIsNone { inner: t },
] {
assert!(
check_core_call(
vec![Ty::Bool, ref_opt_u32.clone()],
1,
op_ctor(u32_ty.clone()),
vec![Operand::Copy { local: 1 }],
)
.is_ok()
);
for (label, locals, op) in [
(
"opt_pred_mismatched_inner",
vec![Ty::Bool, ref_opt_u64.clone()],
op_ctor(u32_ty.clone()),
),
(
"opt_pred_non_option_pointee",
vec![Ty::Bool, ref_u32.clone()],
op_ctor(u32_ty.clone()),
),
(
"opt_pred_bad_dst_ty",
vec![u32_ty.clone(), ref_opt_u32.clone()],
op_ctor(u32_ty.clone()),
),
] {
let err = check_core_call(locals, 1, op, vec![Operand::Copy { local: 1 }])
.unwrap_err();
assert!(err.contains("invalid CoreCall"), "{label}: {err}");
}
}
// `check_place` rejects post-field, post-downcast, and nested `Deref`.
let ref_u8_ty = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u8_ty.clone()),
};
let mut_ref_u8_ty = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(u8_ty.clone()),
};
let tuple_ref_u8 = Ty::Tuple {
fields: vec![ref_u8_ty.clone(), u8_ty.clone()],
};
let tuple_mut_ref_u8 = Ty::Tuple {
fields: vec![mut_ref_u8_ty.clone(), u8_ty.clone()],
};
let opt_ref_u8 = Ty::Option {
elem: Box::new(ref_u8_ty.clone()),
};
for (label, arg_ty, projection) in [
(
"post_field_deref",
tuple_ref_u8,
vec![
PlaceElem::Field {
index: 0,
ty: ref_u8_ty.clone(),
},
PlaceElem::Deref,
],
),
(
"post_downcast_field_deref",
opt_ref_u8,
vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field {
index: 0,
ty: ref_u8_ty.clone(),
},
PlaceElem::Deref,
],
),
(
"nested_deref",
ref_u8_ty,
vec![PlaceElem::Deref, PlaceElem::Deref],
),
] {
let err = Body::try_new(
1,
false,
vec![u8_ty.clone(), arg_ty],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection,
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::bad_deref_read".into(),
)
.unwrap_err();
assert!(
err.contains("nested or post-field deref projections are unsupported"),
"{label}: {err}"
);
}
let post_field_write_err = Body::try_new(
2,
false,
vec![Ty::Unit, tuple_mut_ref_u8, u8_ty.clone()],
vec![Block {
statements: vec![Statement::AssignPlace {
place: Place {
local: 1,
projection: vec![
PlaceElem::Field {
index: 0,
ty: mut_ref_u8_ty,
},
PlaceElem::Deref,
],
},
value: Rvalue::Use {
operand: Operand::Copy { local: 2 },
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::bad_deref_write".into(),
)
.unwrap_err();
assert!(
post_field_write_err.contains("nested or post-field deref projections are unsupported"),
"{post_field_write_err}"
);
// `check_place` admits a read through a post-deref `Downcast`, which
// `Trusted.MirSemantics.projectMemoryPlaceV2` models, and rejects a
// nested `Downcast`.
let opt_u8 = Ty::Option {
elem: Box::new(u8_ty.clone()),
};
let ref_opt_u8 = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(opt_u8.clone()),
};
for (label, arg_ty, projection, refused) in [
(
"post_deref_downcast_read",
ref_opt_u8,
vec![
PlaceElem::Deref,
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field {
index: 0,
ty: u8_ty.clone(),
},
],
false,
),
(
"nested_downcast",
opt_u8,
vec![
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field {
index: 0,
ty: u8_ty.clone(),
},
],
true,
),
] {
let result = Body::try_new(
1,
false,
vec![u8_ty.clone(), arg_ty],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: Place {
local: 1,
projection,
},
},
with_retag: false,
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::downcast_read".into(),
);
if refused {
let err = result.unwrap_err();
assert!(err.contains("nested downcast projections"), "{label}: {err}");
} else {
assert!(result.is_ok(), "{label}: {result:?}");
}
}
}
#[test]
fn core_panic_ops_validate_diverging_signatures() {
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let str_ref_ty = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
};
let valid_str_arg = Operand::Constant {
ty: str_ref_ty.clone(),
lit: ConstLit::RodataRef {
bytes: vec![
RodataByte::Init { byte: b'o' },
RodataByte::Init { byte: b'k' },
],
align_log2: 0,
offset_bytes: 0,
slice_len: Some(2),
},
};
let never_dst = Place {
local: 1,
projection: vec![],
};
let unit_dst = Place {
local: 0,
projection: vec![],
};
// Valid `PanicAbort`: 1 `&str` rodata arg, `dst: !`, `target: None`.
assert!(
Body::try_new(
0,
false,
vec![Ty::Unit, Ty::Never],
vec![Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::PanicAbort,
args: vec![valid_str_arg.clone()],
dst: never_dst.clone(),
target: None,
unwind: UnwindAction::Unreachable,
},
}],
"rust-path-v1::panic_abort_ok".into(),
)
.is_ok()
);
// `PanicAbort` with `target: Some(_)` reaches the diverging target
// guard ("diverging panic CoreCall PanicAbort must not have a return
// target").
let target_err = Body::try_new(
0,
false,
vec![Ty::Unit, Ty::Never],
vec![Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::PanicAbort,
args: vec![valid_str_arg.clone()],
dst: never_dst.clone(),
target: Some(0),
unwind: UnwindAction::Unreachable,
},
}],
"rust-path-v1::panic_abort_bad_target".into(),
)
.unwrap_err();
assert!(
target_err
.contains("diverging panic CoreCall PanicAbort must not have a return target"),
"{target_err}"
);
// `PanicAbort` rejects 0 args, 2 args, non-`&str` args, and non-`!`
// destinations (killing every guard clause).
for bad_args in [
vec![],
vec![valid_str_arg.clone(), valid_str_arg.clone()],
vec![Operand::Constant {
ty: usize_ty.clone(),
lit: ConstLit::Scalar { bits: 3 },
}],
vec![Operand::Constant {
ty: Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty),
}),
},
lit: ConstLit::RodataRef {
bytes: vec![RodataByte::Init { byte: b'o' }],
align_log2: 0,
offset_bytes: 0,
slice_len: Some(1),
},
}],
] {
let err = Body::try_new(
0,
false,
vec![Ty::Unit, Ty::Never],
vec![Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::PanicAbort,
args: bad_args,
dst: never_dst.clone(),
target: None,
unwind: UnwindAction::Unreachable,
},
}],
"rust-path-v1::panic_abort_bad_args".into(),
)
.unwrap_err();
assert!(err.contains("invalid CoreCall PanicAbort"), "{err}");
}
let dst_err = Body::try_new(
0,
false,
vec![Ty::Unit, Ty::Never],
vec![Block {
statements: vec![],
terminator: Terminator::CoreCall {
op: CoreCallOp::PanicAbort,
args: vec![valid_str_arg],
dst: unit_dst,
target: None,
unwind: UnwindAction::Unreachable,
},
}],
"rust-path-v1::panic_abort_bad_dst".into(),
)
.unwrap_err();
assert!(dst_err.contains("invalid CoreCall PanicAbort"), "{dst_err}");
// `validate_constant` enforces UTF-8, initialization, bounds,
// alignment, and shared-reference-only invariants on `&str` rodata
// constants.
let hello_bytes: Vec<RodataByte> =
b"hello".iter().map(|&byte| RodataByte::Init { byte }).collect();
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: 0,
slice_len: Some(5),
},
)
.is_ok()
);
// Valid interior and exact-end subslices
// (`offset_bytes + len <= bytes.len()`), plus maximum allowed
// `align_log2 == 29`.
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 29,
offset_bytes: 1,
slice_len: Some(3),
},
)
.is_ok()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: 2,
slice_len: Some(3),
},
)
.is_ok()
);
// Out-of-bounds subslice (`offset_bytes + len > bytes.len()`), `usize`
// addition overflow, excessive alignment (`align_log2 > 29`), excessive
// `len >= 2^63`, missing `slice_len`, and `&mut str` must fail closed
// without panicking.
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: 3,
slice_len: Some(3),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: usize::MAX,
slice_len: Some(1),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 30,
offset_bytes: 0,
slice_len: Some(5),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: 0,
slice_len: Some(1usize << 63),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: hello_bytes.clone(),
align_log2: 0,
offset_bytes: 0,
slice_len: None,
},
)
.is_err()
);
assert!(
validate_constant(
&Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Str),
},
&ConstLit::RodataRef {
bytes: hello_bytes,
align_log2: 0,
offset_bytes: 0,
slice_len: Some(5),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: vec![RodataByte::Init { byte: 0xff }],
align_log2: 0,
offset_bytes: 0,
slice_len: Some(1),
},
)
.is_err()
);
assert!(
validate_constant(
&str_ref_ty,
&ConstLit::RodataRef {
bytes: vec![RodataByte::Uninit],
align_log2: 0,
offset_bytes: 0,
slice_len: Some(1),
},
)
.is_err()
);
assert!(
validate_constant(
&Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
},
&ConstLit::RodataRef {
bytes: vec![RodataByte::Init { byte: b'a' }],
align_log2: 0,
offset_bytes: 0,
slice_len: Some(1),
},
)
.is_err()
);
// `Ty::Str` and `&str` predicates (`is_sized`,
// `is_array_eq_elem_supported`, `v2_layout`, `is_supported_v2_local`,
// `is_profile_v2`).
let mut_str_ref_ty = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Str),
};
let const_str_ptr_ty = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
};
let mut_str_ptr_ty = Ty::RawPtr {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Str),
};
assert!(!Ty::Str.is_sized());
assert!(!Ty::Str.is_array_eq_elem_supported());
assert_eq!(Ty::Str.v2_layout(), None);
assert!(!Ty::Str.is_supported_v2_local());
assert!(Ty::Str.is_profile_v2());
assert!(str_ref_ty.is_sized());
assert!(!str_ref_ty.is_array_eq_elem_supported());
assert_eq!(str_ref_ty.v2_layout(), Some((16, 3)));
assert!(str_ref_ty.is_supported_v2_local());
assert!(str_ref_ty.is_profile_v2());
assert!(mut_str_ref_ty.is_sized());
assert_eq!(mut_str_ref_ty.v2_layout(), Some((16, 3)));
assert!(!mut_str_ref_ty.is_supported_v2_local());
assert!(!const_str_ptr_ty.is_supported_v2_local());
assert!(!mut_str_ptr_ty.is_supported_v2_local());
// `check_unary_types` for `UnOp::PtrMetadata` across shared/mut `&str`,
// raw `str` pointers, slice references/pointers, and sized pointers.
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
let u8_slice_ty = Ty::Slice {
elem: Box::new(u8_ty.clone()),
};
assert!(check_unary_types(UnOp::PtrMetadata, &str_ref_ty, &usize_ty).is_ok());
assert!(check_unary_types(UnOp::PtrMetadata, &str_ref_ty, &u64_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &str_ref_ty, &Ty::Unit).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &mut_str_ref_ty, &usize_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &mut_str_ref_ty, &Ty::Unit).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &const_str_ptr_ty, &usize_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &const_str_ptr_ty, &Ty::Unit).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &mut_str_ptr_ty, &usize_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &Ty::Str, &usize_ty).is_err());
for mutability in [Mutability::Shared, Mutability::Mut] {
let slice_ref = Ty::Ref {
mutability,
pointee: Box::new(u8_slice_ty.clone()),
};
let slice_ptr = Ty::RawPtr {
mutability,
pointee: Box::new(u8_slice_ty.clone()),
};
let sized_ref = Ty::Ref {
mutability,
pointee: Box::new(u8_ty.clone()),
};
let sized_ptr = Ty::RawPtr {
mutability,
pointee: Box::new(u8_ty.clone()),
};
assert!(check_unary_types(UnOp::PtrMetadata, &slice_ref, &usize_ty).is_ok());
assert!(check_unary_types(UnOp::PtrMetadata, &slice_ref, &Ty::Unit).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &slice_ptr, &usize_ty).is_ok());
assert!(check_unary_types(UnOp::PtrMetadata, &slice_ptr, &u64_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &slice_ptr, &Ty::Unit).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &sized_ref, &Ty::Unit).is_ok());
assert!(check_unary_types(UnOp::PtrMetadata, &sized_ref, &usize_ty).is_err());
assert!(check_unary_types(UnOp::PtrMetadata, &sized_ptr, &Ty::Unit).is_ok());
assert!(check_unary_types(UnOp::PtrMetadata, &sized_ptr, &usize_ty).is_err());
}
// `Body::uses_profile_v2` `Assert` narrowing: primitive Profile v1
// `AssertKind`s stay in Profile v1, while optional overflow kinds
// route to Profile v2.
let mk_assert_body = |cond: Operand, msg: AssertKind| {
Body::try_new(
0,
false,
vec![Ty::Unit, Ty::Bool],
vec![
Block {
statements: Vec::new(),
terminator: Terminator::Assert {
cond,
expected: true,
msg,
target: 1,
unwind: UnwindAction::Continue,
},
},
Block {
statements: Vec::new(),
terminator: Terminator::Ret,
},
],
"rust-path-v1::assert_profile_routing".into(),
)
.unwrap()
};
let v1_bool_cond = Operand::Copy { local: 1 };
for v1_msg in [
AssertKind::DivByZero,
AssertKind::RemByZero,
AssertKind::Overflow { op: BinOp::Div },
AssertKind::Overflow { op: BinOp::Rem },
AssertKind::BoundsCheck,
AssertKind::MisalignedPtrDeref,
AssertKind::NullPtrDeref,
] {
assert!(
!mk_assert_body(v1_bool_cond.clone(), v1_msg).uses_profile_v2(),
"expected Profile v1 for {v1_msg:?}"
);
}
for v2_msg in [
AssertKind::Overflow { op: BinOp::Add },
AssertKind::Overflow { op: BinOp::Sub },
AssertKind::Overflow { op: BinOp::Mul },
AssertKind::Overflow { op: BinOp::Shl },
AssertKind::Overflow { op: BinOp::Shr },
AssertKind::OverflowNeg,
] {
assert!(
mk_assert_body(v1_bool_cond.clone(), v2_msg).uses_profile_v2(),
"expected Profile v2 for {v2_msg:?}"
);
}
}
#[test]
fn is_owned_data_admits_handles_and_refuses_pointers_and_overflow_pairs() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let boxed = || Box::new(u8_ty.clone());
for ty in [
u8_ty.clone(),
Ty::Bool,
Ty::Char,
Ty::Unit,
Ty::Array {
elem: boxed(),
len: 2,
},
Ty::Vec { elem: boxed() },
Ty::Box { pointee: boxed() },
Ty::Box {
pointee: Box::new(Ty::Slice { elem: boxed() }),
},
Ty::Option {
elem: Box::new(Ty::Box { pointee: boxed() }),
},
// `Option` of plain sized data has its `rustc` layout.
Ty::Option { elem: boxed() },
] {
assert!(ty.is_owned_data(), "{ty:?}");
}
for ty in [
Ty::OverflowPair(IntTy {
width: IntWidth::I8,
signed: false,
}),
Ty::Tuple {
fields: vec![u8_ty.clone(), Ty::Bool],
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: boxed(),
},
Ty::RawPtr {
mutability: Mutability::Mut,
pointee: boxed(),
},
Ty::Slice { elem: boxed() },
Ty::Option {
elem: Box::new(Ty::Ref {
mutability: Mutability::Shared,
pointee: boxed(),
}),
},
Ty::Vec {
elem: Box::new(Ty::RawPtr {
mutability: Mutability::Shared,
pointee: boxed(),
}),
},
] {
assert!(!ty.is_owned_data(), "{ty:?}");
}
}
#[test]
fn box_and_vec_core_calls_and_box_as_ref_reject_mismatched_types() {
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u16_ty = Ty::Int(IntTy {
width: IntWidth::I16,
signed: false,
});
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let shared_ref = |pointee: &Ty| Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(pointee.clone()),
};
let box_of = |pointee: &Ty| Ty::Box {
pointee: Box::new(pointee.clone()),
};
let vec_u8 = Ty::Vec {
elem: Box::new(u8_ty.clone()),
};
// Local 0 is the destination; locals 1.. are the arguments, in order.
let call = |op: CoreCallOp, local_tys: Vec<Ty>| {
let args = (1..local_tys.len() as u32)
.map(|local| Operand::Copy { local })
.collect();
Body::try_new(
local_tys.len() - 1,
false,
local_tys,
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op,
args,
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::box_vec_core_call".into(),
)
};
let assert_invalid = |op: CoreCallOp, local_tys: Vec<Ty>| {
let err = call(op.clone(), local_tys.clone()).unwrap_err();
assert!(
err.contains("invalid CoreCall"),
"{op:?} {local_tys:?}: {err}"
);
};
// `VecLen` needs both a `&Vec<_>` argument and a `usize` destination.
call(
CoreCallOp::VecLen,
vec![usize_ty.clone(), shared_ref(&vec_u8)],
)
.unwrap();
assert_invalid(CoreCallOp::VecLen, vec![u8_ty.clone(), shared_ref(&vec_u8)]);
assert_invalid(
CoreCallOp::VecLen,
vec![usize_ty.clone(), shared_ref(&u8_ty)],
);
// `BoxDeref` maps `&Box<T>` to `&T` for the same `T`.
let ref_box_u8 = shared_ref(&box_of(&u8_ty));
call(
CoreCallOp::BoxDeref,
vec![shared_ref(&u8_ty), ref_box_u8.clone()],
)
.unwrap();
assert_invalid(
CoreCallOp::BoxDeref,
vec![shared_ref(&u16_ty), ref_box_u8.clone()],
);
assert_invalid(
CoreCallOp::BoxDeref,
vec![shared_ref(&u8_ty), shared_ref(&u8_ty)],
);
// `BoxClone` maps `&Box<T>` to `Box<T>` for the same `T`.
call(
CoreCallOp::BoxClone,
vec![box_of(&u8_ty), ref_box_u8.clone()],
)
.unwrap();
assert_invalid(CoreCallOp::BoxClone, vec![box_of(&u16_ty), ref_box_u8]);
assert_invalid(
CoreCallOp::BoxClone,
vec![u8_ty.clone(), shared_ref(&u8_ty)],
);
// `BoxNew { pointee: T }` maps a `T` to `Box<T>`.
let box_new_u8 = || CoreCallOp::BoxNew {
pointee: u8_ty.clone(),
};
call(box_new_u8(), vec![box_of(&u8_ty), u8_ty.clone()]).unwrap();
assert_invalid(box_new_u8(), vec![box_of(&u16_ty), u8_ty.clone()]);
assert_invalid(box_new_u8(), vec![box_of(&u8_ty), u16_ty.clone()]);
// `BoxAsRef` casts `Box<T>` to `&T` for the same `T`.
check_cast_types(
CastKind::BoxAsRef,
&box_of(&u8_ty),
&shared_ref(&u8_ty),
&shared_ref(&u8_ty),
)
.unwrap();
let err = check_cast_types(
CastKind::BoxAsRef,
&box_of(&u8_ty),
&shared_ref(&u16_ty),
&shared_ref(&u16_ty),
)
.unwrap_err();
assert!(err.contains("unsupported cast"), "{err}");
}
/// `Body::profile_v2_trigger` routes a `Not`/`Neg` to Profile v2 exactly
/// when its operand needs Profile v2. `rustc` usually copies a tuple field
/// to a scalar temporary first, so the integration tests only see scalar
/// operands; this builds the projected-operand case directly.
#[test]
fn profile_v2_trigger_unary_follows_operand_profile() {
let u32_ity = IntTy {
width: IntWidth::I32,
signed: false,
};
let unary_body = |locals: Vec<Ty>, op: UnOp, operand: Operand| {
Body::try_new(
1,
false,
locals,
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::Unary { op, operand },
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unary_profile_routing".into(),
)
.unwrap()
};
// Scalar operands stay in Profile v1.
let not_scalar = unary_body(
vec![Ty::Bool, Ty::Bool],
UnOp::Not,
Operand::Copy { local: 1 },
);
assert_eq!(not_scalar.profile_v2_trigger(), None);
let i32_ty = Ty::Int(IntTy {
width: IntWidth::I32,
signed: true,
});
let neg_scalar = unary_body(
vec![i32_ty.clone(), i32_ty],
UnOp::Neg,
Operand::Copy { local: 1 },
);
assert_eq!(neg_scalar.profile_v2_trigger(), None);
// `!copy (_1.1)` on a Profile v1 `(u32, bool)` local: every local type
// is Profile v1, so only the projected operand can select Profile v2.
let not_field = unary_body(
vec![Ty::Bool, Ty::OverflowPair(u32_ity)],
UnOp::Not,
Operand::CopyPlace {
place: Place {
local: 1,
projection: vec![PlaceElem::Field {
index: 1,
ty: Ty::Bool,
}],
},
},
);
assert!(!Ty::OverflowPair(u32_ity).is_profile_v2());
let trigger = not_field
.profile_v2_trigger()
.expect("projected operand selects Profile v2");
assert!(trigger.starts_with("bb0[0]: unary `Not` of "), "{trigger}");
}
fn u8_ty() -> Ty {
Ty::Int(IntTy { width: IntWidth::I8, signed: false })
}
fn u32_ty() -> Ty {
Ty::Int(IntTy { width: IntWidth::I32, signed: false })
}
fn usize_ty() -> Ty {
Ty::Int(IntTy { width: IntWidth::Isize, signed: false })
}
/// A struct type with layout id `id`, built directly so that tests can
/// form fields that `StructTy::try_new` would reject.
fn raw_struct(id: u32, size: usize, field_offsets: Vec<usize>, fields: Vec<Ty>) -> Ty {
Ty::Struct(StructTy {
layout: StructLayout { id, size, align_log2: 3, field_offsets },
fields,
synthetic: None,
})
}
/// `struct Node { id: u64, parent: Option<Box<Node>> }` as layout id `7`.
fn rec_node(field_offsets: Vec<usize>) -> Ty {
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
let parent = Ty::Option {
elem: Box::new(Ty::Box { pointee: Box::new(Ty::RecSelf { id: 7 }) }),
};
Ty::RecAdt { id: 7, defn: Box::new(raw_struct(7, 16, field_offsets, vec![u64_ty, parent])) }
}
/// An array of owned data is owned data and a local type, mirroring
/// `Trusted.MirSemantics.isOwnedDataTyV2` and `isSupportedV2LocalTy`; an
/// array of references is neither.
#[test]
fn arrays_of_owned_data_are_owned_and_local() {
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let boxes = Ty::Array { elem: Box::new(Ty::Box { pointee: Box::new(u8_ty.clone()) }), len: 2 };
assert!(boxes.is_owned_data());
assert!(boxes.is_supported_v2_local());
let nodes = Ty::Array { elem: Box::new(rec_node(vec![0, 8])), len: 10 };
assert!(nodes.is_owned_data());
assert!(nodes.is_supported_v2_local());
let refs = Ty::Array {
elem: Box::new(Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty) }),
len: 2,
};
assert!(!refs.is_owned_data());
assert!(!refs.is_supported_v2_local());
}
/// Only a dead local (neither the return place nor an argument, and
/// mentioned by nothing, not even a storage marker) whose type is outside
/// the local fragment or untranslatable gets `()`; a mentioned local, an
/// argument, the return place, and a dead local of a supported type keep
/// their translation, so validation still refuses the first three.
#[test]
fn dead_local_ty_erases_only_unmentioned_unsupported_locals() {
let bool_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(Ty::Bool) };
// `&mut &bool` is outside the local fragment.
let ref_ref = Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(bool_ref.clone()) };
assert!(!ref_ref.is_supported_v2_local());
let bad = || Err::<Ty, String>("unsupported type: str".into());
// Dead: erased whether the type is outside the fragment or fails.
assert_eq!(dead_local_ty(3, 1, false, Ok(ref_ref.clone())), Ok(Ty::Unit));
assert_eq!(dead_local_ty(3, 1, false, bad()), Ok(Ty::Unit));
// Dead but supported: unchanged.
assert_eq!(dead_local_ty(3, 1, false, Ok(bool_ref.clone())), Ok(bool_ref));
// Mentioned (for example only by `StorageLive`): unchanged.
assert_eq!(dead_local_ty(3, 1, true, Ok(ref_ref.clone())), Ok(ref_ref.clone()));
assert_eq!(dead_local_ty(3, 1, true, bad()), bad());
// The return place and arguments: unchanged even when unmentioned.
assert_eq!(dead_local_ty(0, 1, false, Ok(ref_ref.clone())), Ok(ref_ref.clone()));
assert_eq!(dead_local_ty(1, 1, false, Ok(ref_ref.clone())), Ok(ref_ref));
assert_eq!(dead_local_ty(1, 1, false, bad()), bad());
}
/// Synthetic structs (tuples and monomorphized sysroot structs lowered to
/// `MirTy.struct_`) are keyed by canonical identity strings, skipped by
/// nominal `collect_struct_ids`, and checked by
/// `check_synthetic_struct_ids` against crate-local struct/enum ids and
/// against one another (including distinct synthetic types sharing a
/// layout and field list).
#[test]
fn synthetic_structs_are_keyed_and_checked_for_collisions() {
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let vec_u8 = Ty::Vec { elem: Box::new(u8_ty.clone()) };
let a = StructTy::try_new_tuple(32, 3, vec![24, 0], vec![u64_ty.clone(), vec_u8.clone()])
.unwrap();
let a2 = StructTy::try_new_tuple(32, 3, vec![24, 0], vec![u64_ty.clone(), vec_u8.clone()])
.unwrap();
assert!(a.is_synthetic());
assert_eq!(a, a2);
let b = StructTy::try_new_tuple(32, 3, vec![0, 8], vec![u64_ty.clone(), vec_u8.clone()])
.unwrap();
assert_ne!(a.layout().id(), b.layout().id());
let range_u64 = StructTy::try_new_synthetic(
"anneal:adt:v1:core::ops::range::Range<u64>".into(),
16,
3,
vec![0, 8],
vec![u64_ty.clone(), u64_ty.clone()],
)
.unwrap();
let range_to_u64 = StructTy::try_new_synthetic(
"anneal:adt:v1:core::ops::range::RangeTo<u64>".into(),
8,
3,
vec![0],
vec![u64_ty.clone()],
)
.unwrap();
let range_from_u64 = StructTy::try_new_synthetic(
"anneal:adt:v1:core::ops::range::RangeFrom<u64>".into(),
8,
3,
vec![0],
vec![u64_ty.clone()],
)
.unwrap();
assert!(range_u64.is_synthetic());
assert_ne!(range_to_u64.layout().id(), range_from_u64.layout().id());
assert!(
StructTy::try_new_synthetic(String::new(), 8, 3, vec![0], vec![u64_ty.clone()])
.unwrap_err()
.contains("non-empty")
);
let none = BTreeSet::new();
assert_eq!(
check_synthetic_struct_ids(
[&a, &a2, &b, &range_u64, &range_to_u64, &range_from_u64],
&none,
&none,
),
Ok(())
);
// Synthetic structs are skipped by nominal `collect_struct_ids` and
// collected by `collect_synthetic_structs`.
let mut ids = BTreeSet::new();
let mut synthetics = Vec::new();
Ty::Struct(a.clone()).collect_struct_ids(&mut ids);
Ty::Struct(range_u64.clone()).collect_struct_ids(&mut ids);
assert!(ids.is_empty());
Ty::Struct(a.clone()).collect_synthetic_structs(&mut synthetics);
Ty::Struct(range_u64.clone()).collect_synthetic_structs(&mut synthetics);
assert_eq!(synthetics, vec![a.clone(), range_u64.clone()]);
// Injected collisions fail closed against local structs and enums.
let id = a.layout().id();
let clash = BTreeSet::from([id]);
assert!(check_synthetic_struct_ids([&a], &clash, &none).unwrap_err().contains("collision"));
assert!(check_synthetic_struct_ids([&a], &none, &clash).unwrap_err().contains("collision"));
let range_clash = BTreeSet::from([range_u64.layout().id()]);
assert!(
check_synthetic_struct_ids([&range_u64], &range_clash, &none)
.unwrap_err()
.contains("collision")
);
assert!(
check_synthetic_struct_ids([&range_u64], &none, &range_clash)
.unwrap_err()
.contains("collision")
);
// Distinct synthetic structs with different layouts sharing an id fail.
let forged_diff_layout = StructTy {
synthetic: Some("anneal:adt:v1:forged".into()),
..StructTy::try_new(id, 8, 3, vec![0], vec![u64_ty.clone()]).unwrap()
};
assert!(
check_synthetic_struct_ids([&a, &forged_diff_layout], &none, &none)
.unwrap_err()
.contains("two synthetic struct types")
);
// Distinct synthetic structs with identical layout & fields (such as
// `RangeTo<u64>` vs `RangeFrom<u64>`, or a 1-tuple vs a range) sharing
// a 32-bit id still fail closed via their pre-hash keys.
let forged_same_layout = StructTy {
synthetic: Some("anneal:adt:v1:core::ops::range::RangeFrom<u64>".into()),
..StructTy::try_new(range_to_u64.layout().id(), 8, 3, vec![0], vec![u64_ty.clone()])
.unwrap()
};
assert!(
check_synthetic_struct_ids([&range_to_u64, &forged_same_layout], &none, &none)
.unwrap_err()
.contains("two synthetic struct types")
);
let tuple_vec = StructTy::try_new_tuple(24, 3, vec![0], vec![vec_u8.clone()]).unwrap();
let forged_tuple_vs_range = StructTy {
synthetic: Some("anneal:adt:v1:core::ops::range::RangeTo<alloc::vec::Vec<u8>>".into()),
..StructTy::try_new(tuple_vec.layout().id(), 24, 3, vec![0], vec![vec_u8]).unwrap()
};
assert!(
check_synthetic_struct_ids([&tuple_vec, &forged_tuple_vs_range], &none, &none)
.unwrap_err()
.contains("two synthetic struct types")
);
// Passing a nominal (non-synthetic) struct fails closed.
let nominal = StructTy::try_new(12345, 8, 3, vec![0], vec![u64_ty]).unwrap();
assert!(
check_synthetic_struct_ids([&nominal], &none, &none)
.unwrap_err()
.contains("non-synthetic struct")
);
}
#[test]
fn check_rec_tys_admits_closed_guarded_coherent_recursion() {
let node = rec_node(vec![0, 8]);
let shared = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(node.clone()) };
assert_eq!(check_rec_tys([&node, &shared]), Ok(()));
// A closed recursive struct nested as a field of another one.
let outer = Ty::RecAdt {
id: 8,
defn: Box::new(raw_struct(
8,
24,
vec![0, 16],
vec![node.clone(), Ty::Box { pointee: Box::new(Ty::RecSelf { id: 8 }) }],
)),
};
assert_eq!(check_rec_tys([&outer, &node]), Ok(()));
// One unfolding closes the definition.
let Some(Ty::Struct(unfolded)) = node.unfold_rec() else { panic!("unfold") };
assert_eq!(
unfolded.fields()[1],
Ty::Option { elem: Box::new(Ty::Box { pointee: Box::new(node.clone()) }) }
);
}
/// The recursive-struct and handle arms of `has_ref_v2`,
/// `has_raw_ptr_v2`, and `is_supported_v2_local` mirror Lean's
/// `tyHasRefV2`, `tyHasRawPtrV2`, and `isSupportedV2LocalTy`.
#[test]
fn rec_adt_local_predicates_mirror_lean() {
let node = rec_node(vec![0, 8]);
// `parent: Option<Box<Node>>` holds a `Box`, which counts as a
// reference.
assert!(node.has_ref_v2());
assert!(!node.has_raw_ptr_v2());
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let raw = Ty::RawPtr { mutability: Mutability::Shared, pointee: Box::new(u8_ty) };
let with_raw = Ty::RecAdt {
id: 9,
defn: Box::new(raw_struct(
9,
16,
vec![0, 8],
vec![raw, Ty::Box { pointee: Box::new(Ty::RecSelf { id: 9 }) }],
)),
};
assert!(with_raw.has_raw_ptr_v2());
assert!(node.is_supported_v2_local());
assert!(Ty::Box { pointee: Box::new(node.clone()) }.is_supported_v2_local());
// A bare back edge is not a local type, even behind a handle.
let back = Ty::Box { pointee: Box::new(Ty::RecSelf { id: 7 }) };
assert!(!back.is_supported_v2_local());
assert!(!Ty::Vec { elem: Box::new(Ty::RecSelf { id: 7 }) }.is_supported_v2_local());
let shared_back = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(back) };
assert!(!shared_back.is_supported_v2_local());
}
#[test]
fn check_rec_tys_refuses_ill_formed_or_incoherent_recursion() {
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
let back = |id| Ty::Box { pointee: Box::new(Ty::RecSelf { id }) };
let cases: [(&str, Vec<Ty>, &str); 9] = [
(
"inline back edge",
vec![Ty::RecAdt {
id: 7,
defn: Box::new(raw_struct(7, 8, vec![0], vec![Ty::RecSelf { id: 7 }])),
}],
"ill-formed",
),
("unbound back edge", vec![back(7)], "ill-formed"),
(
"mutual recursion",
vec![Ty::RecAdt {
id: 7,
defn: Box::new(raw_struct(
7,
8,
vec![0],
vec![Ty::Box {
pointee: Box::new(Ty::RecAdt {
id: 8,
defn: Box::new(raw_struct(8, 8, vec![0], vec![back(7)])),
}),
}],
)),
}],
"ill-formed",
),
(
"rebinding",
vec![Ty::RecAdt {
id: 7,
defn: Box::new(raw_struct(
7,
8,
vec![0],
vec![Ty::Box { pointee: Box::new(rec_node(vec![0, 8])) }],
)),
}],
"two different definitions",
),
(
"head mismatch",
vec![Ty::RecAdt { id: 7, defn: Box::new(raw_struct(8, 8, vec![0], vec![back(7)])) }],
"ill-formed",
),
(
"two definitions",
vec![rec_node(vec![0, 8]), rec_node(vec![8, 0])],
"two different definitions",
),
(
"plain struct reuses the id",
vec![rec_node(vec![0, 8]), raw_struct(7, 8, vec![0], vec![u64_ty.clone()])],
"reused by a plain struct",
),
(
"binder reuses an earlier plain id",
vec![raw_struct(7, 8, vec![0], vec![u64_ty]), rec_node(vec![0, 8])],
"reused by a plain struct",
),
(
"conflicting definition nested under a repeated binder",
vec![
Ty::Box { pointee: Box::new(rec_node(vec![0, 8])) },
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(rec_node(vec![0, 8])),
},
rec_node(vec![8, 0]),
],
"two different definitions",
),
];
for (name, tys, needle) in cases {
let err = check_rec_tys(tys.iter()).expect_err(name);
assert!(err.contains(needle), "{name}: {err}");
}
}
/// The binder walk in `check_rec_tys` decides admission exactly as the
/// checks it replaced: every type is well-formed (`Ty::rec_ty_wf`), every
/// binder occurrence of an id has the same definition, and no plain
/// struct or payload enum reuses a binder id. Both are run on every
/// ordered triple drawn from a pool of coherent, conflicting, nested,
/// plain, and ill-formed types.
#[test]
fn check_rec_tys_walk_matches_wf_and_pairwise_coherence() {
fn keys<'a>(ty: &'a Ty, binders: &mut Vec<(u32, &'a Ty)>, plain: &mut Vec<u32>) {
match ty {
Ty::RecAdt { id, defn } => {
binders.push((*id, defn));
match &**defn {
Ty::Struct(sty) => sty.fields().iter().for_each(|f| keys(f, binders, plain)),
Ty::AdtEnum(aty) => {
aty.variants().iter().for_each(|v| keys(v, binders, plain))
}
other => keys(other, binders, plain),
}
}
Ty::Struct(sty) => {
plain.push(sty.layout().id());
sty.fields().iter().for_each(|f| keys(f, binders, plain));
}
Ty::AdtEnum(aty) => {
plain.push(aty.layout().id());
aty.variants().iter().for_each(|v| keys(v, binders, plain));
}
Ty::Ref { pointee, .. } | Ty::Box { pointee } => keys(pointee, binders, plain),
Ty::Option { elem } | Ty::Vec { elem } => keys(elem, binders, plain),
_ => {}
}
}
fn pairwise(tys: &[&Ty]) -> bool {
let (mut binders, mut plain) = (Vec::new(), Vec::new());
tys.iter().for_each(|t| keys(t, &mut binders, &mut plain));
binders.iter().all(|(i, d)| {
binders.iter().all(|(j, e)| i != j || d == e) && !plain.contains(i)
})
}
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
// `enum E { A(u8), B(Box<E>) }` with layout id 5, its payload structs
// having layout ids `a` and `a + 1`; `B`'s field is `back`.
let adt = |a: u32, back: Ty| {
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
5,
true,
16,
3,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I8, signed: false },
(0, 1),
AdtTagEncoding::Direct,
vec![
Ty::Struct(StructTy::try_new(a, 16, 3, vec![1], vec![u8_ty]).unwrap()),
Ty::Struct(StructTy::try_new(a + 1, 16, 3, vec![8], vec![back]).unwrap()),
],
)
.unwrap(),
))
};
let back5 = || Ty::Box { pointee: Box::new(Ty::RecSelf { id: 5 }) };
let node = rec_node(vec![0, 8]);
let swapped = rec_node(vec![8, 0]);
let other = Ty::RecAdt {
id: 8,
defn: Box::new(raw_struct(
8,
24,
vec![0, 16],
vec![node.clone(), Ty::Box { pointee: Box::new(Ty::RecSelf { id: 8 }) }],
)),
};
let other_swapped = Ty::RecAdt {
id: 8,
defn: Box::new(raw_struct(
8,
24,
vec![0, 16],
vec![swapped.clone(), Ty::Box { pointee: Box::new(Ty::RecSelf { id: 8 }) }],
)),
};
let pool = [
node.clone(),
swapped,
other,
other_swapped,
Ty::Box { pointee: Box::new(node.clone()) },
raw_struct(7, 8, vec![0], vec![u64_ty.clone()]),
raw_struct(8, 8, vec![0], vec![u64_ty.clone()]),
raw_struct(9, 16, vec![0, 8], vec![u64_ty, Ty::Vec { elem: Box::new(node.clone()) }]),
// Rebinds id 7 inside its own definition.
Ty::RecAdt {
id: 7,
defn: Box::new(raw_struct(
7,
8,
vec![0],
vec![Ty::Box { pointee: Box::new(node.clone()) }],
)),
},
// Head mismatch: binder 7 defines the struct with layout id 9.
Ty::RecAdt {
id: 7,
defn: Box::new(raw_struct(9, 8, vec![0], vec![Ty::Box {
pointee: Box::new(Ty::RecSelf { id: 7 }),
}])),
},
// A back edge naming another binder, nested under a binder.
Ty::RecAdt {
id: 9,
defn: Box::new(raw_struct(9, 8, vec![0], vec![Ty::Vec {
elem: Box::new(Ty::RecSelf { id: 8 }),
}])),
},
Ty::Vec { elem: Box::new(Ty::RecSelf { id: 7 }) },
// A recursive payload enum, a conflicting definition of it, and a
// plain payload enum reusing its layout id.
Ty::RecAdt { id: 5, defn: Box::new(adt(61, back5())) },
Ty::Box { pointee: Box::new(Ty::RecAdt { id: 5, defn: Box::new(adt(63, back5())) }) },
adt(65, Ty::Box { pointee: Box::new(Ty::Unit) }),
];
for a in &pool {
for b in &pool {
for c in &pool {
let tys = [a, b, c];
assert_eq!(
check_rec_tys(tys).is_ok(),
tys.iter().all(|t| t.rec_ty_wf(None)) && pairwise(&tys),
"{a:?}\n{b:?}\n{c:?}"
);
}
}
}
}
/// `niche_field_untagged` mirrors
/// `Trusted.MirSemantics.adtNicheFieldUntaggedV2` on the cases of
/// `refute_step_v2_ref_mut_niche_field`.
#[test]
fn niche_field_untagged_mirrors_lean() {
let u8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: false });
let opt_u8 = Ty::Option { elem: Box::new(u8_ty.clone()) };
let niche = |id: u32, size: usize, align: u32, tag: IntWidth, valid: (u128, u128),
start: u128, payload: StructTy| {
AdtEnumTy::try_new(
id,
true,
size,
align,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: tag, signed: false },
valid,
AdtTagEncoding::Niche { untagged: 1, first: 0, last: 0, start },
vec![
Ty::Struct(StructTy::try_new(id * 10 + 1, size, align, vec![], vec![]).unwrap()),
Ty::Struct(payload),
],
)
.unwrap()
};
// `enum O { None, Some(Option<u8>, u8) }`, niche `start`.
let o = |start: u128, valid_end: u128| {
niche(6, 3, 0, IntWidth::I8, (0, valid_end), start,
StructTy::try_new(62, 3, 0, vec![0, 2], vec![opt_u8.clone(), u8_ty.clone()])
.unwrap())
};
assert!(niche_field_untagged(&o(2, 2), 1, 0, &opt_u8));
assert!(niche_field_untagged(&o(2, 2), 1, 1, &u8_ty));
assert!(!niche_field_untagged(&o(2, 2), 1, 1, &opt_u8));
assert!(!niche_field_untagged(&o(1, 2), 1, 0, &opt_u8));
assert!(!niche_field_untagged(&o(2, 0), 1, 0, &opt_u8));
// The tagged variant `None` has no fields.
assert!(!niche_field_untagged(&o(2, 2), 0, 0, &u8_ty));
// `Option<W>` for `struct W { v: Vec<u8> }`: `None` is the capacity
// niche `u64::MAX`.
let w = Ty::Struct(
StructTy::try_new(73, 24, 3, vec![0], vec![Ty::Vec { elem: Box::new(u8_ty.clone()) }])
.unwrap(),
);
let vec_opt = niche(7, 24, 3, IntWidth::I64, (u64::MAX as u128, i64::MAX as u128),
u64::MAX as u128, StructTy::try_new(72, 24, 3, vec![0], vec![w.clone()]).unwrap());
assert!(niche_field_untagged(&vec_opt, 1, 0, &w));
// A tag in the padding of the field's struct.
let pad = Ty::Struct(StructTy::try_new(83, 3, 0, vec![1], vec![u8_ty.clone()]).unwrap());
let pad_opt = niche(8, 3, 0, IntWidth::I8, (0, 2), 2,
StructTy::try_new(82, 3, 0, vec![0], vec![pad.clone()]).unwrap());
assert!(!niche_field_untagged(&pad_opt, 1, 0, &pad));
// A `char` (an unmodeled valid range) holding the tag.
let ch = niche(9, 4, 2, IntWidth::I32, (0, 0x110000), 0x110000,
StructTy::try_new(92, 4, 2, vec![0], vec![Ty::Char]).unwrap());
assert!(!niche_field_untagged(&ch, 1, 0, &Ty::Char));
}
/// `struct Pair { a: u8, b: u32 }` with `rustc`'s reordered layout
/// (`b` at offset 0, `a` at offset 4).
fn pair_ty() -> Ty {
Ty::Struct(StructTy::try_new(77, 8, 2, vec![4, 0], vec![u8_ty(), u32_ty()]).unwrap())
}
fn place(local: u32, projection: Vec<PlaceElem>) -> Place {
Place { local, projection }
}
fn single_block_body(
arg_count: usize,
locals: Vec<Ty>,
statements: Vec<Statement>,
terminator: Terminator,
identity: &str,
) -> Result<Body, String> {
let mut blocks = vec![Block { statements, terminator }];
if !matches!(blocks[0].terminator, Terminator::Ret) {
blocks.push(Block { statements: vec![], terminator: Terminator::Ret });
}
Body::try_new(arg_count, false, locals, blocks, identity.into())
}
#[test]
fn struct_ty_try_new_mirrors_struct_layout_valid() {
assert!(StructTy::try_new(1, 0, 0, vec![], vec![]).is_ok());
let pair = pair_ty();
assert_eq!(pair.v2_layout(), Some((8, 2)));
assert!(pair.is_supported_v2_data());
assert!(pair.is_supported_v2_local());
assert!(pair.is_retag_noop());
assert!(pair.is_sized());
assert!(pair.is_profile_v2());
assert!(!pair.is_array_eq_elem_supported());
assert!(!pair.has_ref_v2() && !pair.has_raw_ptr_v2());
let err = |r: Result<StructTy, String>| r.unwrap_err();
assert!(
err(StructTy::try_new(1, 8, 2, vec![0], vec![u8_ty(), u32_ty()])).contains("offsets")
);
assert!(
err(StructTy::try_new(1, 8, 2, vec![0, 1], vec![u8_ty(), u32_ty()]))
.contains("misaligned")
);
assert!(
err(StructTy::try_new(1, 8, 2, vec![0, 0], vec![u32_ty(), u32_ty()]))
.contains("overlaps")
);
assert!(
err(StructTy::try_new(1, 4, 2, vec![0, 4], vec![u32_ty(), u8_ty()]))
.contains("exceeds the struct size")
);
assert!(
err(StructTy::try_new(1, 6, 2, vec![0, 4], vec![u32_ty(), u8_ty()]))
.contains("not a multiple")
);
assert!(
err(StructTy::try_new(1, 4, 1, vec![0], vec![u32_ty()])).contains("alignment exceeds")
);
assert!(err(StructTy::try_new(1, 1 << 61, 0, vec![], vec![])).contains("2^61"));
let shared_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty()) };
assert!(
err(StructTy::try_new(1, 8, 3, vec![0], vec![shared_ref]))
.contains("Profile v2 owned data")
);
// Owned `Box<[T]>` and `Vec<T>` fields of data elements are admitted,
// but a `Box` of a reference is not.
let boxed_slice = Ty::Box { pointee: Box::new(Ty::Slice { elem: Box::new(u8_ty()) }) };
let vec_u8 = Ty::Vec { elem: Box::new(u8_ty()) };
assert!(StructTy::try_new(1, 40, 3, vec![0, 16], vec![boxed_slice, vec_u8]).is_ok());
let box_ref = Ty::Box {
pointee: Box::new(Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty()) }),
};
assert!(err(StructTy::try_new(1, 8, 3, vec![0], vec![box_ref])).contains("owned data"));
// Zero-sized fields may share offsets with other fields.
assert!(StructTy::try_new(1, 4, 2, vec![0, 0], vec![u32_ty(), Ty::Unit]).is_ok());
// Nested structs and arrays of structs are data types.
let nested = Ty::Struct(
StructTy::try_new(
2,
24,
2,
vec![0, 8],
vec![pair_ty(), Ty::Array { elem: Box::new(pair_ty()), len: 2 }],
)
.unwrap(),
);
let mut ids = BTreeSet::new();
nested.collect_struct_ids(&mut ids);
assert_eq!(ids, BTreeSet::from([2, 77]));
}
#[test]
fn struct_constants_require_zero_sized_or_full_layout_bytes() {
let unit_struct = Ty::Struct(StructTy::try_new(3, 0, 0, vec![], vec![]).unwrap());
assert!(validate_constant(&unit_struct, &ConstLit::ZeroSized).is_ok());
assert!(validate_constant(&unit_struct, &ConstLit::RodataBytes { bytes: vec![] }).is_err());
let pair = pair_ty();
assert!(validate_constant(&pair, &ConstLit::ZeroSized).is_err());
assert!(validate_constant(&pair, &ConstLit::Scalar { bits: 0 }).is_err());
let bytes = |n| ConstLit::RodataBytes { bytes: vec![RodataByte::Uninit; n] };
assert!(validate_constant(&pair, &bytes(8)).is_ok());
assert!(validate_constant(&pair, &bytes(7)).is_err());
}
#[test]
fn struct_aggregates_fields_and_index_projections_are_typed() {
let pair = pair_ty();
let aggregate = |ty: Ty, fields: Vec<Operand>| {
single_block_body(
2,
vec![pair.clone(), u8_ty(), u32_ty()],
vec![Statement::Assign { local: 0, value: Rvalue::AggregateStruct { ty, fields } }],
Terminator::Ret,
"rust-path-v1::make_pair",
)
};
let good =
aggregate(pair.clone(), vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }])
.unwrap();
assert!(good.uses_profile_v2());
let mut ids = BTreeSet::new();
good.collect_struct_ids(&mut ids);
assert_eq!(ids, BTreeSet::from([77]));
assert!(
aggregate(pair.clone(), vec![Operand::Copy { local: 2 }, Operand::Copy { local: 1 }])
.unwrap_err()
.contains("AggregateStruct field type")
);
assert!(
aggregate(pair.clone(), vec![Operand::Copy { local: 1 }])
.unwrap_err()
.contains("arity")
);
assert!(
aggregate(u8_ty(), vec![Operand::Copy { local: 1 }])
.unwrap_err()
.contains("requires a struct type")
);
// A recursive struct aggregate takes the fields of its one-step
// unfolding.
let node = rec_node(vec![0, 8]);
let u64_ty = Ty::Int(IntTy { width: IntWidth::I64, signed: false });
let Some(Ty::Struct(unfolded)) = node.unfold_rec() else { panic!("unfold") };
let parent = unfolded.fields()[1].clone();
let rec_aggregate = |fields: Vec<Operand>| {
single_block_body(
2,
vec![node.clone(), u64_ty.clone(), parent.clone()],
vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateStruct { ty: node.clone(), fields },
}],
Terminator::Ret,
"rust-path-v1::make_node",
)
};
rec_aggregate(vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }]).unwrap();
assert!(
rec_aggregate(vec![Operand::Copy { local: 2 }, Operand::Copy { local: 1 }])
.unwrap_err()
.contains("AggregateStruct field type")
);
// `_0 = copy (_1.1)` reads the declaration-order field `b: u32`.
let field_read = |index: usize, ty: Ty, dst: Ty| {
single_block_body(
1,
vec![dst, pair.clone()],
vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace {
place: place(1, vec![PlaceElem::Field { index, ty }]),
},
with_retag: true,
},
}],
Terminator::Ret,
"rust-path-v1::get_b",
)
};
assert!(field_read(1, u32_ty(), u32_ty()).is_ok());
assert!(field_read(0, u32_ty(), u32_ty()).is_err());
assert!(field_read(2, u32_ty(), u32_ty()).is_err());
// `(*_1)[_2].0` through `&[Pair; 2]`, and `(*_1)[_2]` through `&[u8]`.
let array_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array { elem: Box::new(pair.clone()), len: 2 }),
};
let slice_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice { elem: Box::new(u8_ty()) }),
};
let indexed = |base: Ty, index_ty: Ty, index_local: u32, tail: Vec<PlaceElem>, dst: Ty| {
let mut projection = vec![PlaceElem::Deref, PlaceElem::Index { local: index_local }];
projection.extend(tail);
single_block_body(
2,
vec![dst, base, index_ty],
vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace { place: place(1, projection) },
with_retag: true,
},
}],
Terminator::Ret,
"rust-path-v1::index",
)
};
let field_a = vec![PlaceElem::Field { index: 0, ty: u8_ty() }];
let ok = indexed(array_ref.clone(), usize_ty(), 2, field_a.clone(), u8_ty()).unwrap();
let program = Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![ok]).unwrap();
let rendered = crate::lean::render(&program);
assert!(rendered.contains("Trusted.MirAst.ProjectionElem.index 2"), "{rendered}");
assert!(
rendered.contains(
"(Trusted.MirAst.MirTy.struct_ (Trusted.MirAst.StructLayout.mk 77 8 2 [4, 0])"
),
"{rendered}"
);
assert!(indexed(slice_ref.clone(), usize_ty(), 2, vec![], u8_ty()).is_ok());
assert!(
indexed(array_ref.clone(), u32_ty(), 2, field_a.clone(), u8_ty())
.unwrap_err()
.contains("not usize")
);
assert!(
indexed(array_ref, usize_ty(), 9, field_a, u8_ty())
.unwrap_err()
.contains("index local 9 out of bounds")
);
// An unsized slice deref without a following `Index` stays refused.
let bare_slice = single_block_body(
1,
vec![u8_ty(), slice_ref],
vec![Statement::Assign {
local: 0,
value: Rvalue::Use {
operand: Operand::CopyPlace { place: place(1, vec![PlaceElem::Deref]) },
with_retag: true,
},
}],
Terminator::Ret,
"rust-path-v1::bare_slice",
);
assert!(bare_slice.unwrap_err().contains("unsized deref"));
}
#[test]
fn refs_to_projected_places_are_typed_and_respect_mutability() {
let pair_ref = |mutability| Ty::Ref { mutability, pointee: Box::new(pair_ty()) };
let field_ref = |base: Mutability, borrow: Mutability| {
single_block_body(
1,
vec![Ty::Ref { mutability: borrow, pointee: Box::new(u32_ty()) }, pair_ref(base)],
vec![Statement::Assign {
local: 0,
value: Rvalue::Ref {
mutability: borrow,
place: place(
1,
vec![PlaceElem::Deref, PlaceElem::Field { index: 1, ty: u32_ty() }],
),
},
}],
Terminator::Ret,
"rust-path-v1::field_ref",
)
};
// `&((*_1).1)` through `&Pair` and `&mut ((*_1).1)` through
// `&mut Pair`.
assert!(field_ref(Mutability::Shared, Mutability::Shared).is_ok());
assert!(field_ref(Mutability::Mut, Mutability::Mut).is_ok());
assert!(
field_ref(Mutability::Shared, Mutability::Mut).unwrap_err().contains("cannot reborrow")
);
}
#[test]
fn call_ne_partial_eq_ne_and_drop_terminators_are_typed() {
let pair = pair_ty();
let pair_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair.clone()) };
let eq = single_block_body(
2,
vec![Ty::Bool, pair_ref.clone(), pair_ref.clone()],
vec![],
Terminator::Ret,
"rust-path-v1::<Pair as PartialEq>::eq",
)
.unwrap();
let call_ne = |locals: Vec<Ty>| {
single_block_body(
2,
locals,
vec![],
Terminator::CallNe {
eq_callee: 1,
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Terminate { reason: UnwindTerminateReason::Abi },
},
"rust-path-v1::differ",
)
};
let ne = call_ne(vec![Ty::Bool, pair_ref.clone(), pair_ref.clone()]).unwrap();
assert!(ne.uses_profile_v2());
let program = Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![ne, eq.clone()]).unwrap();
assert_eq!(program.mir_profile_version(), 2);
let rendered = crate::lean::render(&program);
assert!(rendered.contains("(Trusted.MirAst.TerminatorKind.callNe\n"), "{rendered}");
assert!(rendered.contains("Trusted.MirAst.UnwindAction.terminate)"), "{rendered}");
// The `eq` callee's signature must match the call.
let bad_eq = single_block_body(
2,
vec![u8_ty(), pair_ref.clone(), pair_ref.clone()],
vec![],
Terminator::Ret,
"rust-path-v1::<Pair as PartialEq>::eq",
)
.unwrap();
let ne = call_ne(vec![Ty::Bool, pair_ref.clone(), pair_ref.clone()]).unwrap();
assert!(Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![ne, bad_eq]).is_err());
assert!(call_ne(vec![u8_ty(), pair_ref.clone(), pair_ref.clone()]).is_err());
let u8_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty()) };
assert!(call_ne(vec![Ty::Bool, u8_ref.clone(), u8_ref.clone()]).is_err());
// `CoreCallOp::PartialEqNe` covers the structural primitive/array
// fragment only.
let array_ty = Ty::Array { elem: Box::new(u8_ty()), len: 4 };
let array_ref =
Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(array_ty.clone()) };
let core_ne = |ty: Ty, arg: Ty| {
single_block_body(
2,
vec![Ty::Bool, arg.clone(), arg],
vec![],
Terminator::CoreCall {
op: CoreCallOp::PartialEqNe { ty },
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: place(0, vec![]),
target: Some(1),
unwind: UnwindAction::Continue,
},
"rust-path-v1::array_ne",
)
};
let body = core_ne(array_ty.clone(), array_ref.clone()).unwrap();
let rendered = crate::lean::render(&Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body]).unwrap());
assert!(rendered.contains("Trusted.MirAst.CoreCallOp.partialEqNe"), "{rendered}");
assert!(core_ne(pair.clone(), pair_ref.clone()).is_err());
assert!(core_ne(u8_ty(), array_ref).is_err());
// `Drop` admits an unprojected in-bounds local only.
let drop_body = |place: Place| {
single_block_body(
1,
vec![Ty::Unit, pair.clone()],
vec![],
Terminator::Drop { place, target: 1, unwind: UnwindAction::Unreachable },
"rust-path-v1::consume",
)
};
let body = drop_body(place(1, vec![])).unwrap();
assert!(body.uses_profile_v2());
let rendered = crate::lean::render(&Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body]).unwrap());
assert!(
rendered.contains("(Trusted.MirAst.TerminatorKind.drop (Trusted.MirAst.Place.mk 1 []) 1 Trusted.MirAst.UnwindAction.unreachable)"),
"{rendered}"
);
assert!(drop_body(place(5, vec![])).unwrap_err().contains("out of bounds"));
// A field of a local is admitted only when its type has drop glue.
assert!(
drop_body(place(1, vec![PlaceElem::Field { index: 0, ty: u8_ty() }]))
.unwrap_err()
.contains("drop glue")
);
let vec_tuple = Ty::Tuple {
fields: vec![u8_ty(), Ty::Vec { elem: Box::new(u8_ty()) }],
};
let tuple_field_drop = |local_ty: Ty, projection: Vec<PlaceElem>| {
single_block_body(
1,
vec![Ty::Unit, local_ty],
vec![],
Terminator::Drop {
place: place(1, projection),
target: 1,
unwind: UnwindAction::Unreachable,
},
"rust-path-v1::consume_field",
)
};
let vec_field =
PlaceElem::Field { index: 1, ty: Ty::Vec { elem: Box::new(u8_ty()) } };
assert!(tuple_field_drop(vec_tuple.clone(), vec![vec_field.clone()]).is_ok());
assert!(
tuple_field_drop(vec_tuple.clone(), vec![PlaceElem::Field { index: 0, ty: u8_ty() }])
.unwrap_err()
.contains("drop glue")
);
assert!(
tuple_field_drop(
vec_tuple.clone(),
vec![vec_field.clone(), PlaceElem::Field { index: 0, ty: u8_ty() }]
)
.is_err()
);
// Field and element places of a struct local are dropped in its stack
// allocation; a downcast is refused.
let vec_u8_ty = || Ty::Vec { elem: Box::new(u8_ty()) };
let vec_pair_struct = Ty::Struct(
StructTy::try_new(79, 48, 3, vec![0, 24], vec![vec_u8_ty(), vec_u8_ty()])
.unwrap(),
);
assert!(tuple_field_drop(
vec_pair_struct.clone(),
vec![PlaceElem::Field { index: 1, ty: vec_u8_ty() }]
)
.is_ok());
let vec_arr2 = Ty::Array { elem: Box::new(vec_u8_ty()), len: 2 };
let arr_struct = Ty::Struct(
StructTy::try_new(80, 56, 3, vec![48, 0], vec![u32_ty(), vec_arr2.clone()])
.unwrap(),
);
assert!(tuple_field_drop(
arr_struct.clone(),
vec![
PlaceElem::Field { index: 1, ty: vec_arr2.clone() },
PlaceElem::ConstantIndex { offset: 1, min_length: 2, from_end: false },
]
)
.is_ok());
assert!(
tuple_field_drop(
arr_struct,
vec![
PlaceElem::Field { index: 1, ty: vec_arr2 },
PlaceElem::Downcast { variant_idx: 0 },
]
)
.is_err()
);
// A variant field of an enum field of a tuple local,
// `(t.1 as Some).0`, is moved out of the tuple's value and its glue
// run; a nested tuple place through a constant index is refused.
let opt_vec_tuple = Ty::Tuple {
fields: vec![u8_ty(), Ty::Option { elem: Box::new(vec_u8_ty()) }],
};
assert!(tuple_field_drop(
opt_vec_tuple,
vec![
PlaceElem::Field { index: 1, ty: Ty::Option { elem: Box::new(vec_u8_ty()) } },
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: vec_u8_ty() },
]
)
.is_ok());
let arr_tuple = Ty::Tuple {
fields: vec![u8_ty(), Ty::Array { elem: Box::new(vec_u8_ty()), len: 2 }],
};
assert!(
tuple_field_drop(
arr_tuple,
vec![
PlaceElem::Field {
index: 1,
ty: Ty::Array { elem: Box::new(vec_u8_ty()), len: 2 }
},
PlaceElem::ConstantIndex { offset: 0, min_length: 2, from_end: false },
]
)
.unwrap_err()
.contains("Profile v2 layout")
);
// A variant field of an enum field of a struct local,
// `(s.0 as Some).0`, has its glue run in place.
let opt_vec = Ty::Option { elem: Box::new(vec_u8_ty()) };
let opt_struct = Ty::Struct(
StructTy::try_new(83, 32, 3, vec![0, 24], vec![opt_vec.clone(), u32_ty()]).unwrap(),
);
assert!(tuple_field_drop(
opt_struct,
vec![
PlaceElem::Field { index: 0, ty: opt_vec },
PlaceElem::Downcast { variant_idx: 1 },
PlaceElem::Field { index: 0, ty: vec_u8_ty() },
]
)
.is_ok());
// A `Drop` through a dereference needs `&mut T`, and a pointee other
// than `Vec<T>` or `Box<P>` must be a supported local type with drop
// glue, possibly reached through field projections.
let vec_u8 = Ty::Vec { elem: Box::new(u8_ty()) };
let box_u8 = Ty::Box { pointee: Box::new(u8_ty()) };
let deref_drop = |ptr_ty: Ty| {
single_block_body(
1,
vec![Ty::Unit, ptr_ty],
vec![],
Terminator::Drop {
place: place(1, vec![PlaceElem::Deref]),
target: 1,
unwind: UnwindAction::Unreachable,
},
"rust-path-v1::reassign",
)
};
for pointee in [vec_u8.clone(), box_u8.clone()] {
let body =
deref_drop(Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(pointee) })
.unwrap();
let rendered = crate::lean::render(
&Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body])
.unwrap(),
);
assert!(
rendered.contains(
"(Trusted.MirAst.TerminatorKind.drop (Trusted.MirAst.Place.mk 1 \
[Trusted.MirAst.ProjectionElem.deref]) 1"
),
"{rendered}"
);
}
for ptr_ty in [
Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(vec_u8.clone()) },
Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(u8_ty()) },
] {
assert!(deref_drop(ptr_ty).unwrap_err().contains("dereference"));
}
// Raw pointers to handles are not admitted local types at all.
let raw_box = Ty::RawPtr { mutability: Mutability::Mut, pointee: Box::new(box_u8.clone()) };
assert!(deref_drop(raw_box).is_err());
let opt_box = Ty::Option { elem: Box::new(box_u8.clone()) };
assert!(
deref_drop(Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(opt_box) })
.is_ok()
);
let vec_struct = Ty::Struct(
StructTy::try_new(78, 32, 3, vec![24, 0], vec![u32_ty(), vec_u8.clone()]).unwrap(),
);
let mut_ref_struct =
Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(vec_struct) };
let deref_field =
|projection: Vec<PlaceElem>| tuple_field_drop(mut_ref_struct.clone(), projection);
assert!(deref_field(vec![
PlaceElem::Deref,
PlaceElem::Field { index: 1, ty: vec_u8.clone() }
])
.is_ok());
assert!(deref_field(vec![PlaceElem::Deref, PlaceElem::Field { index: 0, ty: u32_ty() }])
.unwrap_err()
.contains("drop glue"));
assert!(deref_field(vec![PlaceElem::Deref, PlaceElem::Downcast { variant_idx: 0 }])
.unwrap_err()
.contains("Drop place must be"));
// An element of an array of handles, by a constant or a local index.
let vec_array = Ty::Array { elem: Box::new(vec_u8.clone()), len: 2 };
let array_drop = |projection: Vec<PlaceElem>| {
single_block_body(
1,
vec![
Ty::Unit,
Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(vec_array.clone()) },
Ty::Int(IntTy { width: IntWidth::Isize, signed: false }),
],
vec![],
Terminator::Drop {
place: place(1, projection),
target: 1,
unwind: UnwindAction::Unreachable,
},
"rust-path-v1::drop_elem",
)
};
assert!(array_drop(vec![PlaceElem::Deref, PlaceElem::Index { local: 2 }]).is_ok());
// A slice of handles has no layout, so an element of one is refused.
let slice_drop = single_block_body(
1,
vec![
Ty::Unit,
Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice { elem: Box::new(vec_u8.clone()) }),
},
Ty::Int(IntTy { width: IntWidth::Isize, signed: false }),
],
vec![],
Terminator::Drop {
place: place(1, vec![PlaceElem::Deref, PlaceElem::Index { local: 2 }]),
target: 1,
unwind: UnwindAction::Unreachable,
},
"rust-path-v1::drop_slice_elem",
);
assert!(slice_drop.unwrap_err().contains("sized"));
assert!(array_drop(vec![
PlaceElem::Deref,
PlaceElem::ConstantIndex { offset: 1, min_length: 2, from_end: false }
])
.is_ok());
// `needs_drop_v2` mirrors `Trusted.MirSemantics.tyNeedsDropV2`.
assert!(vec_u8.needs_drop_v2());
assert!(box_u8.needs_drop_v2());
assert!(Ty::Tuple { fields: vec![u8_ty(), vec_u8.clone()] }.needs_drop_v2());
assert!(Ty::Option { elem: Box::new(box_u8.clone()) }.needs_drop_v2());
assert!(Ty::Array { elem: Box::new(vec_u8.clone()), len: 1 }.needs_drop_v2());
assert!(!Ty::Array { elem: Box::new(vec_u8.clone()), len: 0 }.needs_drop_v2());
assert!(
!Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(vec_u8) }.needs_drop_v2()
);
assert!(!pair.needs_drop_v2());
assert!(!Ty::OverflowPair(IntTy { width: IntWidth::I8, signed: false }).needs_drop_v2());
}
#[test]
fn aggregate_tuple_unit_empty_and_arity_refusal() {
let ok_body = Body::try_new(
0,
false,
vec![Ty::Unit],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateTuple { fields: vec![] },
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unit_agg".into(),
)
.expect("empty AggregateTuple into Ty::Unit must be admitted");
assert!(ok_body.uses_profile_v2());
let bad_arity = Body::try_new(
0,
false,
vec![Ty::Unit],
vec![Block {
statements: vec![Statement::Assign {
local: 0,
value: Rvalue::AggregateTuple {
fields: vec![Operand::Constant {
ty: Ty::Bool,
lit: ConstLit::Scalar { bits: 1 },
}],
},
}],
terminator: Terminator::Ret,
}],
"rust-path-v1::unit_agg_bad_arity".into(),
)
.unwrap_err();
assert!(
bad_arity.contains("AggregateTuple arity disagrees"),
"{bad_arity}"
);
}
#[test]
fn program_admits_sysroot_call_in_profile_v2() {
let u64_ty = Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
});
let body = Body::try_new(
2,
false,
vec![
Ty::Tuple {
fields: vec![u64_ty.clone(), Ty::Unit],
},
u64_ty.clone(),
u64_ty.clone(),
u64_ty.clone(),
Ty::Unit,
],
vec![
Block {
statements: vec![],
terminator: Terminator::SysrootCall {
op: SysrootNumOp {
kind: SysrootNumKind::WrappingAdd,
ty: IntTy {
width: IntWidth::I64,
signed: false,
},
},
args: vec![Operand::Copy { local: 1 }, Operand::Copy { local: 2 }],
dst: 3,
target: Some(1),
unwind: UnwindAction::Unreachable,
},
},
Block {
statements: vec![
Statement::Assign {
local: 4,
value: Rvalue::AggregateTuple { fields: vec![] },
},
Statement::Assign {
local: 0,
value: Rvalue::AggregateTuple {
fields: vec![Operand::Move { local: 3 }, Operand::Move { local: 4 }],
},
},
],
terminator: Terminator::Ret,
},
],
"rust-path-v1::v2_sysroot_wrap".into(),
)
.expect("v2 body with SysrootCall must validate");
assert!(body.uses_profile_v2());
let prog = Program::try_new(Scope::Crate { excluded_traits: BTreeSet::new() }, vec![body])
.expect("Profile v2 program must admit SysrootCall");
assert_eq!(prog.mir_profile_version(), 2);
}
#[test]
fn core_scalar_slice_and_size_of_signature_guards() {
let i8_ty = Ty::Int(IntTy { width: IntWidth::I8, signed: true });
let u16_ity = IntTy { width: IntWidth::I16, signed: false };
let i16_ity = IntTy { width: IntWidth::I16, signed: true };
let i32_ity = IntTy { width: IntWidth::I32, signed: true };
let u64_ity = IntTy { width: IntWidth::I64, signed: false };
let i64_ity = IntTy { width: IntWidth::I64, signed: true };
let isize_signed = Ty::Int(IntTy { width: IntWidth::Isize, signed: true });
let u16_ty = Ty::Int(u16_ity);
let i16_ty = Ty::Int(i16_ity);
let i32_ty = Ty::Int(i32_ity);
let u64_ty = Ty::Int(u64_ity);
let i64_ty = Ty::Int(i64_ity);
let call_body = |dst_ty: Ty, arg_tys: Vec<Ty>, op: CoreCallOp| {
let arg_count = arg_tys.len();
let args = (0..arg_count).map(|i| Operand::Copy { local: (i + 1) as u32 }).collect();
let mut locals = vec![dst_ty];
locals.extend(arg_tys);
single_block_body(
arg_count,
locals,
vec![],
Terminator::CoreCall {
op,
args,
dst: place(0, vec![]),
target: Some(1),
unwind: UnwindAction::Continue,
},
"rust-path-v1::core_scalar_sig_guard",
)
};
let assert_invalid_call = |label: &str, dst_ty: Ty, arg_tys: Vec<Ty>, op: CoreCallOp| {
let err = call_body(dst_ty, arg_tys, op)
.expect_err(&format!("{label}: expected CoreCall rejection"));
assert!(err.contains("invalid CoreCall"), "{label}: unexpected error `{err}`");
};
// 1. Generalized `SliceGetUnchecked{RangeTo, RangeFrom, Range}` over
// integer slices.
let slice_ref = |m: Mutability, elem: Ty| Ty::Ref {
mutability: m,
pointee: Box::new(Ty::Slice { elem: Box::new(elem) }),
};
let u16_sl = slice_ref(Mutability::Shared, u16_ty.clone());
let u16_sl_mut = slice_ref(Mutability::Mut, u16_ty.clone());
let i32_sl = slice_ref(Mutability::Shared, i32_ty.clone());
let i32_sl_mut = slice_ref(Mutability::Mut, i32_ty.clone());
let bool_sl = slice_ref(Mutability::Shared, Ty::Bool);
let bool_sl_mut = slice_ref(Mutability::Mut, Ty::Bool);
let u16_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u16_ty.clone()) };
let range_to_usize = Ty::RangeTo { elem: Box::new(usize_ty()) };
let range_to_u32 = Ty::RangeTo { elem: Box::new(u32_ty()) };
let range_from_usize = Ty::RangeFrom { elem: Box::new(usize_ty()) };
let range_from_u32 = Ty::RangeFrom { elem: Box::new(u32_ty()) };
let range_usize = Ty::Range { elem: Box::new(usize_ty()) };
let range_u32 = Ty::Range { elem: Box::new(u32_ty()) };
assert!(
call_body(
u16_sl.clone(),
vec![u16_sl.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
)
.is_ok()
);
assert_invalid_call(
"range_to_bad_idx",
u16_sl.clone(),
vec![u16_sl.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert!(
call_body(
u16_sl.clone(),
vec![u16_sl.clone(), range_to_u32],
CoreCallOp::SliceGetUncheckedRangeTo,
)
.is_err()
);
assert_invalid_call(
"range_to_non_int_elem",
bool_sl.clone(),
vec![bool_sl.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert_invalid_call(
"range_to_non_slice",
u16_ref.clone(),
vec![u16_ref.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert_invalid_call(
"range_to_mut_in",
u16_sl.clone(),
vec![u16_sl_mut.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert_invalid_call(
"range_to_mut_dst",
u16_sl_mut.clone(),
vec![u16_sl.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert_invalid_call(
"range_to_mismatched_dst_elem",
i32_sl.clone(),
vec![u16_sl.clone(), range_to_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert_invalid_call(
"range_to_bad_arity",
u16_sl.clone(),
vec![u16_sl.clone()],
CoreCallOp::SliceGetUncheckedRangeTo,
);
assert!(
call_body(
i32_sl.clone(),
vec![i32_sl.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
)
.is_ok()
);
assert_invalid_call(
"range_from_bad_idx",
i32_sl.clone(),
vec![i32_sl.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert!(
call_body(
i32_sl.clone(),
vec![i32_sl.clone(), range_from_u32],
CoreCallOp::SliceGetUncheckedRangeFrom,
)
.is_err()
);
assert_invalid_call(
"range_from_non_int_elem",
bool_sl.clone(),
vec![bool_sl.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert_invalid_call(
"range_from_non_slice",
u16_ref.clone(),
vec![u16_ref.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert_invalid_call(
"range_from_mut_in",
i32_sl.clone(),
vec![i32_sl_mut.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert_invalid_call(
"range_from_mut_dst",
i32_sl_mut.clone(),
vec![i32_sl.clone(), range_from_usize.clone()],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert_invalid_call(
"range_from_mismatched_dst_elem",
u16_sl.clone(),
vec![i32_sl.clone(), range_from_usize],
CoreCallOp::SliceGetUncheckedRangeFrom,
);
assert!(
call_body(
u16_sl.clone(),
vec![u16_sl.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRange,
)
.is_ok()
);
assert_invalid_call(
"range_bad_idx",
u16_sl.clone(),
vec![u16_sl.clone(), range_to_usize],
CoreCallOp::SliceGetUncheckedRange,
);
assert!(
call_body(
u16_sl.clone(),
vec![u16_sl.clone(), range_u32],
CoreCallOp::SliceGetUncheckedRange,
)
.is_err()
);
assert_invalid_call(
"range_non_int_elem",
bool_sl.clone(),
vec![bool_sl.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRange,
);
assert_invalid_call(
"range_non_slice",
u16_ref.clone(),
vec![u16_ref.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRange,
);
assert_invalid_call(
"range_mut_in",
u16_sl.clone(),
vec![u16_sl_mut.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRange,
);
assert_invalid_call(
"range_mut_dst",
u16_sl_mut,
vec![u16_sl.clone(), range_usize.clone()],
CoreCallOp::SliceGetUncheckedRange,
);
assert_invalid_call(
"range_mismatched_dst_elem",
i32_sl,
vec![u16_sl.clone(), range_usize],
CoreCallOp::SliceGetUncheckedRange,
);
// 2. `SliceGetUncheckedIndex` over sized ref-free elements.
let bool_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(Ty::Bool) };
let bool_ref_mut = Ty::Ref { mutability: Mutability::Mut, pointee: Box::new(Ty::Bool) };
let arr_u8_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array { elem: Box::new(u8_ty()), len: 4 }),
};
let u8_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty()) };
assert!(
call_body(
bool_ref.clone(),
vec![bool_sl.clone(), usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
)
.is_ok()
);
assert_invalid_call(
"idx_bad_idx_ty",
bool_ref.clone(),
vec![bool_sl.clone(), u32_ty()],
CoreCallOp::SliceGetUncheckedIndex,
);
assert_invalid_call(
"idx_non_slice_pointee",
u8_ref.clone(),
vec![arr_u8_ref, usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
);
assert_invalid_call(
"idx_mut_in",
bool_ref.clone(),
vec![bool_sl_mut, usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
);
assert_invalid_call(
"idx_mut_dst",
bool_ref_mut,
vec![bool_sl.clone(), usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
);
assert_invalid_call(
"idx_mismatched_dst_elem",
u8_ref,
vec![bool_sl, usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
);
// Struct slice elements are also rejected (`!Pair.is_sized_no_ref()`).
let pair = pair_ty();
assert!(
call_body(
Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair.clone()) },
vec![slice_ref(Mutability::Shared, pair.clone()), usize_ty()],
CoreCallOp::SliceGetUncheckedIndex,
)
.is_err()
);
// 3. `IntFromLeBytes`: exact `[u8; bits / 8] -> Int(int_ty)` checks.
let byte_arr = |len: usize| Ty::Array { elem: Box::new(u8_ty()), len };
assert!(
call_body(
u8_ty(),
vec![byte_arr(1)],
CoreCallOp::IntFromLeBytes { int_ty: IntTy { width: IntWidth::I8, signed: false } },
)
.is_ok()
);
assert!(
call_body(
u16_ty.clone(),
vec![byte_arr(2)],
CoreCallOp::IntFromLeBytes { int_ty: u16_ity },
)
.is_ok()
);
assert!(
call_body(
i64_ty.clone(),
vec![byte_arr(8)],
CoreCallOp::IntFromLeBytes { int_ty: i64_ity },
)
.is_ok()
);
for (label, dst_ty, arg_tys) in [
("from_le_len_zero_mod8", u16_ty.clone(), vec![byte_arr(0)]),
("from_le_len_short", u16_ty.clone(), vec![byte_arr(1)]),
("from_le_len_long", u16_ty.clone(), vec![byte_arr(4)]),
("from_le_len_mul8", u16_ty.clone(), vec![byte_arr(128)]),
(
"from_le_signed_byte_elem",
u16_ty.clone(),
vec![Ty::Array { elem: Box::new(i8_ty), len: 2 }],
),
(
"from_le_u16_elem",
u16_ty.clone(),
vec![Ty::Array { elem: Box::new(u16_ty.clone()), len: 2 }],
),
("from_le_non_array_arg", u16_ty.clone(), vec![u16_ty.clone()]),
("from_le_bad_dst_width", u32_ty(), vec![byte_arr(2)]),
("from_le_bad_dst_sign", i16_ty.clone(), vec![byte_arr(2)]),
("from_le_empty_args", u16_ty.clone(), vec![]),
("from_le_two_args", u16_ty.clone(), vec![byte_arr(2), byte_arr(2)]),
] {
assert_invalid_call(
label,
dst_ty,
arg_tys,
CoreCallOp::IntFromLeBytes { int_ty: u16_ity },
);
}
// 4. `NumNextMultipleOf` and `NumDivCeil` (unsigned-only, `Int(ity)`
// return, unlike `NumIsMultipleOf`).
for (name, mk_op) in [
("next_multiple_of", CoreCallOp::NumNextMultipleOf as fn(IntTy) -> CoreCallOp),
("div_ceil", CoreCallOp::NumDivCeil as fn(IntTy) -> CoreCallOp),
] {
assert!(
call_body(u64_ty.clone(), vec![u64_ty.clone(), u64_ty.clone()], mk_op(u64_ity),)
.is_ok()
);
assert_invalid_call(
&format!("{name}_signed"),
i64_ty.clone(),
vec![i64_ty.clone(), i64_ty.clone()],
mk_op(i64_ity),
);
assert_invalid_call(
&format!("{name}_bad_lhs"),
u64_ty.clone(),
vec![u32_ty(), u64_ty.clone()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_rhs"),
u64_ty.clone(),
vec![u64_ty.clone(), u32_ty()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bool_dst"),
Ty::Bool,
vec![u64_ty.clone(), u64_ty.clone()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_dst_sign"),
i64_ty.clone(),
vec![u64_ty.clone(), u64_ty.clone()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_arity"),
u64_ty.clone(),
vec![u64_ty.clone()],
mk_op(u64_ity),
);
}
// Also ensure `NumIsMultipleOf` still rejects `Int(ity)` destination
// (preserving the `if matches!` split).
assert_invalid_call(
"is_multiple_of_int_dst",
u64_ty.clone(),
vec![u64_ty.clone(), u64_ty.clone()],
CoreCallOp::NumIsMultipleOf(u64_ity),
);
// 5. `NumCheckedShl(ity)`: `(Int(ity), u32) -> Option<Int(ity)>` for
// signed and unsigned `ity`.
let opt_u64 = Ty::Option { elem: Box::new(u64_ty.clone()) };
let opt_i16 = Ty::Option { elem: Box::new(i16_ty.clone()) };
assert!(
call_body(
opt_u64.clone(),
vec![u64_ty.clone(), u32_ty()],
CoreCallOp::NumCheckedShl(u64_ity),
)
.is_ok()
);
assert!(
call_body(opt_i16, vec![i16_ty.clone(), u32_ty()], CoreCallOp::NumCheckedShl(i16_ity),)
.is_ok()
);
for (label, dst_ty, arg_tys) in [
("cshl_bad_lhs_width", opt_u64.clone(), vec![u32_ty(), u32_ty()]),
("cshl_bad_lhs_sign", opt_u64.clone(), vec![i64_ty.clone(), u32_ty()]),
("cshl_bad_rhs_width", opt_u64.clone(), vec![u64_ty.clone(), u64_ty.clone()]),
("cshl_bad_rhs_sign", opt_u64.clone(), vec![u64_ty.clone(), i32_ty.clone()]),
("cshl_non_option_dst", u64_ty.clone(), vec![u64_ty.clone(), u32_ty()]),
(
"cshl_bad_dst_inner_width",
Ty::Option { elem: Box::new(u32_ty()) },
vec![u64_ty.clone(), u32_ty()],
),
(
"cshl_bad_dst_inner_sign",
Ty::Option { elem: Box::new(i64_ty.clone()) },
vec![u64_ty.clone(), u32_ty()],
),
("cshl_bad_arity", opt_u64.clone(), vec![u64_ty.clone()]),
] {
assert_invalid_call(label, dst_ty, arg_tys, CoreCallOp::NumCheckedShl(u64_ity));
}
// 6. `NumCountOnes` and `NumTrailingZeros`: `(Int(ity)) -> u32`.
for (name, mk_op) in [
("count_ones", CoreCallOp::NumCountOnes as fn(IntTy) -> CoreCallOp),
("trailing_zeros", CoreCallOp::NumTrailingZeros as fn(IntTy) -> CoreCallOp),
] {
assert!(call_body(u32_ty(), vec![i16_ty.clone()], mk_op(i16_ity)).is_ok());
assert!(call_body(u32_ty(), vec![u64_ty.clone()], mk_op(u64_ity)).is_ok());
assert_invalid_call(
&format!("{name}_bad_lhs_sign"),
u32_ty(),
vec![u16_ty.clone()],
mk_op(i16_ity),
);
assert_invalid_call(
&format!("{name}_bad_lhs_width"),
u32_ty(),
vec![u8_ty()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_dst_width"),
u64_ty.clone(),
vec![u64_ty.clone()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_dst_sign"),
i32_ty.clone(),
vec![u64_ty.clone()],
mk_op(u64_ity),
);
assert_invalid_call(
&format!("{name}_bad_arity"),
u32_ty(),
vec![u64_ty.clone(), u64_ty.clone()],
mk_op(u64_ity),
);
}
// 7. `NumNextPowerOfTwo(ity)`: unsigned-only `(Int(ity)) -> Int(ity)`.
assert!(call_body(
u16_ty.clone(),
vec![u16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
)
.is_ok());
assert_invalid_call(
"npot_signed_ity",
i16_ty.clone(),
vec![i16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(i16_ity),
);
assert_invalid_call(
"npot_bad_lhs_width",
u16_ty.clone(),
vec![u32_ty()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
);
assert_invalid_call(
"npot_bad_lhs_sign",
u16_ty.clone(),
vec![i16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
);
assert_invalid_call(
"npot_bad_dst_width",
u32_ty(),
vec![u16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
);
assert_invalid_call(
"npot_bad_dst_sign",
i16_ty,
vec![u16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
);
assert_invalid_call(
"npot_bad_arity",
u16_ty.clone(),
vec![u16_ty.clone(), u16_ty.clone()],
CoreCallOp::NumNextPowerOfTwo(u16_ity),
);
// 8. `NumOverflowingMul(ity)`: `(Int, Int) -> OverflowPair(ity)`.
assert!(
call_body(
Ty::OverflowPair(u64_ity),
vec![u64_ty.clone(), u64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
)
.is_ok()
);
assert!(
call_body(
Ty::OverflowPair(i32_ity),
vec![i32_ty.clone(), i32_ty.clone()],
CoreCallOp::NumOverflowingMul(i32_ity),
)
.is_ok()
);
assert_invalid_call(
"omul_bad_lhs",
Ty::OverflowPair(u64_ity),
vec![u32_ty(), u64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
);
assert_invalid_call(
"omul_bad_rhs",
Ty::OverflowPair(u64_ity),
vec![u64_ty.clone(), i64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
);
assert_invalid_call(
"omul_bad_dst_pair_ty",
Ty::OverflowPair(i64_ity),
vec![u64_ty.clone(), u64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
);
assert_invalid_call(
"omul_tuple_dst",
Ty::Tuple { fields: vec![u64_ty.clone(), Ty::Bool] },
vec![u64_ty.clone(), u64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
);
assert_invalid_call(
"omul_bad_arity",
Ty::OverflowPair(u64_ity),
vec![u64_ty.clone()],
CoreCallOp::NumOverflowingMul(u64_ity),
);
// 9. `MemSizeOf { ty }`: `is_sized()`, `is_supported_v2_local()`,
// `v2_layout().is_some()`, and `dst_ty == usize_ty`.
assert!(
call_body(usize_ty(), vec![], CoreCallOp::MemSizeOf { ty: u64_ty.clone() }).is_ok()
);
assert!(call_body(usize_ty(), vec![], CoreCallOp::MemSizeOf { ty: opt_u64 }).is_ok());
let struct_size_body =
call_body(usize_ty(), vec![], CoreCallOp::MemSizeOf { ty: pair.clone() }).unwrap();
let mut struct_ids = BTreeSet::new();
struct_size_body.collect_struct_ids(&mut struct_ids);
assert_eq!(struct_ids, BTreeSet::from([77]));
let size_term = Terminator::CoreCall {
op: CoreCallOp::MemSizeOf { ty: pair.clone() },
args: vec![],
dst: place(0, vec![]),
target: Some(1),
unwind: UnwindAction::Continue,
};
assert_eq!(size_term.ast_nodes(), 2 + pair.ast_nodes() + place(0, vec![]).ast_nodes());
// Unsized (`!is_sized()`).
assert_invalid_call(
"sizeof_unsized_slice",
usize_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: Ty::Slice { elem: Box::new(u8_ty()) } },
);
assert_invalid_call(
"sizeof_unsized_str",
usize_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: Ty::Str },
);
// Sized with `v2_layout` (`Some((8, 3))`), `!is_supported_v2_local()`.
let nested_ref = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Bool),
}),
};
assert!(
nested_ref.is_sized()
&& nested_ref.v2_layout().is_some()
&& !nested_ref.is_supported_v2_local()
);
assert_invalid_call(
"sizeof_unsupported_v2_local",
usize_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: nested_ref },
);
// Sized + `is_supported_v2_local()`, but `v2_layout().is_none()`
// (`(u8, u16)` and `Option<&u8>`).
let local_tuple = Ty::Tuple { fields: vec![u8_ty(), u16_ty] };
assert!(
local_tuple.is_sized()
&& local_tuple.is_supported_v2_local()
&& local_tuple.v2_layout().is_none()
);
assert_invalid_call(
"sizeof_tuple_no_v2_layout",
usize_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: local_tuple },
);
let opt_ref = Ty::Option {
elem: Box::new(Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(u8_ty()) }),
};
assert!(
opt_ref.is_sized() && opt_ref.is_supported_v2_local() && opt_ref.v2_layout().is_none()
);
assert_invalid_call(
"sizeof_option_ref_no_v2_layout",
usize_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: opt_ref },
);
// Bad destination type (`dst_ty != usize_ty`) and non-empty arguments.
assert_invalid_call(
"sizeof_bad_dst_width",
u32_ty(),
vec![],
CoreCallOp::MemSizeOf { ty: u64_ty.clone() },
);
assert_invalid_call(
"sizeof_bad_dst_sign",
isize_signed,
vec![],
CoreCallOp::MemSizeOf { ty: u64_ty.clone() },
);
assert_invalid_call(
"sizeof_non_empty_args",
usize_ty(),
vec![u64_ty],
CoreCallOp::MemSizeOf { ty: u8_ty() },
);
}
#[test]
fn call_via_ref_partial_eq_is_typed_against_its_callee() {
// `<&Pair as PartialEq>::eq(move _3, move _4)` with `_3, _4: &&Pair`,
// executed as `<Pair as PartialEq>::eq(*_3, *_4)`.
let pair_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair_ty()) };
let pair_ref_ref =
Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair_ref.clone()) };
let eq = |ret: Ty| {
single_block_body(
2,
vec![ret, pair_ref.clone(), pair_ref.clone()],
vec![],
Terminator::Ret,
"rust-path-v1::<Pair as PartialEq>::eq",
)
.unwrap()
};
let caller = |dst_ty: Ty, arg_ty: Ty, negate: bool| {
single_block_body(
2,
vec![dst_ty, pair_ref.clone(), pair_ref.clone(), arg_ty.clone(), arg_ty],
vec![],
Terminator::CallVia {
via: CallVia::RefPartialEq { negate },
callee: 1,
args: vec![Operand::Move { local: 3 }, Operand::Move { local: 4 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
"rust-path-v1::same",
)
};
let scope = || Scope::Crate { excluded_traits: BTreeSet::new() };
let body = caller(Ty::Bool, pair_ref_ref.clone(), true).unwrap();
assert!(body.uses_profile_v2());
let program = Program::try_new(scope(), vec![body, eq(Ty::Bool)]).unwrap();
let rendered = crate::lean::render(&program);
assert!(rendered.contains("(Trusted.MirAst.TerminatorKind.callVia\n"), "{rendered}");
assert!(rendered.contains("(Trusted.MirAst.CallVia.refPartialEq true)"), "{rendered}");
// The callee must return `bool`.
let body = caller(Ty::Bool, pair_ref_ref.clone(), false).unwrap();
assert!(Program::try_new(scope(), vec![body, eq(u8_ty())]).is_err());
// The arguments must be `&&A` and the destination `bool`.
assert!(caller(Ty::Bool, pair_ref.clone(), false).is_err());
assert!(caller(u8_ty(), pair_ref_ref, false).is_err());
}
#[test]
fn call_via_partial_ord_is_typed_against_its_callee() {
// `PartialOrd::ge(move _3, move _4)` with `_3, _4: &Pair`, executed as
// `<Pair as PartialOrd>::partial_cmp(_3, _4)`.
let pair_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair_ty()) };
// `Option<Ordering>`, whose `None` is the niche value 2 of the `i8`
// tag of `Ordering`.
let opt_ord = Ty::AdtEnum(Box::new(
AdtEnumTy::try_new(
90,
false,
1,
0,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I8, signed: true },
(254, 1),
AdtTagEncoding::Niche { untagged: 1, first: 0, last: 0, start: 254 },
vec![
Ty::Struct(StructTy::try_new(91, 1, 0, vec![], vec![]).unwrap()),
Ty::Struct(StructTy::try_new(92, 1, 0, vec![0], vec![Ty::Ordering]).unwrap()),
],
)
.unwrap(),
));
let partial_cmp = |ret: Ty| {
single_block_body(
2,
vec![ret, pair_ref.clone(), pair_ref.clone()],
vec![],
Terminator::Ret,
"rust-path-v1::<Pair as PartialOrd>::partial_cmp",
)
.unwrap()
};
let caller = |dst_ty: Ty, arg_ty: Ty| {
single_block_body(
2,
vec![dst_ty, pair_ref.clone(), pair_ref.clone(), arg_ty.clone(), arg_ty],
vec![],
Terminator::CallVia {
via: CallVia::PartialOrd { greater: true, or_equal: true },
callee: 1,
args: vec![Operand::Move { local: 3 }, Operand::Move { local: 4 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
"rust-path-v1::ge",
)
};
let scope = || Scope::Crate { excluded_traits: BTreeSet::new() };
let body = caller(Ty::Bool, pair_ref.clone()).unwrap();
assert!(body.uses_profile_v2());
let program = Program::try_new(scope(), vec![body, partial_cmp(opt_ord.clone())]).unwrap();
let rendered = crate::lean::render(&program);
assert!(rendered.contains("(Trusted.MirAst.CallVia.partialOrd true true)"), "{rendered}");
// The callee must return `Option<Ordering>`.
let body = caller(Ty::Bool, pair_ref.clone()).unwrap();
assert!(Program::try_new(scope(), vec![body, partial_cmp(Ty::Bool)]).is_err());
// The arguments must be `&A` and the destination `bool`.
let pair_ref_ref =
Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair_ref.clone()) };
assert!(caller(Ty::Bool, pair_ref_ref).is_err());
assert!(caller(u8_ty(), pair_ref.clone()).is_err());
}
#[test]
fn call_via_box_clone_is_typed_against_its_callee() {
// `<Box<Pair> as Clone>::clone(move _1)` with `_1: &Box<Pair>`,
// executed as a call of `<Pair as Clone>::clone(&**_1)`.
let pair = pair_ty();
let pair_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(pair.clone()) };
let boxed = Ty::Box { pointee: Box::new(pair.clone()) };
let box_ref = Ty::Ref { mutability: Mutability::Shared, pointee: Box::new(boxed.clone()) };
let clone = |ret: Ty| {
single_block_body(
1,
vec![ret, pair_ref.clone()],
vec![],
Terminator::Ret,
"rust-path-v1::<Pair as Clone>::clone",
)
.unwrap()
};
let caller = |dst_ty: Ty, arg_ty: Ty| {
single_block_body(
1,
vec![dst_ty, arg_ty],
vec![],
Terminator::CallVia {
via: CallVia::BoxClone { pointee: pair.clone() },
callee: 1,
args: vec![Operand::Move { local: 1 }],
dst: 0,
target: Some(1),
unwind: UnwindAction::Continue,
},
"rust-path-v1::dup",
)
};
let scope = || Scope::Crate { excluded_traits: BTreeSet::new() };
let body = caller(boxed.clone(), box_ref.clone()).unwrap();
let program = Program::try_new(scope(), vec![body, clone(pair.clone())]).unwrap();
let rendered = crate::lean::render(&program);
assert!(rendered.contains("(Trusted.MirAst.CallVia.boxClone "), "{rendered}");
// The callee must return the pointee.
let body = caller(boxed.clone(), box_ref.clone()).unwrap();
assert!(Program::try_new(scope(), vec![body, clone(u8_ty())]).is_err());
// The argument must be `&Box<T>` and the destination `Box<T>`.
assert!(caller(boxed.clone(), pair_ref).is_err());
assert!(caller(u8_ty(), box_ref).is_err());
}
#[test]
fn array_index_range_and_range_from_validators_cover_ok_and_malformed_ir() {
let usize_ty = Ty::Int(IntTy {
width: IntWidth::Isize,
signed: false,
});
let u8_ty = Ty::Int(IntTy {
width: IntWidth::I8,
signed: false,
});
let u16_ty = Ty::Int(IntTy {
width: IntWidth::I16,
signed: false,
});
let range_usize = Ty::Range {
elem: Box::new(usize_ty.clone()),
};
let range_from_usize = Ty::RangeFrom {
elem: Box::new(usize_ty.clone()),
};
let mk_body = |op: CoreCallOp, in_ty: Ty, idx_ty: Ty, dst_ty: Ty| {
Body::try_new(
2,
false,
vec![dst_ty, in_ty, idx_ty],
vec![
Block {
statements: vec![],
terminator: Terminator::CoreCall {
op,
args: vec![Operand::Move { local: 1 }, Operand::Move { local: 2 }],
dst: Place {
local: 0,
projection: vec![],
},
target: Some(1),
unwind: UnwindAction::Continue,
},
},
Block {
statements: vec![],
terminator: Terminator::Ret,
},
],
"rust-path-v1::arr_idx_test".into(),
)
};
let assert_invalid = |label: &str, op: CoreCallOp, in_ty: Ty, idx_ty: Ty, dst_ty: Ty| {
let err = mk_body(op, in_ty, idx_ty, dst_ty)
.expect_err(&format!("{label}: expected CoreCall rejection"));
assert!(err.contains("invalid CoreCall"), "{label}: unexpected error `{err}`");
};
for mutability in [Mutability::Shared, Mutability::Mut] {
let arr_ref = Ty::Ref {
mutability,
pointee: Box::new(Ty::Array {
elem: Box::new(u8_ty.clone()),
len: 8,
}),
};
let max_arr_ref = Ty::Ref {
mutability,
pointee: Box::new(Ty::Array {
elem: Box::new(u8_ty.clone()),
len: isize::MAX as usize,
}),
};
let slice_ref = Ty::Ref {
mutability,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone()),
}),
};
assert!(mk_body(
CoreCallOp::SliceIndexRange {
mutability,
elem: u8_ty.clone(),
},
arr_ref.clone(),
range_usize.clone(),
slice_ref.clone(),
)
.is_ok());
assert!(mk_body(
CoreCallOp::SliceIndexRange {
mutability,
elem: u8_ty.clone(),
},
max_arr_ref.clone(),
range_usize.clone(),
slice_ref.clone(),
)
.is_ok());
assert!(mk_body(
CoreCallOp::SliceIndexRange {
mutability,
elem: u8_ty.clone(),
},
slice_ref.clone(),
range_usize.clone(),
slice_ref.clone(),
)
.is_ok());
assert!(mk_body(
CoreCallOp::SliceIndexRangeFrom {
mutability,
elem: u8_ty.clone(),
},
arr_ref,
range_from_usize.clone(),
slice_ref.clone(),
)
.is_ok());
assert!(mk_body(
CoreCallOp::SliceIndexRangeFrom {
mutability,
elem: u8_ty.clone(),
},
max_arr_ref,
range_from_usize.clone(),
slice_ref.clone(),
)
.is_ok());
assert!(mk_body(
CoreCallOp::SliceIndexRangeFrom {
mutability,
elem: u8_ty.clone(),
},
slice_ref.clone(),
range_from_usize.clone(),
slice_ref,
)
.is_ok());
}
// Negative: shared array ref cannot satisfy IndexMut op.
let shared_u8_arr = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(u8_ty.clone()),
len: 8,
}),
};
let mut_u8_slice = Ty::Ref {
mutability: Mutability::Mut,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone()),
}),
};
assert_invalid(
"range_mut_mismatch",
CoreCallOp::SliceIndexRange {
mutability: Mutability::Mut,
elem: u8_ty.clone(),
},
shared_u8_arr.clone(),
range_usize.clone(),
mut_u8_slice.clone(),
);
assert_invalid(
"range_from_mut_mismatch",
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Mut,
elem: u8_ty.clone(),
},
shared_u8_arr,
range_from_usize.clone(),
mut_u8_slice,
);
// Negative: mismatched element type between array and op.
let shared_u16_arr = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(u16_ty.clone()),
len: 4,
}),
};
let shared_u8_slice = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u8_ty.clone()),
}),
};
assert_invalid(
"range_elem_mismatch",
CoreCallOp::SliceIndexRange {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
shared_u16_arr.clone(),
range_usize.clone(),
shared_u8_slice.clone(),
);
assert_invalid(
"range_from_elem_mismatch",
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
shared_u16_arr,
range_from_usize.clone(),
shared_u8_slice.clone(),
);
// Negative: overflowing array layout (`> isize::MAX` or `None`).
let over_isize_arr = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(u8_ty.clone()),
len: (isize::MAX as usize) + 1,
}),
};
let over_usize_u16_arr = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(u16_ty.clone()),
len: usize::MAX / 2 + 1,
}),
};
let shared_u16_slice = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(u16_ty.clone()),
}),
};
assert_invalid(
"range_over_isize",
CoreCallOp::SliceIndexRange {
mutability: Mutability::Shared,
elem: u8_ty.clone(),
},
over_isize_arr.clone(),
range_usize.clone(),
shared_u8_slice.clone(),
);
assert_invalid(
"range_from_over_isize",
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: u8_ty,
},
over_isize_arr,
range_from_usize.clone(),
shared_u8_slice,
);
assert_invalid(
"range_layout_none",
CoreCallOp::SliceIndexRange {
mutability: Mutability::Shared,
elem: u16_ty.clone(),
},
over_usize_u16_arr.clone(),
range_usize.clone(),
shared_u16_slice.clone(),
);
assert_invalid(
"range_from_layout_none",
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: u16_ty,
},
over_usize_u16_arr,
range_from_usize.clone(),
shared_u16_slice,
);
// Negative: Option<u64> array is not yet an admitted array pointee.
let opt_u64 = Ty::Option {
elem: Box::new(Ty::Int(IntTy {
width: IntWidth::I64,
signed: false,
})),
};
assert!(mk_body(
CoreCallOp::SliceIndexRange {
mutability: Mutability::Shared,
elem: opt_u64.clone(),
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(opt_u64.clone()),
len: 2,
}),
},
range_usize,
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(opt_u64.clone()),
}),
},
)
.is_err());
assert!(mk_body(
CoreCallOp::SliceIndexRangeFrom {
mutability: Mutability::Shared,
elem: opt_u64.clone(),
},
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Array {
elem: Box::new(opt_u64.clone()),
len: 2,
}),
},
range_from_usize,
Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Slice {
elem: Box::new(opt_u64),
}),
},
)
.is_err());
}
#[test]
fn option_box_str_v2_layout_matches_wide_box_str() {
let box_str = Ty::Box { pointee: Box::new(Ty::Str) };
let opt_box_str = Ty::Option { elem: Box::new(box_str.clone()) };
assert_eq!(box_str.v2_layout(), Some((16, 3)));
assert_eq!(opt_box_str.v2_layout(), Some((16, 3)));
}
#[test]
fn external_stub_body_validates_signature_and_selects_profile_v2() {
let u32_ty = Ty::Int(IntTy { width: IntWidth::I32, signed: false });
let stub = Body::try_new_external_stub(
1,
true,
vec![u32_ty.clone(), u32_ty.clone()],
"rust-path-v1::ext_helper".into(),
)
.unwrap();
assert!(stub.is_external());
assert!(stub.blocks().is_empty());
assert!(stub.uses_profile_v2());
let stub_json = serde_json::to_value(&stub).unwrap();
assert_eq!(stub_json["is_external"], true);
let normal = Body::try_new(
0,
false,
vec![Ty::Unit],
vec![Block { statements: vec![], terminator: Terminator::Ret }],
"rust-path-v1::portable".into(),
)
.unwrap();
assert!(!normal.is_external());
let normal_json = serde_json::to_value(&normal).unwrap();
assert!(normal_json.get("is_external").is_none());
let prog = Program::try_new(
Scope::Crate { excluded_traits: BTreeSet::new() },
vec![normal, stub],
)
.unwrap();
assert_eq!(prog.mir_profile_version(), 2);
// Reject empty identity, wrong local count, mixed ref/raw-ptr, and
// `&&int`.
assert!(
Body::try_new_external_stub(0, false, vec![Ty::Unit], String::new()).is_err()
);
assert!(
Body::try_new_external_stub(
1,
false,
vec![u32_ty.clone(), u32_ty.clone(), u32_ty.clone()],
"rust-path-v1::extra_local".into(),
)
.is_err()
);
let shared_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(u32_ty.clone()),
};
let raw_ptr = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(u32_ty.clone()),
};
assert!(
Body::try_new_external_stub(
2,
true,
vec![u32_ty, shared_ref.clone(), raw_ptr],
"rust-path-v1::mixed_ref_ptr".into(),
)
.is_err()
);
let nested_ref = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(shared_ref),
};
assert!(
Body::try_new_external_stub(
1,
false,
vec![Ty::Unit, nested_ref],
"rust-path-v1::nested_ref".into(),
)
.is_err()
);
}
#[test]
fn str_ref_rejected_in_nested_ref_and_ref_enum_v2() {
let shared_str = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(Ty::Str),
};
assert!(shared_str.is_supported_v2_local());
assert!(!shared_str.is_ref_enum_field_v2());
let nested_str = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(shared_str),
};
assert!(!nested_str.is_supported_v2_local());
}
#[test]
fn validate_constant_admits_heap_free_rec_adt_variant_and_refuses_heap_variant() {
let v_empty = Ty::Struct(StructTy::try_new(901, 16, 3, vec![], vec![]).unwrap());
let v_rec = Ty::Struct(
StructTy::try_new(
902,
16,
3,
vec![8],
vec![Ty::Box { pointee: Box::new(Ty::RecSelf { id: 900 }) }],
)
.unwrap(),
);
let adt = AdtEnumTy::try_new(
900,
true,
16,
3,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I8, signed: false },
(0, 1),
AdtTagEncoding::Direct,
vec![v_empty, v_rec],
)
.unwrap();
let rec_ty = Ty::RecAdt { id: 900, defn: Box::new(Ty::AdtEnum(Box::new(adt))) };
let mut empty_bytes = vec![RodataByte::Uninit; 16];
empty_bytes[0] = RodataByte::Init { byte: 0 };
let mut rec_bytes = vec![RodataByte::Uninit; 16];
rec_bytes[0] = RodataByte::Init { byte: 1 };
assert!(
validate_constant(&rec_ty, &ConstLit::RodataBytes { bytes: empty_bytes.clone() })
.is_ok()
);
assert!(
validate_constant(&rec_ty, &ConstLit::RodataBytes { bytes: rec_bytes.clone() })
.is_err()
);
let ref_ty = Ty::Ref {
mutability: Mutability::Shared,
pointee: Box::new(rec_ty.clone()),
};
assert!(
validate_constant(
&ref_ty,
&ConstLit::RodataRef {
bytes: empty_bytes.clone(),
align_log2: 3,
offset_bytes: 0,
slice_len: None,
},
)
.is_ok()
);
assert!(
validate_constant(
&ref_ty,
&ConstLit::RodataRef {
bytes: rec_bytes,
align_log2: 3,
offset_bytes: 0,
slice_len: None,
},
)
.is_err()
);
// Raw pointers into `.rodata` stay restricted to pure V2 data types.
let raw_ptr_ty = Ty::RawPtr {
mutability: Mutability::Shared,
pointee: Box::new(rec_ty),
};
assert!(
validate_constant(
&raw_ptr_ty,
&ConstLit::RodataRef {
bytes: empty_bytes,
align_log2: 3,
offset_bytes: 0,
slice_len: None,
},
)
.is_err()
);
// Niche-encoded Box-null recursive enum `{ A(Box<Self>), B }`:
// tag 0 selects heap-free variant `B` (admitted), non-zero tag 8
// selects `A(Box<Self>)` (refused), and uninit tag is refused.
let niche_v_rec = Ty::Struct(
StructTy::try_new(
911,
8,
3,
vec![0],
vec![Ty::Box { pointee: Box::new(Ty::RecSelf { id: 910 }) }],
)
.unwrap(),
);
let niche_v_empty = Ty::Struct(StructTy::try_new(912, 8, 3, vec![], vec![]).unwrap());
let niche_adt = AdtEnumTy::try_new(
910,
true,
8,
3,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I64, signed: false },
(1, u64::MAX as u128),
AdtTagEncoding::Niche { untagged: 0, first: 1, last: 1, start: 0 },
vec![niche_v_rec, niche_v_empty],
)
.unwrap();
let niche_rec_ty = Ty::RecAdt { id: 910, defn: Box::new(Ty::AdtEnum(Box::new(niche_adt))) };
let niche_empty_bytes = vec![RodataByte::Init { byte: 0 }; 8];
let mut niche_rec_bytes = vec![RodataByte::Init { byte: 0 }; 8];
niche_rec_bytes[0] = RodataByte::Init { byte: 8 };
let niche_uninit_bytes = vec![RodataByte::Uninit; 8];
assert!(
validate_constant(
&niche_rec_ty,
&ConstLit::RodataBytes { bytes: niche_empty_bytes },
)
.is_ok()
);
assert!(
validate_constant(
&niche_rec_ty,
&ConstLit::RodataBytes { bytes: niche_rec_bytes },
)
.is_err()
);
assert!(
validate_constant(
&niche_rec_ty,
&ConstLit::RodataBytes { bytes: niche_uninit_bytes },
)
.is_err()
);
// Heap-free non-recursive payload enum carrying `Option<u32>` (e.g.
// `Result<Option<u32>, ()>::Ok(Some(5))`) remains admitted as a
// `.rodataBytes` constant.
let opt_u32 = Ty::Option {
elem: Box::new(Ty::Int(IntTy { width: IntWidth::I32, signed: false })),
};
let v_ok_opt =
Ty::Struct(StructTy::try_new(921, 12, 2, vec![4], vec![opt_u32]).unwrap());
let v_err_unit = Ty::Struct(StructTy::try_new(922, 12, 2, vec![], vec![]).unwrap());
let res_opt_adt = AdtEnumTy::try_new(
920,
false,
12,
2,
IntTy { width: IntWidth::Isize, signed: true },
vec![0, 1],
0,
IntTy { width: IntWidth::I8, signed: false },
(0, 1),
AdtTagEncoding::Direct,
vec![v_ok_opt, v_err_unit],
)
.unwrap();
let res_opt_ty = Ty::AdtEnum(Box::new(res_opt_adt));
let mut res_opt_bytes = vec![RodataByte::Init { byte: 0 }; 12];
res_opt_bytes[4] = RodataByte::Init { byte: 1 };
res_opt_bytes[8] = RodataByte::Init { byte: 5 };
assert!(
validate_constant(&res_opt_ty, &ConstLit::RodataBytes { bytes: res_opt_bytes })
.is_ok()
);
}
}