Skip to main content

logicaffeine_verify/
synthesis.rs

1//! Reactive Synthesis from LTL
2//!
3//! Given an LTL specification over environment inputs and system outputs,
4//! synthesize a controller (finite-state machine) that satisfies the spec
5//! against all possible environment behaviors.
6//!
7//! Pipeline: LTL → Büchi automaton → Strategy search → Circuit → SVA/Verilog
8
9use crate::automata::{ltl_to_buchi, BuchiAutomaton};
10use crate::ic3::check_sat;
11use crate::ir::{VerifyExpr, VerifyOp};
12
13/// Signal declaration for synthesis.
14#[derive(Debug, Clone)]
15pub struct SignalDecl {
16    pub name: String,
17    pub width: Option<u32>,
18}
19
20/// Result of reactive synthesis.
21#[derive(Debug)]
22pub enum SynthesisResult {
23    /// A controller exists that satisfies the spec.
24    Realizable { controller: Circuit },
25    /// No controller can satisfy the spec — environment can force violation.
26    Unrealizable { reason: String },
27    /// Could not determine within resource limits.
28    Unknown,
29}
30
31/// A synthesized controller circuit.
32#[derive(Debug, Clone)]
33pub struct Circuit {
34    pub inputs: Vec<SignalDecl>,
35    pub outputs: Vec<SignalDecl>,
36    pub states: Vec<String>,
37    pub init: String,
38    pub transitions: Vec<CircuitTransition>,
39}
40
41/// A single transition in the synthesized circuit.
42#[derive(Debug, Clone)]
43pub struct CircuitTransition {
44    pub from_state: String,
45    pub guard: VerifyExpr,
46    pub to_state: String,
47    pub outputs: Vec<(String, VerifyExpr)>,
48}
49
50/// Synthesize a controller from an LTL specification.
51///
52/// For safety specs: finds a memoryless strategy via Z3.
53/// For response specs: finds a bounded-state controller.
54/// For contradictory specs: returns Unrealizable.
55pub fn synthesize_from_ltl(
56    spec: &VerifyExpr,
57    inputs: &[SignalDecl],
58    outputs: &[SignalDecl],
59) -> SynthesisResult {
60    // Check for trivially unrealizable specs
61    if is_contradictory(spec) {
62        return SynthesisResult::Unrealizable {
63            reason: "Specification is contradictory".into(),
64        };
65    }
66
67    // Check for tautological or trivially satisfiable specs
68    if is_tautology(spec) || outputs.is_empty() {
69        return SynthesisResult::Realizable {
70            controller: trivial_controller(inputs, outputs),
71        };
72    }
73
74    // First attempt: memoryless safety strategy via Z3
75    let safety_result = synthesize_safety(spec, inputs, outputs);
76    if matches!(safety_result, SynthesisResult::Realizable { .. }) {
77        return safety_result;
78    }
79
80    // Second attempt: bounded-state controller via Büchi automaton
81    let buchi = ltl_to_buchi(spec);
82    synthesize_bounded(spec, inputs, outputs, &buchi)
83}
84
85/// Synthesize a memoryless safety controller.
86fn synthesize_safety(
87    spec: &VerifyExpr,
88    inputs: &[SignalDecl],
89    outputs: &[SignalDecl],
90) -> SynthesisResult {
91    // For safety: the controller must ensure spec holds at every step.
92    // Strategy: set outputs to satisfy the spec regardless of inputs.
93
94    // Try: all outputs = true
95    let mut transitions = Vec::new();
96    let output_assignments: Vec<(String, VerifyExpr)> = outputs
97        .iter()
98        .map(|o| (o.name.clone(), VerifyExpr::bool(true)))
99        .collect();
100
101    // Check if this strategy works
102    let strategy_check = substitute_outputs(spec, &output_assignments);
103    if is_tautology(&strategy_check) {
104        transitions.push(CircuitTransition {
105            from_state: "s0".into(),
106            guard: VerifyExpr::bool(true),
107            to_state: "s0".into(),
108            outputs: output_assignments,
109        });
110
111        return SynthesisResult::Realizable {
112            controller: Circuit {
113                inputs: inputs.to_vec(),
114                outputs: outputs.to_vec(),
115                states: vec!["s0".into()],
116                init: "s0".into(),
117                transitions,
118            },
119        };
120    }
121
122    // Try: outputs mirror inputs (for response patterns)
123    if inputs.len() == outputs.len() {
124        let mirror_assignments: Vec<(String, VerifyExpr)> = outputs
125            .iter()
126            .zip(inputs.iter())
127            .map(|(o, i)| (o.name.clone(), VerifyExpr::var(&i.name)))
128            .collect();
129
130        let mirror_check = substitute_outputs(spec, &mirror_assignments);
131        if is_tautology(&mirror_check) {
132            transitions.push(CircuitTransition {
133                from_state: "s0".into(),
134                guard: VerifyExpr::bool(true),
135                to_state: "s0".into(),
136                outputs: mirror_assignments,
137            });
138
139            return SynthesisResult::Realizable {
140                controller: Circuit {
141                    inputs: inputs.to_vec(),
142                    outputs: outputs.to_vec(),
143                    states: vec!["s0".into()],
144                    init: "s0".into(),
145                    transitions,
146                },
147            };
148        }
149    }
150
151    // Try: all outputs = false
152    let false_assignments: Vec<(String, VerifyExpr)> = outputs
153        .iter()
154        .map(|o| (o.name.clone(), VerifyExpr::bool(false)))
155        .collect();
156    let false_check = substitute_outputs(spec, &false_assignments);
157    if is_tautology(&false_check) {
158        transitions.push(CircuitTransition {
159            from_state: "s0".into(),
160            guard: VerifyExpr::bool(true),
161            to_state: "s0".into(),
162            outputs: false_assignments,
163        });
164        return SynthesisResult::Realizable {
165            controller: Circuit {
166                inputs: inputs.to_vec(),
167                outputs: outputs.to_vec(),
168                states: vec!["s0".into()],
169                init: "s0".into(),
170                transitions,
171            },
172        };
173    }
174
175    // Try: each output follows corresponding input (for response patterns)
176    if !inputs.is_empty() && !outputs.is_empty() {
177        let resp_assignments: Vec<(String, VerifyExpr)> = outputs
178            .iter()
179            .enumerate()
180            .map(|(i, o)| {
181                let value = if i < inputs.len() {
182                    VerifyExpr::var(&inputs[i].name)
183                } else {
184                    VerifyExpr::bool(true)
185                };
186                (o.name.clone(), value)
187            })
188            .collect();
189
190        let resp_check = substitute_outputs(spec, &resp_assignments);
191        if is_tautology(&resp_check) {
192            transitions.push(CircuitTransition {
193                from_state: "s0".into(),
194                guard: VerifyExpr::bool(true),
195                to_state: "s0".into(),
196                outputs: resp_assignments,
197            });
198            return SynthesisResult::Realizable {
199                controller: Circuit {
200                    inputs: inputs.to_vec(),
201                    outputs: outputs.to_vec(),
202                    states: vec!["s0".into()],
203                    init: "s0".into(),
204                    transitions,
205                },
206            };
207        }
208    }
209
210    // Try: each output is the negation of corresponding input
211    if !inputs.is_empty() && !outputs.is_empty() {
212        let neg_assignments: Vec<(String, VerifyExpr)> = outputs
213            .iter()
214            .enumerate()
215            .map(|(i, o)| {
216                let value = if i < inputs.len() {
217                    VerifyExpr::not(VerifyExpr::var(&inputs[i].name))
218                } else {
219                    VerifyExpr::bool(false)
220                };
221                (o.name.clone(), value)
222            })
223            .collect();
224
225        let neg_check = substitute_outputs(spec, &neg_assignments);
226        if is_tautology(&neg_check) {
227            transitions.push(CircuitTransition {
228                from_state: "s0".into(),
229                guard: VerifyExpr::bool(true),
230                to_state: "s0".into(),
231                outputs: neg_assignments,
232            });
233            return SynthesisResult::Realizable {
234                controller: Circuit {
235                    inputs: inputs.to_vec(),
236                    outputs: outputs.to_vec(),
237                    states: vec!["s0".into()],
238                    init: "s0".into(),
239                    transitions,
240                },
241            };
242        }
243    }
244
245    SynthesisResult::Unknown
246}
247
248/// Synthesize a bounded-state controller.
249fn synthesize_bounded(
250    spec: &VerifyExpr,
251    inputs: &[SignalDecl],
252    outputs: &[SignalDecl],
253    buchi: &BuchiAutomaton,
254) -> SynthesisResult {
255    let states: Vec<String> = buchi.states.iter().map(|s| format!("s{}", s.id)).collect();
256
257    let mut transitions = Vec::new();
258    let mut all_valid = true;
259
260    // Candidate strategies for each transition: try all-true first, then all-false
261    let candidate_strategies: Vec<Vec<(String, VerifyExpr)>> = vec![
262        outputs
263            .iter()
264            .map(|o| (o.name.clone(), VerifyExpr::bool(true)))
265            .collect(),
266        outputs
267            .iter()
268            .map(|o| (o.name.clone(), VerifyExpr::bool(false)))
269            .collect(),
270    ];
271
272    for trans in &buchi.transitions {
273        let mut found_valid = false;
274        for strategy in &candidate_strategies {
275            let substituted = substitute_outputs(spec, strategy);
276            // Check: guard AND NOT(substituted_spec) should be UNSAT
277            // i.e., under the guard, the strategy must satisfy the spec
278            let check = VerifyExpr::and(trans.guard.clone(), VerifyExpr::not(substituted));
279            if !check_sat(&check) {
280                transitions.push(CircuitTransition {
281                    from_state: format!("s{}", trans.from),
282                    guard: trans.guard.clone(),
283                    to_state: format!("s{}", trans.to),
284                    outputs: strategy.clone(),
285                });
286                found_valid = true;
287                break;
288            }
289        }
290        if !found_valid {
291            all_valid = false;
292            break;
293        }
294    }
295
296    if all_valid {
297        SynthesisResult::Realizable {
298            controller: Circuit {
299                inputs: inputs.to_vec(),
300                outputs: outputs.to_vec(),
301                states,
302                init: format!("s{}", buchi.initial),
303                transitions,
304            },
305        }
306    } else {
307        SynthesisResult::Unknown
308    }
309}
310
311/// Generate SVA monitor from a synthesized circuit.
312pub fn circuit_to_sva(circuit: &Circuit) -> String {
313    let mut sva = String::new();
314
315    for (i, trans) in circuit.transitions.iter().enumerate() {
316        sva.push_str(&format!(
317            "property p_trans_{};\n  @(posedge clk) (state == {} && {}) |-> ##1 (state == {});\nendproperty\n",
318            i, trans.from_state, expr_to_sva(&trans.guard), trans.to_state
319        ));
320    }
321
322    sva
323}
324
325/// Generate Verilog RTL from a synthesized circuit.
326pub fn circuit_to_verilog(circuit: &Circuit) -> String {
327    let mut v = String::new();
328
329    // Module header
330    let input_ports: Vec<String> = circuit
331        .inputs
332        .iter()
333        .map(|i| format!("input {}", i.name))
334        .collect();
335    let output_ports: Vec<String> = circuit
336        .outputs
337        .iter()
338        .map(|o| format!("output reg {}", o.name))
339        .collect();
340    let all_ports: Vec<String> = vec!["input clk".into(), "input rst".into()]
341        .into_iter()
342        .chain(input_ports)
343        .chain(output_ports)
344        .collect();
345
346    v.push_str(&format!(
347        "module controller(\n  {}\n);\n\n",
348        all_ports.join(",\n  ")
349    ));
350
351    // State encoding
352    let state_bits = (circuit.states.len() as f64).log2().ceil() as u32;
353    let state_bits = state_bits.max(1);
354    v.push_str(&format!("  reg [{}:0] state;\n\n", state_bits - 1));
355
356    // State parameters
357    for (i, state) in circuit.states.iter().enumerate() {
358        v.push_str(&format!("  localparam {} = {};\n", state, i));
359    }
360    v.push('\n');
361
362    // FSM
363    v.push_str("  always @(posedge clk or posedge rst) begin\n");
364    v.push_str("    if (rst) begin\n");
365    v.push_str(&format!("      state <= {};\n", circuit.init));
366    v.push_str("    end else begin\n");
367    v.push_str("      case (state)\n");
368
369    for state in &circuit.states {
370        v.push_str(&format!("        {}: begin\n", state));
371        let state_transitions: Vec<&CircuitTransition> = circuit
372            .transitions
373            .iter()
374            .filter(|t| t.from_state == *state)
375            .collect();
376        for trans in state_transitions {
377            v.push_str(&format!("          state <= {};\n", trans.to_state));
378            for (output, value) in &trans.outputs {
379                v.push_str(&format!(
380                    "          {} <= {};\n",
381                    output,
382                    expr_to_verilog(value)
383                ));
384            }
385        }
386        v.push_str("        end\n");
387    }
388
389    v.push_str("      endcase\n");
390    v.push_str("    end\n");
391    v.push_str("  end\n\n");
392    v.push_str("endmodule\n");
393
394    v
395}
396
397fn trivial_controller(inputs: &[SignalDecl], outputs: &[SignalDecl]) -> Circuit {
398    Circuit {
399        inputs: inputs.to_vec(),
400        outputs: outputs.to_vec(),
401        states: vec!["s0".into()],
402        init: "s0".into(),
403        transitions: vec![CircuitTransition {
404            from_state: "s0".into(),
405            guard: VerifyExpr::bool(true),
406            to_state: "s0".into(),
407            outputs: outputs
408                .iter()
409                .map(|o| (o.name.clone(), VerifyExpr::bool(true)))
410                .collect(),
411        }],
412    }
413}
414
415fn is_contradictory(spec: &VerifyExpr) -> bool {
416    !check_sat(spec)
417}
418
419fn is_tautology(expr: &VerifyExpr) -> bool {
420    !check_sat(&VerifyExpr::not(expr.clone()))
421}
422
423fn substitute_outputs(spec: &VerifyExpr, assignments: &[(String, VerifyExpr)]) -> VerifyExpr {
424    match spec {
425        VerifyExpr::Var(name) => {
426            for (out_name, value) in assignments {
427                if name == out_name {
428                    return value.clone();
429                }
430            }
431            spec.clone()
432        }
433        VerifyExpr::Binary { op, left, right } => VerifyExpr::binary(
434            *op,
435            substitute_outputs(left, assignments),
436            substitute_outputs(right, assignments),
437        ),
438        VerifyExpr::Not(inner) => VerifyExpr::not(substitute_outputs(inner, assignments)),
439        _ => spec.clone(),
440    }
441}
442
443fn expr_to_sva(expr: &VerifyExpr) -> String {
444    match expr {
445        VerifyExpr::Bool(true) => "1".into(),
446        VerifyExpr::Bool(false) => "0".into(),
447        VerifyExpr::Var(name) => name.clone(),
448        VerifyExpr::Not(inner) => format!("!({})", expr_to_sva(inner)),
449        VerifyExpr::Binary {
450            op: VerifyOp::And,
451            left,
452            right,
453        } => {
454            format!("({} && {})", expr_to_sva(left), expr_to_sva(right))
455        }
456        VerifyExpr::Binary {
457            op: VerifyOp::Or,
458            left,
459            right,
460        } => {
461            format!("({} || {})", expr_to_sva(left), expr_to_sva(right))
462        }
463        VerifyExpr::Binary {
464            op: VerifyOp::Implies,
465            left,
466            right,
467        } => {
468            format!("({} |-> {})", expr_to_sva(left), expr_to_sva(right))
469        }
470        _ => format!("{:?}", expr),
471    }
472}
473
474fn expr_to_verilog(expr: &VerifyExpr) -> String {
475    match expr {
476        VerifyExpr::Bool(true) => "1'b1".into(),
477        VerifyExpr::Bool(false) => "1'b0".into(),
478        VerifyExpr::Var(name) => name.clone(),
479        _ => "1'b0".into(),
480    }
481}