1use super::fol_to_verify::FolTranslator;
7use super::sva_model::{parse_sva, sva_exprs_structurally_equivalent, SvaExpr};
8use super::sva_to_verify::{BoundedExpr, SvaTranslator, TranslateResult};
9use super::{emit_sva_property, sanitize_property_name, SvaAssertionKind, SvaProperty};
10use logicaffeine_language::semantics::knowledge_graph::{HwKnowledgeGraph, SignalRole};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone)]
23pub struct SignalMap {
24 map: HashMap<String, String>,
25}
26
27impl SignalMap {
28 pub fn new() -> Self {
29 Self {
30 map: HashMap::new(),
31 }
32 }
33
34 pub fn add(&mut self, fol_arg: &str, sva_signal: &str) {
36 self.map.insert(fol_arg.to_string(), sva_signal.to_string());
37 }
38
39 pub fn resolve(&self, fol_arg: &str) -> Option<&str> {
41 self.map.get(fol_arg).map(|s| s.as_str())
42 }
43
44 pub fn from_decls(decls: &[HwSignalDecl]) -> Self {
46 let mut map = Self::new();
47 for decl in decls {
48 map.add(&decl.english_name, &decl.sva_name);
49 }
50 map
51 }
52}
53
54#[derive(Debug, Clone)]
64pub struct HwSignalDecl {
65 pub english_name: String,
66 pub sva_name: String,
67 pub width: u32,
68 pub role: SignalRole,
69}
70
71impl HwSignalDecl {
72 pub fn new(english_name: &str, sva_name: &str, width: u32, role: SignalRole) -> Self {
73 Self {
74 english_name: english_name.to_string(),
75 sva_name: sva_name.to_string(),
76 width,
77 role,
78 }
79 }
80}
81
82#[derive(Debug)]
88pub struct EquivalenceResult {
89 pub equivalent: bool,
91 pub counterexample: Option<Vec<(String, String)>>,
93 pub bound: u32,
95}
96
97#[derive(Debug)]
99pub struct HwSpec {
100 pub fol_text: String,
102 pub kg: HwKnowledgeGraph,
104}
105
106#[derive(Debug)]
108pub struct PipelineResult {
109 pub property_name: String,
111 pub result: EquivalenceResult,
113 pub sva_text: String,
115 pub fol_text: String,
117}
118
119#[derive(Debug)]
121pub enum HwError {
122 ParseError(String),
123 SvaParseError(String),
124 VerificationError(String),
125}
126
127impl std::fmt::Display for HwError {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 match self {
130 HwError::ParseError(msg) => write!(f, "Parse error: {}", msg),
131 HwError::SvaParseError(msg) => write!(f, "SVA parse error: {}", msg),
132 HwError::VerificationError(msg) => write!(f, "Verification error: {}", msg),
133 }
134 }
135}
136
137pub fn check_structural_equivalence(sva_a: &str, sva_b: &str) -> Result<bool, HwError> {
143 let expr_a = parse_sva(sva_a).map_err(|e| HwError::SvaParseError(e.message))?;
144 let expr_b = parse_sva(sva_b).map_err(|e| HwError::SvaParseError(e.message))?;
145 Ok(sva_exprs_structurally_equivalent(&expr_a, &expr_b))
146}
147
148pub fn check_bounded_equivalence(
150 fol_bounded: &BoundedExpr,
151 sva_bounded: &BoundedExpr,
152 bound: u32,
153) -> EquivalenceResult {
154 let equivalent = bounded_exprs_equal(fol_bounded, sva_bounded);
155 EquivalenceResult {
156 equivalent,
157 counterexample: None,
158 bound,
159 }
160}
161
162pub fn translate_sva_to_bounded(sva_text: &str, bound: u32) -> Result<TranslateResult, HwError> {
166 let sva_expr = parse_sva(sva_text).map_err(|e| HwError::SvaParseError(e.message))?;
167 let mut translator = SvaTranslator::new(bound);
168 let result = translator.translate_property(&sva_expr);
169 Ok(result)
170}
171
172fn translate_sva_for_equiv(sva_text: &str, bound: u32) -> Result<TranslateResult, HwError> {
176 let sva_expr = parse_sva(sva_text).map_err(|e| HwError::SvaParseError(e.message))?;
177 let mut translator = SvaTranslator::new(bound);
178 if sva_has_outermost_temporal(&sva_expr) {
179 let expr = translator.translate(&sva_expr, 0);
180 let declarations: Vec<String> = translator.declarations.iter().cloned().collect();
181 Ok(TranslateResult { expr, declarations })
182 } else {
183 Ok(translator.translate_property(&sva_expr))
184 }
185}
186
187fn sva_has_outermost_temporal(expr: &SvaExpr) -> bool {
191 matches!(
192 expr,
193 SvaExpr::SEventually(_) | SvaExpr::Nexttime(_, _) | SvaExpr::SAlways(_)
194 )
195}
196
197pub fn translate_spec_to_bounded(spec: &str, bound: u32) -> Result<TranslateResult, HwError> {
199 logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
200 let mut translator = FolTranslator::new(interner, bound);
201 translator.translate_property(ast)
202 })
203 .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
204}
205
206pub fn compile_hw_property(
212 spec: &str,
213 decls: &[HwSignalDecl],
214 bound: u32,
215) -> Result<TranslateResult, HwError> {
216 let signal_map = SignalMap::from_decls(decls);
217 logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
218 let mut translator = FolTranslator::new(interner, bound);
219 translator.set_signal_map(&signal_map);
220 translator.translate_property(ast)
221 })
222 .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
223}
224
225pub fn compile_hw_spec(source: &str) -> Result<String, HwError> {
227 logicaffeine_language::compile_kripke(source)
228 .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
229}
230
231pub fn emit_hw_sva(name: &str, clock: &str, body: &str, kind: SvaAssertionKind) -> String {
233 let prop = SvaProperty {
234 name: sanitize_property_name(name),
235 clock: clock.to_string(),
236 body: body.to_string(),
237 kind,
238 };
239 emit_sva_property(&prop)
240}
241
242pub fn extract_kg(spec: &str) -> Result<HwKnowledgeGraph, HwError> {
244 logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
245 logicaffeine_language::semantics::knowledge_graph::extract_from_kripke_ast(ast, interner)
246 })
247 .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
248}
249
250#[cfg(feature = "verification")]
254pub fn check_z3_equivalence(
255 spec_source: &str,
256 sva_text: &str,
257 bound: u32,
258) -> Result<logicaffeine_verify::equivalence::EquivalenceResult, HwError> {
259 use super::sva_to_verify::{bounded_to_verify, extract_signal_names};
260
261 let spec_bounded = translate_spec_to_bounded(spec_source, bound)?;
262 let spec_verify = bounded_to_verify(&spec_bounded.expr);
263
264 let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
265 let sva_verify = bounded_to_verify(&sva_bounded.expr);
266
267 let mut all_signals = extract_signal_names(&spec_bounded);
268 let sva_signals = extract_signal_names(&sva_bounded);
269 for sig in sva_signals {
270 if !all_signals.contains(&sig) {
271 all_signals.push(sig);
272 }
273 }
274
275 Ok(logicaffeine_verify::equivalence::check_equivalence(
276 &spec_verify,
277 &sva_verify,
278 &all_signals,
279 bound as usize,
280 ))
281}
282
283#[cfg(feature = "verification")]
288pub fn check_z3_hw_equivalence(
289 spec: &str,
290 sva_text: &str,
291 decls: &[HwSignalDecl],
292 bound: u32,
293) -> Result<logicaffeine_verify::equivalence::EquivalenceResult, HwError> {
294 use super::sva_to_verify::{bounded_to_verify, extract_signal_names};
295
296 let spec_bounded = compile_hw_property(spec, decls, bound)?;
298 let spec_verify = bounded_to_verify(&spec_bounded.expr);
299
300 let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
302 let sva_verify = bounded_to_verify(&sva_bounded.expr);
303
304 let mut all_signals: Vec<String> = decls.iter().map(|d| d.sva_name.clone()).collect();
306 let spec_signals = extract_signal_names(&spec_bounded);
307 let sva_signals = extract_signal_names(&sva_bounded);
308 for sig in spec_signals.into_iter().chain(sva_signals.into_iter()) {
309 if !all_signals.contains(&sig) {
310 all_signals.push(sig);
311 }
312 }
313
314 Ok(logicaffeine_verify::equivalence::check_equivalence(
316 &spec_verify,
317 &sva_verify,
318 &all_signals,
319 bound as usize,
320 ))
321}
322
323pub fn prove_bounded_equivalence(
331 fol_bounded: &BoundedExpr,
332 sva_bounded: &BoundedExpr,
333 bound: u32,
334) -> Result<EquivalenceResult, HwError> {
335 use super::sva_to_proof::bounded_to_proof;
336 use logicaffeine_proof::sat::{prove_equivalence, EquivOutcome};
337
338 let fol = bounded_to_proof(fol_bounded).ok_or_else(|| {
339 HwError::VerificationError(
340 "FOL obligation is outside the Boolean fragment (bit-blasting not yet wired)".into(),
341 )
342 })?;
343 let sva = bounded_to_proof(sva_bounded).ok_or_else(|| {
344 HwError::VerificationError(
345 "SVA obligation is outside the Boolean fragment (bit-blasting not yet wired)".into(),
346 )
347 })?;
348
349 match prove_equivalence(&fol, &sva) {
350 EquivOutcome::Equivalent => Ok(EquivalenceResult {
351 equivalent: true,
352 counterexample: None,
353 bound,
354 }),
355 EquivOutcome::Differ(model) => Ok(EquivalenceResult {
356 equivalent: false,
357 counterexample: Some(
358 model
359 .into_iter()
360 .map(|(name, v)| (name, if v { "1" } else { "0" }.to_string()))
361 .collect(),
362 ),
363 bound,
364 }),
365 EquivOutcome::Unsupported => Err(HwError::VerificationError(
366 "obligation not purely propositional — escalate to bit-blasting".into(),
367 )),
368 }
369}
370
371pub fn prove_spec_sva_equivalence(
375 spec_source: &str,
376 sva_text: &str,
377 bound: u32,
378) -> Result<EquivalenceResult, HwError> {
379 let spec_bounded = translate_spec_to_bounded(spec_source, bound)?;
380 let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
381 prove_bounded_equivalence(&spec_bounded.expr, &sva_bounded.expr, bound)
382}
383
384#[derive(Debug, Clone, PartialEq, Eq)]
386pub struct KgNode {
387 pub name: String,
388 pub role: String,
389 pub width: u32,
390}
391
392#[derive(Debug, Clone, PartialEq, Eq)]
394pub struct KgLink {
395 pub from: usize,
396 pub to: usize,
397 pub relation: String,
398}
399
400#[derive(Debug, Clone, PartialEq, Eq, Default)]
403pub struct KgSummary {
404 pub nodes: Vec<KgNode>,
405 pub links: Vec<KgLink>,
406}
407
408pub fn kg_summary(spec: &str) -> Result<KgSummary, HwError> {
411 use logicaffeine_language::semantics::knowledge_graph::{KgRelation, SignalRole};
412 use std::collections::HashMap;
413
414 let kg = extract_kg(spec)?;
415 let mut nodes = Vec::new();
416 let mut index: HashMap<String, usize> = HashMap::new();
417 for s in &kg.signals {
418 let role = match s.role {
419 SignalRole::Input => "input",
420 SignalRole::Output => "output",
421 SignalRole::Internal => "internal",
422 SignalRole::Clock => "clock",
423 }
424 .to_string();
425 index.insert(s.name.clone(), nodes.len());
426 nodes.push(KgNode {
427 name: s.name.clone(),
428 role,
429 width: s.width,
430 });
431 }
432
433 let mut links = Vec::new();
434 let mut seen = std::collections::HashSet::new();
435 let mut add = |from: &str, to: &str, rel: String, links: &mut Vec<KgLink>| {
436 if let (Some(&f), Some(&t)) = (index.get(from), index.get(to)) {
437 if f != t && seen.insert((f, t, rel.clone())) {
438 links.push(KgLink {
439 from: f,
440 to: t,
441 relation: rel,
442 });
443 }
444 }
445 };
446 for e in &kg.edges {
447 let rel = match e.relation {
448 KgRelation::Temporal => "temporal",
449 KgRelation::Triggers => "triggers",
450 KgRelation::Constrains => "constrains",
451 KgRelation::TypeOf => "type",
452 }
453 .to_string();
454 add(&e.from, &e.to, rel, &mut links);
455 }
456 for (from, to, rel) in &kg.typed_edges {
457 add(from, to, typed_relation_label(rel), &mut links);
458 }
459
460 Ok(KgSummary { nodes, links })
461}
462
463fn typed_relation_label(
464 rel: &logicaffeine_language::semantics::knowledge_graph::HwRelation,
465) -> String {
466 use logicaffeine_language::semantics::knowledge_graph::HwRelation as R;
467 match rel {
468 R::Drives | R::DrivesRegistered { .. } => "drives",
469 R::DataFlow => "data",
470 R::Reads => "reads",
471 R::Writes => "writes",
472 R::Controls => "controls",
473 R::Selects => "selects",
474 R::Enables => "enables",
475 R::Resets => "resets",
476 R::Triggers { .. } => "triggers",
477 R::Constrains => "constrains",
478 R::Follows { .. } => "follows",
479 R::Precedes => "precedes",
480 R::Preserves => "preserves",
481 R::Contains => "contains",
482 R::Instantiates => "instantiates",
483 R::ConnectsTo => "connects",
484 R::BelongsToDomain { .. } => "domain",
485 R::HandshakesWith => "handshake",
486 R::Acknowledges => "acks",
487 R::Pipelines { .. } => "pipeline",
488 R::MutuallyExcludes => "mutex",
489 R::EventuallyFollows => "eventually",
490 R::AssumedBy => "assumed",
491 }
492 .to_string()
493}
494
495#[derive(Debug, Clone, PartialEq, Eq)]
499pub struct WaveSignal {
500 pub name: String,
501 pub width: u32,
502 pub values: Vec<Option<u64>>,
503}
504
505#[derive(Debug, Clone, PartialEq, Eq, Default)]
507pub struct Waveform {
508 pub timesteps: u32,
509 pub signals: Vec<WaveSignal>,
510}
511
512pub fn counterexample_waveform(counterexample: &[(String, String)]) -> Waveform {
517 use std::collections::BTreeMap;
518 struct Acc {
520 width: u32,
521 per_t: BTreeMap<u32, BTreeMap<u32, bool>>,
522 }
523 let mut sigs: BTreeMap<String, Acc> = BTreeMap::new();
524 let mut max_t = 0u32;
525 let mut any = false;
526 for (key, val) in counterexample {
527 let bit_val = match val.as_str() {
528 "1" | "true" => true,
529 "0" | "false" => false,
530 _ => continue,
531 };
532 let (base, bit, multibit) = match key.rsplit_once('#') {
534 Some((b, idx)) => match idx.parse::<u32>() {
535 Ok(i) => (b, i, true),
536 Err(_) => continue,
537 },
538 None => (key.as_str(), 0u32, false),
539 };
540 let Some((name, t_str)) = base.rsplit_once('@') else {
541 continue;
542 };
543 let Ok(t) = t_str.parse::<u32>() else {
544 continue;
545 };
546 let acc = sigs.entry(name.to_string()).or_insert(Acc {
547 width: 1,
548 per_t: BTreeMap::new(),
549 });
550 if multibit {
551 acc.width = acc.width.max(bit + 1);
552 }
553 acc.per_t.entry(t).or_default().insert(bit, bit_val);
554 max_t = max_t.max(t);
555 any = true;
556 }
557 let timesteps = if any { max_t + 1 } else { 0 };
558 let signals = sigs
559 .into_iter()
560 .map(|(name, acc)| {
561 let values = (0..timesteps)
562 .map(|t| {
563 acc.per_t.get(&t).map(|bits| {
564 bits.iter()
565 .fold(0u64, |v, (&i, &b)| if b { v | (1u64 << i) } else { v })
566 })
567 })
568 .collect();
569 WaveSignal {
570 name,
571 width: acc.width,
572 values,
573 }
574 })
575 .collect();
576 Waveform { timesteps, signals }
577}
578
579#[derive(Debug, Clone, PartialEq, Eq)]
581pub enum VacuityReport {
582 NonVacuous,
584 Vacuous,
586 NoTrigger,
588 Unsupported,
590}
591
592fn first_antecedent(e: &BoundedExpr) -> Option<&BoundedExpr> {
595 match e {
596 BoundedExpr::Implies(a, _) => Some(a),
597 BoundedExpr::And(l, r) | BoundedExpr::Or(l, r) => {
598 first_antecedent(l).or_else(|| first_antecedent(r))
599 }
600 BoundedExpr::Not(x) => first_antecedent(x),
601 _ => None,
602 }
603}
604
605pub fn check_spec_vacuity(spec_source: &str, bound: u32) -> Result<VacuityReport, HwError> {
609 use super::sva_to_proof::bounded_to_proof;
610 use logicaffeine_proof::bmc::{check_vacuity, VacuityOutcome};
611
612 let fol = translate_spec_to_bounded(spec_source, bound)?;
613 let antecedent = match first_antecedent(&fol.expr) {
614 Some(a) => a,
615 None => return Ok(VacuityReport::NoTrigger),
616 };
617 let proof = match bounded_to_proof(antecedent) {
618 Some(p) => p,
619 None => return Ok(VacuityReport::Unsupported),
620 };
621 Ok(match check_vacuity(&proof) {
622 VacuityOutcome::Vacuous => VacuityReport::Vacuous,
623 VacuityOutcome::Reachable(_) => VacuityReport::NonVacuous,
624 VacuityOutcome::Unsupported => VacuityReport::Unsupported,
625 })
626}
627
628#[cfg(test)]
629#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/hw_pipeline/native_prove_tests.rs"]
630mod native_prove_tests;
631
632fn bounded_exprs_equal(a: &BoundedExpr, b: &BoundedExpr) -> bool {
634 match (a, b) {
635 (BoundedExpr::Var(va), BoundedExpr::Var(vb)) => va == vb,
636 (BoundedExpr::Bool(va), BoundedExpr::Bool(vb)) => va == vb,
637 (BoundedExpr::Int(va), BoundedExpr::Int(vb)) => va == vb,
638 (BoundedExpr::And(la, ra), BoundedExpr::And(lb, rb)) => {
639 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
640 }
641 (BoundedExpr::Or(la, ra), BoundedExpr::Or(lb, rb)) => {
642 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
643 }
644 (BoundedExpr::Not(ia), BoundedExpr::Not(ib)) => bounded_exprs_equal(ia, ib),
645 (BoundedExpr::Implies(la, ra), BoundedExpr::Implies(lb, rb)) => {
646 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
647 }
648 (BoundedExpr::Eq(la, ra), BoundedExpr::Eq(lb, rb)) => {
649 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
650 }
651 (BoundedExpr::Lt(la, ra), BoundedExpr::Lt(lb, rb)) => {
652 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
653 }
654 (BoundedExpr::Gt(la, ra), BoundedExpr::Gt(lb, rb)) => {
655 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
656 }
657 (BoundedExpr::Lte(la, ra), BoundedExpr::Lte(lb, rb)) => {
658 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
659 }
660 (BoundedExpr::Gte(la, ra), BoundedExpr::Gte(lb, rb)) => {
661 bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
662 }
663 _ => false,
664 }
665}