blob: 97200356120d99855d670af72803e1053a9397d2 [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.
prelude
import Init.NotationExtra
import GuardRefuteWf
/-!
# Negative Refutations for `Trusted.MirSemantics.Bytes` Validity Guards
Exercises every scalar-validity, constant-width, type-check, padding-uninit,
byte-length, uninitialized-byte, and `validUtf8Go` RFC 3629 UTF-8 state
machine guard in `Trusted/MirSemantics/Bytes.lean`.
-/
namespace GuardMutation
open Trusted.MirAst Trusted.MirSemantics
/-- Guard `bytes_invalid_bool_value`: a 1-byte `bool` scalar whose value is
`2` (neither `0` nor `1`) faults with `.undefined`. -/
theorem refute_bytes_invalid_bool_value :
ReachesResult (mkConstRetProg .bool 2) queryEmpty (.fault .undefined) ∧
¬ WellFormed (mkConstRetProg .bool 2) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_invalid_char_surrogate`: a `char` constant holding surrogate
code point `0xD800` faults with `.undefined` rather than passing through
`Char.ofNat`. -/
theorem refute_bytes_invalid_char_surrogate :
ReachesResult (mkConstRetProg .char 0xd800) queryEmpty
(.fault .undefined) ∧
¬ WellFormed (mkConstRetProg .char 0xd800) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_invalid_ordering_tag`: a `core::cmp::Ordering` constant with
tag `2` (outside `{-1_i8, 0, 1}`) faults with `.undefined`. -/
theorem refute_bytes_invalid_ordering_tag :
ReachesResult (mkConstRetProg .ordering 2) queryEmpty
(.fault .undefined) ∧
¬ WellFormed (mkConstRetProg .ordering 2) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_invalid_enum_tag`: a `ReprU8 { A = 10, B = 20 }` constant
with tag `1` faults with `.undefined`. -/
theorem refute_bytes_invalid_enum_tag :
ReachesResult (mkConstRetProg (.enum reprU8EnumTy) 1) queryEmpty
(.fault .undefined) ∧
¬ WellFormed (mkConstRetProg (.enum reprU8EnumTy) 1) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program `StorageLive(_1: u32); _0 = copy _1; return`, used to test indirect
uninitialized-byte reads after `forceAllocation`. -/
noncomputable def progIndirectUninitRead : Program :=
mkSingleBlockProg 0 [u32Ty, u32Ty]
[.storageLive 1, .assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `bytes_uninit_memory_read`: reading uninitialized bytes from an
indirect stack allocation via `initBytes?` / `decodeVal` / `loadIndirect`
faults with `.undefined`. -/
theorem refute_bytes_uninit_memory_read :
(match initState progIndirectUninitRead queryEmpty with
| .ok s₀ =>
match evalStep progIndirectUninitRead 0 s₀ with
| .step s₁ =>
match forceAllocation progIndirectUninitRead s₁ 1 with
| .ok (s₂, _) =>
evalStep progIndirectUninitRead 0 s₂ = .fault .undefined
| .error _ => False
| _ => False
| .error _ => False) :=
rfl
/-- Guard `bytes_const_int_width_overflow`: a `u8` constant whose raw bit
pattern `256` exceeds 8 bits faults with `.unsupported`. -/
theorem refute_bytes_const_int_width_overflow :
ReachesResult (mkConstRetProg u8Ty 256) queryEmpty (.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg u8Ty 256) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_const_bool_width_overflow`: a `bool` constant whose raw bit
pattern `257` exceeds 1 byte (even though its low byte is `1`) faults with
`.unsupported`. -/
theorem refute_bytes_const_bool_width_overflow :
ReachesResult (mkConstRetProg .bool 257) queryEmpty (.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg .bool 257) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_const_char_width_overflow` (lockstep fault classification):
a `char` constant whose raw bit pattern `2^32 + 65` exceeds 4 bytes faults
with `.unsupported` rather than `.undefined`. -/
theorem refute_bytes_const_char_width_overflow :
ReachesResult (mkConstRetProg .char (Nat.pow 2 32 + 65)) queryEmpty
(.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg .char (Nat.pow 2 32 + 65)) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_const_ordering_width_overflow` (lockstep fault classification):
an `Ordering` constant whose raw bit pattern `256` exceeds 1 byte faults with
`.unsupported` rather than `.undefined`. -/
theorem refute_bytes_const_ordering_width_overflow :
ReachesResult (mkConstRetProg .ordering 256) queryEmpty
(.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg .ordering 256) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program assigning a `ConstLit.zeroSized` literal to a scalar-tagged enum
local. -/
noncomputable def progZeroSizedScalarEnumConst : Program :=
mkSingleBlockProg 0 [.enum reprU8EnumTy]
[.assign ⟨0, []⟩ (.use (.constant ⟨.enum reprU8EnumTy, .zeroSized⟩))]
/-- Guard `bytes_const_zst_enum_requires_zst`: `ConstLit.zeroSized` at a
scalar-tagged enum faults with `.unsupported`. -/
theorem refute_bytes_const_zst_enum_requires_zst :
ReachesResult progZeroSizedScalarEnumConst queryEmpty
(.fault .unsupported) ∧
¬ WellFormed progZeroSizedScalarEnumConst queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_const_scalar_enum_width_overflow`: a `ReprU8` constant whose
raw bit pattern `266` (`256 + 10`) exceeds its 1-byte tag width faults with
`.unsupported`. -/
theorem refute_bytes_const_scalar_enum_width_overflow :
ReachesResult (mkConstRetProg (.enum reprU8EnumTy) 266) queryEmpty
(.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg (.enum reprU8EnumTy) 266) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_const_mismatched_lit_kind`: a `ConstLit.scalar` literal at
`.unit` faults with `.unsupported`. -/
theorem refute_bytes_const_mismatched_lit_kind :
ReachesResult (mkConstRetProg .unit 0) queryEmpty (.fault .unsupported) ∧
¬ WellFormed (mkConstRetProg .unit 0) queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_encode_val_checks_type`: `encodeVal` rejects a non-canonical
`u8` scalar (`bits = 256`) with `.unsupported`. -/
theorem refute_bytes_encode_val_checks_type :
encodeVal .big u8Ty (u8Val 256) = .error .unsupported :=
rfl
/-- Guard `bytes_encode_overflow_pair_padding_uninit`: `encodeVal` leaves the
tail padding bytes of an overflow pair `(u32, bool)` uninitialized rather than
zero-filled. -/
theorem refute_bytes_encode_overflow_pair_padding_uninit :
encodeVal .big (.tuple [u32Ty, .bool]) (.tuple [u32Val 0, .bool false]) =
.ok [.init 0 none, .init 0 none, .init 0 none, .init 0 none,
.init 0 none, .uninit, .uninit, .uninit] :=
rfl
/-- Guard `bytes_decode_never_returns_uninit`: `decodeVal` for uninhabited
`.never` returns `.ok none` so no valid value can be materialized. -/
theorem refute_bytes_decode_never_returns_uninit :
decodeVal .big .never [] = .ok none :=
rfl
/-- Guard `bytes_decode_length_mismatch`: `decodeVal` rejects a byte slice
whose length disagrees with `layoutOfTy u32Ty` (`1 ≠ 4`) with `.unsupported`.
-/
theorem refute_bytes_decode_length_mismatch :
decodeVal .big u32Ty [.init 0 none] = .error .unsupported :=
rfl
/-- Guard `bytes_decode_overflow_pair_length_mismatch`: `decodeVal` rejects a
byte slice whose length disagrees with `overflowPairLayout .i32` (`5 ≠ 8`) with
`.unsupported`. -/
theorem refute_bytes_decode_overflow_pair_length_mismatch :
decodeVal .big (.tuple [u32Ty, .bool]) (List.replicate 5 (.init 0 none)) =
.error .unsupported :=
rfl
/-- Guard `bytes_decode_overflow_pair_uninit_bool`: `decodeVal` returns
`.ok none` when the `bool` byte of a `(u32, bool)` overflow pair is `.uninit`.
-/
theorem refute_bytes_decode_overflow_pair_uninit_bool :
decodeVal .big (.tuple [u32Ty, .bool])
[.init 0 none, .init 0 none, .init 0 none, .init 0 none,
.uninit, .uninit, .uninit, .uninit] = .ok none :=
rfl
/-- Single-variant zero-sized enum (`tagRepr := .zeroSized`). -/
noncomputable def zstScalarLitEnumTy : EnumTy := {
id := 77
discrWidth := .i8
discrSigned := false
tagRepr := .zeroSized
discriminants := [0]
}
/-- Program assigning a `ConstLit.scalar` literal to a `.zeroSized` enum
local. -/
noncomputable def progScalarLitOnZstEnum : Program :=
mkSingleBlockProg 0 [.enum zstScalarLitEnumTy]
[.assign ⟨0, []⟩
(.use (.constant ⟨.enum zstScalarLitEnumTy,
.scalar (BitVec.ofNat 128 5)⟩))]
/-- Guard `bytes_const_scalar_lit_on_zst_enum`: `evalConstLit` rejects a
`ConstLit.scalar` literal on a `.zeroSized` enum with `.unsupported`. -/
theorem refute_bytes_const_scalar_lit_on_zst_enum :
ReachesResult progScalarLitOnZstEnum queryEmpty (.fault .unsupported) ∧
¬ WellFormed progScalarLitOnZstEnum queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `bytes_utf8_two_byte_lead_min`: an overlong two-byte encoding (lead
`0xC0` or `0xC1`) is rejected, while the shortest two-byte encodings `U+0080`
and `U+07FF` are accepted. -/
theorem refute_bytes_utf8_two_byte_lead_min :
validUtf8Bytes [0xC1, 0xBF] = false ∧
validUtf8Bytes [0xC2, 0x80] = true ∧
validUtf8Bytes [0xDF, 0xBF] = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_utf8_e0_overlong`: the overlong three-byte encoding of `U+07FF`
(`E0 9F BF`) is rejected, while `U+0800` (`E0 A0 80`) is accepted. -/
theorem refute_bytes_utf8_e0_overlong :
validUtf8Bytes [0xE0, 0x9F, 0xBF] = false ∧
validUtf8Bytes [0xE0, 0xA0, 0x80] = true :=
⟨rfl, rfl⟩
/-- Guard `bytes_utf8_ed_surrogate`: the UTF-16 surrogate `U+D800` (`ED A0 80`)
is rejected, while its neighbors `U+D7FF` (`ED 9F BF`) and `U+E000` (`EE 80 80`)
are accepted. -/
theorem refute_bytes_utf8_ed_surrogate :
validUtf8Bytes [0xED, 0xA0, 0x80] = false ∧
validUtf8Bytes [0xED, 0x9F, 0xBF] = true ∧
validUtf8Bytes [0xEE, 0x80, 0x80] = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_utf8_f0_overlong`: the overlong four-byte encoding of `U+FFFF`
(`F0 8F BF BF`) is rejected, while `U+10000` (`F0 90 80 80`) and `U+1F600`
(`F0 9F 98 80`) are accepted. -/
theorem refute_bytes_utf8_f0_overlong :
validUtf8Bytes [0xF0, 0x8F, 0xBF, 0xBF] = false ∧
validUtf8Bytes [0xF0, 0x90, 0x80, 0x80] = true ∧
validUtf8Bytes [0xF0, 0x9F, 0x98, 0x80] = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_utf8_f4_max`: `U+110000` (`F4 90 80 80`), one past the largest
code point, is rejected, while `U+10FFFF` (`F4 8F BF BF`) is accepted. -/
theorem refute_bytes_utf8_f4_max :
validUtf8Bytes [0xF4, 0x90, 0x80, 0x80] = false ∧
validUtf8Bytes [0xF4, 0x8F, 0xBF, 0xBF] = true :=
⟨rfl, rfl⟩
/-- Guard `bytes_utf8_invalid_lead`: a lone continuation byte (`80`) and the
never-valid leads `F5` and `FF` are rejected. -/
theorem refute_bytes_utf8_invalid_lead :
validUtf8Bytes [0x80] = false ∧
validUtf8Bytes [0xF5, 0x80, 0x80, 0x80] = false ∧
validUtf8Bytes [0xFF] = false :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_utf8_truncated`: a three-byte sequence cut short (`E2 82`) is
rejected, while the complete `U+20AC` (`E2 82 AC`) is accepted. -/
theorem refute_bytes_utf8_truncated :
validUtf8Bytes [0xE2, 0x82] = false ∧
validUtf8Bytes [0xE2, 0x82, 0xAC] = true :=
⟨rfl, rfl⟩
/-- Guard `bytes_utf8_continuation_hi`: a continuation byte above `0xBF`
(`C2 C0`) is rejected. -/
theorem refute_bytes_utf8_continuation_hi :
validUtf8Bytes [0xC2, 0xC0] = false ∧
validUtf8Bytes [0xC2, 0xBF] = true :=
⟨rfl, rfl⟩
/-- Guard `bytes_utf8_continuation_lo`: an ASCII byte in a continuation position
(`C2 7F`) is rejected. -/
theorem refute_bytes_utf8_continuation_lo :
validUtf8Bytes [0xC2, 0x7F] = false ∧
validUtf8Bytes [0xC2, 0x80] = true :=
⟨rfl, rfl⟩
/-- Memory whose allocation 1 is one 8-byte `Box<bool>` element pointing into
allocation 2, which does not exist. -/
def danglingInnerBoxMem : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 3
mutability := .mut
bytes := List.replicate 8 (.init 0 (some 2))
live := true
}]
nextAllocId := 3
}
/-- Memory whose allocation 1 holds an 8-byte struct whose only field is a
`Box<bool>` with a null, provenance-free pointer. -/
def nullBoxFieldMem : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 3
mutability := .shared
bytes := List.replicate 8 (.init 0 none)
live := true
}]
nextAllocId := 2
}
/-- Guard `bytes_owned_vec_elems_validated`: validating a `Vec<Box<bool>>`
checks the buffer of every element box, so a dangling element box faults. -/
theorem refute_bytes_owned_vec_elems_validated :
(match ownedValidInMem danglingInnerBoxMem true (.vec (.box .bool))
(.vec ⟨some 1, 0, .isize⟩ 1 1) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `bytes_owned_struct_fields_validated`: validating a struct checks
the buffer of a `Box` field. -/
theorem refute_bytes_owned_struct_fields_validated :
(match ownedValidInMem emptyMemory true
(.struct_ ⟨7, 8, 3, [0]⟩ [.box .bool])
(.tuple [.boxPtr ⟨none, 0, .isize⟩ none]) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `bytes_owned_option_some_validated`: validating `Some(box)` checks
the box's buffer. -/
theorem refute_bytes_owned_option_some_validated :
(match ownedValidInMem emptyMemory true (.option (.box .bool))
(.optionVal (some (.boxPtr ⟨none, 0, .isize⟩ none))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `bytes_ref_pointee_owned_validated`: a reference to a struct with a
`Box` field is valid only if the box's buffer is. -/
theorem refute_bytes_ref_pointee_owned_validated :
(match refValidInMem nullBoxFieldMem .shared
(.struct_ ⟨7, 8, 3, [0]⟩ [.box .bool]) (.ptr ⟨some 1, 0, .isize⟩) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `bytes_slice_owned_elems_validated`: a slice reference whose elements
are boxes is valid only if every element box's buffer is. -/
theorem refute_bytes_slice_owned_elems_validated :
(match refValidInMem danglingInnerBoxMem .shared (.slice (.box .bool))
(.slicePtr ⟨some 1, 0, .isize⟩ 1) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `bytes_option_box_null_some_refused`: `Some` of a null box would
encode like `None`, so it is refused. -/
theorem refute_bytes_option_box_null_some_refused :
(match encodeValV2 profileV2TargetEndian (.option (.box .bool))
(.optionVal (some (.boxPtr ⟨none, 0, .isize⟩ none))) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `bytes_option_box_null_decode_refused`: zero pointer bytes with mixed
provenance (one byte carries allocation `1`) decode to a null box, the `None`
niche, so `Option<Box<i8>>` decoding refuses them as invalid instead of
returning `Some` of a value `encodeValV2` cannot re-encode. -/
theorem refute_bytes_option_box_null_decode_refused :
(match decodeValV2 profileV2TargetEndian (.option (.box (.int .i8 false)))
(.init 0 (some 1) :: List.replicate 7 (.init 0 none)) with
| .ok none => True
| _ => False) :=
trivial
/-- Guard `bytes_option_vec_niche_cap_refused`: encoding a `Vec` (or
`Option<Vec<T>>::Some`) whose capacity is `>= 2^63` (`isizeMaxBytes`) is
refused with `.unsupported`. -/
theorem refute_bytes_option_vec_niche_cap_refused :
(match encodeValV2 profileV2TargetEndian (.option (.vec .bool))
(.optionVal (some (.vec ⟨some 1, 0, .isize⟩
(UInt64.ofNat (Nat.pow 2 63)) 0))) with
| .error .unsupported => True
| _ => False) ∧
(match encodeValV2 profileV2TargetEndian (.option (.vec .unit))
(.optionVal (some (.vec ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63 + 1)) 0))) with
| .error .unsupported => True
| _ => False) :=
⟨trivial, trivial⟩
/-- A padded struct `{ a: u8, b: u16 }` (`b` at offset 2, so byte 1 is
padding). -/
def paddedElemTy : MirTy :=
.struct_ ⟨5, 4, 1, [0, 2]⟩ [.int .i8 false, .int .i16 false]
/-- Memory whose allocation 1 is a one-element heap buffer of `bytes`. -/
def heapBufMem (bytes : List AllocByte) : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 1
mutability := .mut
bytes := bytes
live := true
}]
nextAllocId := 2
}
/-- Guard `bytes_heap_buf_elems_decoded`: a heap buffer of a padded struct
whose field `b` is partly uninitialized is not valid. -/
theorem refute_bytes_heap_buf_elems_decoded :
(match heapBufValidInMem
(heapBufMem [.init 1 none, .uninit, .uninit, .init 0 none]) false
paddedElemTy ⟨some 1, 0, .isize⟩ 1 1 with
| .error .undefined => True
| _ => False) :=
trivial
/-- Anti-overreach canary: a heap buffer of a padded struct whose only
uninitialized byte is padding is valid. -/
theorem canary_bytes_heap_buf_padding_uninit :
heapBufValidInMem
(heapBufMem [.init 1 none, .uninit, .init 2 none, .init 0 none]) false
paddedElemTy ⟨some 1, 0, .isize⟩ 1 1 = .ok () :=
rfl
/-! ### Inline `.recSelf` fails closed -/
/-- Guard `bytes_v2_rec_self_decode`: decoding at an inline `.recSelf` faults
with `.unsupported`. -/
theorem refute_bytes_v2_rec_self_decode :
decodeValV2 profileV2TargetEndian (.recSelf 7)
[.init 0 none, .init 0 none, .init 0 none, .init 0 none,
.init 0 none, .init 0 none, .init 0 none, .init 0 none] =
.error .unsupported :=
rfl
/-- Canary: encoding at an inline `.recSelf` faults with `.unsupported`
(`checkValV2` accepts no value at `.recSelf`). -/
theorem positive_bytes_v2_rec_self_encode_faults :
encodeValV2 profileV2TargetEndian (.recSelf 7) .unit =
.error .unsupported :=
rfl
/-! ### Heap validity of self-recursive structs (`recOwnedValidV2`) -/
/-- A padding-free stand-in for `MemoryId`, a `struct Node` with fields
`tag: u64`, `id: u64`, and `parent: Option<Box<Node>>` (layout id `7`, fields
at `[16, 0, 8]`). -/
noncomputable def bRecDefn : MirTy :=
.struct_ ⟨7, 24, 3, [16, 0, 8]⟩
[.int .i64 false, .int .i64 false, .option (.box (.recSelf 7))]
/-- The closed recursive type of `bRecDefn`. -/
noncomputable def bRecTy : MirTy := .recAdt 7 bRecDefn
/-- A `u64` scalar value. -/
noncomputable def bU64 (n : Nat) : Val :=
.scalar ⟨.i64, false, BitVec.ofNat 128 n⟩
/-- A node value whose parent is the buffer `parent`, if any. -/
noncomputable def bRecNode (id : Nat) : Option AllocId → Val
| none => .tuple [bU64 1, bU64 id, .optionVal none]
| some a =>
.tuple [bU64 1, bU64 id,
.optionVal (some (.boxPtr ⟨some a, 0, .isize⟩ none))]
/-- The heap allocation `aid` holding the node `v`. -/
noncomputable def bRecAlloc (aid : AllocId) (v : Val) : Allocation := {
allocId := aid
alignLog2 := 3
mutability := .mut
bytes :=
match encodeValV2 profileV2TargetEndian bRecDefn v with
| .ok bs => bs
| .error _ => []
}
/-- Buffer 1 is a root node; buffer 2's parent is buffer 1. -/
noncomputable def bRecChainMem : MemoryState := {
allocations :=
[bRecAlloc 1 (bRecNode 5 none), bRecAlloc 2 (bRecNode 6 (some 1))]
nextAllocId := 3
}
/-- Buffer 1's parent is buffer 1, a cycle that safe Rust cannot build. -/
noncomputable def bRecLoopMem : MemoryState := {
allocations := [bRecAlloc 1 (bRecNode 5 (some 1))]
nextAllocId := 2
}
/-- Guard `bytes_v2_rec_owned_valid`: owned-data validity hands a recursive
struct to `recOwnedValidV2`, so a reference to a node on a cyclic parent chain
is invalid. -/
theorem refute_bytes_v2_rec_owned_valid :
refValidInMem bRecLoopMem .shared bRecTy (.ptr ⟨some 1, 0, .isize⟩) =
.error .undefined :=
rfl
/-- Guard `bytes_v2_rec_walk_revisit`: entering a buffer twice is
`.undefined` (the walk does not merely run out of fuel). -/
theorem refute_bytes_v2_rec_walk_revisit :
recOwnedValidV2 bRecLoopMem false bRecTy (bRecNode 7 (some 1)) =
.error .undefined :=
rfl
/-- Guard `bytes_v2_rec_walk_fuel`: running out of heap fuel fails closed. -/
theorem refute_bytes_v2_rec_walk_fuel :
recOwnedValidAtV2 bRecChainMem false 1 [] bRecTy (bRecNode 7 (some 2)) =
.error .unsupported :=
rfl
/-- A recursive type whose back edge names `8`, not its binder `7`. -/
noncomputable def bRecUnboundTy : MirTy :=
.recAdt 7 (.struct_ ⟨7, 16, 3, [0, 8]⟩
[.int .i64 false, .option (.box (.recSelf 8))])
/-- Buffer 1 is a valid 16-byte node with no parent. -/
noncomputable def bRecUnboundMem : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 3
mutability := .mut
bytes :=
match encodeValV2 profileV2TargetEndian
(.struct_ ⟨7, 16, 3, [0, 8]⟩
[.int .i64 false, .option (.box (.recSelf 7))])
(.tuple [bU64 5, .optionVal none]) with
| .ok bs => bs
| .error _ => []
}]
nextAllocId := 2
}
/-- Canary: a back edge that does not name the innermost binder is not
resolved, so the walk fails closed. -/
theorem positive_bytes_v2_rec_unbound_back_edge_faults :
recOwnedValidV2 bRecUnboundMem false bRecUnboundTy
(.tuple [bU64 6,
.optionVal (some (.boxPtr ⟨some 1, 0, .isize⟩ none))]) =
.error .unsupported :=
rfl
/-- Guard `bytes_v2_rec_walk_inline_self`: an inline `.recSelf` is never
validated as data. -/
theorem refute_bytes_v2_rec_walk_inline_self :
recOwnedValidV2 emptyMemory false (.recSelf 7) (bU64 0) =
.error .unsupported :=
rfl
/-- Anti-overreach canary: a node with a two-buffer parent chain is valid,
directly, as owned data, and behind a reference; two handles owning one
buffer are not. -/
theorem positive_bytes_v2_rec_chain_valid :
recOwnedValidV2 bRecChainMem false bRecTy (bRecNode 7 (some 2)) = .ok () ∧
ownedValidInMem bRecChainMem false bRecTy (bRecNode 7 (some 2)) = .ok () ∧
refValidInMem bRecChainMem .shared bRecTy (.ptr ⟨some 2, 0, .isize⟩) =
.ok () ∧
recOwnedValidV2 bRecChainMem false
(.struct_ ⟨9, 16, 3, [0, 8]⟩ [.box bRecTy, .box bRecTy])
(.tuple [.boxPtr ⟨some 1, 0, .isize⟩ none,
.boxPtr ⟨some 2, 0, .isize⟩ none]) = .error .undefined :=
⟨rfl, rfl, rfl, rfl⟩
/-- `struct Tree { kids: Vec<Box<Tree>> }` (layout id `11`), whose back edge
sits under two handles. -/
noncomputable def bTreeDefn : MirTy :=
.struct_ ⟨11, 24, 3, [0]⟩ [.vec (.box (.recSelf 11))]
/-- The closed recursive type of `bTreeDefn`. -/
noncomputable def bTreeTy : MirTy := .recAdt 11 bTreeDefn
/-- A tree whose children vector has buffer `p` and length `n`. -/
noncomputable def bTreeNode (p : PtrVal) (n : UInt64) : Val :=
.tuple [.vec p n n]
/-- A tree whose children vector is the one-element buffer 1. -/
noncomputable def bTreeRoot : Val := bTreeNode ⟨some 1, 0, .isize⟩ 1
/-- The heap allocation `aid` holding the value `v` of type `ty`. -/
noncomputable def bTyAlloc (aid : AllocId) (ty : MirTy) (v : Val) :
Allocation := {
allocId := aid
alignLog2 := 3
mutability := .mut
bytes :=
match encodeValV2 profileV2TargetEndian ty v with
| .ok bs => bs
| .error _ => []
}
/-- Buffer 1 is a one-element children vector whose `Box` owns buffer 2, a
leaf. -/
noncomputable def bTreeMem : MemoryState := {
allocations := [
bTyAlloc 1 (.box bTreeTy) (.boxPtr ⟨some 2, 0, .isize⟩ none),
bTyAlloc 2 bTreeDefn (bTreeNode ⟨none, 8, .isize⟩ 0)]
nextAllocId := 3
}
/-- As `bTreeMem`, but buffer 2's children vector is buffer 1 again. -/
noncomputable def bTreeLoopMem : MemoryState := {
allocations := [
bTyAlloc 1 (.box bTreeTy) (.boxPtr ⟨some 2, 0, .isize⟩ none),
bTyAlloc 2 bTreeDefn bTreeRoot]
nextAllocId := 3
}
/-- Guard `bytes_v2_rec_resolve_nested`: a back edge under two handles
resolves to its binder, so the admitted (`recTyWfV2`) tree type has valid
non-empty values; a tree that owns itself is still invalid. -/
theorem refute_bytes_v2_rec_resolve_nested :
recTyWfV2 none bTreeTy = true ∧
recOwnedValidV2 bTreeMem false bTreeTy bTreeRoot = .ok () ∧
refsValidInMem bTreeMem bTreeTy bTreeRoot = true ∧
recOwnedValidV2 bTreeLoopMem false bTreeTy bTreeRoot =
.error .undefined :=
⟨rfl, rfl, rfl, rfl⟩
/-- Buffer 2's parent is buffer 99, which does not exist. -/
noncomputable def bRecDanglingMem : MemoryState := {
allocations := [bRecAlloc 2 (bRecNode 6 (some 99))]
nextAllocId := 3
}
/-- Guard `bytes_v2_rec_refs_valid`: entry, retag, return, and call validity
(`refsValidInMem`) checks the owned data of a by-value recursive struct,
directly and as a struct field, so a cyclic or dangling parent chain is
invalid. -/
theorem refute_bytes_v2_rec_refs_valid :
refsValidInMem bRecLoopMem bRecTy (bRecNode 7 (some 1)) = false ∧
refsValidInMem bRecDanglingMem bRecTy (bRecNode 7 (some 2)) = false ∧
refsValidInMem bRecLoopMem (.struct_ ⟨9, 24, 3, [0]⟩ [bRecTy])
(.tuple [bRecNode 7 (some 1)]) = false :=
⟨rfl, rfl, rfl⟩
/-- Anti-overreach canary: a by-value node with a two-buffer parent chain
passes `refsValidInMem`, directly and as a struct field. -/
theorem positive_bytes_v2_rec_refs_valid_chain :
refsValidInMem bRecChainMem bRecTy (bRecNode 7 (some 2)) = true ∧
refsValidInMem bRecChainMem (.struct_ ⟨9, 24, 3, [0]⟩ [bRecTy])
(.tuple [bRecNode 7 (some 2)]) = true :=
⟨rfl, rfl⟩
/-! ### The `Vec` handle's word order (`encodeVecHandleV2`) -/
/-- A `Vec<u8>` handle with distinct capacity, pointer, and length words. -/
def bVecHandle : Val := .vec ⟨some 3, 5, .isize⟩ 7 6
/-- Guards `bytes_vec_cap_offset`, `bytes_vec_ptr_offset`,
`bytes_vec_len_offset`, and `bytes_vec_encode_order`: a `Vec` handle
decodes to itself, its capacity is the word at offset 0 (`rustc`'s), and
the model's `Option<Vec<T>>` `None` decodes to `None`. -/
theorem refute_bytes_vec_word_order :
decodeValV2 profileV2TargetEndian (.vec (.int .i8 false))
(encodeVecHandleV2 profileV2TargetEndian ⟨some 3, 5, .isize⟩ 7 6) =
.ok (some bVecHandle) ∧
initBytes? ((encodeVecHandleV2 profileV2TargetEndian
⟨some 3, 5, .isize⟩ 7 6).take 8) =
some (encodeUInt profileV2TargetEndian 8 7) ∧
decodeValV2 profileV2TargetEndian (.option (.vec (.int .i8 false)))
(encodeVecNoneV2 profileV2TargetEndian) =
.ok (some (.optionVal none)) :=
⟨rfl, rfl, rfl⟩
/-! ### Zero-capacity / ZST handles, nested alias checks, and nested spans -/
/-- Recursive struct `{ data: Vec<u8>, next: Option<Box<Self>> }` (id `13`). -/
noncomputable def bZeroCapDefn : MirTy :=
.struct_ ⟨13, 32, 3, [0, 24]⟩
[.vec (.int .i8 false), .option (.box (.recSelf 13))]
/-- Closed recursive type of `bZeroCapDefn`. -/
noncomputable def bZeroCapTy : MirTy := .recAdt 13 bZeroCapDefn
/-- Allocation 1 holds a leaf `bZeroCapDefn` whose zero-capacity `Vec<u8>`
points into allocation 1 itself (`cap = 0, len = 0`). -/
noncomputable def bZeroCapSharedMem : MemoryState := {
allocations := [
bTyAlloc 1 bZeroCapDefn
(.tuple [.vec ⟨some 1, 0, .isize⟩ 0 0, .optionVal none])
]
nextAllocId := 2
}
/-- Guard `bytes_v2_rec_enter_owns_bytes`: two zero-capacity `Vec<u8>` handles
inside a recursive value may share provenance with a live allocation because
neither handle owns bytes (`cap * size = 0`). -/
theorem refute_bytes_v2_rec_enter_owns_bytes :
ownedValidInMem bZeroCapSharedMem false bZeroCapTy
(.tuple [.vec ⟨some 1, 0, .isize⟩ 0 0,
.optionVal (some (.boxPtr ⟨some 1, 0, .isize⟩ none))]) = .ok () :=
rfl
/-- Memory in which allocation 1 holds two `Vec<u8>` handles that both claim
ownership of non-empty allocation 2 (`cap = 1, len = 1`). -/
noncomputable def bDupInnerVecMem : MemoryState := {
allocations := [
{ allocId := 1
alignLog2 := 3
mutability := .mut
bytes :=
encodeVecHandleV2 profileV2TargetEndian ⟨some 2, 0, .isize⟩ 1 1 ++
encodeVecHandleV2 profileV2TargetEndian ⟨some 2, 0, .isize⟩ 1 1
live := true },
{ allocId := 2
alignLog2 := 0
mutability := .mut
bytes := [.init 9 none]
live := true }
]
nextAllocId := 3
}
/-- Guard `bytes_v2_owned_nested_alias`: `ownedValidInMem` delegates all owned
types to `recOwnedValidV2`, rejecting a `Vec<Vec<u8>>` whose two inner `Vec<u8>`
elements own the same positive-capacity allocation. -/
theorem refute_bytes_v2_owned_nested_alias :
ownedValidInMem bDupInnerVecMem true (.vec (.vec (.int .i8 false)))
(.vec ⟨some 1, 0, .isize⟩ 2 2) = .error .undefined :=
rfl
/-- Guard `bytes_v2_owned_array_alias`: `recOwnedWalkV2` walks `.array`
elements threading visited allocations, rejecting duplicate buffer ownership and
length mismatches. -/
theorem refute_bytes_v2_owned_array_alias :
ownedValidInMem bDupInnerVecMem true (.array (.vec (.int .i8 false)) 2)
(.array [.vec ⟨some 2, 0, .isize⟩ 1 1,
.vec ⟨some 2, 0, .isize⟩ 1 1]) = .error .undefined ∧
ownedValidInMem bDupInnerVecMem true (.array (.int .i8 false) 2)
(.array [.scalar ⟨.i8, false, 0⟩]) = .error .undefined :=
⟨rfl, rfl⟩
/-- Guard `bytes_v2_slice_owned_alias`: `refValidInMem` threads visited
allocations across slice elements, rejecting `&[Vec<u8>]` whose elements alias
one buffer. -/
theorem refute_bytes_v2_slice_owned_alias :
refValidInMem bDupInnerVecMem .shared (.slice (.vec (.int .i8 false)))
(.slicePtr ⟨some 1, 0, .isize⟩ 2) = .error .undefined :=
rfl
/-- Guard `bytes_v2_rec_handle_spans`: `ownedHandleAccessSpans` unfolds
`.recAdt` so top-level owned buffers of a recursive struct conflict with
aliasing sibling handles. -/
theorem refute_bytes_v2_rec_handle_spans :
spansPairwiseDisjoint
(refAccessSpans (.tuple [bRecTy, .box (.int .i8 false)])
(.tuple [bRecNode 7 (some 1), .boxPtr ⟨some 1, 0, .isize⟩ none])) =
false :=
rfl
/-- Guard `bytes_v2_nested_owned_spans`: `valueAccessSpans` includes strictly
nested heap buffers in `m` (depth >= 2) without duplicating depth-1 outer
handles. -/
theorem refute_bytes_v2_nested_owned_spans :
spansPairwiseDisjoint
(valueAccessSpans bRecChainMem (.tuple [bRecTy, .box bRecTy])
(.tuple [bRecNode 7 (some 2), .boxPtr ⟨some 1, 0, .isize⟩ none])) =
false ∧
spansPairwiseDisjoint
(valueAccessSpans bRecChainMem bRecTy (bRecNode 7 (some 2))) = true :=
⟨rfl, rfl⟩
/-- Guard `bytes_vec_decode_high_bit_cap`: `decodeVecHandleV2` rejects a
`Vec` capacity word `>= 2^63` (violating `RawVecInner.cap : UsizeNoHighBit`),
so `decodeValV2` rejects `cap = 2^63` for both `Vec<()>` and `Option<Vec<()>>`
and `cap = 2^63 + 1` for `Option<Vec<()>>`, while decoding `vecNoneNicheV2`
(`u64::MAX`) as `Option<Vec<()>>::None` and `cap = 2^63 - 1` as `Some`. -/
theorem refute_bytes_vec_decode_high_bit_cap :
decodeValV2 profileV2TargetEndian (.vec .unit)
(encodeVecHandleV2 profileV2TargetEndian ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63)) 0) = .ok none ∧
decodeValV2 profileV2TargetEndian (.option (.vec .unit))
(encodeVecHandleV2 profileV2TargetEndian ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63)) 0) = .ok none ∧
decodeValV2 profileV2TargetEndian (.option (.vec .unit))
(encodeVecHandleV2 profileV2TargetEndian ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63 + 1)) 0) = .ok none ∧
decodeValV2 profileV2TargetEndian (.option (.vec .unit))
(encodeVecNoneV2 profileV2TargetEndian) = .ok (some (.optionVal none)) ∧
decodeValV2 profileV2TargetEndian (.option (.vec .unit))
(encodeVecHandleV2 profileV2TargetEndian ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63 - 1)) 0) =
.ok (some (.optionVal (some (.vec ⟨none, 1, .isize⟩
(UInt64.ofNat (Nat.pow 2 63 - 1)) 0)))) :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `bytes_option_vec_none_niche_u64_max`: `Option<Vec<T>>::None`
encodes and decodes `rustc`'s actual `u64::MAX` (`0xff`×8) niche value
(`vecNoneNicheV2`), matching `ir::VEC_NONE_NICHE`. -/
theorem refute_bytes_option_vec_none_niche_u64_max :
encodeVecNoneV2 profileV2TargetEndian =
List.replicate 8 (.init 0xff none) ++ List.replicate 16 .uninit ∧
decodeValV2 profileV2TargetEndian (.option (.vec (.int .i8 false)))
(List.replicate 8 (.init 0xff none) ++ List.replicate 16 .uninit) =
.ok (some (.optionVal none)) :=
⟨rfl, rfl⟩
/-- Guard `bytes_heap_buf_zst_len_unbounded`: for zero-sized elements
(`lay.size = 0`), `heapBufValidInMem` does not bound `len <= cap`, so valid
`Vec<()>` values with `cap = 0` and `len >= 2^63` (up to `u64::MAX`) remain
admitted by `ValidEntryArgsV2`. -/
theorem refute_bytes_heap_buf_zst_len_unbounded :
heapBufValidInMem MemoryState.empty true .unit
⟨none, 1, .isize⟩ 0 (UInt64.ofNat (Nat.pow 2 63)) = .ok () ∧
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ 0 (UInt64.ofNat (Nat.pow 2 63))) = .ok () ∧
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ 0 (UInt64.ofNat (Nat.pow 2 64 - 1))) =
.ok () :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_v2_owned_zst_vec_cap_high_bit`: `recOwnedWalkV2` enforces
`cap < 2^63` even for zero-sized elements (`Vec<()>`), rejecting `cap = 2^63`
and `cap = 2^63 + 1` while accepting `cap = 0` and `cap = 2^63 - 1`. -/
theorem refute_bytes_v2_owned_zst_vec_cap_high_bit :
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ (UInt64.ofNat (Nat.pow 2 63)) 0) =
.error .undefined ∧
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ (UInt64.ofNat (Nat.pow 2 63 + 1)) 0) =
.error .undefined ∧
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ 0 0) = .ok () ∧
ownedValidInMem MemoryState.empty true (.vec .unit)
(.vec ⟨none, 1, .isize⟩ (UInt64.ofNat (Nat.pow 2 63 - 1)) 0) =
.ok () :=
⟨rfl, rfl, rfl, rfl⟩
/-! ### `Option` of plain data as a field -/
/-! ### Payload enums (`MirTy.adtEnum`) -/
/-- A `u16` value. -/
noncomputable def aU16 (n : Nat) : Val := .scalar ⟨.i16, false, BitVec.ofNat 128 n⟩
/-- A `u32` value. -/
noncomputable def aU32 (n : Nat) : Val := .scalar ⟨.i32, false, BitVec.ofNat 128 n⟩
/-- `enum E { A(u32), B(u16), C(u32) }` with `rustc`'s layout: a direct `u16`
tag at offset 0 holding the discriminant. -/
noncomputable def aETy : MirTy :=
.adtEnum ⟨1, 8, 2, .isize, true, [0, 1, 2], 0, .i16, false, 0, 2, .direct⟩
[.struct_ ⟨11, 8, 2, [4]⟩ [.int .i32 false],
.struct_ ⟨12, 8, 2, [2]⟩ [.int .i16 false],
.struct_ ⟨13, 8, 2, [4]⟩ [.int .i32 false]]
/-- `Result<u32, E>` with `rustc`'s layout: `Err` is untagged, and `Ok` is the
niche value `0xffff` of `E`'s tag, whose valid range becomes `0xffff..=2`. -/
noncomputable def aRTy : MirTy :=
.adtEnum ⟨2, 8, 2, .isize, true, [0, 1], 0, .i16, false, 65535, 2,
.niche 1 0 0 65535⟩
[.struct_ ⟨21, 8, 2, [4]⟩ [.int .i32 false],
.struct_ ⟨22, 8, 2, [0]⟩ [aETy]]
/-- A niche enum whose untagged variant holds a plain `u16` at the tag, with
niche `{5}` and valid range `0..=5`. No `rustc` layout puts a niche in a
plain integer; it tests the encoder's own check. -/
noncomputable def aNTy : MirTy :=
.adtEnum ⟨3, 2, 1, .isize, true, [0, 1], 0, .i16, false, 0, 5,
.niche 1 0 0 5⟩
[.struct_ ⟨31, 2, 1, []⟩ [], .struct_ ⟨32, 2, 1, [0]⟩ [.int .i16 false]]
/-- Guard `bytes_adt_untagged_check`: the untagged variant writes no tag, so
its payload bytes at the tag must decode to it: a payload in the niche
(`5`) or outside the valid range (`9`) is refused, and `3` is accepted. -/
theorem refute_bytes_adt_untagged_check :
encodeValV2 profileV2TargetEndian aNTy (.adtVal 1 (.tuple [aU16 5])) =
.error .unsupported ∧
encodeValV2 profileV2TargetEndian aNTy (.adtVal 1 (.tuple [aU16 9])) =
.error .unsupported ∧
encodeValV2 profileV2TargetEndian aNTy (.adtVal 1 (.tuple [aU16 3])) =
.ok [.init 3 none, .init 0 none] :=
⟨rfl, rfl, rfl⟩
/-- `Ok(7)` and `Err(E::A(5))` of `Result<u32, E>`, as `rustc` lays them out. -/
theorem bytes_adt_result_encodings :
encodeValV2 profileV2TargetEndian aRTy (.adtVal 0 (.tuple [aU32 7])) =
.ok [.init 255 none, .init 255 none, .uninit, .uninit,
.init 7 none, .init 0 none, .init 0 none, .init 0 none] ∧
encodeValV2 profileV2TargetEndian aRTy
(.adtVal 1 (.tuple [.adtVal 0 (.tuple [aU32 5])])) =
.ok [.init 0 none, .init 0 none, .uninit, .uninit,
.init 5 none, .init 0 none, .init 0 none, .init 0 none] :=
⟨rfl, rfl⟩
/-- A direct-tag enum `enum { A = 0, B = 2 }` with a `u8` tag whose valid
range `0..=2` contains the value `1` of no variant. -/
noncomputable def aE2Ty : MirTy :=
.adtEnum ⟨9, 1, 0, .isize, true, [0, 2], 0, .i8, false, 0, 2, .direct⟩
[.struct_ ⟨91, 1, 0, []⟩ [], .struct_ ⟨92, 1, 0, []⟩ []]
/-- Guard `bytes_adt_direct_unknown_tag`: a direct tag that is no variant's
discriminant is invalid, both outside the valid range (`3`) and inside it
(`1`). -/
theorem refute_bytes_adt_direct_unknown_tag :
decodeValV2 profileV2TargetEndian aETy
[.init 3 none, .init 0 none, .uninit, .uninit,
.init 5 none, .init 0 none, .init 0 none, .init 0 none] =
.ok none ∧
decodeValV2 profileV2TargetEndian aE2Ty [.init 1 none] = .ok none ∧
decodeValV2 profileV2TargetEndian aE2Ty [.init 2 none] =
.ok (some (.adtVal 1 (.tuple []))) ∧
decodeValV2 profileV2TargetEndian aETy
[.init 2 none, .init 0 none, .uninit, .uninit,
.init 5 none, .init 0 none, .init 0 none, .init 0 none] =
.ok (some (.adtVal 2 (.tuple [aU32 5]))) :=
⟨rfl, rfl, rfl, rfl⟩
/-- Guard `bytes_adt_niche_valid_range`: a niche-enum tag outside the niche
and outside the tag's valid range (`3`) is invalid, while `0xffff` (the
niche) is `Ok` and `0` (in range) is the untagged `Err`. -/
theorem refute_bytes_adt_niche_valid_range :
decodeValV2 profileV2TargetEndian aRTy
[.init 3 none, .init 0 none, .uninit, .uninit,
.init 5 none, .init 0 none, .init 0 none, .init 0 none] =
.ok none ∧
decodeValV2 profileV2TargetEndian aNTy [.init 9 none, .init 0 none] =
.ok none ∧
decodeValV2 profileV2TargetEndian aRTy
[.init 255 none, .init 255 none, .uninit, .uninit,
.init 7 none, .init 0 none, .init 0 none, .init 0 none] =
.ok (some (.adtVal 0 (.tuple [aU32 7]))) ∧
decodeValV2 profileV2TargetEndian aRTy
[.init 0 none, .init 0 none, .uninit, .uninit,
.init 5 none, .init 0 none, .init 0 none, .init 0 none] =
.ok (some (.adtVal 1 (.tuple [.adtVal 0 (.tuple [aU32 5])]))) :=
⟨rfl, rfl, rfl, rfl⟩
/-- A three-variant niche enum whose niche range `0..=2` contains its untagged
variant `1`, with a `u8` tag at offset 0, niche start `10`, and valid range
`10..=12`. -/
noncomputable def aN3Ty : MirTy :=
.adtEnum ⟨4, 1, 0, .isize, true, [0, 1, 2], 0, .i8, false, 10, 12,
.niche 1 0 2 10⟩
[.struct_ ⟨41, 1, 0, []⟩ [], .struct_ ⟨42, 1, 0, []⟩ [],
.struct_ ⟨43, 1, 0, []⟩ []]
/-- Guard `bytes_adt_niche_untagged_index`: the niche value of the untagged
variant (`11`) is not a valid encoding, while `12` is variant 2. -/
theorem refute_bytes_adt_niche_untagged_index :
decodeValV2 profileV2TargetEndian aN3Ty [.init 11 none] = .ok none ∧
decodeValV2 profileV2TargetEndian aN3Ty [.init 12 none] =
.ok (some (.adtVal 2 (.tuple []))) :=
⟨rfl, rfl⟩
/-- A niche enum whose niche values wrap: untagged variant 0 holds a `u16` at
the tag (valid range `0..=0xfffe` plus the niche), niche variants `1..=2`,
niche start `0xffff`, so variant 2's tag is `0`. Again no `rustc` layout
puts a niche in a plain integer. -/
noncomputable def aWTy : MirTy :=
.adtEnum ⟨5, 2, 1, .isize, true, [0, 1, 2], 0, .i16, false, 65535, 1,
.niche 0 1 2 65535⟩
[.struct_ ⟨51, 2, 1, [0]⟩ [.int .i16 false], .struct_ ⟨52, 2, 1, []⟩ [],
.struct_ ⟨53, 2, 1, []⟩ []]
/-- Guard `bytes_adt_niche_rel_wrap`: the niche-relative index wraps at
`2^16`, so tag `0` decodes as variant 2 and variant 2 encodes to tag `0`. -/
theorem refute_bytes_adt_niche_rel_wrap :
decodeValV2 profileV2TargetEndian aWTy [.init 0 none, .init 0 none] =
.ok (some (.adtVal 2 (.tuple []))) ∧
encodeValV2 profileV2TargetEndian aWTy (.adtVal 2 (.tuple [])) =
.ok [.init 0 none, .init 0 none] ∧
encodeValV2 profileV2TargetEndian aWTy (.adtVal 1 (.tuple [])) =
.ok [.init 255 none, .init 255 none] :=
⟨rfl, rfl, rfl⟩
/-- `Result<Box<u8>, ()>`-shaped: `Ok` is untagged with a `Box` at offset 0,
and `Err` is the null niche of the pointer (a pointer niche `{0}`). -/
noncomputable def aPTy : MirTy :=
.adtEnum ⟨6, 8, 3, .isize, true, [0, 1], 0, .isize, false, 0,
18446744073709551615, .niche 0 1 1 0⟩
[.struct_ ⟨61, 8, 3, [0]⟩ [.box (.int .i8 false)],
.struct_ ⟨62, 8, 3, []⟩ []]
/-- Eight bytes of a pointer with provenance `aid` at offset 0. -/
noncomputable def aPtrBytes (aid : AllocId) : List AllocByte :=
List.replicate 8 (.init 0 (some aid))
/-- Guard `bytes_adt_tag_provenance`: a tag with provenance is the untagged
variant only for a pointer niche `{0}` (a `Box` at offset 0 is not null);
for any other niche, or with provenance on only some bytes, it is
`.unsupported`. -/
theorem refute_bytes_adt_tag_provenance :
adtDecodeVariantV2 profileV2TargetEndian
⟨6, 8, 3, .isize, true, [0, 1], 0, .isize, false, 0,
18446744073709551615, .niche 0 1 1 0⟩ (aPtrBytes 7) = .ok (some 0) ∧
adtDecodeVariantV2 profileV2TargetEndian
⟨6, 8, 3, .isize, true, [0, 1], 0, .isize, false, 0,
18446744073709551615, .niche 0 1 1 5⟩ (aPtrBytes 7) =
.error .unsupported ∧
adtDecodeVariantV2 profileV2TargetEndian
⟨6, 8, 3, .isize, true, [0, 1], 0, .isize, false, 0,
18446744073709551615, .niche 0 1 1 0⟩
(.init 0 none :: List.replicate 7 (.init 0 (some 7))) =
.error .unsupported :=
⟨rfl, rfl, rfl⟩
/-- Guard `enum_adt_check_val`: an `.adtVal` checks against its variant's
payload struct, and an out-of-range variant does not check. -/
theorem refute_enum_adt_check_val :
checkValV2 (.adtVal 3 (.tuple [aU32 1])) aETy = false ∧
checkValV2 (.adtVal 1 (.tuple [aU32 1])) aETy = false ∧
checkValV2 (.adtVal 1 (.tuple [aU16 1])) aETy = true :=
⟨rfl, rfl, rfl⟩
/-- A one-variant payload enum holding a `Vec<u8>`. -/
noncomputable def aVTy : MirTy :=
.adtEnum ⟨7, 24, 3, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨71, 24, 3, [0]⟩ [.vec (.int .i8 false)]]
/-- Guards `state_adt_has_ref` and `alloc_adt_needs_drop`: a payload enum
holding a `Vec` counts as holding a reference (no raw pointers may share its
body) and has drop glue, and one holding a raw pointer counts as holding one
(guard `mem_v2_adt_raw_ptr_ty`, refuted in `MemoryRefutations`). -/
theorem refute_state_adt_ref_and_drop :
tyHasRefV2 aVTy = true ∧
tyHasRawPtrV2 (.adtEnum ⟨8, 8, 3, .isize, true, [0], 0, .i8, false, 0, 0,
.single⟩ [.struct_ ⟨81, 8, 3, [0]⟩ [.rawPtr .shared (.int .i8 false)]]) =
true ∧
tyNeedsDropV2 aVTy = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `enum_adt_owned_data`: a payload enum is owned data only when every
variant is, so one holding a reference is not. -/
theorem refute_enum_adt_owned_data :
isOwnedDataTyV2 (.adtEnum ⟨8, 8, 3, .isize, true, [0], 0, .i8, false, 0, 0,
.single⟩ [.struct_ ⟨81, 8, 3, [0]⟩ [.ref .shared (.int .i8 false)]]) =
false ∧
isOwnedDataTyV2 aVTy = true :=
⟨rfl, rfl⟩
/-- Guard `enum_adt_inhabited`: a payload enum is inhabited only when some
variant is, so one whose only variant holds a `!` is not. -/
theorem refute_enum_adt_inhabited :
isInhabitedV2Ty (.adtEnum ⟨8, 8, 3, .isize, true, [0], 0, .i8, false, 0, 0,
.single⟩ [.struct_ ⟨81, 8, 3, [0]⟩ [.never]]) = false ∧
isInhabitedV2Ty aVTy = true :=
⟨rfl, rfl⟩
/-- Guards `bytes_adt_owned_valid` and `bytes_adt_refs_valid`: a payload enum
is valid only if its active variant is, so one holding a `Vec` whose buffer
does not exist is not. -/
theorem refute_bytes_adt_owned_valid :
ownedValidInMem MemoryState.empty true aVTy
(.adtVal 0 (.tuple [.vec ⟨some 9, 0, .isize⟩ 1 1])) = .error .undefined ∧
refsValidInMem MemoryState.empty aVTy
(.adtVal 0 (.tuple [.vec ⟨some 9, 0, .isize⟩ 1 1])) = false ∧
ownedValidInMem bDupInnerVecMem true (.tuple [aVTy, aVTy])
(.tuple [.adtVal 0 (.tuple [.vec ⟨some 2, 0, .isize⟩ 1 1]),
.adtVal 0 (.tuple [.vec ⟨some 2, 0, .isize⟩ 1 1])]) =
.error .undefined :=
⟨rfl, rfl, rfl⟩
/-- Canary (exercised alongside `bytes_ref_access_spans_ref_enum`):
`refAccessSpans` walks a payload enum's active variant so its top-level owned
buffers conflict with aliasing sibling handles. -/
theorem refute_bytes_adt_handle_spans :
spansPairwiseDisjoint
(refAccessSpans (.tuple [aVTy, .box (.int .i8 false)])
(.tuple [.adtVal 0 (.tuple [.vec ⟨some 2, 0, .isize⟩ 1 1]),
.boxPtr ⟨some 2, 0, .isize⟩ none])) = false :=
rfl
/-- A one-variant payload enum holding a nested `Vec<Vec<u8>>`. -/
noncomputable def aNestedVecTy : MirTy :=
.adtEnum ⟨9, 24, 3, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨91, 24, 3, [0]⟩ [.vec (.vec (.int .i8 false))]]
/-- Allocation 1 holds one `Vec<u8>` handle pointing to allocation 2. -/
noncomputable def aNestedVecMem : MemoryState := {
allocations := [
{ allocId := 1
alignLog2 := 3
mutability := .mut
bytes :=
encodeVecHandleV2 profileV2TargetEndian ⟨some 2, 0, .isize⟩ 1 1
live := true },
{ allocId := 2
alignLog2 := 0
mutability := .mut
bytes := [.init 9 none]
live := true }
]
nextAllocId := 3
}
/-- Value of `aNestedVecTy` owning outer allocation 1 and inner allocation 2. -/
noncomputable def aNestedVecVal : Val :=
.adtVal 0 (.tuple [.vec ⟨some 1, 0, .isize⟩ 1 1])
/-- Guard `bytes_adt_nested_owned_spans`: `nestedOwnedWalkSpansV2` walks a
payload enum's active variant so depth-2 heap buffers conflict with aliasing
sibling handles without duplicating outer depth-1 handles. -/
theorem refute_bytes_adt_nested_owned_spans :
spansPairwiseDisjoint
(valueAccessSpans aNestedVecMem
(.tuple [aNestedVecTy, .box (.int .i8 false)])
(.tuple [aNestedVecVal, .boxPtr ⟨some 2, 0, .isize⟩ none])) = false ∧
spansPairwiseDisjoint
(valueAccessSpans aNestedVecMem aNestedVecTy aNestedVecVal) = true :=
⟨rfl, rfl⟩
/-- Recursive payload enum `enum R { Leaf(u8), Node(Box<Self>) }` (id `14`). -/
noncomputable def aRecEnumDefn : MirTy :=
.adtEnum ⟨14, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨141, 16, 3, [8]⟩ [.int .i8 false],
.struct_ ⟨142, 16, 3, [8]⟩ [.box (.recSelf 14)]]
/-- Closed recursive type of `aRecEnumDefn`. -/
noncomputable def aRecEnumTy : MirTy := .recAdt 14 aRecEnumDefn
/-- Value of `aRecEnumTy` holding `Node(Box(aid))` or `Leaf(n)`. -/
noncomputable def aRecEnumNode (next : Option AllocId) : Val :=
match next with
| none => .adtVal 0 (.tuple [.scalar ⟨.i8, false, 5⟩])
| some aid => .adtVal 1 (.tuple [.boxPtr ⟨some aid, 0, .isize⟩ none])
/-- Two-node recursive payload enum chain: alloc 2 holds `Node(Box(1))` and
alloc 1 holds `Leaf(5)`. -/
noncomputable def aRecEnumChainMem : MemoryState := {
allocations := [
bTyAlloc 1 aRecEnumDefn (aRecEnumNode none),
bTyAlloc 2 aRecEnumDefn (aRecEnumNode (some 1))
]
nextAllocId := 3
}
/-- Guard `bytes_adt_rec_handle_spans`: `ownedHandleWalkAccessSpans` and
`nestedOwnedWalkSpansV2` walk `.recAdt _ (.adtEnum _ _)` so both top-level
`Box<Self>` buffers and depth-2 nested buffers conflict with aliasing sibling
handles without duplicating depth-1 spans. -/
theorem refute_bytes_adt_rec_handle_spans :
spansPairwiseDisjoint
(refAccessSpans (.tuple [aRecEnumTy, .box (.int .i8 false)])
(.tuple [aRecEnumNode (some 2),
.boxPtr ⟨some 2, 0, .isize⟩ none])) = false ∧
spansPairwiseDisjoint
(valueAccessSpans aRecEnumChainMem
(.tuple [aRecEnumTy, .box (.int .i8 false)])
(.tuple [aRecEnumNode (some 2),
.boxPtr ⟨some 1, 0, .isize⟩ none])) = false ∧
spansPairwiseDisjoint
(valueAccessSpans aRecEnumChainMem aRecEnumTy
(aRecEnumNode (some 2))) = true :=
⟨rfl, rfl, rfl⟩
/-! ### Tuples lowered to structs (`(MemoryId, u64)`) -/
/-- `MemoryId` with `rustc`'s layout (24 bytes, align 8): `namespace` (a
one-byte stand-in) at 16, `id` at 0, `parent` at 8, and 7 bytes of padding. -/
noncomputable def tMemIdDefn : MirTy :=
.struct_ ⟨7, 24, 3, [16, 0, 8]⟩
[.int .i8 false, .int .i64 false, .option (.box (.recSelf 7))]
/-- The closed recursive type of `tMemIdDefn`. -/
noncomputable def tMemIdTy : MirTy := .recAdt 7 tMemIdDefn
/-- The tuple `(MemoryId, u64)` as capture lowers it: `rustc`'s 32-byte
layout with the `MemoryId` at 0 and the `u64` at 24 (measured with
`offset_of!` on `rustc` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`). -/
noncomputable def tPairTy : MirTy :=
.struct_ ⟨99, 32, 3, [0, 24]⟩ [tMemIdTy, .int .i64 false]
/-- The value `(MemoryId { namespace: 1, id, parent }, n)`. -/
noncomputable def tPairVal (id n : Nat) (parent : Option AllocId) : Val :=
.tuple [.tuple [.scalar ⟨.i8, false, 1⟩, bU64 id,
.optionVal (parent.map fun a => .boxPtr ⟨some a, 0, .isize⟩ none)],
bU64 n]
/-- The little-endian bytes of `n` in `k` bytes, without provenance. -/
noncomputable def tLe : Nat → Nat → List AllocByte
| 0, _ => []
| k + 1, n => .init (UInt8.ofNat (n % 256)) none :: tLe k (n / 256)
/-- Canary: encoding `(MemoryId { 1, 5, Some(Box@3) }, 9)` puts every byte
where `rustc` does: `id` at 0..8, the `parent` pointer (with provenance) at
8..16, `namespace` at 16, uninitialized padding at 17..24, and the `u64` at
24..32; decoding gives the value back. -/
theorem positive_bytes_tuple_struct_bytes :
encodeValV2 profileV2TargetEndian tPairTy (tPairVal 5 9 (some 3)) =
.ok (tLe 8 5 ++ (List.replicate 8 (.init 0 (some 3))) ++
[.init 1 none] ++ List.replicate 7 .uninit ++ tLe 8 9) ∧
decodeValV2 profileV2TargetEndian tPairTy
(tLe 8 5 ++ (List.replicate 8 (.init 0 (some 3))) ++
[.init 1 none] ++ List.replicate 7 .uninit ++ tLe 8 9) =
.ok (some (tPairVal 5 9 (some 3))) :=
⟨rfl, rfl⟩
/-! ### Arrays of owned data -/
/-- The `u8` type. -/
noncomputable def aU8 : MirTy := .int .i8 false
/-- A `Box<u8>` handle owning allocation `aid`. -/
noncomputable def aBox (aid : AllocId) : Val := .boxPtr ⟨some aid, 0, .isize⟩ none
/-- Allocations 1 and 2 each hold a `u8` owned by a `Box`. -/
noncomputable def aBoxMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 7 none] },
{ allocId := 2, alignLog2 := 0, mutability := .mut,
bytes := [.init 8 none] }]
nextAllocId := 3
}
/-- Guard `bytes_array_owned_each_elem`: an array that owns heap buffers is
valid only if every element is, so a dangling second `Box` is invalid. -/
theorem refute_bytes_array_owned_each_elem :
ownedValidInMem aBoxMem false (.array (.box aU8) 2)
(.array [aBox 1, aBox 99]) = .error .undefined :=
rfl
/-- Guard `bytes_array_owned_len`: the array value must have `n` elements. -/
theorem refute_bytes_array_owned_len :
ownedValidInMem aBoxMem false (.array (.box aU8) 2) (.array [aBox 1]) =
.error .undefined :=
rfl
/-- Guard `bytes_refs_valid_array`: entry, retag, return, and call validity
(`refsValidInMem`) checks an array of owned data element by element. -/
theorem refute_bytes_refs_valid_array :
refsValidInMem aBoxMem (.array (.box aU8) 2) (.array [aBox 1, aBox 99]) =
false ∧
refsValidInMem aBoxMem (.array (.box aU8) 2) (.array [aBox 1]) = false :=
⟨rfl, rfl⟩
/-- Guard `bytes_rec_walk_array_each_elem`: the recursive walk checks every
element of an array of recursive structs, so a dangling parent in the second
element is invalid. -/
theorem refute_bytes_rec_walk_array_each_elem :
recOwnedValidV2 bRecChainMem false (.array bRecTy 2)
(.array [bRecNode 7 (some 2), bRecNode 8 (some 99)]) =
.error .undefined :=
rfl
/-- Guard `bytes_array_owned_shape`: a non-array value at an array type that
owns heap buffers is invalid, in `ownedValidInMem` and so in
`refsValidInMem`. -/
theorem refute_bytes_array_owned_shape :
ownedValidInMem aBoxMem false (.array (.box aU8) 2) .unit =
.error .undefined ∧
refsValidInMem aBoxMem (.array (.box aU8) 2) .unit = false :=
⟨rfl, rfl⟩
/-- Guard `bytes_rec_walk_array_shape`: the recursive walk rejects a
non-array value at an array of recursive structs. -/
theorem refute_bytes_rec_walk_array_shape :
recOwnedValidV2 bRecChainMem false (.array bRecTy 2) .unit =
.error .undefined :=
rfl
/-- Anti-overreach canary: arrays of owned data are owned data and local
types; two valid `Box`es, an empty array, and an array of recursive structs
with disjoint chains are valid; and two elements owning one buffer are not. -/
theorem positive_bytes_array_owned_valid :
isOwnedDataTyV2 (.array (.box aU8) 2) = true ∧
isSupportedV2LocalTy (.array bRecTy 10) = true ∧
ownedValidInMem aBoxMem false (.array (.box aU8) 2)
(.array [aBox 1, aBox 2]) = .ok () ∧
ownedValidInMem aBoxMem false (.array (.box aU8) 0) (.array []) = .ok () ∧
recOwnedValidV2 bRecChainMem false (.array bRecTy 2)
(.array [bRecNode 7 (some 2), bRecNode 8 none]) = .ok () ∧
recOwnedValidV2 bRecChainMem false (.array bRecTy 2)
(.array [bRecNode 7 (some 2), bRecNode 8 (some 1)]) =
.error .undefined :=
⟨rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- `Result<&bool, u8>`-shaped: `Ok` holds a `&bool` at offset 8, and `Err`
a `u8` at offset 1, behind a direct `u8` tag at offset 0. -/
noncomputable def rRefTy : MirTy :=
.adtEnum ⟨7, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨71, 16, 3, [8]⟩ [.ref .shared .bool],
.struct_ ⟨72, 16, 3, [1]⟩ [.int .i8 false]]
/-- Allocation 1 holds a live `bool` and allocation 4 a read-only `.rodata`
`bool`; allocation 9 does not exist. -/
noncomputable def rRefMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 1 none], live := true },
{ allocId := 4, alignLog2 := 0, mutability := .shared,
bytes := [.init 1 none], live := true }]
nextAllocId := 5
}
/-- The caller's memory: allocation 1 only. -/
noncomputable def rRefCaller : CallerMemory := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 1 none], live := true }]
}
/-- `Ok(r)` of `rRefTy` with `r` pointing into allocation `aid`. -/
noncomputable def rOk (aid : AllocId) : Val :=
.adtVal 0 (.tuple [.ptr ⟨some aid, 0, .isize⟩])
/-- Guard `bytes_refs_valid_ref_enum`: a payload enum's reference fields are
validated through the active variant, so a dangling `Ok` reference is
invalid, while a valid one and an `Err` are valid. -/
theorem refute_bytes_refs_valid_ref_enum :
refsValidInMem rRefMem rRefTy (rOk 9) = false ∧
refsValidInMem rRefMem rRefTy (rOk 1) = true ∧
refsValidInMem rRefMem rRefTy
(.adtVal 1 (.tuple [.scalar ⟨.i8, false, BitVec.ofNat 128 3⟩])) = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_refs_valid_ref_enum_shape`: a payload that is not a tuple of
the variant's fields is invalid. -/
theorem refute_bytes_refs_valid_ref_enum_shape :
refsValidInMem rRefMem rRefTy (.adtVal 0 .unit) = false :=
rfl
/-- Guard `bytes_ref_alloc_ids_ref_enum`: returning `Ok(&local)` of a callee
local (allocation 4 is not caller memory) is caught by
`refsStayInCallerMem`, which sees the reference through the enum. -/
theorem refute_bytes_ref_alloc_ids_ref_enum :
refAllocIds rRefTy (rOk 4) = [4] ∧
refsStayInCallerMem rRefCaller rRefTy (rOk 4) = false ∧
refsStayInCallerMem rRefCaller rRefTy (rOk 1) = true :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_ptr_or_ref_alloc_ids_ref_enum`: an `Ok` reference into a
callee `.rodata` allocation escapes (`hasEscapingRodataPtr`). -/
theorem refute_bytes_ptr_or_ref_alloc_ids_ref_enum :
hasEscapingRodataPtr rRefCaller rRefMem rRefTy (rOk 4) = true ∧
hasEscapingRodataPtr rRefCaller rRefMem rRefTy (rOk 1) = false :=
⟨rfl, rfl⟩
/-- Guard `bytes_ref_access_spans_ref_enum`: an `Ok` reference contributes its
access span for the entry aliasing check. -/
theorem refute_bytes_ref_access_spans_ref_enum :
refAccessSpans rRefTy (rOk 1) = [(false, 1, 0, 1)] :=
rfl
/-- Guard `enum_v2_ref_enum_fields`: a payload enum with reference fields is
a local only when every field is a shared reference or heap-free owned data,
so `Result<&mut bool, u8>` and `Result<&bool, Box<u8>>` are not. -/
theorem refute_enum_v2_ref_enum_fields :
isSupportedV2LocalTy
(.adtEnum ⟨7, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨71, 16, 3, [8]⟩ [.ref .mut .bool],
.struct_ ⟨72, 16, 3, [1]⟩ [.int .i8 false]]) = false ∧
isSupportedV2LocalTy
(.adtEnum ⟨7, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨71, 16, 3, [8]⟩ [.ref .shared .bool],
.struct_ ⟨72, 16, 3, [8]⟩ [.box (.int .i8 false)]]) = false :=
⟨rfl, rfl⟩
/-- Anti-overreach canary: `Result<&bool, u8>` is a local but not owned
data, so it may not be a `Vec` element, a pointee, or an `Option` payload. -/
theorem positive_enum_v2_ref_enum_local_only :
isSupportedV2LocalTy rRefTy = true ∧
isOwnedDataTyV2 rRefTy = false ∧
isSupportedV2LocalTy (.vec rRefTy) = false ∧
isSupportedV2LocalTy (.ref .shared rRefTy) = false ∧
isSupportedV2LocalTy (.option rRefTy) = false :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-- `enum E { A, B(u8) }`: a direct `u8` tag at offset 0 and `B`'s `u8` at
offset 1. -/
noncomputable def tryETy : MirTy :=
.adtEnum ⟨11, 2, 0, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨111, 2, 0, []⟩ [], .struct_ ⟨112, 2, 0, [1]⟩ [.int .i8 false]]
/-- `Result<Infallible, E>`: `rustc`'s `Variants::Single { index: 1 }`, so
the layout is `E`'s and only `Err` exists. -/
noncomputable def tryResTy : MirTy :=
.adtEnum ⟨12, 2, 0, .isize, true, [0, 1], 0, .i8, false, 1, 1, .single⟩
[.struct_ ⟨121, 2, 0, [0]⟩ [.never], .struct_ ⟨122, 2, 0, [0]⟩ [tryETy]]
/-- `Option<Infallible>`: `Variants::Single { index: 0 }`, zero-sized. -/
noncomputable def tryOptTy : MirTy :=
.adtEnum ⟨13, 0, 0, .isize, true, [0, 1], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨131, 0, 0, []⟩ [], .struct_ ⟨132, 0, 0, [0]⟩ [.never]]
/-- `ControlFlow<Result<Infallible, E>, u8>`: `Continue` (0) is tagged with
niche value 2 in `E`'s tag byte, and `Break` (1) is untagged. -/
noncomputable def tryCfTy : MirTy :=
.adtEnum ⟨14, 2, 0, .isize, true, [0, 1], 0, .i8, false, 0, 2,
.niche 1 0 0 2⟩
[.struct_ ⟨141, 2, 0, [1]⟩ [.int .i8 false],
.struct_ ⟨142, 2, 0, [0]⟩ [tryResTy]]
/-- `E::B(n)`. -/
noncomputable def tryEB (n : Nat) : Val :=
.adtVal 1 (.tuple [.scalar ⟨.i8, false, BitVec.ofNat 128 n⟩])
/-- Anti-overreach canary, matching `rustc`'s bytes (`transmute` on
x86_64): `Err(E::B(9)) : Result<Infallible, E>` is `[1, 9]`,
`None : Option<Infallible>` is no bytes, and
`ControlFlow::Break(Err(E::B(7)))` and `ControlFlow::Continue(3)` are
`[1, 7]` and `[2, 3]`; the residuals have layouts and decode to their
inhabited variants. -/
theorem positive_bytes_try_residual_layouts :
layoutOfTyV2 tryResTy = some ⟨2, 0⟩ ∧
layoutOfTyV2 tryOptTy = some ⟨0, 0⟩ ∧
layoutOfTyV2 tryCfTy = some ⟨2, 0⟩ ∧
encodeValV2 profileV2TargetEndian tryResTy
(.adtVal 1 (.tuple [tryEB 9])) = .ok [.init 1 none, .init 9 none] ∧
encodeValV2 profileV2TargetEndian tryOptTy (.adtVal 0 (.tuple [])) =
.ok [] ∧
encodeValV2 profileV2TargetEndian tryCfTy
(.adtVal 1 (.tuple [.adtVal 1 (.tuple [tryEB 7])])) =
.ok [.init 1 none, .init 7 none] ∧
encodeValV2 profileV2TargetEndian tryCfTy
(.adtVal 0 (.tuple [.scalar ⟨.i8, false, BitVec.ofNat 128 3⟩])) =
.ok [.init 2 none, .init 3 none] ∧
decodeValV2 profileV2TargetEndian tryResTy [.init 1 none, .init 9 none] =
.ok (some (.adtVal 1 (.tuple [tryEB 9]))) ∧
decodeValV2 profileV2TargetEndian tryOptTy [] =
.ok (some (.adtVal 0 (.tuple []))) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `bytes_adt_single_index`: an untagged enum holds the variant its
layout names, so `Result<Infallible, E>`'s bytes are an `Err`. -/
theorem refute_bytes_adt_single_index :
adtDecodeVariantV2 profileV2TargetEndian
⟨12, 2, 0, .isize, true, [0, 1], 0, .i8, false, 1, 1, .single⟩
[.init 1 none, .init 9 none] = .ok (some 1) :=
rfl
/-- Guard `bytes_v2_never_no_value`: `!` has no value, so decoding it gives
none, and an `Ok(Infallible)` cannot be checked into existence. -/
theorem refute_bytes_v2_never_no_value :
decodeValV2 profileV2TargetEndian .never [] = .ok none ∧
checkValV2 .unit .never = false :=
⟨rfl, rfl⟩
end GuardMutation