blob: 310289bd4ea964e994bb13a3aee50ab5b88ecde8 [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.
//! Optional Pass-1 Lean 4 structural parity lemma exporter (`--emit-lean`).
//!
//! Emits a self-contained Pass-1 Lean module pairing each verified
//! `Trusted.CppAst.CppRecordDef` with an `Anneal.RepAlgebra.Geometry Nat` and
//! a tactic-light (`rfl`) parity theorem checking size, alignment, and
//! field-by-field byte/bit offsets.
//!
//! Fails closed when any C/C++ field omits `is_const` (preserving
//! `Trusted.CppAst`'s zero-default member constness invariant), when a
//! namespace targets reserved root namespaces (`Trusted`, `Init`, `Std`,
//! `Lean`) or Lean keywords, or when untrusted strings contain control or
//! bidirectional Unicode characters.
use std::{collections::BTreeSet, fmt::Write as _};
use crate::{check::MatchedRecord, cpp_bundle::CppType, report::ParseError};
// Mirrors `TrustedBoundary.lean` (`reservedKernelRoots` and
// `reservedRepoTargetDeclRoots`) plus `Trusted`.
const FORBIDDEN_ROOT_NAMESPACES: &[&str] = &[
"Trusted",
"Init",
"Std",
"Lean",
"Lake",
"Nat",
"String",
"Char",
"Bool",
"Int",
"Int8",
"Int16",
"Int32",
"Int64",
"ISize",
"UInt8",
"UInt16",
"UInt32",
"UInt64",
"USize",
"BitVec",
"Float",
"Float32",
"ByteArray",
"Subarray",
"Array",
"List",
"Option",
"Sum",
"Prod",
"Fin",
"Subtype",
"Eq",
"HEq",
"Quot",
"Classical",
"LeanExport",
"LeanIR",
"System",
"IO",
"Task",
"Thunk",
"Unit",
"PUnit",
"Empty",
"PEmpty",
"True",
"False",
"And",
"Or",
"Not",
"Iff",
"Exists",
"Sigma",
"PSigma",
"Decidable",
"Nonempty",
"Ordering",
"Rat",
"Except",
"EStateM",
"StateM",
"Expected",
"Captured",
"Proof",
"IncorrectnessCheck",
"IncorrectnessExpected",
"Spec",
"Specs",
"SpecPreflight",
"TrustedBoundary",
];
const LEAN_KEYWORDS: &[&str] = &[
"abbrev",
"axiom",
"by",
"catch",
"class",
"def",
"deriving",
"do",
"elab",
"else",
"end",
"example",
"false",
"finally",
"for",
"fun",
"if",
"import",
"in",
"inductive",
"instance",
"lemma",
"let",
"macro",
"match",
"module",
"mut",
"namespace",
"noncomputable",
"opaque",
"open",
"partial",
"prelude",
"private",
"protected",
"public",
"return",
"section",
"set_option",
"sorry",
"structure",
"syntax",
"then",
"theorem",
"true",
"try",
"universe",
"unsafe",
"variable",
"where",
"while",
"with",
];
fn is_lean_keyword(seg: &str) -> bool {
LEAN_KEYWORDS.contains(&seg)
}
/// Validates a dotted Pass-1 Lean namespace identifier.
///
/// Rejects empty strings, segments starting with `_` (blocking `_root_`,
/// `_private`, and bare `_`), reserved kernel/boundary root namespaces, Lean
/// keywords, and non-ASCII-identifier segments.
pub fn is_valid_lean_namespace(ns: &str) -> bool {
if ns.is_empty() {
return false;
}
let parts: Vec<&str> = ns.split('.').collect();
if FORBIDDEN_ROOT_NAMESPACES.contains(&parts[0]) {
return false;
}
parts.into_iter().all(|part| {
let mut cs = part.chars();
matches!(cs.next(), Some(c) if c.is_ascii_alphabetic())
&& cs.all(|c| c.is_ascii_alphanumeric() || c == '_')
&& !is_lean_keyword(part)
})
}
/// Emits a Pass-1 Lean 4 module defining `Trusted.CppAst.CppRecordDef` and
/// `Anneal.RepAlgebra.Geometry Nat` terms together with structural layout
/// parity theorems for every verified matched record.
pub fn emit_lean_parity(
namespace: &str,
target_triple: &str,
matched: &[MatchedRecord],
) -> Result<String, ParseError> {
if !is_valid_lean_namespace(namespace) {
return Err(ParseError::Schema(format!(
"`{namespace}` is not an allowed Pass-1 Lean namespace"
)));
}
validate_lean_text(target_triple, "target_triple")?;
let safe_triple = sanitize_comment_text(target_triple);
let mut out = String::new();
let _ = writeln!(out, "-- Copyright 2026 The Fuchsia Authors");
let _ = writeln!(out, "--");
let _ = writeln!(
out,
"-- Licensed under a BSD-style license <LICENSE-BSD>, \
Apache License, Version 2.0"
);
let _ = writeln!(
out,
"-- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, \
or the MIT"
);
let _ = writeln!(
out,
"-- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, \
at your option."
);
let _ = writeln!(
out,
"-- This file may not be copied, modified, or distributed except \
according to"
);
let _ = writeln!(out, "-- those terms.");
let _ = writeln!(out);
let _ = writeln!(out, "module");
let _ = writeln!(out, "prelude");
let _ = writeln!(out, "public import Init.Core");
let _ = writeln!(out, "public import Init.Data.List.Basic");
let _ = writeln!(out, "public import Trusted.CppAst");
let _ = writeln!(out, "public import Anneal.RepAlgebra");
let _ = writeln!(out);
let _ = writeln!(out, "@[expose] public section");
let _ = writeln!(out);
let _ = writeln!(out, "-- Generated by anneal-ffi-check for target `{safe_triple}`.");
let _ = writeln!(out, "namespace {namespace}");
let _ = writeln!(out);
let _ = writeln!(out, "open Trusted.CppAst");
let _ = writeln!(out, "open Anneal.RepAlgebra");
let _ = writeln!(out);
let _ =
writeln!(out, "/-- Returns the bit offset of field `idx` in `fields`, if in bounds. -/");
let _ = writeln!(
out,
"def fieldOffsetBits? (fields : List CppFieldDecl) (idx : Nat) : Option Nat :="
);
let _ = writeln!(out, " List.foldr");
let _ = writeln!(out, " (fun f rest i =>");
let _ = writeln!(out, " match i with");
let _ = writeln!(out, " | 0 => some f.offsetBits");
let _ = writeln!(out, " | n + 1 => rest n)");
let _ = writeln!(out, " (fun _ => none)");
let _ = writeln!(out, " fields idx");
let _ = writeln!(out);
let mut used_idents = BTreeSet::new();
for pair in matched {
let ident = unique_ident(&pair.rust.rust_name, &mut used_idents);
emit_record_parity(&mut out, pair, &ident)?;
}
let _ = writeln!(out, "end {namespace}");
let _ = writeln!(out);
let _ = writeln!(out, "end");
Ok(out)
}
fn emit_record_parity(
out: &mut String,
pair: &MatchedRecord,
ident: &str,
) -> Result<(), ParseError> {
validate_lean_text(&pair.cpp.id, "cpp record id")?;
validate_lean_text(&pair.rust.rust_name, "rust record name")?;
let align_log2 = power_of_two_log2(pair.rust.align_bytes).ok_or_else(|| {
ParseError::Schema(format!(
"record `{}` alignment {} is not a positive power of two",
pair.rust.rust_name, pair.rust.align_bytes
))
})?;
let safe_cpp_id = sanitize_comment_text(&pair.cpp.id);
let safe_rust_name = sanitize_comment_text(&pair.rust.rust_name);
// 1. Trusted.CppAst.CppRecordDef term (requires explicit `is_const` on
// every field to preserve `Trusted.CppAst`'s zero-default invariant).
let _ = writeln!(out, "/-- Captured C/C++ record `{safe_cpp_id}` (`{safe_rust_name}`). -/");
let _ = writeln!(out, "def cppRecord_{ident} : CppRecordDef :=");
let _ = writeln!(out, " {{ recordId := {}", lean_str(&pair.cpp.id)?);
let _ = writeln!(out, " isUnion := {}", pair.cpp.is_union);
let _ = writeln!(out, " sizeBytes := {}", pair.cpp.size_bytes);
let _ = writeln!(out, " alignBytes := {}", pair.cpp.align_bytes);
let _ = writeln!(out, " fields := [");
for (idx, cf) in pair.cpp.fields.iter().enumerate() {
let Some(is_const) = cf.is_const else {
return Err(ParseError::Schema(format!(
"cannot emit `Trusted.CppAst.CppFieldDecl` for `{}.{}`: \
`is_const` is absent from RawCppBundle (`Trusted.CppAst` \
forbids defaulting member constness)",
pair.cpp.id, cf.name
)));
};
let sep = if idx + 1 == pair.cpp.fields.len() { "" } else { "," };
let bw = match cf.bit_width {
None => "none".to_owned(),
Some(n) => format!("some {n}"),
};
let ty = render_cpp_ty(&cf.ty)?;
let _ = writeln!(
out,
" {{ name := {}, offsetBits := {}, bitWidth := {bw}, \
ty := {ty}, isConst := {is_const} }}{sep}",
lean_str(&cf.name)?,
cf.offset_bits,
);
}
let _ = writeln!(out, " ] }}");
let _ = writeln!(out);
// 2. Anneal.RepAlgebra.Geometry Nat term for the Rust `#[repr(C)]` layout.
let rust_value_fields: Vec<_> = pair.rust.fields.iter().filter(|f| !f.is_padding).collect();
for rf in &rust_value_fields {
if !rf.offset_bits.is_multiple_of(8) {
return Err(ParseError::Schema(format!(
"cannot emit Lean geometry for `{}.{}`: offset_bits ({}) is \
not a multiple of 8",
pair.rust.rust_name, rf.name, rf.offset_bits
)));
}
}
let _ = writeln!(
out,
"/-- Rust `#[repr(C)]` geometry for `{safe_rust_name}` (indexed by \
value field). -/"
);
let _ = writeln!(out, "def rustGeom_{ident} : Geometry Nat :=");
let _ = writeln!(out, " {{ extent := {}", pair.rust.size_bytes);
let _ = writeln!(out, " alignLog2 := {align_log2}");
let _ = writeln!(out, " offsetOf := fun idx => match idx with");
for (idx, rf) in rust_value_fields.iter().enumerate() {
let _ = writeln!(out, " | {idx} => some {}", rf.offset_bits / 8);
}
let _ = writeln!(out, " | _ => none }}");
let _ = writeln!(out);
// 3. Structural parity theorem discharged by `rfl`.
let _ = writeln!(
out,
"/-- Structural layout parity between Rust `{safe_rust_name}` and \
C/C++ `{safe_cpp_id}`. -/"
);
let _ = writeln!(out, "theorem {ident}_layout_parity :");
let mut clauses = vec![
format!("rustGeom_{ident}.extent = cppRecord_{ident}.sizeBytes"),
format!("rustGeom_{ident}.alignBytes = cppRecord_{ident}.alignBytes"),
];
for (idx, rf) in rust_value_fields.iter().enumerate() {
let off_bytes = rf.offset_bits / 8;
let off_bits = rf.offset_bits;
clauses.push(format!("rustGeom_{ident}.offsetOf {idx} = some {off_bytes}"));
clauses.push(format!("fieldOffsetBits? cppRecord_{ident}.fields {idx} = some {off_bits}"));
}
for (i, clause) in clauses.iter().enumerate() {
let suffix = if i + 1 == clauses.len() { " := by" } else { " ∧" };
let _ = writeln!(out, " {clause}{suffix}");
}
let rfls = vec!["rfl"; clauses.len()].join(", ");
let _ = writeln!(out, " exact ⟨{rfls}⟩");
let _ = writeln!(out);
Ok(())
}
fn render_cpp_ty(ty: &CppType) -> Result<String, ParseError> {
Ok(match ty {
CppType::Void => "CppTy.void".to_owned(),
CppType::Bool => "CppTy.bool".to_owned(),
CppType::Int { bits, signed, is_char_like, .. } => {
let w = match bits {
8 => "CppIntWidth.w8",
16 => "CppIntWidth.w16",
32 => "CppIntWidth.w32",
64 => "CppIntWidth.w64",
128 => "CppIntWidth.w128",
other => {
return Err(ParseError::Schema(format!(
"cannot emit Lean CppIntWidth for {other}-bit int"
)));
}
};
let s = if *signed { "Signedness.signed" } else { "Signedness.unsigned" };
format!("(CppTy.int {w} {s} {is_char_like})")
}
CppType::Ptr { pointee, is_const, is_restrict, may_alias } => {
let p = render_cpp_ty(pointee)?;
format!("(CppTy.ptr {p} {is_const} {is_restrict} {may_alias})")
}
CppType::Ref { pointee, is_const, may_alias, .. } => {
let p = render_cpp_ty(pointee)?;
format!("(CppTy.ptr {p} {is_const} false {may_alias})")
}
CppType::Array { elem, len } => {
let e = render_cpp_ty(elem)?;
format!("(CppTy.array {e} {len})")
}
CppType::Record { id } => format!("(CppTy.record {})", lean_str(id)?),
CppType::NullPtrT => "(CppTy.ptr CppTy.void false false false)".to_owned(),
CppType::Unsupported { desc } => {
return Err(ParseError::Schema(format!(
"cannot emit Lean CppTy for unsupported type `{desc}`"
)));
}
})
}
fn power_of_two_log2(n: u64) -> Option<u32> {
if n == 0 || !n.is_power_of_two() {
return None;
}
Some(n.trailing_zeros())
}
fn unique_ident(raw: &str, used: &mut BTreeSet<String>) -> String {
let mut base = String::new();
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
base.push(ch);
} else {
base.push('_');
}
}
if base.is_empty()
|| !base.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|| is_lean_keyword(&base)
{
base.insert_str(0, "rec_");
}
if used.insert(base.clone()) {
return base;
}
let mut suffix = 2usize;
loop {
let cand = format!("{base}_{suffix}");
if used.insert(cand.clone()) {
return cand;
}
suffix += 1;
}
}
/// Rejects NUL, control characters, and Unicode bidi/invisible format code
/// points so emitted Lean modules always pass Pass-1 Unicode hygiene.
fn validate_lean_text(s: &str, ctx: &str) -> Result<(), ParseError> {
for ch in s.chars() {
if ch == '\0' || ch.is_control() || is_bidi_or_invisible(ch) {
return Err(ParseError::Schema(format!(
"{ctx} contains disallowed control or bidi character U+{:04X}",
ch as u32
)));
}
}
Ok(())
}
fn is_bidi_or_invisible(ch: char) -> bool {
matches!(
ch as u32,
0x061C
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0xFEFF
)
}
/// Strips any character outside a strict printable ASCII comment allowlist
/// (excluding `/`, `\r`, `\n`, and backticks), making `--` and `/-- ... -/`
/// comment breakouts impossible by construction.
fn sanitize_comment_text(s: &str) -> String {
s.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric()
|| matches!(ch, '_' | '.' | ':' | '<' | '>' | ' ' | ',' | '-')
{
ch
} else {
'_'
}
})
.collect()
}
fn lean_str(s: &str) -> Result<String, ParseError> {
validate_lean_text(s, "Lean string literal")?;
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for ch in s.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
c => out.push(c),
}
}
out.push('"');
Ok(out)
}