1pub mod static_agent;
23
24#[cfg(feature = "llm")]
25pub mod llm_agent;
26
27pub use static_agent::{synthesize_from_ensures, StaticAgent};
28
29use tpt_telos_ir::{extract, VerificationProblem};
30use tpt_telos_parser::ast::*;
31use tpt_telos_verifier::{counterexample, verify, Model, VerificationResult};
32
33#[derive(Clone)]
50pub struct FuncSpec {
51 pub module_attrs: Vec<Attribute>,
52 pub func: Func,
53}
54
55impl FuncSpec {
56 pub fn new(module_attrs: Vec<Attribute>, func: Func) -> Self {
57 FuncSpec { module_attrs, func }
58 }
59}
60
61#[derive(Clone, PartialEq, Eq)]
73pub struct Candidate {
74 pub stmts: Vec<Stmt>,
75}
76
77pub trait CodeAgent {
81 fn name(&self) -> &str;
83
84 fn generate(&self, spec: &FuncSpec) -> Result<Candidate, String>;
86
87 fn rewrite(&self, spec: &FuncSpec, prev: &Candidate, ce: &Model) -> Result<Candidate, String>;
91}
92
93#[derive(Clone)]
95pub struct LoopStep {
96 pub iteration: usize,
97 pub action: String,
98 pub candidate: Candidate,
99 pub passed: bool,
100 pub counterexample: Option<Model>,
101}
102
103#[derive(Clone)]
105pub struct FuncOutcome {
106 pub func_name: String,
107 pub target: tpt_telos_router::Target,
108 pub agent: String,
109 pub iterations: Vec<LoopStep>,
110 pub final_candidate: Candidate,
111 pub problem: VerificationProblem,
112 pub result: VerificationResult,
113 pub verified: bool,
114}
115
116const MAX_ITERS: usize = 8;
117
118fn problem_for(
121 module: &Module,
122 func_idx: usize,
123 stmts: &[Stmt],
124) -> Result<VerificationProblem, String> {
125 let mut module = module.clone();
126 module.items[func_idx] = match &module.items[func_idx] {
127 Item::Func(f) => {
128 let mut f = f.clone();
129 f.body = stmts.to_vec();
130 f.elided = false;
131 Item::Func(f)
132 }
133 other => other.clone(),
134 };
135 let problems = extract(&[module.clone()])?;
136 problems
137 .into_iter()
138 .find(|p| p.func_name == module.items[func_idx].func_name())
139 .ok_or_else(|| {
140 format!(
141 "internal error: no verification problem extracted for function '{}'",
142 module.items[func_idx].func_name()
143 )
144 })
145}
146
147fn find_counterexample(
148 problem: &VerificationProblem,
149 result: &VerificationResult,
150) -> Option<Model> {
151 for (concl, check) in problem.conclusions.iter().zip(result.checks.iter()) {
152 if !check.passed {
153 if let Some(m) = counterexample(&problem.premises, &concl.constraint) {
154 return Some(m);
155 }
156 }
157 }
158 None
159}
160
161pub fn transpile_func(
187 module: &Module,
188 func_idx: usize,
189 agent: &dyn CodeAgent,
190) -> Result<FuncOutcome, String> {
191 let func = match &module.items[func_idx] {
192 Item::Func(f) => f.clone(),
193 _ => return Err("transpile_func requires a function item".into()),
194 };
195 let spec = FuncSpec::new(module.attributes.clone(), func.clone());
196 let target = tpt_telos_router::route(&module.attributes).target;
197
198 let mut candidate = if func.elided || func.body.is_empty() {
199 agent.generate(&spec)?
200 } else {
201 Candidate {
203 stmts: func.body.clone(),
204 }
205 };
206
207 let mut iterations = Vec::new();
208
209 for iter in 0..MAX_ITERS {
210 let problem = problem_for(module, func_idx, &candidate.stmts)?;
211 let result = verify(&problem);
212 let passed = result.all_passed;
213
214 iterations.push(LoopStep {
215 iteration: iter,
216 action: if iter == 0 {
217 "generate".to_string()
218 } else {
219 "rewrite".to_string()
220 },
221 candidate: candidate.clone(),
222 passed,
223 counterexample: if passed {
224 None
225 } else {
226 find_counterexample(&problem, &result)
227 },
228 });
229
230 if passed {
231 return Ok(FuncOutcome {
232 func_name: func.name.clone(),
233 target,
234 agent: agent.name().to_string(),
235 iterations,
236 final_candidate: candidate,
237 problem,
238 result,
239 verified: true,
240 });
241 }
242
243 let ce = find_counterexample(&problem, &result).unwrap_or_default();
244 let repaired = agent.rewrite(&spec, &candidate, &ce)?;
245 if repaired.stmts == candidate.stmts {
246 let syn = static_agent::synthesize_from_ensures(&spec);
249 let syn_problem = problem_for(module, func_idx, &syn.stmts)?;
250 let syn_result = verify(&syn_problem);
251 iterations.push(LoopStep {
252 iteration: iter + 1,
253 action: "synthesize-from-ensures".to_string(),
254 candidate: syn.clone(),
255 passed: syn_result.all_passed,
256 counterexample: None,
257 });
258 return Ok(FuncOutcome {
259 func_name: func.name.clone(),
260 target,
261 agent: agent.name().to_string(),
262 iterations,
263 final_candidate: syn,
264 problem: syn_problem,
265 result: syn_result.clone(),
266 verified: syn_result.all_passed,
267 });
268 }
269 candidate = repaired;
270 }
271
272 let problem = problem_for(module, func_idx, &candidate.stmts)?;
274 let result = verify(&problem);
275 Ok(FuncOutcome {
276 func_name: func.name.clone(),
277 target,
278 agent: agent.name().to_string(),
279 iterations,
280 final_candidate: candidate,
281 problem,
282 result,
283 verified: false,
284 })
285}
286
287pub fn transpile_module(
311 module: &Module,
312 agent: &dyn CodeAgent,
313) -> Result<Vec<FuncOutcome>, String> {
314 let mut out = Vec::new();
315 for (idx, item) in module.items.iter().enumerate() {
316 if let Item::Func(_) = item {
317 out.push(transpile_func(module, idx, agent)?);
318 }
319 }
320 Ok(out)
321}
322
323pub fn render_candidate(c: &Candidate) -> String {
346 let mut s = String::new();
347 for stmt in &c.stmts {
348 s.push_str(&render_stmt(stmt));
349 s.push('\n');
350 }
351 s
352}
353
354fn render_stmt(s: &Stmt) -> String {
355 match s {
356 Stmt::MutateState(assigns) => {
357 let inner = assigns
358 .iter()
359 .map(render_assign)
360 .collect::<Vec<_>>()
361 .join("\n");
362 format!("mutate state {{\n{}\n}}", indent(&inner))
363 }
364 Stmt::Assign(a) => render_assign(a),
365 Stmt::Let(lb) => {
366 let ty = lb
367 .ty
368 .as_ref()
369 .map(|t| format!(": {}", render_type(t)))
370 .unwrap_or_default();
371 format!("let {}{} = {};", lb.name, ty, pretty(&lb.value))
372 }
373 Stmt::If(is) => {
374 let mut out = format!("if {} {{\n", pretty(&is.condition));
375 for s in &is.then_body {
376 out.push_str(&indent(&render_stmt(s)));
377 out.push('\n');
378 }
379 out.push('}');
380 if let Some(else_body) = &is.else_body {
381 out.push_str(" else {\n");
382 for s in else_body {
383 out.push_str(&indent(&render_stmt(s)));
384 out.push('\n');
385 }
386 out.push('}');
387 }
388 out
389 }
390 Stmt::Match(ms) => {
391 let mut out = format!("match {} {{\n", pretty(&ms.scrutinee));
392 for arm in &ms.arms {
393 out.push_str(&format!(" {} => {{\n", render_pattern(&arm.pattern)));
394 for s in &arm.body {
395 out.push_str(&indent(&render_stmt(s)));
396 out.push('\n');
397 }
398 out.push_str(" }\n");
399 }
400 out.push('}');
401 out
402 }
403 Stmt::Return(e) => match e {
404 Some(expr) => format!("return {};", pretty(expr)),
405 None => "return;".to_string(),
406 },
407 }
408}
409
410fn render_assign(a: &Assign) -> String {
411 let op = match a.op {
412 AssignOp::Set => "=",
413 AssignOp::Add => "+=",
414 AssignOp::Sub => "-=",
415 };
416 format!("{} {} {};", pretty(&a.target), op, pretty(&a.value))
417}
418
419fn pretty(e: &Expr) -> String {
420 match e {
421 Expr::Int(n) => n.to_string(),
422 Expr::Var(v) => v.clone(),
423 Expr::Field { base, field } => format!("{}.{}", base, field),
424 Expr::Old(inner) => format!("old({})", pretty(inner)),
425 Expr::Unary { op, expr } => match op {
426 UnOp::Neg => format!("-{}", pretty(expr)),
427 },
428 Expr::Bin { op, lhs, rhs } => {
429 let s = match op {
430 BinOp::Add => "+",
431 BinOp::Sub => "-",
432 BinOp::Mul => "*",
433 BinOp::Div => "/",
434 BinOp::Eq => "==",
435 BinOp::Ne => "!=",
436 BinOp::Lt => "<",
437 BinOp::Le => "<=",
438 BinOp::Gt => ">",
439 BinOp::Ge => ">=",
440 BinOp::And => "&&",
441 BinOp::Or => "||",
442 };
443 format!("{} {} {}", pretty(lhs), s, pretty(rhs))
444 }
445 Expr::Call(c) => {
446 let args: Vec<_> = c.args.iter().map(pretty).collect();
447 format!("{}({})", c.func, args.join(", "))
448 }
449 Expr::MethodCall(m) => {
450 let args: Vec<_> = m.args.iter().map(pretty).collect();
451 format!("{}.{}({})", pretty(&m.receiver), m.method, args.join(", "))
452 }
453 Expr::Index(i) => format!("{}[{}]", pretty(&i.receiver), pretty(&i.index)),
454 Expr::If(i) => format!(
455 "if {} {{ {} }} else {{ {} }}",
456 pretty(&i.condition),
457 pretty(&i.then_expr),
458 pretty(&i.else_expr)
459 ),
460 Expr::Match(m) => {
461 let arms: Vec<_> = m
462 .arms
463 .iter()
464 .map(|a| format!("... => {}", pretty(&a.expr)))
465 .collect();
466 format!("match {} {{ {} }}", pretty(&m.scrutinee), arms.join(", "))
467 }
468 Expr::Try(e) => format!("{}?", pretty(e)),
469 Expr::Forall(f) => format!(
470 "forall {}: {} {{ {} }}",
471 f.var,
472 f.var_ty.name(),
473 pretty(&f.body)
474 ),
475 Expr::Aggregate(a) => {
476 let args: Vec<_> = a.args.iter().map(pretty).collect();
477 let op = match a.op {
478 AggregateOp::Sum => "sum",
479 AggregateOp::Min => "min",
480 AggregateOp::Max => "max",
481 AggregateOp::Count => "count",
482 };
483 format!("{}({})", op, args.join(", "))
484 }
485 Expr::Range { lo, hi } => format!("{}..{}", pretty(lo), pretty(hi)),
486 }
487}
488
489fn render_type(t: &Type) -> String {
490 match t {
491 Type::Named(s) => match s.as_str() {
492 "Float32" => "f32".to_string(),
493 "Float64" => "f64".to_string(),
494 "Int" => "i64".to_string(),
495 "PositiveInt" => "i64".to_string(),
496 other => other.to_string(),
497 },
498 Type::Generic(name, args) => {
499 let args: Vec<_> = args.iter().map(render_type).collect();
500 format!("{}<{}>", name, args.join(", "))
501 }
502 Type::Tuple(elems) => {
503 let elems: Vec<_> = elems.iter().map(render_type).collect();
504 format!("({})", elems.join(", "))
505 }
506 Type::Array(elem, len) => format!("[{}; {}]", render_type(elem), len),
507 Type::Slice(elem) => format!("[{}]", render_type(elem)),
508 }
509}
510
511fn render_pattern(p: &Pattern) -> String {
512 match p {
513 Pattern::Literal(n) => n.to_string(),
514 Pattern::Var(v) => v.clone(),
515 Pattern::Constructor(name, fields) => {
516 if fields.is_empty() {
517 name.clone()
518 } else {
519 let fields: Vec<_> = fields.iter().map(render_pattern).collect();
520 format!("{}({})", name, fields.join(", "))
521 }
522 }
523 Pattern::Wildcard => "_".to_string(),
524 }
525}
526
527fn indent(s: &str) -> String {
528 s.lines()
529 .map(|line| {
530 if line.is_empty() {
531 line.to_string()
532 } else {
533 format!(" {}", line)
534 }
535 })
536 .collect::<Vec<_>>()
537 .join("\n")
538}