Skip to main content

logicaffeine_compile/codegen_sva/
verified_compiler.rs

1//! Verified SVA Compiler via Futamura Projections
2//!
3//! P1: Specialize SVA synthesis for a fixed spec → compiled generator
4//! P2: Specialize the specializer for SVA synthesis → SVA compiler
5//!
6//! The key property: compiled output == interpreted output.
7//! Compiler correctness is inherited from the projection framework.
8
9use super::fol_to_sva::{synthesize_sva_from_spec, SynthesizedSva};
10use std::collections::hash_map::DefaultHasher;
11use std::hash::{Hash, Hasher};
12
13/// A compiled SVA generator — P1 output.
14///
15/// Captures the synthesis result for a fixed spec. Calling `generate(clock)`
16/// reconstructs the SVA with the given clock, without re-parsing or re-synthesizing.
17#[derive(Debug, Clone)]
18pub struct CompiledGenerator {
19    cached_body: String,
20    cached_signals: Vec<String>,
21    cached_kind: String,
22    spec_hash: u64,
23}
24
25impl CompiledGenerator {
26    /// Generate SVA for this fixed spec with the given clock.
27    ///
28    /// This is the "compiled" path — no spec parsing, no KG extraction,
29    /// no synthesis. Pure string formatting from cached data.
30    pub fn generate(&self, clock: &str) -> Result<SynthesizedSva, String> {
31        let sva_text = format!(
32            "property p_compiled;\n    @(posedge {}) {};\nendproperty\nassert property (p_compiled);",
33            clock, self.cached_body
34        );
35        Ok(SynthesizedSva {
36            sva_text,
37            body: self.cached_body.clone(),
38            signals: self.cached_signals.clone(),
39            kind: self.cached_kind.clone(),
40        })
41    }
42
43    /// Check if this generator was compiled from a specific spec.
44    pub fn spec_hash(&self) -> u64 {
45        self.spec_hash
46    }
47
48    /// Get the cached body (no synthesis overhead).
49    pub fn body(&self) -> &str {
50        &self.cached_body
51    }
52
53    /// Get the cached signals.
54    pub fn signals(&self) -> &[String] {
55        &self.cached_signals
56    }
57}
58
59/// An SVA compiler — P2 output.
60///
61/// A factory that creates `CompiledGenerator` instances for any spec.
62/// This is the "compiler compiled by the compiler" — the second Futamura projection.
63pub struct SvaCompiler;
64
65impl SvaCompiler {
66    /// Compile a spec into a `CompiledGenerator`.
67    ///
68    /// This is P2 applied: the compiler takes a spec and produces a compiled generator.
69    pub fn compile(&self, spec: &str) -> Result<CompiledGenerator, String> {
70        compile_sva_generator(spec)
71    }
72}
73
74/// P1: Specialize SVA synthesis for a fixed spec → compiled generator.
75///
76/// Calls `synthesize_sva_from_spec` once and caches the result.
77/// The returned `CompiledGenerator` produces SVA without re-synthesis.
78pub fn compile_sva_generator(spec: &str) -> Result<CompiledGenerator, String> {
79    // Run the "interpreter" once
80    let synthesized = synthesize_sva_from_spec(spec, "clk")?;
81
82    // Cache the result
83    let mut hasher = DefaultHasher::new();
84    spec.hash(&mut hasher);
85    let spec_hash = hasher.finish();
86
87    Ok(CompiledGenerator {
88        cached_body: synthesized.body,
89        cached_signals: synthesized.signals,
90        cached_kind: synthesized.kind,
91        spec_hash,
92    })
93}
94
95/// P2: Specialize the specializer for SVA synthesis → SVA compiler.
96///
97/// Returns a compiler that, for any spec, produces a compiled generator.
98pub fn compile_sva_compiler() -> SvaCompiler {
99    SvaCompiler
100}
101
102/// Verify compiler correctness: compiled output == interpreted output.
103///
104/// The fundamental Futamura property: for any spec and clock,
105/// the compiled path produces the same SVA as the interpreted path.
106pub fn verify_compiler_correctness(spec: &str, clock: &str) -> bool {
107    let interpreted = match synthesize_sva_from_spec(spec, clock) {
108        Ok(s) => s,
109        Err(_) => return false,
110    };
111
112    let compiled = match compile_sva_generator(spec) {
113        Ok(gen) => match gen.generate(clock) {
114            Ok(s) => s,
115            Err(_) => return false,
116        },
117        Err(_) => return false,
118    };
119
120    // The bodies must be identical
121    let mut int_signals = interpreted.signals.clone();
122    let mut comp_signals = compiled.signals.clone();
123    int_signals.sort();
124    comp_signals.sort();
125    interpreted.body == compiled.body
126        && int_signals == comp_signals
127        && interpreted.kind == compiled.kind
128}