blob: d463c9b95c33509f30f77d8e65c32b8f8fc6ecb7 [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.
//! Differential verdict algebra and canonical C11/C++20 scalar values for
//! `anneal-cpp-diff`.
//!
//! Mirrors the fail-closed classification model of `tests/differential/`:
//! every corpus case evaluates to one of five verdicts:
//! - [`Verdict::DefinedMatch`] (pass),
//! - [`Verdict::StrictUbConfirmed`] (pass),
//! - [`Verdict::ExpectedUnsupported`] (pass),
//! - [`Verdict::DefinedMismatch`] (fail), or
//! - [`Verdict::UnexpectedError`] (fail).
use std::fmt;
use serde::{Deserialize, Serialize};
/// Fixed-width integer bit widths matching `Trusted.CppAst.CppIntWidth`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CppIntWidth {
W8,
W16,
W32,
W64,
W128,
}
impl CppIntWidth {
/// Width in bits.
pub const fn bits(self) -> u32 {
match self {
Self::W8 => 8,
Self::W16 => 16,
Self::W32 => 32,
Self::W64 => 64,
Self::W128 => 128,
}
}
/// Low-bit mask for canonical two's-complement bit storage.
pub const fn mask(self) -> u128 {
match self.bits() {
128 => u128::MAX,
n => (1u128 << n) - 1,
}
}
/// Lean `Trusted.CppAst.CppIntWidth` constructor name.
pub const fn lean_ctor(self) -> &'static str {
match self {
Self::W8 => ".w8",
Self::W16 => ".w16",
Self::W32 => ".w32",
Self::W64 => ".w64",
Self::W128 => ".w128",
}
}
/// Parse a Lean `CppIntWidth` constant name (qualified or bare).
pub fn parse_lean_name(raw: &str) -> Result<Self, String> {
let leaf = raw.rsplit('.').next().unwrap_or(raw).trim();
match leaf {
"w8" => Ok(Self::W8),
"w16" => Ok(Self::W16),
"w32" => Ok(Self::W32),
"w64" => Ok(Self::W64),
"w128" => Ok(Self::W128),
other => Err(format!("unknown Lean CppIntWidth {other:?}")),
}
}
}
/// Integer signedness matching `Trusted.CppAst.Signedness`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CppSign {
Signed,
Unsigned,
}
impl CppSign {
/// Lean `Trusted.CppAst.Signedness` constructor name.
pub const fn lean_ctor(self) -> &'static str {
match self {
Self::Signed => ".signed",
Self::Unsigned => ".unsigned",
}
}
/// Parse a Lean `Signedness` constant name (qualified or bare).
pub fn parse_lean_name(raw: &str) -> Result<Self, String> {
let leaf = raw.rsplit('.').next().unwrap_or(raw).trim();
match leaf {
"signed" => Ok(Self::Signed),
"unsigned" => Ok(Self::Unsigned),
other => Err(format!("unknown Lean Signedness {other:?}")),
}
}
}
/// Serialize and deserialize `u128` as a base-10 string so JSON reports remain
/// exact beyond 53-bit IEEE-754 floats and work inside internally tagged enums.
mod u128_as_string {
use serde::{de, Deserializer, Serializer};
pub fn serialize<S: Serializer>(v: &u128, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&v.to_string())
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u128, D::Error> {
let raw: String = serde::Deserialize::deserialize(d)?;
raw.parse::<u128>().map_err(de::Error::custom)
}
}
/// Canonical scalar return or argument value shared across Lean and compiler
/// legs.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CppScalarValue {
Void,
Bool {
value: bool,
},
Int {
width: CppIntWidth,
sign: CppSign,
/// Unsigned two's-complement bit representation masked to `width`.
#[serde(with = "u128_as_string")]
unsigned_bits: u128,
},
}
impl CppScalarValue {
/// Construct a signed `int32_t` scalar value.
pub const fn i32(v: i32) -> Self {
Self::Int {
width: CppIntWidth::W32,
sign: CppSign::Signed,
unsigned_bits: (v as u32) as u128,
}
}
/// Construct an unsigned `uint32_t` scalar value.
pub const fn u32(v: u32) -> Self {
Self::Int { width: CppIntWidth::W32, sign: CppSign::Unsigned, unsigned_bits: v as u128 }
}
/// Construct a signed `int64_t` scalar value.
pub const fn i64(v: i64) -> Self {
Self::Int {
width: CppIntWidth::W64,
sign: CppSign::Signed,
unsigned_bits: (v as u64) as u128,
}
}
/// Construct an unsigned `uint64_t` scalar value.
pub const fn u64(v: u64) -> Self {
Self::Int { width: CppIntWidth::W64, sign: CppSign::Unsigned, unsigned_bits: v as u128 }
}
/// Construct a signed `int8_t` scalar value.
pub const fn i8(v: i8) -> Self {
Self::Int {
width: CppIntWidth::W8,
sign: CppSign::Signed,
unsigned_bits: (v as u8) as u128,
}
}
/// Construct an unsigned `uint8_t` scalar value.
pub const fn u8(v: u8) -> Self {
Self::Int { width: CppIntWidth::W8, sign: CppSign::Unsigned, unsigned_bits: v as u128 }
}
/// Construct an unsigned `uint16_t` scalar value.
pub const fn u16(v: u16) -> Self {
Self::Int { width: CppIntWidth::W16, sign: CppSign::Unsigned, unsigned_bits: v as u128 }
}
/// Construct a `bool` scalar value.
pub const fn bool_val(value: bool) -> Self {
Self::Bool { value }
}
/// Interpret an integer's `unsigned_bits` as a signed `i128`.
pub const fn signed_i128(width: CppIntWidth, unsigned_bits: u128) -> i128 {
let masked = unsigned_bits & width.mask();
let shift = 128 - width.bits();
((masked << shift) as i128) >> shift
}
/// Render this value as a `Trusted.CppSemantics.CppVal` Lean expression.
pub fn to_lean_val(&self) -> String {
match self {
Self::Void => ".void".to_owned(),
Self::Bool { value } => format!(".bool {value}"),
Self::Int { width, sign, unsigned_bits } => {
let masked = unsigned_bits & width.mask();
format!(".int {} {} {}", width.lean_ctor(), sign.lean_ctor(), masked)
}
}
}
/// Render this value as a valid C11/C++20 argument expression.
pub fn to_c_expr(&self) -> Result<String, String> {
match self {
Self::Void => Err("void cannot be passed as a C/C++ argument".to_owned()),
Self::Bool { value } => Ok(if *value { "1" } else { "0" }.to_owned()),
Self::Int { width, sign, unsigned_bits } => {
let masked = unsigned_bits & width.mask();
match (width, sign) {
(CppIntWidth::W8, CppSign::Signed) => {
Ok(format!("((int8_t)({}))", Self::signed_i128(*width, masked)))
}
(CppIntWidth::W8, CppSign::Unsigned) => Ok(format!("((uint8_t)({masked}u))")),
(CppIntWidth::W16, CppSign::Signed) => {
Ok(format!("((int16_t)({}))", Self::signed_i128(*width, masked)))
}
(CppIntWidth::W16, CppSign::Unsigned) => Ok(format!("((uint16_t)({masked}u))")),
(CppIntWidth::W32, CppSign::Signed) => {
let s = Self::signed_i128(*width, masked);
if s == i32::MIN as i128 {
Ok("(-2147483647 - 1)".to_owned())
} else {
Ok(format!("((int32_t)({s}))"))
}
}
(CppIntWidth::W32, CppSign::Unsigned) => Ok(format!("((uint32_t)({masked}u))")),
(CppIntWidth::W64, CppSign::Signed) => {
let s = Self::signed_i128(*width, masked);
if s == i64::MIN as i128 {
Ok("(-9223372036854775807LL - 1LL)".to_owned())
} else {
Ok(format!("((int64_t)({s}LL))"))
}
}
(CppIntWidth::W64, CppSign::Unsigned) => {
Ok(format!("((uint64_t)({masked}ULL))"))
}
(CppIntWidth::W128, _) => {
Err("128-bit C argument formatting is not supported".to_owned())
}
}
}
}
}
/// Parse a tagged value string (`void`, `bool:true`, `int:w32:signed:42`).
pub fn parse_tagged(raw: &str) -> Result<Self, String> {
let s = raw.trim();
if s == "void" {
return Ok(Self::Void);
}
if let Some(rest) = s.strip_prefix("bool:") {
return match rest.trim() {
"true" | "1" => Ok(Self::Bool { value: true }),
"false" | "0" => Ok(Self::Bool { value: false }),
other => Err(format!("invalid bool value {other:?}")),
};
}
if let Some(rest) = s.strip_prefix("int:") {
let parts: Vec<&str> = rest.split(':').collect();
if parts.len() != 3 {
return Err(format!("expected int:<width>:<sign>:<bits>, got {s:?}"));
}
let width = CppIntWidth::parse_lean_name(parts[0])?;
let sign = CppSign::parse_lean_name(parts[1])?;
let bits = parts[2]
.trim()
.parse::<u128>()
.map_err(|e| format!("invalid unsigned_bits {:?}: {e}", parts[2]))?;
if bits > width.mask() {
return Err(format!(
"unsigned_bits {bits} exceeds width {:?} mask {}",
width,
width.mask()
));
}
return Ok(Self::Int { width, sign, unsigned_bits: bits });
}
Err(format!("unrecognized tagged scalar value {s:?}"))
}
}
impl fmt::Display for CppScalarValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Void => write!(f, "void"),
Self::Bool { value } => write!(f, "bool({value})"),
Self::Int { width, sign, unsigned_bits } => {
let bits = width.bits();
match sign {
CppSign::Signed => {
write!(f, "i{bits}({})", Self::signed_i128(*width, *unsigned_bits))
}
CppSign::Unsigned => write!(f, "u{bits}({})", unsigned_bits & width.mask()),
}
}
}
}
}
/// Expected semantic outcome for a corpus case.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaseExpectation {
/// Well-defined C11/C++20 execution; Lean and compiler leg(s) must agree.
Defined,
/// Strict Undefined Behavior; Lean must fault `.undefined` and UBSan/ASan
/// must confirm UB unless `ubsan_detectable` is `false`.
StrictUb,
/// Conservative fail-closed boundary (either `anneal-lower-cpp` rejection
/// or `Trusted.CppSemantics` `.fault .unsupported`).
ExpectedUnsupported,
}
/// Where an `Unsupported` rejection occurred on the Lean leg.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnsupportedStage {
/// Rejected by `anneal-lower-cpp` before Lean elaboration (e.g., SSENF
/// unsequenced side-effects, `volatile`, unions, unsupported policy).
Lowering,
/// Rejected by `Trusted.CppSemantics.initCppState` before stepping.
Init,
/// Rejected by `Trusted.CppSemantics.evalStep` during execution.
Step,
}
/// Observed terminal outcome from either the Lean leg or a compiler/UBSan leg.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum LegOutcome {
/// Normal return with a canonical scalar value.
Returned { value: CppScalarValue },
/// Undefined Behavior detected (`.fault .undefined` in Lean, or UBSan/ASan
/// runtime trap / fatal signal on a compiler leg).
UndefinedBehavior { detail: String },
/// Conservative unsupported rejection on the Lean/lowering leg.
Unsupported { stage: UnsupportedStage, detail: String },
/// Fuel exhausted before reaching a terminal state on the Lean leg.
OutOfFuel { fuel: usize },
/// Compilation failed on a compiler leg.
CompileError { detail: String },
/// Tooling, I/O, or protocol error.
ToolError { detail: String },
}
/// Five-state differential oracle verdict for one corpus case.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "verdict", rename_all = "snake_case")]
pub enum Verdict {
/// Defined case where Lean and all compiler leg(s) agreed on the exact
/// scalar return value (and optional pinned `expected_return`).
DefinedMatch { value: CppScalarValue },
/// Failing semantic discrepancy: value mismatch between legs, unsound
/// missed UB (compiler trapped while Lean returned defined), false-positive
/// UB (Lean faulted UB on a defined case), or mismatch against a pinned
/// expected value.
DefinedMismatch { detail: String },
/// Strict UB case confirmed by Lean `.fault .undefined` (and confirmed by
/// compiler UBSan/ASan when `ubsan_detectable == true`).
StrictUbConfirmed { ubsan_confirmed: bool, detail: String },
/// Expected fail-closed `.unsupported` boundary confirmed at lowering,
/// init, or step time.
ExpectedUnsupported { stage: UnsupportedStage, detail: String },
/// Failing infrastructure, fuel, unexpected-unsupported, or vacuity error.
UnexpectedError { detail: String },
}
impl Verdict {
/// Returns `true` iff this verdict is an admissible passing outcome.
pub const fn is_pass(&self) -> bool {
matches!(
self,
Self::DefinedMatch { .. }
| Self::StrictUbConfirmed { .. }
| Self::ExpectedUnsupported { .. }
)
}
/// Short uppercase tag for human-readable reports.
pub const fn tag(&self) -> &'static str {
match self {
Self::DefinedMatch { .. } => "DEFINED_MATCH",
Self::DefinedMismatch { .. } => "DEFINED_MISMATCH",
Self::StrictUbConfirmed { .. } => "STRICT_UB_CONFIRMED",
Self::ExpectedUnsupported { .. } => "EXPECTED_UNSUPPORTED",
Self::UnexpectedError { .. } => "UNEXPECTED_ERROR",
}
}
}
/// Policy knobs for classifying a single corpus case's observed outcomes.
#[derive(Clone, Debug)]
pub struct VerdictSpec<'a> {
pub expectation: CaseExpectation,
pub expected_return: Option<&'a CppScalarValue>,
/// When `expectation == StrictUb`, whether the primary compiler/UBSan leg
/// is expected to trap. Set `false` only for UB classes that UBSan/ASan
/// cannot instrument (such as uninitialized local reads or subobject
/// provenance violations), where Lean's stricter `.fault .undefined` is
/// still sound.
pub ubsan_detectable: bool,
/// Optional expected stage when `expectation == ExpectedUnsupported`.
pub expected_unsupported_stage: Option<UnsupportedStage>,
}
/// Classify a case given its expectation, the Lean leg outcome, the primary
/// compiler/UBSan leg outcome, and an optional secondary compiler leg (e.g.
/// `g++`/`gcc`).
pub fn classify_case(
spec: &VerdictSpec<'_>,
lean: &LegOutcome,
primary_compiler: &LegOutcome,
secondary_compiler: Option<&LegOutcome>,
) -> Verdict {
// Any infrastructure or fuel failure on the Lean leg fails closed first.
match lean {
LegOutcome::ToolError { detail } => {
return Verdict::UnexpectedError { detail: format!("lean tool error: {detail}") };
}
LegOutcome::OutOfFuel { fuel } => {
return Verdict::UnexpectedError { detail: format!("lean out of fuel ({fuel} steps)") };
}
LegOutcome::CompileError { detail } => {
return Verdict::UnexpectedError {
detail: format!("lean elaboration error: {detail}"),
};
}
_ => {}
}
// Any infrastructure error on a compiler leg also fails closed.
if let LegOutcome::ToolError { detail } = primary_compiler {
return Verdict::UnexpectedError {
detail: format!("primary compiler tool error: {detail}"),
};
}
if let Some(LegOutcome::ToolError { detail }) = secondary_compiler {
return Verdict::UnexpectedError {
detail: format!("secondary compiler tool error: {detail}"),
};
}
match spec.expectation {
CaseExpectation::Defined => {
classify_defined(spec.expected_return, lean, primary_compiler, secondary_compiler)
}
CaseExpectation::StrictUb => {
classify_strict_ub(spec.ubsan_detectable, lean, primary_compiler, secondary_compiler)
}
CaseExpectation::ExpectedUnsupported => classify_expected_unsupported(
spec.expected_unsupported_stage,
lean,
primary_compiler,
secondary_compiler,
),
}
}
fn classify_defined(
expected_return: Option<&CppScalarValue>,
lean: &LegOutcome,
primary: &LegOutcome,
secondary: Option<&LegOutcome>,
) -> Verdict {
let primary_val = match primary {
LegOutcome::Returned { value } => value,
LegOutcome::UndefinedBehavior { detail } => match lean {
LegOutcome::Returned { value } => {
return Verdict::DefinedMismatch {
detail: format!(
"unsound missed UB: compiler trapped ({detail}) while Lean returned {value}"
),
};
}
other => {
return Verdict::UnexpectedError {
detail: format!(
"defined case trapped in compiler ({detail}); Lean reported {other:?}"
),
};
}
},
LegOutcome::CompileError { detail } => {
return Verdict::UnexpectedError {
detail: format!("primary compiler failed to compile defined case: {detail}"),
};
}
other => {
return Verdict::UnexpectedError {
detail: format!("unexpected primary compiler outcome on defined case: {other:?}"),
};
}
};
if let Some(sec) = secondary {
match sec {
LegOutcome::Returned { value: sec_val } => {
if sec_val != primary_val {
return Verdict::DefinedMismatch {
detail: format!(
"compiler legs disagreed on defined case: primary={primary_val}, secondary={sec_val}"
),
};
}
}
LegOutcome::UndefinedBehavior { detail } => {
return Verdict::DefinedMismatch {
detail: format!(
"secondary compiler trapped ({detail}) on defined case where primary returned {primary_val}"
),
};
}
LegOutcome::CompileError { detail } => {
return Verdict::UnexpectedError {
detail: format!("secondary compiler failed to compile defined case: {detail}"),
};
}
other => {
return Verdict::UnexpectedError {
detail: format!(
"unexpected secondary compiler outcome on defined case: {other:?}"
),
};
}
}
}
match lean {
LegOutcome::Returned { value: lean_val } => {
if lean_val != primary_val {
Verdict::DefinedMismatch {
detail: format!(
"value mismatch: Lean returned {lean_val}, compiler returned {primary_val}"
),
}
} else if let Some(exp) = expected_return {
if lean_val != exp {
Verdict::DefinedMismatch {
detail: format!(
"both legs returned {lean_val}, expected pinned value {exp}"
),
}
} else {
Verdict::DefinedMatch { value: lean_val.clone() }
}
} else {
Verdict::DefinedMatch { value: lean_val.clone() }
}
}
LegOutcome::UndefinedBehavior { detail } => Verdict::DefinedMismatch {
detail: format!(
"false-positive UB in Lean ({detail}) where compiler returned {primary_val}"
),
},
LegOutcome::Unsupported { stage, detail } => Verdict::UnexpectedError {
detail: format!("unexpected {stage:?} unsupported on defined case: {detail}"),
},
other => Verdict::UnexpectedError {
detail: format!("unexpected Lean outcome on defined case: {other:?}"),
},
}
}
fn classify_strict_ub(
ubsan_detectable: bool,
lean: &LegOutcome,
primary: &LegOutcome,
secondary: Option<&LegOutcome>,
) -> Verdict {
if let LegOutcome::CompileError { detail } = primary {
return Verdict::UnexpectedError {
detail: format!("primary compiler failed to compile strict_ub case: {detail}"),
};
}
if let Some(LegOutcome::CompileError { detail }) = secondary {
return Verdict::UnexpectedError {
detail: format!("secondary compiler failed to compile strict_ub case: {detail}"),
};
}
if !matches!(primary, LegOutcome::Returned { .. } | LegOutcome::UndefinedBehavior { .. }) {
return Verdict::UnexpectedError {
detail: format!("unexpected primary compiler outcome on strict_ub case: {primary:?}"),
};
}
if let Some(sec) = secondary {
if !matches!(sec, LegOutcome::Returned { .. } | LegOutcome::UndefinedBehavior { .. }) {
return Verdict::UnexpectedError {
detail: format!("unexpected secondary compiler outcome on strict_ub case: {sec:?}"),
};
}
}
let primary_ub = matches!(primary, LegOutcome::UndefinedBehavior { .. });
let secondary_ub = matches!(secondary, Some(LegOutcome::UndefinedBehavior { .. }));
let any_compiler_ub = primary_ub || secondary_ub;
match lean {
LegOutcome::Returned { value } => {
if any_compiler_ub {
Verdict::DefinedMismatch {
detail: format!(
"unsound missed UB: compiler UBSan/ASan trapped while Lean returned {value}"
),
}
} else {
Verdict::UnexpectedError {
detail: format!(
"vacuous strict_ub case: neither Lean ({value}) nor compiler detected UB"
),
}
}
}
LegOutcome::UndefinedBehavior { detail } => {
if ubsan_detectable && !any_compiler_ub {
return Verdict::UnexpectedError {
detail: format!(
"Lean caught UB ({detail}), but expected UBSan/ASan trap did not fire (primary={primary:?}, secondary={secondary:?})"
),
};
}
let summary = if any_compiler_ub {
format!("Lean UB ({detail}) confirmed by compiler sanitizer")
} else {
format!("Lean strict UB ({detail}); beyond UBSan/ASan instrumentation")
};
Verdict::StrictUbConfirmed { ubsan_confirmed: any_compiler_ub, detail: summary }
}
LegOutcome::Unsupported { stage, detail } => Verdict::UnexpectedError {
detail: format!("unexpected {stage:?} unsupported on strict_ub case: {detail}"),
},
other => Verdict::UnexpectedError {
detail: format!("unexpected Lean outcome on strict_ub case: {other:?}"),
},
}
}
fn classify_expected_unsupported(
expected_stage: Option<UnsupportedStage>,
lean: &LegOutcome,
primary: &LegOutcome,
secondary: Option<&LegOutcome>,
) -> Verdict {
if let LegOutcome::CompileError { detail } = primary {
return Verdict::UnexpectedError {
detail: format!(
"expected_unsupported case failed to compile in primary compiler: {detail}"
),
};
}
if let Some(LegOutcome::CompileError { detail }) = secondary {
return Verdict::UnexpectedError {
detail: format!(
"expected_unsupported case failed to compile in secondary compiler: {detail}"
),
};
}
match lean {
LegOutcome::Unsupported { stage, detail } => {
if let Some(exp_stage) = expected_stage {
if *stage != exp_stage {
return Verdict::UnexpectedError {
detail: format!(
"unsupported rejection happened at {stage:?}, expected {exp_stage:?}: {detail}"
),
};
}
}
Verdict::ExpectedUnsupported { stage: *stage, detail: detail.clone() }
}
LegOutcome::Returned { value } => Verdict::UnexpectedError {
detail: format!("expected_unsupported case unexpectedly returned {value}"),
},
LegOutcome::UndefinedBehavior { detail } => Verdict::UnexpectedError {
detail: format!("expected_unsupported case unexpectedly faulted UB ({detail})"),
},
other => Verdict::UnexpectedError {
detail: format!("unexpected Lean outcome on expected_unsupported case: {other:?}"),
},
}
}