blob: e2ef3ea4225e2f77e75b8a9584691d55652ecc57 [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.
//! Batch execution bridge to Anneal's Lean 4 `Anneal.IsaOracleDriver` module.
use std::{
collections::BTreeMap,
io::Write,
path::Path,
process::{Command, Stdio},
};
use crate::{Arch, LeanDecodeStatus, LeanInsn, X86DecoderLane};
/// Query lane forwarded to `Anneal.IsaOracleDriver.OracleLane`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeanQueryLane {
X86BaseStream,
X86WordSimdStream,
AArch64Stream,
X86BaseOne,
X86WordSimdOne,
AArch64One,
}
impl LeanQueryLane {
pub fn stream_for(arch: Arch, x86_lane: X86DecoderLane) -> Self {
match (arch, x86_lane) {
(Arch::X86_64, X86DecoderLane::Base) => Self::X86BaseStream,
(Arch::X86_64, X86DecoderLane::WordSimd) => Self::X86WordSimdStream,
(Arch::AArch64, _) => Self::AArch64Stream,
}
}
pub fn one_for(arch: Arch, x86_lane: X86DecoderLane) -> Self {
match (arch, x86_lane) {
(Arch::X86_64, X86DecoderLane::Base) => Self::X86BaseOne,
(Arch::X86_64, X86DecoderLane::WordSimd) => Self::X86WordSimdOne,
(Arch::AArch64, _) => Self::AArch64One,
}
}
fn lean_ctor(self) -> &'static str {
match self {
Self::X86BaseStream => ".x86BaseStream",
Self::X86WordSimdStream => ".x86WordSimdStream",
Self::AArch64Stream => ".aarch64Stream",
Self::X86BaseOne => ".x86BaseOne",
Self::X86WordSimdOne => ".x86WordSimdOne",
Self::AArch64One => ".aarch64One",
}
}
}
/// Single batch query sent to `Anneal.IsaOracleDriver.evalBatch`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LeanBatchQuery {
pub id: String,
pub lane: LeanQueryLane,
pub pos: u64,
pub require_reloc: bool,
pub bmi1: bool,
pub popcnt: bool,
pub lzcnt: bool,
pub bytes: Vec<u8>,
}
/// Format a byte slice as a chunked Lean `List UInt8` expression (`<= 32`
/// elements per literal so Lean's elaborator stays linear on long sections).
pub fn encode_lean_byte_list(bytes: &[u8]) -> String {
if bytes.is_empty() {
return "[]".to_string();
}
let chunks: Vec<String> = bytes
.chunks(32)
.map(|chunk| {
let elems: Vec<String> = chunk.iter().map(|b| format!("0x{b:02X}")).collect();
format!("[{}]", elems.join(", "))
})
.collect();
chunks.join(" ++ ")
}
/// Escape an ASCII identifier/string for embedding in a Lean string literal.
fn escape_lean_str(s: &str) -> Result<String, String> {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
if !ch.is_ascii() || ch.is_ascii_control() {
return Err(format!("non-printable query id `{s}`"));
}
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
_ => out.push(ch),
}
}
Ok(out)
}
/// Render a transient Lean `--stdin` batch evaluator script that invokes
/// `Anneal.IsaOracleDriver.evalBatch` and prints deterministic `ORACLE|...`
/// wire lines.
pub fn render_lean_batch_script(queries: &[LeanBatchQuery]) -> Result<String, String> {
let mut script = String::new();
script.push_str("import Init\n");
script.push_str("import Anneal.IsaOracleDriver\n");
script.push_str("open Anneal.IsaOracleDriver\n\n");
script.push_str("def oracleQueries : List OracleQuery := [\n");
for (idx, q) in queries.iter().enumerate() {
let escaped_id = escape_lean_str(&q.id)?;
let comma = if idx + 1 == queries.len() { "" } else { "," };
script.push_str(&format!(
" {{ id := \"{escaped_id}\", lane := {}, pos := {}, \
requireReloc := {}, bmi1 := {}, popcnt := {}, lzcnt := {}, \
bytes := {} }}{comma}\n",
q.lane.lean_ctor(),
q.pos,
q.require_reloc,
q.bmi1,
q.popcnt,
q.lzcnt,
encode_lean_byte_list(&q.bytes),
));
}
script.push_str("]\n\n");
script.push_str(
"private def fmtEntry (e : DecodedEntry) : String :=\n\
\x20 if e.detail.isEmpty then\n\
\x20 s!\"{e.offset}:{e.len}:{e.mnemonic}\"\n\
\x20 else\n\
\x20 s!\"{e.offset}:{e.len}:{e.mnemonic}/{e.detail}\"\n\n\
private def fmtResult (r : OracleResult) : String :=\n\
\x20 match r.status with\n\
\x20 | .decodeNone => s!\"ORACLE|{r.id}|NONE\"\n\
\x20 | .ok es =>\n\
\x20 let body := String.intercalate \";\" (es.map fmtEntry)\n\
\x20 s!\"ORACLE|{r.id}|OK {body}\"\n\n\
#eval do\n\
\x20 for r in evalBatch oracleQueries do\n\
\x20 IO.println (fmtResult r)\n",
);
Ok(script)
}
/// Parse deterministic `ORACLE|<id>|OK ...` and `ORACLE|<id>|NONE` lines
/// emitted by `render_lean_batch_script`.
pub fn parse_lean_batch_output(stdout: &str) -> Result<BTreeMap<String, LeanDecodeStatus>, String> {
let mut results = BTreeMap::new();
for line in stdout.lines() {
let trimmed = line.trim();
let Some(rest) = trimmed.strip_prefix("ORACLE|") else {
continue;
};
let Some((id, payload)) = rest.split_once('|') else {
return Err(format!("malformed ORACLE line: `{trimmed}`"));
};
let status = if payload == "NONE" {
LeanDecodeStatus::DecodeNone
} else if let Some(body) = payload.strip_prefix("OK ") {
let mut entries = Vec::new();
if !body.is_empty() {
for item in body.split(';') {
let parts: Vec<&str> = item.splitn(3, ':').collect();
if parts.len() != 3 {
return Err(format!("malformed ORACLE entry `{item}`"));
}
let offset = parts[0]
.parse::<u64>()
.map_err(|e| format!("bad offset `{}`: {e}", parts[0]))?;
let len = parts[1]
.parse::<usize>()
.map_err(|e| format!("bad length `{}`: {e}", parts[1]))?;
let (mnemonic, detail) = match parts[2].split_once('/') {
Some((mn, det)) => (mn.to_string(), det.to_string()),
None => (parts[2].to_string(), String::new()),
};
entries.push(LeanInsn { offset, len, mnemonic, detail });
}
}
LeanDecodeStatus::Ok(entries)
} else if payload == "OK" {
LeanDecodeStatus::Ok(Vec::new())
} else {
return Err(format!("unknown ORACLE payload `{payload}` for `{id}`"));
};
if results.insert(id.to_string(), status).is_some() {
return Err(format!("duplicate ORACLE result id `{id}`"));
}
}
Ok(results)
}
/// Execute a batch of queries against Lean 4 (`lean --stdin`) with `LEAN_PATH`
/// configured to include `olean_dir`.
pub fn run_lean_batch(
lean_bin: &str,
olean_dir: Option<&Path>,
queries: &[LeanBatchQuery],
) -> Result<BTreeMap<String, LeanDecodeStatus>, String> {
if queries.is_empty() {
return Ok(BTreeMap::new());
}
let script = render_lean_batch_script(queries)?;
let mut cmd = Command::new(lean_bin);
cmd.arg("--stdin").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(dir) = olean_dir {
let mut lean_path = dir.as_os_str().to_os_string();
if let Some(existing) = std::env::var_os("LEAN_PATH") {
if !existing.is_empty() {
lean_path.push(":");
lean_path.push(existing);
}
}
cmd.env("LEAN_PATH", lean_path);
}
let mut child = cmd.spawn().map_err(|e| format!("failed to spawn `{lean_bin}`: {e}"))?;
{
let mut stdin =
child.stdin.take().ok_or_else(|| "failed to open lean stdin".to_string())?;
stdin
.write_all(script.as_bytes())
.map_err(|e| format!("failed to write lean stdin: {e}"))?;
}
let out =
child.wait_with_output().map_err(|e| format!("failed waiting for `{lean_bin}`: {e}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
return Err(format!(
"`{lean_bin}` failed (status {}):\nstdout: {}\nstderr: {}",
out.status,
stdout.trim(),
stderr.trim()
));
}
let stdout = String::from_utf8_lossy(&out.stdout);
let parsed = parse_lean_batch_output(&stdout)?;
for q in queries {
if !parsed.contains_key(&q.id) {
return Err(format!("Lean batch output missing query id `{}`", q.id));
}
}
Ok(parsed)
}