logicaffeine_compile/codegen/mod.rs
1//! Code generation from LOGOS AST to Rust source code.
2//!
3//! This module transforms the parsed and type-checked LOGOS program into
4//! idiomatic Rust code. The generated code uses `logicaffeine_data` types
5//! for runtime values and integrates with the kernel for proof verification.
6//!
7//! # Pipeline Position
8//!
9//! ```text
10//! ┌─────────────────────────────────────────────────────────┐
11//! │ LOGOS Source → Lexer → Parser → AST → Analysis → HERE │
12//! └─────────────────────────────────────────────────────────┘
13//! ↓
14//! Rust Source
15//! ```
16//!
17//! # Code Generation Rules
18//!
19//! | LOGOS Statement | Rust Output |
20//! |-----------------|-------------|
21//! | `Let x be 5.` | `let x = 5;` |
22//! | `Set x to 10.` | `x = 10;` |
23//! | `Give x to y.` | `let y = x;` (move) |
24//! | `Show x to show.` | `println!("{}", x);` |
25//! | `If x > 0 then...` | `if x > 0 { ... }` |
26//! | `Repeat while x > 0...` | `while x > 0 { ... }` |
27//! | `Zone "name"...` | `{ /* zone scope */ }` |
28//! | `Mount x at "path".` | `x.mount(vfs, "path").await;` |
29//! | `Sync x on "topic".` | `x.subscribe("topic").await;` |
30//!
31//! # Key Features
32//!
33//! - **Refinement Types**: Generates `debug_assert!` for type predicates
34//! - **Policy Enforcement**: Emits capability checks for access control
35//! - **Zone Safety**: Translates memory zones to Rust scopes
36//! - **CRDT Mutability**: Uses `.set()` for LWWRegister/MVRegister fields
37//! - **Async Detection**: Adds `#[tokio::main]` when async operations are present
38//! - **VFS Detection**: Injects `get_platform_vfs()` for file operations (io_uring on Linux, NativeVfs elsewhere)
39//! - **Mount+Sync Detection**: Uses `Distributed<T>` for combined persistence/sync
40//!
41//! # Refinement Context
42//!
43//! The [`RefinementContext`] tracks type predicates across scopes:
44//!
45//! ```text
46//! Let x: { it: Int | it > 0 } be 5. ← Register constraint
47//! ↓
48//! debug_assert!(5 > 0); ← Check at definition
49//! ↓
50//! Set x to 10. ← Re-check on mutation
51//! ↓
52//! debug_assert!(10 > 0); ← Re-emit assertion
53//! ```
54//!
55//! - When a variable with a refinement type is defined, its constraint is registered
56//! - When that variable is mutated, the assertion is re-emitted
57//! - Variable types are tracked for capability resolution
58//!
59//! # Entry Point
60//!
61//! The main entry point is [`codegen_program`], which generates a complete Rust
62//! program from a list of statements.
63
64// Module declarations
65mod absent;
66pub(crate) mod affine_array;
67pub(crate) mod bigint_promote;
68pub(crate) mod bindings;
69pub(crate) mod context;
70mod control;
71pub(crate) mod detection;
72pub(crate) mod entry_guard;
73pub(crate) mod expr;
74pub(crate) mod fast_div;
75pub(crate) mod ffi;
76pub(crate) mod flow;
77pub(crate) mod hoist;
78pub(crate) mod i64_map;
79pub(crate) mod instantiation;
80pub(crate) mod lent;
81pub(crate) mod lowbits;
82pub(crate) mod marshal;
83pub(crate) mod bits;
84pub(crate) mod narrow;
85pub(crate) mod outline;
86pub(crate) mod peephole;
87pub(crate) mod probe;
88mod policy;
89pub(crate) mod program;
90pub(crate) mod rational;
91mod replay;
92pub(crate) mod stmt;
93pub(crate) mod strsearch;
94pub(crate) mod tce;
95pub(crate) mod tower;
96pub(crate) mod types;
97pub(crate) mod worklist;
98// Per-function codegen slicing for the AOT-native tier (HOTSWAP Axis-3 / P14a).
99pub(crate) mod slice;
100pub(crate) mod slice_escape;
101// AVX2 SIMD reduction of transcendental accumulator loops (math.<transcendental> caps).
102pub(crate) mod simd_reduce;
103
104// ─── External API re-exports ────────────────────────────────────────────────
105// These preserve the public API used by compile.rs, ui_bridge.rs, and test files.
106
107pub use bindings::{generate_python_bindings, generate_typescript_bindings};
108pub use context::{empty_var_caps, RefinementContext, VariableCapabilities};
109pub use detection::{collect_async_functions, collect_pipe_sender_params, collect_pipe_vars};
110pub use expr::{codegen_assertion, codegen_expr, codegen_term};
111pub use ffi::generate_c_header;
112pub use hoist::force_disable_for_test as force_disable_borrow_hoist_for_test;
113pub use marshal::codegen_native_tier_export;
114pub use program::{codegen_program, codegen_program_mapped, codegen_program_with_proven};
115pub use slice::function_slice;
116pub use stmt::codegen_stmt;
117
118// ─── Mode-B (deterministic-replay) codegen gate ─────────────────────────────
119//
120// A compile-global flag: when set, a program that runs on the scheduler lowers every task, pipe,
121// timer and select onto `logicaffeine_system::replay` — the interpreter's scheduler, ported — so the
122// binary replays the interpreter's schedule at the seed `LOGOS_SEED` names. The DEFAULT (Mode A) is
123// off, so default emission is untouched. Codegen is single-threaded per compile, so a thread-local is
124// the natural home; `compile::compile_to_rust_deterministic` sets it for the extent of one compile,
125// and `codegen_program` narrows it to the programs that use the scheduler.
126
127thread_local! {
128 static SEEDED_SELECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
129 static OBSERVED_CODEGEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
130 static EMBED_ASSETS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
131}
132
133/// Is the deterministic-replay lowering active for this compile?
134pub(crate) fn deterministic_replay_enabled() -> bool {
135 SEEDED_SELECT.with(|c| c.get())
136}
137
138/// Is the OBSERVED codegen profile active (Wave 13)? When set, observation is NOT
139/// elided at lowering and the AOT backend EMITS `logicaffeine_system::obs` calls
140/// for `Note`/`Warn`/`Record`/`During`. Default OFF — the release/elided profile,
141/// where observation is erased before codegen (byte-identical artifact, §0.7).
142pub fn observed_codegen_enabled() -> bool {
143 OBSERVED_CODEGEN.with(|c| c.get())
144}
145
146/// Run `f` with the OBSERVED codegen profile enabled, restoring the previous mode
147/// afterwards (panic-safe). Returns `f`'s result.
148pub fn with_observed_codegen<R>(f: impl FnOnce() -> R) -> R {
149 struct Restore(bool);
150 impl Drop for Restore {
151 fn drop(&mut self) {
152 OBSERVED_CODEGEN.with(|c| c.set(self.0));
153 }
154 }
155 let _guard = OBSERVED_CODEGEN.with(|c| {
156 let prev = c.get();
157 c.set(true);
158 Restore(prev)
159 });
160 f()
161}
162
163/// Is the EMBEDDED-ASSETS `Serve` lowering active for this compile (B4)? When
164/// set, the emitted `Serve` closure consults `logos_assets::lookup(&path)`
165/// BEFORE calling the handler — an embedded page/static asset shadows a backend
166/// route, exactly the dev router's precedence, so a `largo build` web binary
167/// serves the bundled site. Default OFF: a plain `Serve` program lowers
168/// byte-identically (the asset hook is inert), which the HTTP differential pins.
169pub fn embed_assets_enabled() -> bool {
170 EMBED_ASSETS.with(|c| c.get())
171}
172
173/// Run `f` with the embedded-assets `Serve` lowering enabled (B4), restoring the
174/// previous mode afterwards (panic-safe). `largo build` wraps the web-project
175/// compile in this so the generated `Serve` consults `logos_assets`.
176pub fn with_embed_assets<R>(f: impl FnOnce() -> R) -> R {
177 struct Restore(bool);
178 impl Drop for Restore {
179 fn drop(&mut self) {
180 EMBED_ASSETS.with(|c| c.set(self.0));
181 }
182 }
183 let _guard = EMBED_ASSETS.with(|c| {
184 let prev = c.get();
185 c.set(true);
186 Restore(prev)
187 });
188 f()
189}
190
191/// Run `f` with the deterministic-replay lowering enabled, restoring the previous mode
192/// afterwards (panic-safe). Returns `f`'s result.
193pub fn with_deterministic_replay<R>(f: impl FnOnce() -> R) -> R {
194 with_replay_mode(true, f)
195}
196
197/// Run `f` with the deterministic-replay lowering set to `on`, restoring the previous mode afterwards (panic-safe).
198pub(crate) fn with_replay_mode<R>(on: bool, f: impl FnOnce() -> R) -> R {
199 struct Restore(bool);
200 impl Drop for Restore {
201 fn drop(&mut self) {
202 SEEDED_SELECT.with(|c| c.set(self.0));
203 }
204 }
205 let _guard = SEEDED_SELECT.with(|c| {
206 let prev = c.get();
207 c.set(on);
208 Restore(prev)
209 });
210 f()
211}
212
213// ─── Internal cross-module re-exports ───────────────────────────────────────
214// These allow sibling submodules to use `use super::item` for items
215// that moved out of mod.rs into submodule files.
216
217pub(crate) use expr::codegen_expr_with_async;
218pub(crate) use ffi::{
219 classify_type_for_c_abi, codegen_c_accessors, collect_c_export_ref_structs, CAbiClass,
220};
221pub(crate) use peephole::{
222 try_emit_for_range_pattern, try_emit_prefix_reverse, try_emit_swap_pattern,
223 try_emit_vec_fill_pattern,
224};
225pub(crate) use stmt::{
226 get_root_identifier, has_copy_element_type, has_copy_value_type, is_copy_type,
227};
228pub(crate) use types::field_is_boxed;
229
230/// Check if a name is a Rust keyword (needs `r#` escaping in generated code).
231pub(crate) fn is_rust_keyword(name: &str) -> bool {
232 matches!(
233 name,
234 "as" | "async"
235 | "await"
236 | "break"
237 | "const"
238 | "continue"
239 | "crate"
240 | "dyn"
241 | "else"
242 | "enum"
243 | "extern"
244 | "false"
245 | "fn"
246 | "for"
247 | "if"
248 | "impl"
249 | "in"
250 | "let"
251 | "loop"
252 | "match"
253 | "mod"
254 | "move"
255 | "mut"
256 | "pub"
257 | "ref"
258 | "return"
259 | "self"
260 | "Self"
261 | "static"
262 | "struct"
263 | "super"
264 | "trait"
265 | "true"
266 | "type"
267 | "unsafe"
268 | "use"
269 | "where"
270 | "while"
271 | "abstract"
272 | "become"
273 | "box"
274 | "do"
275 | "final"
276 | "macro"
277 | "override"
278 | "priv"
279 | "try"
280 | "typeof"
281 | "unsized"
282 | "virtual"
283 | "yield"
284 )
285}
286
287/// A LOGOS name as a Rust identifier: a keyword becomes a raw identifier (`move` → `r#move`), and the
288/// four keywords a raw identifier cannot spell (`self`, `Self`, `crate`, `super`) take a reserved
289/// compiler prefix (`__logos_self`). Every position a name reaches Rust in — a variable, a function, a
290/// record or variant field — goes through this one spelling, so a declaration and every use agree.
291pub(crate) fn escape_rust_ident(name: &str) -> String {
292 match name {
293 "self" | "Self" | "crate" | "super" => format!("__logos_{name}"),
294 _ if is_rust_keyword(name) => format!("r#{name}"),
295 _ => name.to_string(),
296 }
297}
298
299/// A call-site ABI role a function parameter can carry, keyed by parameter index.
300/// A single function may play SEVERAL at once — the canonical case is a readonly
301/// `Seq` param (de-Rc'd to `&[T]`) alongside a value-semantics `mutable` collection
302/// param (passed as `&LogosSeq`/`&LogosMap`).
303#[derive(Clone, Copy)]
304pub(crate) enum FnRole {
305 /// Readonly borrow (`&[T]`) — the `borrow_params_map` opt.
306 Borrow,
307 /// Element-mutating borrow (`&mut [T]`) — the `mut_borrow_params_map` opt.
308 MutBorrow,
309 /// Value-semantics `mutable` collection (`&LogosSeq`/`&LogosMap`).
310 ValueMutable,
311}
312
313/// Pack the per-parameter role index sets a function plays into ONE `variable_types`
314/// slot. The slot is single-valued, so registering each role as its own
315/// `fn_borrow:` / `fn_value_mutable:` string used to make them clobber each other —
316/// a function with both a readonly-borrow param and a `mutable` param would keep
317/// only the last-registered role, and every call site then mis-lowered the other
318/// (cloning an owned `LogosSeq` into a `&[T]` slot). This keeps all roles together.
319pub(crate) fn encode_fn_roles(
320 borrow: &std::collections::HashSet<usize>,
321 mut_borrow: &std::collections::HashSet<usize>,
322 value_mutable: &std::collections::HashSet<usize>,
323) -> String {
324 fn csv(s: &std::collections::HashSet<usize>) -> String {
325 let mut v: Vec<usize> = s.iter().copied().collect();
326 v.sort_unstable();
327 v.iter()
328 .map(|i| i.to_string())
329 .collect::<Vec<_>>()
330 .join(",")
331 }
332 format!(
333 "fn_roles|b={}|m={}|v={}",
334 csv(borrow),
335 csv(mut_borrow),
336 csv(value_mutable)
337 )
338}
339
340/// The parameter indices for one [`FnRole`] out of a slot written by
341/// [`encode_fn_roles`]. Empty when the slot is absent or is an ordinary variable
342/// type rather than a role encoding.
343pub(crate) fn fn_role_indices(
344 encoded: Option<&String>,
345 role: FnRole,
346) -> std::collections::HashSet<usize> {
347 let empty = std::collections::HashSet::new();
348 let Some(rest) = encoded.and_then(|s| s.strip_prefix("fn_roles|")) else {
349 return empty;
350 };
351 let key = match role {
352 FnRole::Borrow => "b=",
353 FnRole::MutBorrow => "m=",
354 FnRole::ValueMutable => "v=",
355 };
356 for section in rest.split('|') {
357 if let Some(csv) = section.strip_prefix(key) {
358 return csv.split(',').filter_map(|i| i.parse().ok()).collect();
359 }
360 }
361 empty
362}
363
364/// True when a `variable_types` slot is a [`encode_fn_roles`] encoding (a function
365/// symbol's ABI role) rather than an ordinary variable type.
366pub(crate) fn is_fn_role_slot(ty: &str) -> bool {
367 ty.starts_with("fn_roles|")
368}
369
370/// Generated-project metadata is a file prologue, so program text cannot select runtime requirements. A program
371/// whose failures a runtime boundary catches — a replay scheduler's task, a served request — opens with this line,
372/// and its release build unwinds so the boundary can catch them.
373pub(crate) const UNWIND_PROFILE_HEADER: &str = "// LOGOS Rust runtime: unwind-v1\n";
374
375/// The panic strategy of a generated program's release build: `unwind` for one that opens with
376/// `UNWIND_PROFILE_HEADER`, `abort` for every other, whose failure hook reports and ends it. Every project writer
377/// takes it from here.
378pub fn release_panic_strategy(rust_code: &str) -> &'static str {
379 if rust_code.starts_with(UNWIND_PROFILE_HEADER) {
380 "unwind"
381 } else {
382 "abort"
383 }
384}