tpt_telos_codegen/project.rs
1//! Dual-backend project assembly for tpt-telos (Phase 3).
2//!
3//! [`generate_project`] routes each module to the Rust or Go backend, generates
4//! the corresponding sources, and -- when a program spans *both* backends --
5//! emits the automatic FFI bridge so the two halves can call each other with no
6//! hand-written glue. The result is a ready-to-build project tree:
7//!
8//! ```text
9//! <out>/
10//! rust/Cargo.toml
11//! rust/src/lib.rs
12//! rust/src/ffi.rs (dual-backend only)
13//! go/go.mod
14//! go/service.go
15//! go/ffi.go (dual-backend only)
16//! go/telos_ffi.h (dual-backend only)
17//! ```
18
19use std::io;
20use std::path::Path;
21
22use tpt_telos_agent::FuncOutcome;
23use tpt_telos_parser::ast::*;
24use tpt_telos_router::{RoutingDiagnostic, Target};
25
26use crate::{collect_bodies, ffi, go, python, render_rust};
27
28/// Go package name used for the generated service and its FFI shims.
29pub const GO_PACKAGE: &str = "gosvc";
30
31/// Crate name used for the generated Rust backend library and its compiled
32/// artifacts (`lib<RUST_CRATE_NAME>.rlib` / `lib<RUST_CRATE_NAME>.a`). Promoted
33/// to a `pub const` so consumers (e.g. `tpt-telos-sdk`) can locate the artifact
34/// bytes without hardcoding the string.
35pub const RUST_CRATE_NAME: &str = "generated_rust";
36
37/// A single generated file, addressed by a path relative to the project root.
38///
39/// # Examples
40///
41/// A `GeneratedFile` is produced by [`generate_project`]; you typically inspect
42/// it by path:
43///
44/// ```
45/// use tpt_telos_parser::parse;
46/// use tpt_telos_agent::{StaticAgent, transpile_module};
47/// use tpt_telos_codegen::generate_project;
48///
49/// let src = r#"
50/// module Bank {
51/// invariant Wallet { balance >= 0 }
52/// func deposit(w: Wallet, amount: PositiveInt)
53/// ensures w.balance == old(w.balance) + amount
54/// ;
55/// }
56/// "#;
57///
58/// let modules = parse(src).unwrap();
59/// let outcomes: Vec<_> = modules.iter()
60/// .flat_map(|m| transpile_module(m, &StaticAgent::new()).unwrap())
61/// .collect();
62///
63/// let project = generate_project(&modules, &outcomes).unwrap();
64/// let lib = project.files.iter().find(|f| f.path == "rust/src/lib.rs").unwrap();
65/// assert!(lib.contents.contains("pub struct Wallet"));
66/// ```
67#[derive(Debug, Clone)]
68pub struct GeneratedFile {
69 pub path: String,
70 pub contents: String,
71}
72
73/// A fully assembled dual-backend project.
74#[derive(Debug, Clone)]
75pub struct Project {
76 pub files: Vec<GeneratedFile>,
77 pub has_rust: bool,
78 pub has_go: bool,
79 pub has_ffi: bool,
80 pub has_python: bool,
81 /// Routing diagnostics (e.g. real_time + Go conflicts) collected during
82 /// module routing. Callers should surface these as warnings.
83 pub diagnostics: Vec<RoutingDiagnostic>,
84}
85
86impl Project {
87 /// Write every generated file under `root`, creating directories as needed.
88 ///
89 /// # Examples
90 ///
91 /// ```no_run
92 /// use tpt_telos_parser::parse;
93 /// use tpt_telos_agent::{StaticAgent, transpile_module};
94 /// use tpt_telos_codegen::generate_project;
95 ///
96 /// let src = r#"
97 /// module Bank {
98 /// invariant Wallet { balance >= 0 }
99 /// func deposit(w: Wallet, amount: PositiveInt)
100 /// ensures w.balance == old(w.balance) + amount
101 /// ;
102 /// }
103 /// "#;
104 ///
105 /// let modules = parse(src).unwrap();
106 /// let outcomes: Vec<_> = modules.iter()
107 /// .flat_map(|m| transpile_module(m, &StaticAgent::new()).unwrap())
108 /// .collect();
109 ///
110 /// let project = generate_project(&modules, &outcomes).unwrap();
111 /// project.write(std::path::Path::new("/tmp/my_bank_project")).unwrap();
112 /// // Writes rust/src/lib.rs, rust/Cargo.toml, and go/service.go etc.
113 /// ```
114 pub fn write(&self, root: &Path) -> io::Result<()> {
115 for f in &self.files {
116 let full = root.join(&f.path);
117 if let Some(parent) = full.parent() {
118 std::fs::create_dir_all(parent)?;
119 }
120 std::fs::write(&full, &f.contents)?;
121 }
122 Ok(())
123 }
124}
125
126/// Assemble the dual-backend project for a program.
127///
128/// Returns `Err` if any FFI-boundary parameter type is unsupported (e.g. a
129/// float, bool, string, array, or slice). All-integer programs always succeed.
130///
131/// # Examples
132///
133/// ```
134/// use tpt_telos_parser::parse;
135/// use tpt_telos_agent::{StaticAgent, transpile_module};
136/// use tpt_telos_codegen::generate_project;
137///
138/// let src = r#"
139/// module Bank {
140/// invariant Wallet { balance >= 0 }
141/// func deposit(w: Wallet, amount: PositiveInt)
142/// ensures w.balance == old(w.balance) + amount
143/// ;
144/// }
145/// "#;
146///
147/// let modules = parse(src).unwrap();
148/// let outcomes: Vec<_> = modules.iter()
149/// .flat_map(|m| transpile_module(m, &StaticAgent::new()).unwrap())
150/// .collect();
151///
152/// let project = generate_project(&modules, &outcomes).unwrap();
153/// // A Rust-only program (no @boundary(network_io) etc.) only produces Rust output.
154/// assert!(project.has_rust);
155/// assert!(!project.has_ffi);
156/// ```
157pub fn generate_project(modules: &[Module], outcomes: &[FuncOutcome]) -> Result<Project, String> {
158 let bodies = collect_bodies(outcomes);
159
160 // Route every module and collect diagnostics.
161 let mut all_diagnostics: Vec<RoutingDiagnostic> = Vec::new();
162 let mut rust_mods: Vec<&Module> = Vec::new();
163 let mut go_mods: Vec<&Module> = Vec::new();
164 let mut py_mods: Vec<&Module> = Vec::new();
165 for m in modules {
166 let (route, diags) = tpt_telos_router::route_checked(&m.attributes, &m.name);
167 all_diagnostics.extend(diags);
168 match route.target {
169 Target::Rust => rust_mods.push(m),
170 Target::Go => go_mods.push(m),
171 Target::Python => py_mods.push(m),
172 }
173 }
174
175 let has_rust = !rust_mods.is_empty();
176 let has_go = !go_mods.is_empty();
177 let has_python = !py_mods.is_empty();
178 let has_ffi = has_rust && has_go;
179
180 let mut files = Vec::new();
181
182 if has_rust {
183 let mut lib = render_rust(&rust_mods, &bodies);
184 if has_ffi {
185 lib.push_str("\npub mod ffi;\n");
186 }
187 files.push(GeneratedFile {
188 path: "rust/src/lib.rs".to_string(),
189 contents: lib,
190 });
191 files.push(GeneratedFile {
192 path: "rust/Cargo.toml".to_string(),
193 contents: rust_cargo_toml(has_ffi),
194 });
195 }
196
197 if has_go {
198 let service = go::generate_go_package(&go_mods, &bodies, GO_PACKAGE);
199 files.push(GeneratedFile {
200 path: "go/service.go".to_string(),
201 contents: service,
202 });
203 files.push(GeneratedFile {
204 path: "go/go.mod".to_string(),
205 contents: go_mod(),
206 });
207 }
208
209 if has_ffi {
210 let bridge = ffi::generate_bridge(modules, &bodies, GO_PACKAGE)?;
211 files.push(GeneratedFile {
212 path: "rust/src/ffi.rs".to_string(),
213 contents: bridge.rust,
214 });
215 files.push(GeneratedFile {
216 path: "go/ffi.go".to_string(),
217 contents: bridge.go,
218 });
219 files.push(GeneratedFile {
220 path: "go/telos_ffi.h".to_string(),
221 contents: bridge.header,
222 });
223 }
224
225 if has_python {
226 // Detect JAX flag for any Python-target module.
227 let use_jax = py_mods.iter().any(|m| {
228 m.attributes.iter().any(|a| {
229 a.name == "boundary"
230 && a.args
231 .iter()
232 .any(|arg| matches!(arg, tpt_telos_parser::ast::Arg::Flag(f) if f == "jax"))
233 })
234 });
235 let service = python::generate_python_package(&py_mods, &bodies, use_jax);
236 files.push(GeneratedFile {
237 path: "python/service.py".to_string(),
238 contents: service,
239 });
240 let req = if use_jax {
241 "jax\n"
242 } else {
243 "# No runtime dependencies\n"
244 };
245 files.push(GeneratedFile {
246 path: "python/requirements.txt".to_string(),
247 contents: req.to_string(),
248 });
249 }
250
251 Ok(Project {
252 files,
253 has_rust,
254 has_go,
255 has_ffi,
256 has_python,
257 diagnostics: all_diagnostics,
258 })
259}
260
261fn rust_cargo_toml(dual: bool) -> String {
262 // A dual-backend crate is built as a staticlib (for linking into the Go
263 // binary) plus an rlib (so `cargo build` type-checks standalone).
264 let lib_section = if dual {
265 "\n[lib]\ncrate-type = [\"staticlib\", \"rlib\"]\n"
266 } else {
267 ""
268 };
269 format!(
270 "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n{lib}\n[dependencies]\n\n[workspace]\n",
271 RUST_CRATE_NAME,
272 lib = lib_section
273 )
274}
275
276fn go_mod() -> String {
277 format!("module telos/{}\n\ngo 1.21\n", GO_PACKAGE)
278}