use std::collections::HashMap;
use tpt_telos_parser::ast::*;
use crate::{analyze_func, collect_types, InputParam, TypeFields};
const PY_KEYWORDS: &[&str] = &[
"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
"in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
"with", "yield",
];
fn py_safe(name: &str) -> String {
if PY_KEYWORDS.contains(&name) {
format!("{}_", name)
} else {
name.to_string()
}
}
pub fn generate_python_package(
modules: &[&Module],
bodies: &HashMap<String, Vec<Stmt>>,
use_jax: bool,
) -> String {
let mut out = String::new();
out.push_str("# Generated by tpt-telos. Do not edit by hand.\n");
out.push_str("# Mathematical contracts were verified by the tpt-telos SMT core.\n");
out.push_str("from __future__ import annotations\n");
out.push_str("from dataclasses import dataclass, field\n");
if use_jax {
out.push_str("import jax.numpy as jnp\n");
}
out.push('\n');
let mut all_types: TypeFields = HashMap::new();
for m in modules {
collect_types(m, &mut all_types);
}
for m in modules {
out.push_str(&generate_py_module(m, bodies, &all_types, use_jax));
out.push('\n');
}
out
}
fn generate_py_module(
module: &Module,
bodies: &HashMap<String, Vec<Stmt>>,
types: &TypeFields,
use_jax: bool,
) -> String {
let mut out = String::new();
out.push_str(&format!(
"# ===== module {} (target: python) =====\n\n",
module.name
));
let int_type = if use_jax { "jnp.int64" } else { "int" };
for (ty, fields) in types {
if fields.is_empty() {
continue;
}
out.push_str("@dataclass\n");
out.push_str(&format!("class {}:\n", ty));
for (f, fty) in fields {
let py_type = render_py_type(fty, int_type);
out.push_str(&format!(" {}: {} = 0\n", f, py_type));
}
out.push('\n');
for item in &module.items {
if let Item::Invariant(inv) = item {
if inv.name == *ty {
let conds = inv
.constraints
.iter()
.map(render_inv_py)
.collect::<Vec<_>>()
.join(" and ");
out.push_str(" def satisfies_invariants(self) -> bool:\n");
out.push_str(&format!(" return {}\n\n", conds));
}
}
}
}
for item in &module.items {
if let Item::Invariant(inv) = item {
if !types.contains_key(&inv.name) {
continue;
}
}
}
for item in &module.items {
if let Item::Func(f) = item {
let key = f.name.clone();
let stmts = bodies.get(&key).cloned().unwrap_or_else(|| f.body.clone());
out.push_str(&render_py_func(f, &stmts, types, int_type));
out.push('\n');
}
}
out
}
fn render_py_type(ty: &tpt_telos_parser::ast::Type, int_type: &str) -> String {
match ty {
tpt_telos_parser::ast::Type::Named(s) => match s.as_str() {
"Float32" => "float".to_string(),
"Float64" => "float".to_string(),
"Int" | "PositiveInt" => int_type.to_string(),
"Bool" => "bool".to_string(),
"String" => "str".to_string(),
other => other.to_string(),
},
tpt_telos_parser::ast::Type::Generic(name, args) => {
let args: Vec<_> = args.iter().map(|a| render_py_type(a, int_type)).collect();
format!("{}[{}]", name, args.join(", "))
}
tpt_telos_parser::ast::Type::Tuple(elems) => {
let elems: Vec<_> = elems.iter().map(|e| render_py_type(e, int_type)).collect();
format!("tuple[{}]", elems.join(", "))
}
tpt_telos_parser::ast::Type::Array(elem, len) => {
format!("list[{}] # length {}", render_py_type(elem, int_type), len)
}
tpt_telos_parser::ast::Type::Slice(elem) => {
format!("list[{}]", render_py_type(elem, int_type))
}
}
}
fn render_py_func(f: &Func, stmts: &[Stmt], types: &TypeFields, int_type: &str) -> String {
let mut out = String::new();
let analysis = analyze_func(f, stmts, types);
let mut params: Vec<String> = Vec::new();
for input in &analysis.inputs {
match input {
InputParam::Scalar { name } => {
params.push(format!("{}: {}", py_safe(name), int_type));
}
InputParam::Struct { name, ty, .. } => {
params.push(format!("{}: {}", py_safe(name), ty));
}
}
}
let ret = if analysis.scalar_out.is_some() {
format!(" -> {}", int_type)
} else {
" -> None".to_string()
};
out.push_str(&format!("def {}({}){} :\n", f.name, params.join(", "), ret));
out.push_str(" \"\"\"\n");
for r in &f.requires {
out.push_str(&format!(" requires: {}\n", render_expr_py_doc(r)));
}
for e in &f.ensures {
out.push_str(&format!(" ensures: {}\n", render_expr_py_doc(e)));
}
out.push_str(" \"\"\"\n");
for r in &f.requires {
let cond = render_expr_py(r);
let msg = render_expr_py_doc(r);
out.push_str(&format!(
" assert {}, \"telos: precondition violated in `{}`: {}\"\n",
cond, f.name, msg
));
}
let old_fields = collect_old_fields_py(f);
for (base, field) in &old_fields {
out.push_str(&format!(
" __old_{}_{} = {}.{}\n",
py_safe(base),
field,
py_safe(base),
field
));
}
if !old_fields.is_empty() {
out.push('\n');
}
for stmt in stmts {
match stmt {
Stmt::MutateState(assigns) => {
for a in assigns {
let lhs = render_assign_target_py(&a.target);
let rhs = render_expr_py(&a.value);
let op = match a.op {
AssignOp::Set => "=",
AssignOp::Add => "+=",
AssignOp::Sub => "-=",
};
out.push_str(&format!(" {} {} {}\n", lhs, op, rhs));
}
}
Stmt::Assign(a) => {
let lhs = render_assign_target_py(&a.target);
let rhs = render_expr_py(&a.value);
let op = match a.op {
AssignOp::Set => "=",
AssignOp::Add => "+=",
AssignOp::Sub => "-=",
};
out.push_str(&format!(" {} {} {}\n", lhs, op, rhs));
}
_ => {}
}
}
if !f.ensures.is_empty() {
out.push('\n');
}
for e in &f.ensures {
let cond = render_ensures_py(e, &old_fields, f);
let msg = render_expr_py_doc(e);
out.push_str(&format!(
" assert {}, \"telos: postcondition violated in `{}`: {}\"\n",
cond, f.name, msg
));
}
if let Some(ref outvar) = analysis.scalar_out {
out.push_str(&format!(" return {}\n", py_safe(outvar)));
}
out
}
fn collect_old_fields_py(f: &Func) -> Vec<(String, String)> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for e in &f.ensures {
collect_old_in_expr(e, &mut seen, &mut out);
}
out
}
fn collect_old_in_expr(
e: &Expr,
seen: &mut std::collections::HashSet<(String, String)>,
out: &mut Vec<(String, String)>,
) {
match e {
Expr::Old(inner) => {
if let Expr::Field { base, field } = inner.as_ref() {
if seen.insert((base.clone(), field.clone())) {
out.push((base.clone(), field.clone()));
}
}
}
Expr::Bin { lhs, rhs, .. } => {
collect_old_in_expr(lhs, seen, out);
collect_old_in_expr(rhs, seen, out);
}
Expr::Unary { expr, .. } => collect_old_in_expr(expr, seen, out),
_ => {}
}
}
fn render_assign_target_py(e: &Expr) -> String {
match e {
Expr::Var(v) => py_safe(v),
Expr::Field { base, field } => format!("{}.{}", py_safe(base), field),
_ => "?".to_string(),
}
}
fn render_ensures_py(e: &Expr, old_fields: &[(String, String)], _f: &Func) -> String {
render_expr_py_with_old(e, old_fields)
}
fn render_expr_py_with_old(e: &Expr, _old_fields: &[(String, String)]) -> String {
match e {
Expr::Old(inner) => {
if let Expr::Field { base, field } = inner.as_ref() {
format!("__old_{}_{}", py_safe(base), field)
} else {
render_expr_py_with_old(inner, _old_fields)
}
}
Expr::Int(n) => n.to_string(),
Expr::Var(v) => py_safe(v),
Expr::Field { base, field } => format!("{}.{}", py_safe(base), field),
Expr::Unary { op, expr } => match op {
UnOp::Neg => format!("-({})", render_expr_py_with_old(expr, _old_fields)),
},
Expr::Bin { op, lhs, rhs } => {
let l = render_expr_py_with_old(lhs, _old_fields);
let r = render_expr_py_with_old(rhs, _old_fields);
let s = py_bin_op(*op);
format!("{} {} {}", l, s, r)
}
other => render_expr_py(other),
}
}
fn render_expr_py(e: &Expr) -> String {
match e {
Expr::Int(n) => n.to_string(),
Expr::Var(v) => py_safe(v),
Expr::Field { base, field } => format!("{}.{}", py_safe(base), field),
Expr::Old(inner) => render_expr_py(inner),
Expr::Unary { op, expr } => match op {
UnOp::Neg => format!("-({})", render_expr_py(expr)),
},
Expr::Bin { op, lhs, rhs } => {
let l = render_expr_py(lhs);
let r = render_expr_py(rhs);
let s = py_bin_op(*op);
format!("{} {} {}", l, s, r)
}
other => crate::render_expr(other),
}
}
fn render_expr_py_doc(e: &Expr) -> String {
match e {
Expr::Int(n) => n.to_string(),
Expr::Var(v) => v.clone(),
Expr::Field { base, field } => format!("{}.{}", base, field),
Expr::Old(inner) => format!("old({})", render_expr_py_doc(inner)),
Expr::Unary { op, expr } => match op {
UnOp::Neg => format!("-{}", render_expr_py_doc(expr)),
},
Expr::Bin { op, lhs, rhs } => {
let l = render_expr_py_doc(lhs);
let r = render_expr_py_doc(rhs);
let s = match op {
BinOp::Add => "+",
BinOp::Sub => "-",
BinOp::Mul => "*",
BinOp::Div => "/",
BinOp::Eq => "==",
BinOp::Ne => "!=",
BinOp::Lt => "<",
BinOp::Le => "<=",
BinOp::Gt => ">",
BinOp::Ge => ">=",
BinOp::And => "&&",
BinOp::Or => "||",
};
format!("{} {} {}", l, s, r)
}
other => crate::render_expr_doc(other),
}
}
fn py_bin_op(op: BinOp) -> &'static str {
match op {
BinOp::Add => "+",
BinOp::Sub => "-",
BinOp::Mul => "*",
BinOp::Div => "//",
BinOp::Eq => "==",
BinOp::Ne => "!=",
BinOp::Lt => "<",
BinOp::Le => "<=",
BinOp::Gt => ">",
BinOp::Ge => ">=",
BinOp::And => "and",
BinOp::Or => "or",
}
}
fn render_inv_py(e: &Expr) -> String {
match e {
Expr::Int(n) => n.to_string(),
Expr::Var(v) => format!("self.{}", v),
Expr::Field { field, .. } => format!("self.{}", field),
Expr::Old(inner) => render_inv_py(inner),
Expr::Unary { op, expr } => match op {
UnOp::Neg => format!("-({})", render_inv_py(expr)),
},
Expr::Bin { op, lhs, rhs } => {
let l = render_inv_py(lhs);
let r = render_inv_py(rhs);
let s = py_bin_op(*op);
format!("{} {} {}", l, s, r)
}
other => crate::render_expr(other),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn py_safe_escapes_keywords() {
assert_eq!(py_safe("from"), "from_");
assert_eq!(py_safe("class"), "class_");
assert_eq!(py_safe("balance"), "balance");
}
#[test]
fn generate_python_emits_dataclass_and_function() {
let src = r#"
@boundary(ml_training)
module PhysicsLayer {
invariant State { energy >= 0 }
func update_energy(s: State, delta: Int)
requires delta >= 0
ensures s.energy == old(s.energy) + delta
{ mutate state { s.energy += delta } }
}
"#;
let modules = tpt_telos_parser::parse(src).unwrap();
let bodies = std::collections::HashMap::new();
let refs: Vec<&tpt_telos_parser::ast::Module> = modules.iter().collect();
let py = generate_python_package(&refs, &bodies, false);
assert!(py.contains("@dataclass"), "missing @dataclass: {py}");
assert!(py.contains("class State"), "missing State class: {py}");
assert!(py.contains("def update_energy"), "missing function: {py}");
assert!(
py.contains("assert delta >= 0"),
"missing precondition: {py}"
);
assert!(
py.contains("def satisfies_invariants"),
"missing invariant method: {py}"
);
}
#[test]
fn generate_python_jax_adds_import() {
let src = "@boundary(jax) module M { func f(x: Int) requires x >= 0 { } }";
let modules = tpt_telos_parser::parse(src).unwrap();
let refs: Vec<&tpt_telos_parser::ast::Module> = modules.iter().collect();
let py = generate_python_package(&refs, &std::collections::HashMap::new(), true);
assert!(
py.contains("import jax.numpy as jnp"),
"missing JAX import: {py}"
);
}
}