Skip to main content

tpt_telos_codegen/
lib.rs

1//! Rust backend code generation for tpt-telos (Phase 2 milestone).
2//!
3//! [`generate_program`] lowers a set of parsed modules into a single,
4//! self-contained Rust library source string. The generated code:
5//!   * declares a `struct` for every user type that is accessed by field,
6//!   * attaches an `invariants()` method to each such struct for every
7//!     `invariant` block of the same name,
8//!   * emits one `fn` per `func`, threading `&mut` only to parameters that are
9//!     actually mutated,
10//!   * carries the original `requires` / `ensures` contracts as doc-comments.
11//!
12//! The function bodies come from the agentic transpiler's final candidates
13//! (see [`tpt_telos_agent`]), so the emitted code is mathematically verified before
14//! it is written out.
15
16use std::collections::{BTreeSet, HashMap, HashSet};
17
18use tpt_telos_agent::FuncOutcome;
19use tpt_telos_parser::ast::*;
20
21pub mod eject;
22pub mod ffi;
23pub mod go;
24pub mod project;
25pub mod proof;
26pub mod python;
27
28pub use project::{generate_project, GeneratedFile, Project};
29
30/// Maps a type name to the set of fields that must appear on its generated
31/// struct.
32/// Per-type field definitions: maps a type name to its ordered list of
33/// `(field_name, field_type)` pairs. Populated from explicit `StructDef`
34/// declarations when available; otherwise inferred from usage.
35pub(crate) type TypeFields = HashMap<String, Vec<(String, Type)>>;
36
37/// Classification of a single (post-analysis) function parameter, shared by the
38/// Rust backend, the Go backend, and the automatic FFI bridge so all three
39/// agree on calling conventions.
40#[derive(Debug, Clone)]
41pub(crate) enum InputParam {
42    /// A scalar (`i64`) input parameter.
43    Scalar { name: String },
44    /// A parameter of a struct type. `mutated` is true when the function body
45    /// writes to any of its fields (so it is passed `&mut` in Rust and by
46    /// pointer across the FFI boundary).
47    Struct {
48        name: String,
49        ty: String,
50        mutated: bool,
51        fields: Vec<String>,
52    },
53}
54
55/// The result of analysing a function body: its effective input parameters and
56/// whether it produces a scalar return value (an assignment to a bare
57/// parameter/variable name).
58#[derive(Debug, Clone)]
59pub(crate) struct FuncAnalysis {
60    pub inputs: Vec<InputParam>,
61    pub scalar_out: Option<String>,
62}
63
64/// Analyse a function's parameters and body once, deriving the mutation set and
65/// scalar-return output so every backend lowers the same signature.
66pub(crate) fn analyze_func(f: &Func, stmts: &[Stmt], types: &TypeFields) -> FuncAnalysis {
67    let mut mutated: HashSet<String> = HashSet::new();
68    let mut scalar_out: Option<String> = None;
69    for stmt in stmts {
70        let assigns = match stmt {
71            Stmt::MutateState(a) => a,
72            Stmt::Assign(a) => std::slice::from_ref(a),
73            _ => continue,
74        };
75        for a in assigns {
76            match &a.target {
77                Expr::Field { base, .. } => {
78                    mutated.insert(base.clone());
79                }
80                Expr::Var(v) if scalar_out.is_none() => {
81                    scalar_out = Some(v.clone());
82                }
83                _ => {}
84            }
85        }
86    }
87
88    let mut inputs = Vec::new();
89    for p in &f.params {
90        if Some(&p.name) == scalar_out.as_ref() {
91            continue; // produced as the return value, not an input
92        }
93        let ty = p.ty.name();
94        let struct_fields: Vec<String> = types
95            .get(ty)
96            .cloned()
97            .unwrap_or_default()
98            .into_iter()
99            .map(|(name, _)| name)
100            .collect();
101        if struct_fields.is_empty() {
102            inputs.push(InputParam::Scalar {
103                name: p.name.clone(),
104            });
105        } else {
106            inputs.push(InputParam::Struct {
107                name: p.name.clone(),
108                ty: ty.to_string(),
109                mutated: mutated.contains(&p.name),
110                fields: struct_fields.into_iter().collect(),
111            });
112        }
113    }
114
115    FuncAnalysis { inputs, scalar_out }
116}
117
118/// Generate a full Rust library source for all modules.
119///
120/// `bodies` supplies the final (verified) body for each function, keyed by
121/// `"<module>.<func>"`. A function absent from the map falls back to its body
122/// in the parsed source.
123///
124/// # Examples
125///
126/// ```
127/// use tpt_telos_parser::parse;
128/// use tpt_telos_agent::{StaticAgent, transpile_module};
129/// use tpt_telos_codegen::generate_program;
130///
131/// let src = r#"
132///     module Bank {
133///         invariant Wallet { balance >= 0 }
134///         func deposit(w: Wallet, amount: PositiveInt)
135///             ensures w.balance == old(w.balance) + amount
136///         ;
137///     }
138/// "#;
139///
140/// let modules = parse(src).unwrap();
141/// let agent = StaticAgent::new();
142/// let outcomes: Vec<_> = modules.iter()
143///     .flat_map(|m| transpile_module(m, &agent).unwrap())
144///     .collect();
145///
146/// let rust_src = generate_program(&modules, &outcomes);
147///
148/// assert!(rust_src.contains("pub struct Wallet"));
149/// assert!(rust_src.contains("pub fn deposit"));
150/// ```
151pub fn generate_program(modules: &[Module], outcomes: &[FuncOutcome]) -> String {
152    let bodies = collect_bodies(outcomes);
153    let refs: Vec<&Module> = modules.iter().collect();
154    render_rust(&refs, &bodies)
155}
156
157/// Render a Rust library for the given modules using the supplied verified
158/// bodies. Shared by [`generate_program`] and the project assembler so both
159/// emit identical Rust.
160pub(crate) fn render_rust(modules: &[&Module], bodies: &HashMap<String, Vec<Stmt>>) -> String {
161    let mut out = String::new();
162    out.push_str("// Generated by tpt-telos. Do not edit by hand.\n");
163    out.push_str("// Mathematical contracts were verified by the tpt-telos SMT core.\n");
164    out.push_str("#![allow(dead_code)]\n\n");
165
166    let mut struct_types: TypeFields = HashMap::new();
167    for m in modules {
168        collect_types(m, &mut struct_types);
169    }
170
171    for m in modules {
172        out.push_str(&generate_module(m, bodies, &struct_types));
173        out.push('\n');
174    }
175
176    out
177}
178
179/// Collect the final (verified) body for each function, keyed by function name.
180pub(crate) fn collect_bodies(outcomes: &[FuncOutcome]) -> HashMap<String, Vec<Stmt>> {
181    let mut bodies: HashMap<String, Vec<Stmt>> = HashMap::new();
182    for o in outcomes {
183        bodies.insert(o.func_name.clone(), o.final_candidate.stmts.clone());
184    }
185    bodies
186}
187
188pub(crate) fn collect_types(module: &Module, types: &mut TypeFields) {
189    // First pass: collect explicit StructDef declarations — these provide
190    // the authoritative type information for each field.
191    for item in &module.items {
192        if let Item::Struct(sd) = item {
193            let entry = types.entry(sd.name.clone()).or_default();
194            for fd in &sd.fields {
195                // Don't overwrite if already present (preserve order from first def).
196                if !entry.iter().any(|(n, _)| n == &fd.name) {
197                    entry.push((fd.name.clone(), fd.ty.clone()));
198                }
199            }
200        }
201        if let Item::Enum(ed) = item {
202            // Enum variants become unit variants in codegen; record the enum
203            // name with no fields (the router/codegen handles enum-specific logic).
204            types.entry(ed.name.clone()).or_default();
205        }
206    }
207
208    // Second pass: infer fields from usage for types without explicit StructDef.
209    let mut raw_fields: HashMap<String, BTreeSet<String>> = HashMap::new();
210    let mut field_users: HashSet<String> = HashSet::new();
211
212    let scan_expr =
213        |e: &Expr, users: &mut HashSet<String>, raw: &mut HashMap<String, BTreeSet<String>>| {
214            let mut fields: Vec<(String, String)> = Vec::new();
215            collect_fields(e, &mut fields);
216            for (base, field) in fields {
217                users.insert(base.clone());
218                raw.entry(base.clone()).or_default().insert(field);
219            }
220        };
221
222    for item in &module.items {
223        if let Item::Func(f) = item {
224            for r in &f.requires {
225                scan_expr(r, &mut field_users, &mut raw_fields);
226            }
227            for e in &f.ensures {
228                scan_expr(e, &mut field_users, &mut raw_fields);
229            }
230            for stmt in &f.body {
231                let assigns = match stmt {
232                    Stmt::MutateState(a) => a,
233                    Stmt::Assign(a) => std::slice::from_ref(a),
234                    _ => continue,
235                };
236                for a in assigns {
237                    if let Expr::Field { base, field } = &a.target {
238                        field_users.insert(base.clone());
239                        raw_fields
240                            .entry(base.clone())
241                            .or_default()
242                            .insert(field.clone());
243                    }
244                    scan_expr(&a.value, &mut field_users, &mut raw_fields);
245                }
246            }
247        }
248    }
249
250    // Re-point: a base that is a parameter of a named type is really that
251    // *type's* field.
252    for item in &module.items {
253        if let Item::Func(f) = item {
254            for p in &f.params {
255                if let Some(fields) = raw_fields.remove(&p.name) {
256                    let ty_name = p.ty.name().to_string();
257                    let entry = types.entry(ty_name).or_default();
258                    for f in fields {
259                        if !entry.iter().any(|(n, _)| n == &f) {
260                            // Infer type as Int for usage-inferred fields.
261                            entry.push((f, Type::int()));
262                        }
263                    }
264                }
265            }
266        }
267    }
268    // Any bases that were never parameters keep their raw (base-named) fields.
269    for (base, fields) in raw_fields {
270        let entry = types.entry(base).or_default();
271        for f in fields {
272            if !entry.iter().any(|(n, _)| n == &f) {
273                entry.push((f, Type::int()));
274            }
275        }
276    }
277}
278
279fn collect_fields(expr: &Expr, out: &mut Vec<(String, String)>) {
280    match expr {
281        Expr::Field { base, field } => out.push((base.clone(), field.clone())),
282        Expr::Old(e) => collect_fields(e, out),
283        Expr::Unary { expr, .. } => collect_fields(expr, out),
284        Expr::Bin { lhs, rhs, .. } => {
285            collect_fields(lhs, out);
286            collect_fields(rhs, out);
287        }
288        _ => {}
289    }
290}
291
292fn generate_module(
293    module: &Module,
294    bodies: &HashMap<String, Vec<Stmt>>,
295    types: &TypeFields,
296) -> String {
297    let route = tpt_telos_router::route(&module.attributes);
298    let is_persistent = route.storage == tpt_telos_router::StorageClass::Persistent;
299    let mut out = String::new();
300    out.push_str(&format!(
301        "// ===== module {} (target: {}, storage: {}) =====\n",
302        module.name,
303        route.target.as_str(),
304        if is_persistent {
305            "persistent"
306        } else {
307            "ephemeral"
308        }
309    ));
310
311    // Structs.
312    for (ty, fields) in types {
313        if fields.is_empty() {
314            continue;
315        }
316        if is_persistent {
317            out.push_str("#[derive(serde::Serialize, serde::Deserialize)]\n");
318        }
319        out.push_str(&format!("pub struct {} {{\n", ty));
320        for (f, fty) in fields {
321            out.push_str(&format!("    pub {}: {},\n", f, render_type(fty)));
322        }
323        out.push_str("}\n\n");
324    }
325
326    // Invariants as `impl` methods.
327    for item in &module.items {
328        if let Item::Invariant(inv) = item {
329            let conds = inv
330                .constraints
331                .iter()
332                .map(render_inv)
333                .collect::<Vec<_>>()
334                .join(" && ");
335            out.push_str(&format!(
336                "impl {} {{\n    pub fn satisfies_invariants(&self) -> bool {{\n        {}\n    }}\n}}\n\n",
337                inv.name, conds
338            ));
339        }
340    }
341
342    // Functions.
343    for item in &module.items {
344        if let Item::Func(f) = item {
345            let key = f.name.clone();
346            let stmts = bodies.get(&key).cloned().unwrap_or_else(|| f.body.clone());
347            if f.is_ejected() {
348                out.push_str(&eject::render_rust_ejected(f, &stmts, types));
349            } else {
350                out.push_str(&render_func(f, &stmts, types));
351            }
352            out.push('\n');
353        }
354    }
355
356    out
357}
358
359pub(crate) fn render_func(f: &Func, stmts: &[Stmt], types: &TypeFields) -> String {
360    let mut out = String::new();
361
362    // Doc-comment carrying the contract.
363    out.push_str(&format!("/// {}({})\n", f.name, render_params_sig(f)));
364    for r in &f.requires {
365        out.push_str(&format!("/// requires: {}\n", render_expr_doc(r)));
366    }
367    for e in &f.ensures {
368        out.push_str(&format!("/// ensures:  {}\n", render_expr_doc(e)));
369    }
370
371    // Determine mutated struct params and scalar-return outputs via the shared
372    // analysis so the Rust, Go, and FFI backends agree on the signature.
373    let analysis = analyze_func(f, stmts, types);
374    let scalar_out = analysis.scalar_out.clone();
375
376    // Build parameter list + return type.
377    let mut params = Vec::new();
378    for input in &analysis.inputs {
379        match input {
380            InputParam::Scalar { name } => {
381                params.push(format!("{}: i64", name));
382            }
383            InputParam::Struct {
384                name, ty, mutated, ..
385            } => {
386                let borrow = if *mutated { "&mut " } else { "&" };
387                params.push(format!("{}: {}{}", name, borrow, ty));
388            }
389        }
390    }
391
392    let uses_try = stmts.iter().any(stmt_contains_try);
393    let ret = if uses_try {
394        if scalar_out.is_some() {
395            " -> Result<i64, String>".to_string()
396        } else {
397            " -> Result<(), String>".to_string()
398        }
399    } else if scalar_out.is_some() {
400        " -> i64".to_string()
401    } else {
402        String::new()
403    };
404
405    out.push_str(&format!(
406        "pub fn {}({}){} {{\n",
407        f.name,
408        params.join(", "),
409        ret
410    ));
411
412    // Body.
413    for stmt in stmts {
414        match stmt {
415            Stmt::MutateState(assigns) => {
416                for a in assigns {
417                    out.push_str("    ");
418                    out.push_str(&render_assign(a));
419                    out.push_str(";\n");
420                }
421            }
422            Stmt::Assign(a) => {
423                let value = render_expr(&a.value);
424                if scalar_out.as_deref() == Some(target_var(&a.target)) {
425                    out.push_str(&format!("    let {} = {};\n", target_var(&a.target), value));
426                } else {
427                    out.push_str("    ");
428                    out.push_str(&render_assign(a));
429                    out.push_str(";\n");
430                }
431            }
432            Stmt::Let(lb) => {
433                let ty = lb
434                    .ty
435                    .as_ref()
436                    .map(|t| format!(": {}", render_type(t)))
437                    .unwrap_or_default();
438                out.push_str(&format!(
439                    "    let {}{} = {};\n",
440                    lb.name,
441                    ty,
442                    render_expr(&lb.value)
443                ));
444            }
445            Stmt::If(is) => {
446                out.push_str(&format!("    if {} {{\n", render_expr(&is.condition)));
447                for s in &is.then_body {
448                    render_stmt_indented(s, &mut out, 2);
449                }
450                out.push_str("    }");
451                if let Some(else_body) = &is.else_body {
452                    out.push_str(" else {\n");
453                    for s in else_body {
454                        render_stmt_indented(s, &mut out, 2);
455                    }
456                    out.push_str("    }");
457                }
458                out.push('\n');
459            }
460            Stmt::Match(ms) => {
461                out.push_str(&format!("    match {} {{\n", render_expr(&ms.scrutinee)));
462                for arm in &ms.arms {
463                    out.push_str(&format!("        {} => {{\n", render_pattern(&arm.pattern)));
464                    for s in &arm.body {
465                        render_stmt_indented(s, &mut out, 3);
466                    }
467                    out.push_str("        }\n");
468                }
469                out.push_str("    }\n");
470            }
471            Stmt::Return(e) => match e {
472                Some(expr) => out.push_str(&format!("    return {};\n", render_expr(expr))),
473                None => out.push_str("    return;\n"),
474            },
475        }
476    }
477
478    if let Some(outvar) = &scalar_out {
479        if uses_try {
480            out.push_str(&format!("    Ok({})\n", outvar));
481        } else {
482            out.push_str(&format!("    {}\n", outvar));
483        }
484    }
485
486    out.push_str("}\n");
487    out
488}
489
490fn stmt_contains_try(s: &Stmt) -> bool {
491    match s {
492        Stmt::MutateState(assigns) => assigns.iter().any(|a| expr_contains_try(&a.value)),
493        Stmt::Assign(a) => expr_contains_try(&a.value),
494        Stmt::Let(lb) => expr_contains_try(&lb.value),
495        Stmt::If(is) => {
496            expr_contains_try(&is.condition)
497                || is.then_body.iter().any(stmt_contains_try)
498                || is
499                    .else_body
500                    .as_ref()
501                    .is_some_and(|b| b.iter().any(stmt_contains_try))
502        }
503        Stmt::Match(ms) => {
504            expr_contains_try(&ms.scrutinee)
505                || ms.arms.iter().any(|a| a.body.iter().any(stmt_contains_try))
506        }
507        Stmt::Return(e) => e.as_ref().is_some_and(expr_contains_try),
508    }
509}
510
511fn expr_contains_try(e: &Expr) -> bool {
512    match e {
513        Expr::Try(_) => true,
514        Expr::Unary { expr, .. } => expr_contains_try(expr),
515        Expr::Bin { lhs, rhs, .. } => expr_contains_try(lhs) || expr_contains_try(rhs),
516        Expr::Call(c) => c.args.iter().any(expr_contains_try),
517        Expr::MethodCall(m) => {
518            expr_contains_try(&m.receiver) || m.args.iter().any(expr_contains_try)
519        }
520        Expr::Index(i) => expr_contains_try(&i.receiver) || expr_contains_try(&i.index),
521        Expr::If(i) => {
522            expr_contains_try(&i.condition)
523                || expr_contains_try(&i.then_expr)
524                || expr_contains_try(&i.else_expr)
525        }
526        Expr::Match(m) => {
527            expr_contains_try(&m.scrutinee) || m.arms.iter().any(|a| expr_contains_try(&a.expr))
528        }
529        Expr::Old(e) => expr_contains_try(e),
530        Expr::Forall(f) => expr_contains_try(&f.body),
531        Expr::Aggregate(a) => a.args.iter().any(expr_contains_try),
532        _ => false,
533    }
534}
535
536pub(crate) fn render_params_sig(f: &Func) -> String {
537    f.params
538        .iter()
539        .map(|p| format!("{}: {}", p.name, p.ty.name()))
540        .collect::<Vec<_>>()
541        .join(", ")
542}
543
544pub(crate) fn target_var(e: &Expr) -> &str {
545    match e {
546        Expr::Var(v) => v,
547        _ => "",
548    }
549}
550
551pub(crate) fn render_assign(a: &Assign) -> String {
552    let lhs = render_expr(&a.target);
553    let rhs = render_expr(&a.value);
554    let op = match a.op {
555        AssignOp::Set => "=",
556        AssignOp::Add => "+=",
557        AssignOp::Sub => "-=",
558    };
559    format!("{} {} {}", lhs, op, rhs)
560}
561
562pub(crate) fn render_expr(e: &Expr) -> String {
563    match e {
564        Expr::Int(n) => n.to_string(),
565        Expr::Var(v) => v.clone(),
566        Expr::Field { base, field } => format!("{}.{}", base, field),
567        Expr::Old(inner) => render_expr(inner),
568        Expr::Unary { op, expr } => match op {
569            UnOp::Neg => format!("-{}", render_expr(expr)),
570        },
571        Expr::Bin { op, lhs, rhs } => {
572            let s = match op {
573                BinOp::Add => "+",
574                BinOp::Sub => "-",
575                BinOp::Mul => "*",
576                BinOp::Div => "/",
577                BinOp::Eq => "==",
578                BinOp::Ne => "!=",
579                BinOp::Lt => "<",
580                BinOp::Le => "<=",
581                BinOp::Gt => ">",
582                BinOp::Ge => ">=",
583                BinOp::And => "&&",
584                BinOp::Or => "||",
585            };
586            format!("{} {} {}", render_expr(lhs), s, render_expr(rhs))
587        }
588        Expr::Call(c) => {
589            let args: Vec<_> = c.args.iter().map(render_expr).collect();
590            format!("{}({})", c.func, args.join(", "))
591        }
592        Expr::MethodCall(m) => {
593            let args: Vec<_> = m.args.iter().map(render_expr).collect();
594            format!(
595                "{}.{}({})",
596                render_expr(&m.receiver),
597                m.method,
598                args.join(", ")
599            )
600        }
601        Expr::Index(i) => {
602            format!("{}[{}]", render_expr(&i.receiver), render_expr(&i.index))
603        }
604        Expr::If(i) => format!(
605            "if {} {{ {} }} else {{ {} }}",
606            render_expr(&i.condition),
607            render_expr(&i.then_expr),
608            render_expr(&i.else_expr)
609        ),
610        Expr::Match(m) => {
611            let arms: Vec<_> = m
612                .arms
613                .iter()
614                .map(|a| format!("{} => {}", render_pattern(&a.pattern), render_expr(&a.expr)))
615                .collect();
616            format!(
617                "match {} {{ {} }}",
618                render_expr(&m.scrutinee),
619                arms.join(", ")
620            )
621        }
622        Expr::Try(e) => format!("{}?", render_expr(e)),
623        Expr::Forall(f) => format!(
624            "forall {}: {} {{ {} }}",
625            f.var,
626            render_type(&f.var_ty),
627            render_expr(&f.body)
628        ),
629        Expr::Aggregate(a) => {
630            let args: Vec<_> = a.args.iter().map(render_expr).collect();
631            let op = match a.op {
632                AggregateOp::Sum => "sum",
633                AggregateOp::Min => "min",
634                AggregateOp::Max => "max",
635                AggregateOp::Count => "count",
636            };
637            format!("{}({})", op, args.join(", "))
638        }
639        Expr::Range { lo, hi } => format!("{}..{}", render_expr(lo), render_expr(hi)),
640    }
641}
642
643/// Like [`render_expr`] but preserves `old(...)` so contracts read faithfully in
644/// doc-comments.
645pub(crate) fn render_expr_doc(e: &Expr) -> String {
646    match e {
647        Expr::Int(n) => n.to_string(),
648        Expr::Var(v) => v.clone(),
649        Expr::Field { base, field } => format!("{}.{}", base, field),
650        Expr::Old(inner) => format!("old({})", render_expr_doc(inner)),
651        Expr::Unary { op, expr } => match op {
652            UnOp::Neg => format!("-{}", render_expr_doc(expr)),
653        },
654        Expr::Bin { op, lhs, rhs } => {
655            let s = match op {
656                BinOp::Add => "+",
657                BinOp::Sub => "-",
658                BinOp::Mul => "*",
659                BinOp::Div => "/",
660                BinOp::Eq => "==",
661                BinOp::Ne => "!=",
662                BinOp::Lt => "<",
663                BinOp::Le => "<=",
664                BinOp::Gt => ">",
665                BinOp::Ge => ">=",
666                BinOp::And => "&&",
667                BinOp::Or => "||",
668            };
669            format!("{} {} {}", render_expr_doc(lhs), s, render_expr_doc(rhs))
670        }
671        // For doc-comments, fall back to the standard renderer for new kinds.
672        other => render_expr(other),
673    }
674}
675
676/// Render an expression inside an `impl` method body, prefixing field/var
677/// references with `self.` (invariants are written against the struct's own
678/// fields).
679fn render_inv(e: &Expr) -> String {
680    match e {
681        Expr::Int(n) => n.to_string(),
682        Expr::Var(v) => format!("self.{}", v),
683        Expr::Field { field, .. } => format!("self.{}", field),
684        Expr::Old(inner) => render_inv(inner),
685        Expr::Unary { op, expr } => match op {
686            UnOp::Neg => format!("-{}", render_inv(expr)),
687        },
688        Expr::Bin { op, lhs, rhs } => {
689            let s = match op {
690                BinOp::Add => "+",
691                BinOp::Sub => "-",
692                BinOp::Mul => "*",
693                BinOp::Div => "/",
694                BinOp::Eq => "==",
695                BinOp::Ne => "!=",
696                BinOp::Lt => "<",
697                BinOp::Le => "<=",
698                BinOp::Gt => ">",
699                BinOp::Ge => ">=",
700                BinOp::And => "&&",
701                BinOp::Or => "||",
702            };
703            format!("{} {} {}", render_inv(lhs), s, render_inv(rhs))
704        }
705        other => render_expr(other),
706    }
707}
708
709pub(crate) fn render_type(t: &Type) -> String {
710    match t {
711        Type::Named(s) => match s.as_str() {
712            "Float32" => "f32".to_string(),
713            "Float64" => "f64".to_string(),
714            "Int" => "i64".to_string(),
715            "PositiveInt" => "i64".to_string(),
716            other => other.to_string(),
717        },
718        Type::Generic(name, args) => {
719            let args: Vec<_> = args.iter().map(render_type).collect();
720            format!("{}<{}>", name, args.join(", "))
721        }
722        Type::Tuple(elems) => {
723            let elems: Vec<_> = elems.iter().map(render_type).collect();
724            format!("({})", elems.join(", "))
725        }
726        Type::Array(elem, len) => format!("[{}; {}]", render_type(elem), len),
727        Type::Slice(elem) => format!("[{}]", render_type(elem)),
728    }
729}
730
731pub(crate) fn render_pattern(p: &Pattern) -> String {
732    match p {
733        Pattern::Literal(n) => n.to_string(),
734        Pattern::Var(v) => v.clone(),
735        Pattern::Constructor(name, fields) => {
736            if fields.is_empty() {
737                name.clone()
738            } else {
739                let fields: Vec<_> = fields.iter().map(render_pattern).collect();
740                format!("{}({})", name, fields.join(", "))
741            }
742        }
743        Pattern::Wildcard => "_".to_string(),
744    }
745}
746
747fn render_stmt_indented(s: &Stmt, out: &mut String, indent: usize) {
748    let prefix = "    ".repeat(indent);
749    let rendered = match s {
750        Stmt::MutateState(assigns) => {
751            let inner: Vec<_> = assigns.iter().map(render_assign).collect();
752            format!("mutate state {{ {} }}", inner.join("; "))
753        }
754        Stmt::Assign(a) => render_assign(a),
755        Stmt::Let(lb) => {
756            let ty = lb
757                .ty
758                .as_ref()
759                .map(|t| format!(": {}", render_type(t)))
760                .unwrap_or_default();
761            format!("let {}{} = {};", lb.name, ty, render_expr(&lb.value))
762        }
763        Stmt::If(is) => {
764            let mut result = format!("if {} {{\n", render_expr(&is.condition));
765            for s in &is.then_body {
766                result.push_str(&format!("{}    ", prefix));
767                render_stmt_indented(s, &mut result, indent + 1);
768            }
769            result.push_str(&format!("{}}}", prefix));
770            if let Some(else_body) = &is.else_body {
771                result.push_str(" else {\n");
772                for s in else_body {
773                    result.push_str(&format!("{}    ", prefix));
774                    render_stmt_indented(s, &mut result, indent + 1);
775                }
776                result.push_str(&format!("{}}}", prefix));
777            }
778            result
779        }
780        Stmt::Match(ms) => {
781            let mut result = format!("match {} {{\n", render_expr(&ms.scrutinee));
782            for arm in &ms.arms {
783                result.push_str(&format!(
784                    "{}    {} => {{\n",
785                    prefix,
786                    render_pattern(&arm.pattern)
787                ));
788                for s in &arm.body {
789                    result.push_str(&format!("{}        ", prefix));
790                    render_stmt_indented(s, &mut result, indent + 2);
791                }
792                result.push_str(&format!("{}}}\n", prefix));
793            }
794            result.push_str(&format!("{}}}", prefix));
795            result
796        }
797        Stmt::Return(e) => match e {
798            Some(expr) => format!("return {};", render_expr(expr)),
799            None => "return;".to_string(),
800        },
801    };
802    out.push_str(&format!("{}{}\n", prefix, rendered));
803}
804
805// ===========================================================================
806// Unit tests for the individual codegen pieces (struct mutability, invariant
807// `impl` generation, doc-comment emission, the shared `analyze_func`, type
808// collection, and the eject hatch). These exercise the generators in isolation
809// from the full `generate_program` / `generate_project` pipeline tests in
810// `tests/gen.rs`.
811// ===========================================================================
812
813#[cfg(test)]
814mod tests {
815    use std::collections::HashMap;
816
817    use tpt_telos_parser::ast::*;
818    use tpt_telos_parser::Span;
819
820    use crate::{
821        analyze_func, collect_types, eject, generate_program, go, render_func, InputParam,
822        TypeFields,
823    };
824
825    fn t_var(v: &str) -> Expr {
826        Expr::Var(v.to_string())
827    }
828    fn t_int(n: i64) -> Expr {
829        Expr::Int(n)
830    }
831    fn t_field(base: &str, f: &str) -> Expr {
832        Expr::Field {
833            base: base.to_string(),
834            field: f.to_string(),
835        }
836    }
837    fn t_old(e: Expr) -> Expr {
838        Expr::Old(Box::new(e))
839    }
840    fn t_bin(op: BinOp, l: Expr, r: Expr) -> Expr {
841        Expr::Bin {
842            op,
843            lhs: Box::new(l),
844            rhs: Box::new(r),
845        }
846    }
847    fn t_assign(target: Expr, op: AssignOp, value: Expr) -> Assign {
848        Assign { target, op, value }
849    }
850    fn t_func(
851        name: &str,
852        params: Vec<Param>,
853        requires: Vec<Expr>,
854        ensures: Vec<Expr>,
855        body: Vec<Stmt>,
856    ) -> Func {
857        Func {
858            attributes: vec![],
859            name: name.to_string(),
860            params,
861            return_ty: None,
862            requires,
863            ensures,
864            body,
865            elided: false,
866            span: Span::default(),
867            requires_spans: vec![],
868            ensures_spans: vec![],
869        }
870    }
871
872    fn counter_types() -> TypeFields {
873        let mut m = HashMap::new();
874        m.insert("Counter".to_string(), vec![("v".to_string(), Type::int())]);
875        m
876    }
877
878    // ---- analyze_func ----
879
880    #[test]
881    fn analyze_scalar_param() {
882        let f = t_func(
883            "f",
884            vec![Param {
885                name: "x".into(),
886                ty: Type::Named("i64".into()),
887                mutability: ParamMutability::Immutable,
888            }],
889            vec![],
890            vec![],
891            vec![],
892        );
893        let a = analyze_func(&f, &f.body, &HashMap::new());
894        assert!(matches!(a.inputs[0], InputParam::Scalar { .. }));
895        assert!(a.scalar_out.is_none());
896    }
897
898    #[test]
899    fn analyze_struct_param_mutated_is_borrow_mut() {
900        let f = t_func(
901            "f",
902            vec![Param {
903                name: "c".into(),
904                ty: Type::Named("Counter".into()),
905                mutability: ParamMutability::Immutable,
906            }],
907            vec![],
908            vec![],
909            vec![Stmt::MutateState(vec![t_assign(
910                t_field("c", "v"),
911                AssignOp::Set,
912                t_int(0),
913            )])],
914        );
915        let a = analyze_func(&f, &f.body, &counter_types());
916        match &a.inputs[0] {
917            InputParam::Struct { mutated, .. } => assert!(*mutated),
918            other => panic!("expected struct param, got {other:?}"),
919        }
920    }
921
922    #[test]
923    fn analyze_struct_param_unmutated_is_borrow_ref() {
924        let f = t_func(
925            "f",
926            vec![Param {
927                name: "c".into(),
928                ty: Type::Named("Counter".into()),
929                mutability: ParamMutability::Immutable,
930            }],
931            vec![],
932            vec![],
933            vec![],
934        );
935        let a = analyze_func(&f, &f.body, &counter_types());
936        match &a.inputs[0] {
937            InputParam::Struct { mutated, .. } => assert!(!*mutated),
938            other => panic!("expected struct param, got {other:?}"),
939        }
940    }
941
942    #[test]
943    fn analyze_scalar_return_value() {
944        // A bare assignment to a parameter-named variable becomes the scalar
945        // return; that parameter is then excluded from the inputs.
946        let f = t_func(
947            "f",
948            vec![
949                Param {
950                    name: "c".into(),
951                    ty: Type::Named("Counter".into()),
952                    mutability: ParamMutability::Immutable,
953                },
954                Param {
955                    name: "result".into(),
956                    ty: Type::Named("i64".into()),
957                    mutability: ParamMutability::Immutable,
958                },
959            ],
960            vec![],
961            vec![],
962            vec![Stmt::Assign(t_assign(
963                t_var("result"),
964                AssignOp::Set,
965                t_bin(BinOp::Add, t_field("c", "v"), t_int(1)),
966            ))],
967        );
968        let a = analyze_func(&f, &f.body, &counter_types());
969        // `result` is the return, so only `c` remains as an input.
970        assert_eq!(a.inputs.len(), 1);
971        assert_eq!(a.scalar_out.as_deref(), Some("result"));
972    }
973
974    // ---- render_func ----
975
976    #[test]
977    fn render_func_emits_contract_doc_comments() {
978        let f = t_func(
979            "transfer",
980            vec![Param {
981                name: "c".into(),
982                ty: Type::Named("Counter".into()),
983                mutability: ParamMutability::Immutable,
984            }],
985            vec![t_bin(BinOp::Ge, t_field("c", "v"), t_int(0))],
986            vec![t_bin(
987                BinOp::Eq,
988                t_field("c", "v"),
989                t_bin(BinOp::Add, t_old(t_field("c", "v")), t_int(1)),
990            )],
991            vec![Stmt::MutateState(vec![t_assign(
992                t_field("c", "v"),
993                AssignOp::Set,
994                t_bin(BinOp::Add, t_field("c", "v"), t_int(1)),
995            )])],
996        );
997        let out = render_func(&f, &f.body, &counter_types());
998        assert!(out.contains("/// requires:"), "missing requires doc: {out}");
999        assert!(out.contains("/// ensures:"), "missing ensures doc: {out}");
1000        // The `old(...)` must be preserved faithfully in the doc comment.
1001        assert!(out.contains("old(c.v)"), "old() lost in doc: {out}");
1002        // The mutated struct param is threaded as `&mut`.
1003        assert!(
1004            out.contains("c: &mut Counter"),
1005            "expected &mut param: {out}"
1006        );
1007    }
1008
1009    #[test]
1010    fn render_func_emits_scalar_return() {
1011        let f = t_func(
1012            "f",
1013            vec![
1014                Param {
1015                    name: "c".into(),
1016                    ty: Type::Named("Counter".into()),
1017                    mutability: ParamMutability::Immutable,
1018                },
1019                Param {
1020                    name: "result".into(),
1021                    ty: Type::Named("i64".into()),
1022                    mutability: ParamMutability::Immutable,
1023                },
1024            ],
1025            vec![],
1026            vec![],
1027            vec![Stmt::Assign(t_assign(
1028                t_var("result"),
1029                AssignOp::Set,
1030                t_bin(BinOp::Add, t_field("c", "v"), t_int(1)),
1031            ))],
1032        );
1033        let out = render_func(&f, &f.body, &counter_types());
1034        assert!(out.contains("-> i64"), "missing return type: {out}");
1035        assert!(
1036            out.contains("let result ="),
1037            "missing return binding: {out}"
1038        );
1039        // The trailing bare expression returns the scalar.
1040        assert!(
1041            out.lines().any(|l| l.trim() == "result"),
1042            "missing return expression: {out}"
1043        );
1044    }
1045
1046    // ---- collect_types ----
1047
1048    #[test]
1049    fn collect_types_gathers_struct_fields() {
1050        let module = Module {
1051            attributes: vec![],
1052            name: "M".into(),
1053            items: vec![Item::Func(t_func(
1054                "f",
1055                vec![Param {
1056                    name: "c".into(),
1057                    ty: Type::Named("Counter".into()),
1058                    mutability: ParamMutability::Immutable,
1059                }],
1060                vec![t_bin(BinOp::Ge, t_field("c", "v"), t_int(0))],
1061                vec![],
1062                vec![Stmt::MutateState(vec![t_assign(
1063                    t_field("c", "v"),
1064                    AssignOp::Set,
1065                    t_int(0),
1066                )])],
1067            ))],
1068        };
1069        let mut types = HashMap::new();
1070        collect_types(&module, &mut types);
1071        assert_eq!(types.get("Counter").map(|s| s.len()), Some(1));
1072        assert!(types.get("Counter").unwrap().iter().any(|(n, _)| n == "v"));
1073    }
1074
1075    // ---- go::exported ----
1076
1077    #[test]
1078    fn go_exported_capitalises() {
1079        assert_eq!(go::exported("enqueue"), "Enqueue");
1080        assert_eq!(go::exported("pending"), "Pending");
1081        assert_eq!(go::exported("Queue"), "Queue");
1082    }
1083
1084    // ---- eject hatch ----
1085
1086    #[test]
1087    fn eject_renders_opaque_block_and_guard() {
1088        let mut f = t_func(
1089            "withdraw",
1090            vec![Param {
1091                name: "b".into(),
1092                ty: Type::Named("Balance".into()),
1093                mutability: ParamMutability::Immutable,
1094            }],
1095            vec![t_bin(BinOp::Ge, t_field("b", "amount"), t_int(0))],
1096            vec![t_bin(
1097                BinOp::Eq,
1098                t_field("b", "amount"),
1099                t_bin(BinOp::Sub, t_old(t_field("b", "amount")), t_int(1)),
1100            )],
1101            vec![Stmt::MutateState(vec![t_assign(
1102                t_field("b", "amount"),
1103                AssignOp::Set,
1104                t_int(0),
1105            )])],
1106        );
1107        f.attributes.push(Attribute {
1108            name: "eject".into(),
1109            args: vec![Arg::Flag("rust".into())],
1110        });
1111
1112        let mut types = HashMap::new();
1113        types.insert(
1114            "Balance".to_string(),
1115            vec![("amount".to_string(), Type::int())],
1116        );
1117        let out = eject::render_rust_ejected(&f, &f.body, &types);
1118
1119        // The trusted opaque block and the generated guard are both present.
1120        assert!(
1121            out.contains("fn withdraw_impl"),
1122            "missing opaque block: {out}"
1123        );
1124        assert!(out.contains("pub fn withdraw"), "missing guard: {out}");
1125        // The guard enforces the contracts with runtime assertions.
1126        assert!(out.contains("assert!("), "missing contract guard: {out}");
1127        // `old(...)` is captured into a snapshot local in the guard.
1128        assert!(
1129            out.contains("__old_b_amount"),
1130            "missing old snapshot: {out}"
1131        );
1132    }
1133
1134    // ---- generate_program (structural) ----
1135
1136    #[test]
1137    fn generate_program_emits_struct_and_invariant_method() {
1138        // The struct fields come from the function's field accesses (the
1139        // invariant alone does not populate the struct type).
1140        let src =
1141            "module M { invariant Counter { v >= 0 } func f(c: Counter) requires c.v >= 0 { } }";
1142        let modules = tpt_telos_parser::parse(src).unwrap();
1143        let rust = generate_program(&modules, &[]);
1144        assert!(rust.contains("pub struct Counter"));
1145        assert!(rust.contains("pub fn satisfies_invariants"));
1146        assert!(rust.contains("pub fn f"));
1147    }
1148
1149    #[test]
1150    fn persistent_storage_emits_serde_derive() {
1151        let src = "@state(persistent) module M { invariant Counter { v >= 0 } func f(c: Counter) requires c.v >= 0 { } }";
1152        let modules = tpt_telos_parser::parse(src).unwrap();
1153        let rust = generate_program(&modules, &[]);
1154        assert!(
1155            rust.contains("#[derive(serde::Serialize, serde::Deserialize)]"),
1156            "expected serde derive for persistent module:\n{rust}"
1157        );
1158    }
1159
1160    #[test]
1161    fn ephemeral_storage_no_serde_derive() {
1162        let src =
1163            "module M { invariant Counter { v >= 0 } func f(c: Counter) requires c.v >= 0 { } }";
1164        let modules = tpt_telos_parser::parse(src).unwrap();
1165        let rust = generate_program(&modules, &[]);
1166        assert!(
1167            !rust.contains("serde"),
1168            "ephemeral module should not have serde:\n{rust}"
1169        );
1170    }
1171}