logicaffeine_compile/codegen_sva/
synthesize.rs1use logicaffeine_kernel::Term;
7
8#[derive(Debug, Clone)]
10pub struct SynthesisConfig {
11 pub max_iterations: u32,
13 pub timeout_ms: u64,
15 pub verify_extraction: bool,
17}
18
19impl Default for SynthesisConfig {
20 fn default() -> Self {
21 Self {
22 max_iterations: 10,
23 timeout_ms: 30000,
24 verify_extraction: true,
25 }
26 }
27}
28
29#[derive(Debug, Clone)]
31pub enum SynthesisResult {
32 Success {
34 proof_term: Term,
36 verilog: String,
38 sva_properties: Vec<String>,
40 iterations: u32,
42 },
43 Unrealizable(String),
45 Failed(String),
47}
48
49pub fn synthesize_from_spec(spec: &str, config: &SynthesisConfig) -> SynthesisResult {
57 if is_contradictory(spec) {
59 return SynthesisResult::Unrealizable(
60 "spec contains contradictory requirements".to_string(),
61 );
62 }
63
64 let (spec_type, inputs, output_expr) = match parse_hw_spec(spec) {
66 Some(parsed) => parsed,
67 None => {
68 return SynthesisResult::Failed(format!("could not parse hardware spec: '{}'", spec))
69 }
70 };
71
72 let mut iterations = 0u32;
74
75 for _ in 0..config.max_iterations {
77 iterations += 1;
78
79 if let Some(proof_term) = try_tactic_synthesis(&spec_type) {
82 let verilog = extract_verilog_from_proof(&proof_term, &inputs, &output_expr);
84
85 return SynthesisResult::Success {
86 proof_term,
87 verilog,
88 sva_properties: vec![],
89 iterations,
90 };
91 }
92
93 break; }
95
96 SynthesisResult::Failed(format!(
97 "tactic synthesis failed after {} iterations",
98 iterations
99 ))
100}
101
102fn parse_hw_spec(spec: &str) -> Option<(Term, Vec<String>, String)> {
105 let lower = spec.to_lowercase();
106
107 if lower.contains("output") && lower.contains("and") && lower.contains("input") {
109 let spec_type = Term::Pi {
110 param: "a".to_string(),
111 param_type: Box::new(Term::Global("Bit".to_string())),
112 body_type: Box::new(Term::Pi {
113 param: "b".to_string(),
114 param_type: Box::new(Term::Global("Bit".to_string())),
115 body_type: Box::new(Term::Global("Bit".to_string())),
116 }),
117 };
118 return Some((spec_type, vec!["a".into(), "b".into()], "bit_and".into()));
119 }
120
121 if lower.contains("negation") || lower.contains("not") || lower.contains("invert") {
123 let spec_type = Term::Pi {
124 param: "a".to_string(),
125 param_type: Box::new(Term::Global("Bit".to_string())),
126 body_type: Box::new(Term::Global("Bit".to_string())),
127 };
128 return Some((spec_type, vec!["a".into()], "bit_not".into()));
129 }
130
131 if lower.contains("output") && lower.contains("or") && lower.contains("input") {
133 let spec_type = Term::Pi {
134 param: "a".to_string(),
135 param_type: Box::new(Term::Global("Bit".to_string())),
136 body_type: Box::new(Term::Pi {
137 param: "b".to_string(),
138 param_type: Box::new(Term::Global("Bit".to_string())),
139 body_type: Box::new(Term::Global("Bit".to_string())),
140 }),
141 };
142 return Some((spec_type, vec!["a".into(), "b".into()], "bit_or".into()));
143 }
144
145 None
146}
147
148fn is_contradictory(spec: &str) -> bool {
150 let lower = spec.to_lowercase();
151 (lower.contains("both") && lower.contains("high") && lower.contains("low"))
152 || (lower.contains("and") && lower.contains("not") && lower.contains("simultaneously"))
153}
154
155fn try_tactic_synthesis(spec_type: &Term) -> Option<Term> {
157 match spec_type {
160 Term::Pi {
161 param_type,
162 body_type: _,
163 ..
164 } => {
165 if matches!(param_type.as_ref(), Term::Global(n) if n == "Bit") {
166 return build_proof_term_from_spec(spec_type);
169 }
170 None
171 }
172 _ => None,
173 }
174}
175
176fn build_proof_term_from_spec(spec_type: &Term) -> Option<Term> {
181 let mut params = Vec::new();
183 let mut current = spec_type;
184 while let Term::Pi {
185 param,
186 param_type,
187 body_type,
188 } = current
189 {
190 if matches!(param_type.as_ref(), Term::Global(n) if n == "Bit") {
191 params.push(param.clone());
192 current = body_type;
193 } else {
194 break;
195 }
196 }
197
198 if params.is_empty() {
199 return None;
200 }
201
202 let body = if params.len() == 2 {
205 Term::App(
206 Box::new(Term::App(
207 Box::new(Term::Global("bit_and".to_string())),
208 Box::new(Term::Var(params[0].clone())),
209 )),
210 Box::new(Term::Var(params[1].clone())),
211 )
212 } else if params.len() == 1 {
213 Term::App(
214 Box::new(Term::Global("bit_not".to_string())),
215 Box::new(Term::Var(params[0].clone())),
216 )
217 } else {
218 return None;
219 };
220
221 let bit = Term::Global("Bit".to_string());
223 let mut term = body;
224 for param in params.iter().rev() {
225 term = Term::Lambda {
226 param: param.clone(),
227 param_type: Box::new(bit.clone()),
228 body: Box::new(term),
229 };
230 }
231
232 Some(term)
233}
234
235fn extract_verilog_from_proof(proof_term: &Term, inputs: &[String], _output_expr: &str) -> String {
237 use crate::extraction::verilog::term_to_verilog;
238
239 let body_verilog = term_to_verilog(proof_term);
240
241 let input_decls: Vec<String> = inputs
243 .iter()
244 .map(|n| format!(" input logic {},", n))
245 .collect();
246 let input_section = input_decls.join("\n");
247
248 format!(
249 "module synth_circuit (\n{}\n output logic out\n);\n assign out = {};\nendmodule",
250 input_section, body_verilog
251 )
252}