Skip to main content

logicaffeine_compile/extraction/
mod.rs

1//! Program extraction from kernel terms to Rust.
2//!
3//! This module compiles verified kernel terms into executable Rust source code.
4//!
5//! # Extraction Rules
6//!
7//! | Kernel Term | Rust Output |
8//! |-------------|-------------|
9//! | Inductive | `enum Name { Ctor(Args...) }` |
10//! | Fix + Lambdas | `fn name(args) -> Ret { body }` |
11//! | Match | `match disc { Name::Ctor(vars) => body }` |
12//! | App | `func(arg)` |
13//!
14//! # Structural Honesty
15//!
16//! We extract types exactly as defined, with no optimization.
17//! For example, `Nat` becomes `enum Nat { Zero, Succ(Box<Nat>) }`.
18//! This guarantees that the extracted code is isomorphic to the verified logic.
19
20mod codegen;
21mod collector;
22mod error;
23pub mod fol_model;
24pub mod verilog;
25
26pub use codegen::{emit_property_check, emit_value, primitive_rust_type, rust_global};
27pub use collector::{is_extractable, is_logical_type};
28pub use error::ExtractError;
29
30use codegen::CodeGen;
31use collector::collect_dependencies;
32use logicaffeine_kernel::Context;
33use std::collections::HashSet;
34
35/// Extract a program rooted at the given entry point.
36///
37/// Returns Rust source code as a string.
38///
39/// # Arguments
40///
41/// * `ctx` - The kernel context containing definitions and inductives
42/// * `entry` - The name of the entry point to extract
43///
44/// # Errors
45///
46/// Returns an error if the entry point is not found or cannot be extracted.
47pub fn extract_program(ctx: &Context, entry: &str) -> Result<String, ExtractError> {
48    extract_programs(ctx, &[entry])
49}
50
51/// Extract a program rooted at several entry points into one Rust module.
52///
53/// Returns Rust source code as a string. The transitive dependencies of every
54/// entry are unioned, topologically sorted once, and emitted through a single
55/// `CodeGen`, so shared dependencies (e.g. a `Nat` enum used by both `add` and
56/// `double`) are emitted exactly once.
57///
58/// # Arguments
59///
60/// * `ctx` - The kernel context containing definitions and inductives
61/// * `entries` - The names of the entry points to extract
62///
63/// # Errors
64///
65/// Returns an error if any entry point is not found or cannot be extracted.
66pub fn extract_programs(ctx: &Context, entries: &[&str]) -> Result<String, ExtractError> {
67    // 1. Collect the union of all dependencies, validating each entry exists.
68    let mut all_deps: HashSet<String> = HashSet::new();
69    for entry in entries {
70        if !ctx.is_inductive(entry) && !ctx.is_definition(entry) && !ctx.is_constructor(entry) {
71            return Err(ExtractError::NotFound((*entry).to_string()));
72        }
73        all_deps.extend(collect_dependencies(ctx, entry));
74    }
75
76    // 2. Topologically sort (inductives first, then definitions)
77    let sorted = topological_sort(ctx, &all_deps);
78
79    // 3. Generate code through a single CodeGen so shared deps dedup.
80    let mut codegen = CodeGen::new(ctx);
81    for name in &sorted {
82        if ctx.is_inductive(name) {
83            // A PRIMITIVE has no enum form: `Int`, `Float`, `Text`, `Bool`, … are represented
84            // directly by their Rust counterparts (`primitive_rust_type`) at every use site,
85            // so emitting a declaration for one would be a second, incompatible spelling of a
86            // type the output already has. The test used to be "declared with no
87            // constructors", which was true of `Int` only while it was opaque; once it became
88            // a real inductive, extraction started emitting `enum Int { Int_ofNat(Nat), … }`
89            // beside the `i64` it maps `Int` to at every use.
90            if primitive_rust_type(name).is_none() && !ctx.get_constructors(name).is_empty() {
91                codegen.emit_inductive(name)?;
92            }
93        } else if ctx.is_definition(name) {
94            // The prelude's arithmetic is OPAQUE to extraction: `add`/`sub`/… at
95            // `Int -> Int -> Int` lower to a Rust OPERATOR at every use site, so there is
96            // nothing to emit for them — and emitting one anyway produces
97            // `pub fn add() -> … { Int_add }`, a nullary function returning a name from the
98            // structural integer tower that is deliberately not emitted beside it. They only
99            // became emittable at all when `Int` turned into a real inductive and these names
100            // stopped being bodyless declarations.
101            if codegen::arith_builtin_operator(ctx, name).is_none() {
102                codegen.emit_definition(name)?;
103            }
104        }
105        // Skip constructors (emitted with their inductive)
106    }
107
108    Ok(codegen.finish())
109}
110
111/// Topologically sort dependencies.
112///
113/// Inductives come first, then definitions in dependency order.
114fn topological_sort(ctx: &Context, deps: &HashSet<String>) -> Vec<String> {
115    let mut inductives = Vec::new();
116    let mut definitions = Vec::new();
117
118    for name in deps {
119        if ctx.is_inductive(name) {
120            inductives.push(name.clone());
121        } else if ctx.is_definition(name) {
122            definitions.push(name.clone());
123        }
124        // Skip constructors - they're emitted with their inductive
125    }
126
127    // Inductives first, then definitions — and each group sorted by name so the
128    // emitted module is DETERMINISTIC regardless of HashSet/HashMap iteration
129    // order (every Compile builds a fresh kernel with new hash seeds). Rust
130    // resolves top-level items order-independently, so sorting is sound.
131    inductives.sort();
132    definitions.sort();
133    inductives.extend(definitions);
134    inductives
135}