tpt-telos-codegen 0.1.0

Rust/Go dual-backend code generation and FFI bridge for tpt-telos
Documentation
//! Go backend code generation for tpt-telos (Phase 3).
//!
//! Mirrors the Rust backend in [`crate`] but emits idiomatic Go for modules the
//! context router assigns to the Go target (`@boundary(network_io)`,
//! `@boundary(high_concurrency)`, `@boundary(distributed)`, ...).
//!
//! The generated Go:
//!   * declares a `struct` for every user type accessed by field, with exported
//!     (capitalised) `int64` fields so they can cross the FFI boundary,
//!   * attaches a `SatisfiesInvariants()` method to each such struct for every
//!     `invariant` block of the same name,
//!   * emits one exported `func` per `func`, taking `*T` for mutated struct
//!     parameters and `T` for read-only ones,
//!   * carries the original `requires` / `ensures` contracts as `//` comments.
//!
//! Function bodies come from the agentic transpiler's final (verified)
//! candidates, exactly as for the Rust backend, so the emitted Go satisfies the
//! same mathematical contracts.

use std::collections::HashMap;

use tpt_telos_parser::ast::*;

use crate::{
    analyze_func, collect_types, render_expr_doc, render_params_sig, InputParam, TypeFields,
};

/// Capitalise the first character (ASCII) so a telos field/func name becomes an
/// exported Go identifier.
pub(crate) fn exported(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) => c.to_ascii_uppercase().to_string() + chars.as_str(),
        None => String::new(),
    }
}

/// A short, lower-cased receiver name for a struct type (`Account` -> `a`).
fn receiver(ty: &str) -> String {
    ty.chars()
        .next()
        .map(|c| c.to_ascii_lowercase().to_string())
        .unwrap_or_else(|| "r".to_string())
}

/// Generate a complete Go package source for the given (Go-routed) modules.
pub fn generate_go_package(
    modules: &[&Module],
    bodies: &HashMap<String, Vec<Stmt>>,
    package: &str,
) -> 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(&format!("package {}\n\n", package));

    let mut struct_types: TypeFields = HashMap::new();
    for m in modules {
        collect_types(m, &mut struct_types);
    }

    for m in modules {
        out.push_str(&generate_module(m, bodies, &struct_types));
        out.push('\n');
    }

    normalize(out)
}

/// Trim trailing blank lines so the output is gofmt-canonical (single trailing
/// newline).
pub(crate) fn normalize(mut s: String) -> String {
    while s.ends_with('\n') {
        s.pop();
    }
    s.push('\n');
    s
}

fn generate_module(
    module: &Module,
    bodies: &HashMap<String, Vec<Stmt>>,
    types: &TypeFields,
) -> String {
    let route = tpt_telos_router::route(&module.attributes);
    let mut out = String::new();
    out.push_str(&format!(
        "// ===== module {} (target: {}) =====\n",
        module.name,
        route.target.as_str()
    ));

    // Structs.
    let mut tys: Vec<(&String, &std::collections::BTreeSet<String>)> = types.iter().collect();
    tys.sort_by(|a, b| a.0.cmp(b.0));
    for (ty, fields) in tys {
        if fields.is_empty() {
            continue;
        }
        out.push_str(&format!("type {} struct {{\n", ty));
        for f in fields {
            out.push_str(&format!("\t{} int64\n", exported(f)));
        }
        out.push_str("}\n\n");
    }

    // Invariants as methods.
    for item in &module.items {
        if let Item::Invariant(inv) = item {
            let recv = receiver(&inv.name);
            let conds = inv
                .constraints
                .iter()
                .map(|c| render_inv(c, &recv))
                .collect::<Vec<_>>()
                .join(" && ");
            out.push_str(&format!(
                "// SatisfiesInvariants reports whether the {name} invariant holds.\n\
                 func ({recv} *{name}) SatisfiesInvariants() bool {{\n\treturn {conds}\n}}\n\n",
                name = inv.name,
                recv = recv,
                conds = conds
            ));
        }
    }

    // Functions.
    for item in &module.items {
        if let Item::Func(f) = item {
            let stmts = bodies
                .get(&f.name)
                .cloned()
                .unwrap_or_else(|| f.body.clone());
            if f.is_ejected() {
                out.push_str(&crate::eject::render_go_ejected(f, &stmts, types));
            } else {
                out.push_str(&render_func(f, &stmts, types));
            }
            out.push('\n');
        }
    }

    out
}

fn render_func(f: &Func, stmts: &[Stmt], types: &TypeFields) -> String {
    render_func_named(f, stmts, types, &exported(&f.name))
}

/// Render a Go function with an explicit name (used by the eject hatch to emit
/// an unexported `*Impl` opaque block).
pub(crate) fn render_func_named(
    f: &Func,
    stmts: &[Stmt],
    types: &TypeFields,
    name: &str,
) -> String {
    let mut out = String::new();

    // Doc-comment carrying the contract (telos-level names for fidelity).
    out.push_str(&format!(
        "// {} implements {}({})\n",
        name,
        f.name,
        render_params_sig(f)
    ));
    for r in &f.requires {
        out.push_str(&format!("// requires: {}\n", render_expr_doc(r)));
    }
    for e in &f.ensures {
        out.push_str(&format!("// ensures:  {}\n", render_expr_doc(e)));
    }

    let analysis = analyze_func(f, stmts, types);

    let mut params = Vec::new();
    for input in &analysis.inputs {
        match input {
            InputParam::Scalar { name } => params.push(format!("{} int64", name)),
            InputParam::Struct {
                name, ty, mutated, ..
            } => {
                if *mutated {
                    params.push(format!("{} *{}", name, ty));
                } else {
                    params.push(format!("{} {}", name, ty));
                }
            }
        }
    }

    let ret = if analysis.scalar_out.is_some() {
        " int64"
    } else {
        ""
    };

    out.push_str(&format!("func {}({}){} {{\n", name, params.join(", "), ret));

    for stmt in stmts {
        match stmt {
            Stmt::MutateState(assigns) => {
                for a in assigns {
                    out.push('\t');
                    out.push_str(&render_assign(a));
                    out.push('\n');
                }
            }
            Stmt::Assign(a) => {
                if analysis.scalar_out.as_deref() == Some(target_var(&a.target)) {
                    out.push_str(&format!(
                        "\t{} := {}\n",
                        target_var(&a.target),
                        render_expr(&a.value)
                    ));
                } else {
                    out.push('\t');
                    out.push_str(&render_assign(a));
                    out.push('\n');
                }
            }
        }
    }

    if let Some(outvar) = &analysis.scalar_out {
        out.push_str(&format!("\treturn {}\n", outvar));
    }

    out.push_str("}\n");
    out
}

pub(crate) fn target_var(e: &Expr) -> &str {
    match e {
        Expr::Var(v) => v,
        _ => "",
    }
}

pub(crate) fn render_assign(a: &Assign) -> String {
    let lhs = render_expr(&a.target);
    let rhs = render_expr(&a.value);
    let op = match a.op {
        AssignOp::Set => "=",
        AssignOp::Add => "+=",
        AssignOp::Sub => "-=",
    };
    format!("{} {} {}", lhs, op, rhs)
}

pub(crate) fn render_expr(e: &Expr) -> String {
    match e {
        Expr::Int(n) => n.to_string(),
        Expr::Var(v) => v.clone(),
        Expr::Field { base, field } => format!("{}.{}", base, exported(field)),
        Expr::Old(inner) => render_expr(inner),
        Expr::Unary { op, expr } => match op {
            UnOp::Neg => format!("-{}", render_expr(expr)),
        },
        Expr::Bin { op, lhs, rhs } => {
            format!("{} {} {}", render_expr(lhs), bin_op(*op), render_expr(rhs))
        }
    }
}

/// Render an invariant expression against the method receiver.
fn render_inv(e: &Expr, recv: &str) -> String {
    match e {
        Expr::Int(n) => n.to_string(),
        Expr::Var(v) => format!("{}.{}", recv, exported(v)),
        Expr::Field { field, .. } => format!("{}.{}", recv, exported(field)),
        Expr::Old(inner) => render_inv(inner, recv),
        Expr::Unary { op, expr } => match op {
            UnOp::Neg => format!("-{}", render_inv(expr, recv)),
        },
        Expr::Bin { op, lhs, rhs } => format!(
            "{} {} {}",
            render_inv(lhs, recv),
            bin_op(*op),
            render_inv(rhs, recv)
        ),
    }
}

pub(crate) fn 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 => "&&",
        BinOp::Or => "||",
    }
}