Skip to main content

logicaffeine_compile/codegen_sva/
sva_to_verify.rs

1//! SVA → Bounded Verification IR Translation
2//!
3//! Translates SvaExpr to a bounded timestep model suitable for Z3 equivalence checking.
4//! Each signal at timestep t becomes a variable "signal@t".
5//! Temporal operators are unrolled to bounded disjunctions/conjunctions.
6
7use super::sva_model::SvaExpr;
8use std::collections::{HashMap, HashSet};
9
10/// A verification expression in the bounded timestep model.
11/// This is a Z3-ready IR — each node maps directly to a Z3 AST construct.
12#[derive(Debug, Clone, PartialEq)]
13pub enum BoundedExpr {
14    /// Boolean variable: "signal@timestep"
15    Var(String),
16    /// Boolean literal
17    Bool(bool),
18    /// Integer literal
19    Int(i64),
20    /// Conjunction
21    And(Box<BoundedExpr>, Box<BoundedExpr>),
22    /// Disjunction
23    Or(Box<BoundedExpr>, Box<BoundedExpr>),
24    /// Negation
25    Not(Box<BoundedExpr>),
26    /// Implication: a → b
27    Implies(Box<BoundedExpr>, Box<BoundedExpr>),
28    /// Equality: a == b
29    Eq(Box<BoundedExpr>, Box<BoundedExpr>),
30    /// Less than: a < b
31    Lt(Box<BoundedExpr>, Box<BoundedExpr>),
32    /// Greater than: a > b
33    Gt(Box<BoundedExpr>, Box<BoundedExpr>),
34    /// Less than or equal: a <= b
35    Lte(Box<BoundedExpr>, Box<BoundedExpr>),
36    /// Greater than or equal: a >= b
37    Gte(Box<BoundedExpr>, Box<BoundedExpr>),
38    /// Unsupported construct (fail closed, not silently true)
39    Unsupported(String),
40
41    // ---- Multi-sorted extensions (SUPERCRUSH S0C) ----
42    /// Bitvector constant with explicit width
43    BitVecConst { width: u32, value: u64 },
44    /// Bitvector variable with known width
45    BitVecVar(String, u32),
46    /// Bitvector binary operation
47    BitVecBinary {
48        op: BitVecBoundedOp,
49        left: Box<BoundedExpr>,
50        right: Box<BoundedExpr>,
51    },
52    /// Bitvector extraction: operand\[high:low\]
53    BitVecExtract {
54        high: u32,
55        low: u32,
56        operand: Box<BoundedExpr>,
57    },
58    /// Bitvector concatenation
59    BitVecConcat(Box<BoundedExpr>, Box<BoundedExpr>),
60    /// Bitvector if-then-else — a predicated SELECT (the CGRA mux tile): `cond ? then : else_`,
61    /// where `cond` is boolean-valued and `then`/`else_` are same-width bitvectors. Lowered
62    /// bit-by-bit through the existing 1-bit mux, so branchy dataflow reduces to pure data.
63    BitVecIte {
64        cond: Box<BoundedExpr>,
65        then: Box<BoundedExpr>,
66        else_: Box<BoundedExpr>,
67    },
68    /// Array select: array\[index\]
69    ArraySelect {
70        array: Box<BoundedExpr>,
71        index: Box<BoundedExpr>,
72    },
73    /// Array store: array\[index\] := value
74    ArrayStore {
75        array: Box<BoundedExpr>,
76        index: Box<BoundedExpr>,
77        value: Box<BoundedExpr>,
78    },
79    /// Integer arithmetic binary operation
80    IntBinary {
81        op: ArithBoundedOp,
82        left: Box<BoundedExpr>,
83        right: Box<BoundedExpr>,
84    },
85    /// Comparison returning Bool from Int/BV operands
86    Comparison {
87        op: CmpBoundedOp,
88        left: Box<BoundedExpr>,
89        right: Box<BoundedExpr>,
90    },
91    /// Universal quantifier
92    ForAll {
93        var: String,
94        sort: BoundedSort,
95        body: Box<BoundedExpr>,
96    },
97    /// Existential quantifier
98    Exists {
99        var: String,
100        sort: BoundedSort,
101        body: Box<BoundedExpr>,
102    },
103    /// Uninterpreted function application (system functions like $onehot0, $bits, $clog2)
104    Apply {
105        name: String,
106        args: Vec<BoundedExpr>,
107    },
108}
109
110/// Bitvector operations in bounded IR.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum BitVecBoundedOp {
113    And,
114    Or,
115    Xor,
116    Not,
117    Shl,
118    Shr,
119    AShr,
120    Add,
121    Sub,
122    Mul,
123    ULt,
124    SLt,
125    Eq,
126}
127
128/// Arithmetic operations in bounded IR.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum ArithBoundedOp {
131    Add,
132    Sub,
133    Mul,
134    Div,
135}
136
137/// Comparison operations in bounded IR.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum CmpBoundedOp {
140    Gt,
141    Lt,
142    Gte,
143    Lte,
144}
145
146/// Sort annotation for bounded quantifiers.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum BoundedSort {
149    Bool,
150    Int,
151    BitVec(u32),
152    /// IEEE 1800-2023: Z3 Real sort for `rand real` checker variables
153    Real,
154}
155
156/// A single match endpoint for a sequence expression.
157///
158/// In IEEE 1800, sequences can have multiple possible match endpoints.
159/// For example, `##[1:3] ack` has three possible match points (at offsets 1, 2, 3).
160/// Each match has a boolean condition (what must hold) and a length (cycles from start).
161///
162/// Used by `translate_sequence()` to compute proper sequence-level AND, OR, intersect,
163/// first_match, throughout, and within semantics.
164#[derive(Debug, Clone)]
165pub struct SequenceMatch {
166    /// The boolean condition that must hold for this match to occur
167    pub condition: BoundedExpr,
168    /// Number of cycles from the sequence start tick to the match endpoint
169    pub length: u32,
170}
171
172/// Result of translating an SVA expression to bounded verification IR.
173pub struct TranslateResult {
174    pub expr: BoundedExpr,
175    pub declarations: Vec<String>, // signal@t variable names
176}
177
178/// Result of translating a directive — includes the semantic role.
179pub struct DirectiveResult {
180    pub expr: BoundedExpr,
181    pub declarations: Vec<String>,
182    pub role: DirectiveRole,
183}
184
185/// Translator that converts SvaExpr to bounded timestep verification IR.
186pub struct SvaTranslator {
187    pub bound: u32,
188    pub(crate) declarations: HashSet<String>,
189    /// Local variable bindings: maps variable name to the BoundedExpr captured
190    /// at assignment time. When a SequenceAction assigns `v = data_in` at timestep t,
191    /// we store `v → translate(data_in, t)`. When LocalVar("v") is later referenced
192    /// at any timestep, we return the captured value, not a fresh `v@t`.
193    local_bindings: HashMap<String, BoundedExpr>,
194    /// Queue timestep: set when entering an implication's consequent to the
195    /// antecedent's evaluation timestep. Used by `const'(expr)` to freeze
196    /// values at the assertion trigger time rather than the consequent's time.
197    queue_timestep: Option<u32>,
198}
199
200impl SvaTranslator {
201    pub fn new(bound: u32) -> Self {
202        Self {
203            bound,
204            declarations: HashSet::new(),
205            local_bindings: HashMap::new(),
206            queue_timestep: None,
207        }
208    }
209
210    /// Translate an SVA expression at a specific timestep.
211    pub fn translate(&mut self, expr: &SvaExpr, t: u32) -> BoundedExpr {
212        match expr {
213            SvaExpr::Signal(name) => {
214                let var_name = format!("{}@{}", name, t);
215                self.declarations.insert(var_name.clone());
216                BoundedExpr::Var(var_name)
217            }
218
219            SvaExpr::Const(value, _width) => BoundedExpr::Int(*value as i64),
220
221            SvaExpr::Rose(inner) => {
222                if t == 0 {
223                    // At t=0, rising edge = signal is high (no prior state)
224                    self.translate(inner, 0)
225                } else {
226                    let current = self.translate(inner, t);
227                    let previous = self.translate(inner, t - 1);
228                    BoundedExpr::And(
229                        Box::new(current),
230                        Box::new(BoundedExpr::Not(Box::new(previous))),
231                    )
232                }
233            }
234
235            SvaExpr::Fell(inner) => {
236                if t == 0 {
237                    BoundedExpr::Not(Box::new(self.translate(inner, 0)))
238                } else {
239                    let current = self.translate(inner, t);
240                    let previous = self.translate(inner, t - 1);
241                    BoundedExpr::And(
242                        Box::new(BoundedExpr::Not(Box::new(current))),
243                        Box::new(previous),
244                    )
245                }
246            }
247
248            SvaExpr::Past(inner, n) => {
249                if t >= *n {
250                    self.translate(inner, t - n)
251                } else {
252                    // No prior state available — return current value (vacuous identity)
253                    // This ensures $stable(sig) ≡ sig == $past(sig,1) at t=0:
254                    // $stable@0 = true, $past(sig,1)@0 = sig@0, so sig@0 == sig@0 = true ✓
255                    self.translate(inner, t)
256                }
257            }
258
259            SvaExpr::And(left, right) => {
260                let l = self.translate(left, t);
261                let r = self.translate(right, t);
262                BoundedExpr::And(Box::new(l), Box::new(r))
263            }
264
265            SvaExpr::Or(left, right) => {
266                let l = self.translate(left, t);
267                let r = self.translate(right, t);
268                BoundedExpr::Or(Box::new(l), Box::new(r))
269            }
270
271            SvaExpr::Not(inner) => {
272                let i = self.translate(inner, t);
273                BoundedExpr::Not(Box::new(i))
274            }
275
276            SvaExpr::Eq(left, right) => {
277                let l = self.translate(left, t);
278                let r = self.translate(right, t);
279                BoundedExpr::Eq(Box::new(l), Box::new(r))
280            }
281
282            SvaExpr::Implication {
283                antecedent,
284                consequent,
285                overlapping,
286            } => {
287                let ante = self.translate(antecedent, t);
288                let cons_t = if *overlapping { t } else { t + 1 };
289                // Set queue_timestep to the antecedent's time for const' freeze
290                let prev_queue = self.queue_timestep;
291                self.queue_timestep = Some(t);
292                let cons = self.translate(consequent, cons_t);
293                self.queue_timestep = prev_queue;
294                BoundedExpr::Implies(Box::new(ante), Box::new(cons))
295            }
296
297            SvaExpr::Delay { body, min, max } => match max {
298                // Unified convention: None = unbounded ($), Some(n) = bounded
299                Some(max_val) if max_val == min => {
300                    // Exact delay ##N: body@{t+N}
301                    self.translate(body, t + min)
302                }
303                Some(max_val) => {
304                    // ##[min:max] body → body@{t+min} ∨ body@{t+min+1} ∨ ... ∨ body@{t+max}
305                    let mut result: Option<BoundedExpr> = None;
306                    for offset in *min..=*max_val {
307                        let step = t + offset;
308                        if step > t + self.bound {
309                            break;
310                        }
311                        let b = self.translate(body, step);
312                        result = Some(match result {
313                            None => b,
314                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(b)),
315                        });
316                    }
317                    result.unwrap_or(BoundedExpr::Bool(false))
318                }
319                None => {
320                    // ##[min:$] body → unbounded, clamp to bound
321                    let mut result: Option<BoundedExpr> = None;
322                    for offset in *min..=self.bound {
323                        let step = t + offset;
324                        if step > t + self.bound {
325                            break;
326                        }
327                        let b = self.translate(body, step);
328                        result = Some(match result {
329                            None => b,
330                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(b)),
331                        });
332                    }
333                    result.unwrap_or(BoundedExpr::Bool(false))
334                }
335            },
336
337            SvaExpr::SEventually(inner) => {
338                // s_eventually(body) → body@{t+1} ∨ body@{t+2} ∨ ... ∨ body@{t+bound}
339                let mut result: Option<BoundedExpr> = None;
340                for offset in 1..=self.bound {
341                    let b = self.translate(inner, t + offset);
342                    result = Some(match result {
343                        None => b,
344                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(b)),
345                    });
346                }
347                result.unwrap_or(BoundedExpr::Bool(false))
348            }
349
350            SvaExpr::Stable(inner) => {
351                // $stable(sig) → sig@t == sig@(t-1)
352                // At t=0, no previous state → vacuously stable
353                if t == 0 {
354                    BoundedExpr::Bool(true)
355                } else {
356                    let current = self.translate(inner, t);
357                    let previous = self.translate(inner, t - 1);
358                    BoundedExpr::Eq(Box::new(current), Box::new(previous))
359                }
360            }
361
362            SvaExpr::Changed(inner) => {
363                // $changed(sig) → !(sig@t == sig@(t-1))
364                // At t=0, no previous state → vacuously not changed
365                if t == 0 {
366                    BoundedExpr::Bool(false)
367                } else {
368                    let current = self.translate(inner, t);
369                    let previous = self.translate(inner, t - 1);
370                    BoundedExpr::Not(Box::new(BoundedExpr::Eq(
371                        Box::new(current),
372                        Box::new(previous),
373                    )))
374                }
375            }
376
377            SvaExpr::Nexttime(inner, n) => {
378                // nexttime[N](body) → body@(t+N)
379                self.translate(inner, t + n)
380            }
381
382            SvaExpr::DisableIff { condition, body } => {
383                // disable iff (cond) body → ¬cond@t → body@t
384                // When disable condition is active, property is vacuously true
385                let cond = self.translate(condition, t);
386                let prop = self.translate(body, t);
387                BoundedExpr::Implies(Box::new(BoundedExpr::Not(Box::new(cond))), Box::new(prop))
388            }
389
390            SvaExpr::Repetition { body, min, max } => {
391                let effective_max = match max {
392                    Some(m) => *m,
393                    None => (*min).max(1) + self.bound,
394                };
395                if *min == effective_max {
396                    // Exact repetition [*N]: body@t ∧ body@{t+1} ∧ ... ∧ body@{t+N-1}
397                    let mut result: Option<BoundedExpr> = None;
398                    for offset in 0..*min {
399                        let b = self.translate(body, t + offset);
400                        result = Some(match result {
401                            None => b,
402                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
403                        });
404                    }
405                    result.unwrap_or(BoundedExpr::Bool(true))
406                } else {
407                    // Range repetition [*min:max]: ∨ over lengths, each a conjunction
408                    let mut outer: Option<BoundedExpr> = None;
409                    for len in *min..=effective_max {
410                        if len > self.bound + t {
411                            break;
412                        }
413                        let mut inner_conj: Option<BoundedExpr> = None;
414                        for offset in 0..len {
415                            let b = self.translate(body, t + offset);
416                            inner_conj = Some(match inner_conj {
417                                None => b,
418                                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
419                            });
420                        }
421                        let conj = inner_conj.unwrap_or(BoundedExpr::Bool(true));
422                        outer = Some(match outer {
423                            None => conj,
424                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(conj)),
425                        });
426                    }
427                    outer.unwrap_or(BoundedExpr::Bool(false))
428                }
429            }
430
431            SvaExpr::SAlways(inner) => {
432                // s_always(body) at t → body@t ∧ body@{t+1} ∧ ... ∧ body@{bound-1}
433                let remaining = if self.bound > t { self.bound - t } else { 1 };
434                let mut result: Option<BoundedExpr> = None;
435                for offset in 0..remaining {
436                    let b = self.translate(inner, t + offset);
437                    result = Some(match result {
438                        None => b,
439                        Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
440                    });
441                }
442                result.unwrap_or(BoundedExpr::Bool(true))
443            }
444
445            SvaExpr::IfElse {
446                condition,
447                then_expr,
448                else_expr,
449            } => {
450                // if (C) P else Q → (C@t → P@t) ∧ (¬C@t → Q@t)
451                let c = self.translate(condition, t);
452                let p = self.translate(then_expr, t);
453                let q = self.translate(else_expr, t);
454                BoundedExpr::And(
455                    Box::new(BoundedExpr::Implies(Box::new(c.clone()), Box::new(p))),
456                    Box::new(BoundedExpr::Implies(
457                        Box::new(BoundedExpr::Not(Box::new(c))),
458                        Box::new(q),
459                    )),
460                )
461            }
462
463            // ── IEEE 1800 Extended (Sprint 1B) ──
464            SvaExpr::NotEq(left, right) => {
465                // a != b → ¬(a == b) at timestep t
466                let l = self.translate(left, t);
467                let r = self.translate(right, t);
468                BoundedExpr::Not(Box::new(BoundedExpr::Eq(Box::new(l), Box::new(r))))
469            }
470
471            SvaExpr::LessThan(left, right) => {
472                let l = self.translate(left, t);
473                let r = self.translate(right, t);
474                BoundedExpr::Lt(Box::new(l), Box::new(r))
475            }
476
477            SvaExpr::GreaterThan(left, right) => {
478                let l = self.translate(left, t);
479                let r = self.translate(right, t);
480                BoundedExpr::Gt(Box::new(l), Box::new(r))
481            }
482
483            SvaExpr::LessEqual(left, right) => {
484                let l = self.translate(left, t);
485                let r = self.translate(right, t);
486                BoundedExpr::Lte(Box::new(l), Box::new(r))
487            }
488
489            SvaExpr::GreaterEqual(left, right) => {
490                let l = self.translate(left, t);
491                let r = self.translate(right, t);
492                BoundedExpr::Gte(Box::new(l), Box::new(r))
493            }
494
495            SvaExpr::Ternary {
496                condition,
497                then_expr,
498                else_expr,
499            } => {
500                // cond ? a : b → (cond@t ∧ a@t) ∨ (¬cond@t ∧ b@t)
501                let c = self.translate(condition, t);
502                let a = self.translate(then_expr, t);
503                let b = self.translate(else_expr, t);
504                BoundedExpr::Or(
505                    Box::new(BoundedExpr::And(Box::new(c.clone()), Box::new(a))),
506                    Box::new(BoundedExpr::And(
507                        Box::new(BoundedExpr::Not(Box::new(c))),
508                        Box::new(b),
509                    )),
510                )
511            }
512
513            SvaExpr::Throughout { signal, sequence } => {
514                // IEEE 16.9.9: sig throughout seq ≡ (sig[*0:$]) intersect seq
515                // The signal must hold at EVERY cycle of the sequence.
516                // Desugar: get sequence matches, and for each match at length L,
517                // conjoin signal at every tick from t to t+L.
518                let seq_matches = self.translate_sequence(sequence, t);
519                let mut outer: Option<BoundedExpr> = None;
520                for sm in &seq_matches {
521                    // Signal must hold at every tick from t to t+sm.length
522                    let mut sig_conj: Option<BoundedExpr> = None;
523                    for offset in 0..=sm.length {
524                        let s = self.translate(signal, t + offset);
525                        sig_conj = Some(match sig_conj {
526                            None => s,
527                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(s)),
528                        });
529                    }
530                    let sig_all = sig_conj.unwrap_or(BoundedExpr::Bool(true));
531                    // Both signal-at-every-tick AND sequence condition must hold
532                    let case = BoundedExpr::And(Box::new(sig_all), Box::new(sm.condition.clone()));
533                    outer = Some(match outer {
534                        None => case,
535                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(case)),
536                    });
537                }
538                outer.unwrap_or(BoundedExpr::Bool(false))
539            }
540
541            SvaExpr::Within { inner, outer } => {
542                // IEEE 16.9.10: seq1 within seq2
543                // Inner must start at or after outer start and end at or before outer end.
544                // For each outer match at length L_outer, try each possible inner start
545                // offset s in [0, L_outer], get inner matches, and only keep those where
546                // inner_start + inner_length <= L_outer.
547                let outer_matches = self.translate_sequence(outer, t);
548                let mut result: Option<BoundedExpr> = None;
549                for om in &outer_matches {
550                    // Try starting inner at each offset within the outer's span
551                    for inner_start in 0..=om.length {
552                        let inner_matches = self.translate_sequence(inner, t + inner_start);
553                        for im in &inner_matches {
554                            // Inner must end within outer's span
555                            if inner_start + im.length <= om.length {
556                                let case = BoundedExpr::And(
557                                    Box::new(om.condition.clone()),
558                                    Box::new(im.condition.clone()),
559                                );
560                                result = Some(match result {
561                                    None => case,
562                                    Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(case)),
563                                });
564                            }
565                        }
566                    }
567                }
568                result.unwrap_or(BoundedExpr::Bool(false))
569            }
570
571            SvaExpr::FirstMatch(inner) => {
572                // IEEE 16.9.8: first_match(seq) → only the earliest-completing match.
573                // Get all matches, find the minimum length, and only keep those.
574                // For priority encoding: shortest match condition AND NOT any shorter.
575                let matches = self.translate_sequence(inner, t);
576                if matches.is_empty() {
577                    return BoundedExpr::Bool(false);
578                }
579                let min_length = matches.iter().map(|m| m.length).min().unwrap_or(0);
580                let mut result: Option<BoundedExpr> = None;
581                for m in &matches {
582                    if m.length == min_length {
583                        result = Some(match result {
584                            None => m.condition.clone(),
585                            Some(acc) => {
586                                BoundedExpr::Or(Box::new(acc), Box::new(m.condition.clone()))
587                            }
588                        });
589                    }
590                }
591                result.unwrap_or(BoundedExpr::Bool(false))
592            }
593
594            SvaExpr::Intersect { left, right } => {
595                // IEEE 16.9.6: intersect requires both sequences to match AND have
596                // the SAME match length. Only pairs where left.length == right.length
597                // contribute to the result.
598                let left_matches = self.translate_sequence(left, t);
599                let right_matches = self.translate_sequence(right, t);
600                let mut outer: Option<BoundedExpr> = None;
601                for lm in &left_matches {
602                    for rm in &right_matches {
603                        if lm.length == rm.length {
604                            // Same length — this pair is valid
605                            let both = BoundedExpr::And(
606                                Box::new(lm.condition.clone()),
607                                Box::new(rm.condition.clone()),
608                            );
609                            outer = Some(match outer {
610                                None => both,
611                                Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(both)),
612                            });
613                        }
614                    }
615                }
616                // If no common lengths exist, the intersect can NEVER match
617                outer.unwrap_or(BoundedExpr::Bool(false))
618            }
619
620            // ── IEEE 1800 System Functions (Audit) ──
621            SvaExpr::OneHot0(inner) => {
622                let sig = self.translate(inner, t);
623                BoundedExpr::Apply {
624                    name: "onehot0".to_string(),
625                    args: vec![sig],
626                }
627            }
628
629            SvaExpr::OneHot(inner) => {
630                let sig = self.translate(inner, t);
631                BoundedExpr::Apply {
632                    name: "onehot".to_string(),
633                    args: vec![sig],
634                }
635            }
636
637            SvaExpr::CountOnes(inner) => {
638                let sig = self.translate(inner, t);
639                BoundedExpr::Apply {
640                    name: "countones".to_string(),
641                    args: vec![sig],
642                }
643            }
644
645            SvaExpr::IsUnknown(_) => {
646                // In 2-state formal verification, X/Z don't exist
647                BoundedExpr::Bool(false)
648            }
649
650            SvaExpr::Sampled(inner) => {
651                // In synchronous single-clock formal, $sampled == identity
652                self.translate(inner, t)
653            }
654
655            SvaExpr::Bits(inner) => {
656                let sig = self.translate(inner, t);
657                BoundedExpr::Apply {
658                    name: "bits".to_string(),
659                    args: vec![sig],
660                }
661            }
662
663            SvaExpr::Clog2(inner) => {
664                let val = self.translate(inner, t);
665                if let BoundedExpr::Int(n) = &val {
666                    let n = *n;
667                    let result = if n <= 1 {
668                        0i64
669                    } else {
670                        // IEEE 1800 $clog2: ceiling of log base 2
671                        // $clog2(n) = ceil(log2(n))
672                        let u = n as u64;
673                        // For power of 2: log2(u) exactly
674                        // For non-power: round up
675                        // u.next_power_of_two() gives the next power of 2 >= u
676                        // trailing_zeros gives log2 of that power
677                        u.next_power_of_two().trailing_zeros() as i64
678                    };
679                    BoundedExpr::Int(result)
680                } else {
681                    BoundedExpr::Apply {
682                        name: "clog2".to_string(),
683                        args: vec![val],
684                    }
685                }
686            }
687
688            // ── Sprint 13 System Functions ──
689            SvaExpr::CountBits(inner, control_chars) => {
690                let sig = self.translate(inner, t);
691                BoundedExpr::Apply {
692                    name: format!("countbits_{}", control_chars.iter().collect::<String>()),
693                    args: vec![sig],
694                }
695            }
696
697            SvaExpr::IsUnbounded(_) => {
698                // $isunbounded evaluates to a boolean constant at compile time
699                // In bounded model checking, parameters are always bounded
700                BoundedExpr::Bool(false)
701            }
702
703            // ── Advanced Sequences (Audit) ──
704            SvaExpr::GotoRepetition { body, count } => {
705                if *count == 0 {
706                    BoundedExpr::Bool(true)
707                } else if *count > self.bound {
708                    BoundedExpr::Bool(false)
709                } else {
710                    // Disjunction over all C(bound, count) subsets of timestep positions
711                    let combos = combinations(self.bound, *count);
712                    let mut disj: Option<BoundedExpr> = None;
713                    for combo in combos {
714                        let mut conj: Option<BoundedExpr> = None;
715                        for &pos in &combo {
716                            let b = self.translate(body, t + pos);
717                            conj = Some(match conj {
718                                None => b,
719                                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
720                            });
721                        }
722                        let term = conj.unwrap_or(BoundedExpr::Bool(true));
723                        disj = Some(match disj {
724                            None => term,
725                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(term)),
726                        });
727                    }
728                    disj.unwrap_or(BoundedExpr::Bool(false))
729                }
730            }
731
732            SvaExpr::NonConsecRepetition { body, min, max } => {
733                let effective_max = match max {
734                    Some(m) => *m,
735                    None => self.bound,
736                };
737                if *min > self.bound {
738                    BoundedExpr::Bool(false)
739                } else {
740                    let capped_max = effective_max.min(self.bound);
741                    let all_positions: Vec<u32> = (1..=self.bound).collect();
742                    let mut outer_disj: Option<BoundedExpr> = None;
743                    for count in *min..=capped_max {
744                        let combos = combinations(self.bound, count);
745                        for combo in combos {
746                            // body true at chosen positions, false at all others
747                            let mut conj: Option<BoundedExpr> = None;
748                            for &pos in &all_positions {
749                                let b = self.translate(body, t + pos);
750                                let term = if combo.contains(&pos) {
751                                    b
752                                } else {
753                                    BoundedExpr::Not(Box::new(b))
754                                };
755                                conj = Some(match conj {
756                                    None => term,
757                                    Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(term)),
758                                });
759                            }
760                            let term = conj.unwrap_or(BoundedExpr::Bool(true));
761                            outer_disj = Some(match outer_disj {
762                                None => term,
763                                Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(term)),
764                            });
765                        }
766                    }
767                    outer_disj.unwrap_or(BoundedExpr::Bool(false))
768                }
769            }
770
771            // ── Property Abort Operators (Audit) ──
772            SvaExpr::AcceptOn { condition, body } => {
773                // accept_on(C) P ≡ C ∨ P
774                let c = self.translate(condition, t);
775                let p = self.translate(body, t);
776                BoundedExpr::Or(Box::new(c), Box::new(p))
777            }
778
779            SvaExpr::RejectOn { condition, body } => {
780                // reject_on(C) P ≡ ¬C ∧ P
781                let c = self.translate(condition, t);
782                let p = self.translate(body, t);
783                BoundedExpr::And(Box::new(BoundedExpr::Not(Box::new(c))), Box::new(p))
784            }
785
786            // ── Property Connectives (Sprint 1, IEEE 16.12.3-8) ──
787            SvaExpr::PropertyNot(inner) => {
788                let i = self.translate(inner, t);
789                BoundedExpr::Not(Box::new(i))
790            }
791
792            SvaExpr::PropertyImplies(left, right) => {
793                let l = self.translate(left, t);
794                let r = self.translate(right, t);
795                BoundedExpr::Implies(Box::new(l), Box::new(r))
796            }
797
798            SvaExpr::PropertyIff(left, right) => {
799                // p iff q → And(Implies(p, q), Implies(q, p))
800                let l = self.translate(left, t);
801                let r = self.translate(right, t);
802                BoundedExpr::And(
803                    Box::new(BoundedExpr::Implies(
804                        Box::new(l.clone()),
805                        Box::new(r.clone()),
806                    )),
807                    Box::new(BoundedExpr::Implies(Box::new(r), Box::new(l))),
808                )
809            }
810
811            // ── LTL Temporal Operators (Sprint 2, IEEE 16.12.11-13) ──
812            SvaExpr::Always(inner) => {
813                // always p → ∀t ∈ [0, bound). p@t (weak: passes if trace ends)
814                let remaining = if self.bound > t { self.bound - t } else { 1 };
815                let mut result: Option<BoundedExpr> = None;
816                for offset in 0..remaining {
817                    let b = self.translate(inner, t + offset);
818                    result = Some(match result {
819                        None => b,
820                        Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
821                    });
822                }
823                result.unwrap_or(BoundedExpr::Bool(true))
824            }
825
826            SvaExpr::AlwaysBounded { body, min, max } => {
827                // always [m:n] p @ t → ∀i ∈ [m, n]. p@(t+i)
828                let effective_max = match max {
829                    Some(m) => *m,
830                    None => self.bound.saturating_sub(t), // $ clamped to bound
831                };
832                let mut result: Option<BoundedExpr> = None;
833                for i in *min..=effective_max {
834                    if t + i >= self.bound + t {
835                        break;
836                    } // clamp
837                    let b = self.translate(body, t + i);
838                    result = Some(match result {
839                        None => b,
840                        Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
841                    });
842                }
843                result.unwrap_or(BoundedExpr::Bool(true)) // weak: vacuously true if no ticks
844            }
845
846            SvaExpr::SAlwaysBounded { body, min, max } => {
847                // s_always [m:n] p @ t → ∀i ∈ [m, n]. p@(t+i) (strong: ticks must exist)
848                let mut result: Option<BoundedExpr> = None;
849                for i in *min..=*max {
850                    let b = self.translate(body, t + i);
851                    result = Some(match result {
852                        None => b,
853                        Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
854                    });
855                }
856                result.unwrap_or(BoundedExpr::Bool(true))
857            }
858
859            SvaExpr::EventuallyBounded { body, min, max } => {
860                // eventually [m:n] p @ t → ∃i ∈ [m, n]. p@(t+i)
861                let mut result: Option<BoundedExpr> = None;
862                for i in *min..=*max {
863                    let b = self.translate(body, t + i);
864                    result = Some(match result {
865                        None => b,
866                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(b)),
867                    });
868                }
869                result.unwrap_or(BoundedExpr::Bool(false))
870            }
871
872            SvaExpr::SEventuallyBounded { body, min, max } => {
873                // s_eventually [m:n] p @ t → ∃i ∈ [m, min(n, bound)]. p@(t+i)
874                let effective_max = match max {
875                    Some(m) => *m,
876                    None => self.bound.saturating_sub(t),
877                };
878                let mut result: Option<BoundedExpr> = None;
879                for i in *min..=effective_max {
880                    let b = self.translate(body, t + i);
881                    result = Some(match result {
882                        None => b,
883                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(b)),
884                    });
885                }
886                result.unwrap_or(BoundedExpr::Bool(false))
887            }
888
889            SvaExpr::Until {
890                lhs,
891                rhs,
892                strong,
893                inclusive,
894            } => {
895                // Bounded until encoding:
896                // ∃k ∈ [t, t+bound). rhs@k ∧ (∀j ∈ [t, k). lhs@j)
897                //   For inclusive (until_with): ∀j ∈ [t, k]. lhs@j (includes k)
898                //   For strong: rhs MUST appear within bound
899                //   For weak: if no rhs within bound, passes if lhs holds throughout
900                let max_k = t + self.bound;
901                let mut outer: Option<BoundedExpr> = None;
902                for k in t..max_k {
903                    let rhs_at_k = self.translate(rhs, k);
904                    // lhs holds at all j in [t, k) or [t, k] for inclusive
905                    let end = if *inclusive { k + 1 } else { k };
906                    let mut lhs_conj: Option<BoundedExpr> = None;
907                    for j in t..end {
908                        let l = self.translate(lhs, j);
909                        lhs_conj = Some(match lhs_conj {
910                            None => l,
911                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(l)),
912                        });
913                    }
914                    let lhs_all = lhs_conj.unwrap_or(BoundedExpr::Bool(true));
915                    let case = BoundedExpr::And(Box::new(rhs_at_k), Box::new(lhs_all));
916                    outer = Some(match outer {
917                        None => case,
918                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(case)),
919                    });
920                }
921                if !strong {
922                    // Weak: also passes if lhs holds at ALL ticks and rhs never appears
923                    let mut all_lhs: Option<BoundedExpr> = None;
924                    for j in t..max_k {
925                        let l = self.translate(lhs, j);
926                        all_lhs = Some(match all_lhs {
927                            None => l,
928                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(l)),
929                        });
930                    }
931                    let fallback = all_lhs.unwrap_or(BoundedExpr::Bool(true));
932                    outer = Some(match outer {
933                        None => fallback,
934                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(fallback)),
935                    });
936                }
937                outer.unwrap_or(BoundedExpr::Bool(false))
938            }
939
940            // ── Sprint 3: Strong/Weak, Advanced Temporal, Sync Abort ──
941            SvaExpr::Strong(inner) => {
942                // strong(seq): existential — at least one match endpoint MUST exist
943                // within bound. Translate as disjunction over sequence match endpoints.
944                // If no match exists → property FAILS.
945                let matches = self.translate_sequence(inner, t);
946                if matches.is_empty() {
947                    return BoundedExpr::Bool(false);
948                }
949                let mut result: Option<BoundedExpr> = None;
950                for m in &matches {
951                    let cond = m.condition.clone();
952                    result = Some(match result {
953                        None => cond,
954                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(cond)),
955                    });
956                }
957                result.unwrap_or(BoundedExpr::Bool(false))
958            }
959
960            SvaExpr::Weak(inner) => {
961                // weak(seq): if no match endpoint exists within bound, property
962                // PASSES (vacuously). Otherwise, at least one match must hold.
963                // Translate as: (exists a match) OR (no match possible within bound).
964                // In bounded model checking the "no match possible" case is when
965                // the trace ends before the sequence can complete — which is
966                // captured by allowing vacuous true when all match conditions are false.
967                let matches = self.translate_sequence(inner, t);
968                if matches.is_empty() {
969                    return BoundedExpr::Bool(true);
970                }
971                // any_match = disjunction of all match conditions
972                let mut any_match: Option<BoundedExpr> = None;
973                for m in &matches {
974                    let cond = m.condition.clone();
975                    any_match = Some(match any_match {
976                        None => cond,
977                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(cond)),
978                    });
979                }
980                // weak: if none of the match conditions hold, pass anyway
981                // This is equivalent to: any_match OR (NOT any_match) = true
982                // BUT that would be trivially true. The correct semantics is:
983                // if the sequence CAN complete (all required ticks exist), then
984                // at least one match must hold. If it CANNOT complete (bound too
985                // small), then pass. We approximate this in bounded BMC by checking
986                // whether the max match length exceeds remaining bound.
987                let max_length = matches.iter().map(|m| m.length).max().unwrap_or(0);
988                if t + max_length > self.bound {
989                    // Sequence cannot complete within bound — weak passes
990                    BoundedExpr::Bool(true)
991                } else {
992                    // Sequence can complete — must have at least one match
993                    any_match.unwrap_or(BoundedExpr::Bool(true))
994                }
995            }
996
997            SvaExpr::SNexttime(inner, n) => {
998                // s_nexttime[N] p → p@(t+N), strong: t+N must exist within bound
999                // IEEE 16.12.10: strong nexttime FAILS if the required timestep
1000                // is at or beyond the bound (the tick must exist)
1001                if t + n >= self.bound {
1002                    BoundedExpr::Bool(false)
1003                } else {
1004                    self.translate(inner, t + n)
1005                }
1006            }
1007
1008            SvaExpr::FollowedBy {
1009                antecedent,
1010                consequent,
1011                overlapping,
1012            } => {
1013                // seq #-# prop ≡ not (seq |-> not prop) (IEEE p.430)
1014                // seq #=# prop ≡ not (seq |=> not prop)
1015                let impl_expr = SvaExpr::Implication {
1016                    antecedent: antecedent.clone(),
1017                    consequent: Box::new(SvaExpr::Not(consequent.clone())),
1018                    overlapping: *overlapping,
1019                };
1020                let impl_result = self.translate(&impl_expr, t);
1021                BoundedExpr::Not(Box::new(impl_result))
1022            }
1023
1024            SvaExpr::PropertyCase {
1025                expression,
1026                items,
1027                default,
1028            } => {
1029                // case(expr) val: prop; ... → nested if-else
1030                let expr_val = self.translate(expression, t);
1031                let mut result = match default {
1032                    Some(d) => self.translate(d, t),
1033                    None => BoundedExpr::Bool(true), // no default → vacuously true
1034                };
1035                // Build from last to first (nested if-else chain)
1036                for (vals, prop) in items.iter().rev() {
1037                    let prop_translated = self.translate(prop, t);
1038                    // OR of all value matches
1039                    let mut cond: Option<BoundedExpr> = None;
1040                    for v in vals {
1041                        let v_translated = self.translate(v, t);
1042                        let eq =
1043                            BoundedExpr::Eq(Box::new(expr_val.clone()), Box::new(v_translated));
1044                        cond = Some(match cond {
1045                            None => eq,
1046                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(eq)),
1047                        });
1048                    }
1049                    let condition = cond.unwrap_or(BoundedExpr::Bool(false));
1050                    // if condition then prop else previous
1051                    result = BoundedExpr::And(
1052                        Box::new(BoundedExpr::Implies(
1053                            Box::new(condition.clone()),
1054                            Box::new(prop_translated),
1055                        )),
1056                        Box::new(BoundedExpr::Implies(
1057                            Box::new(BoundedExpr::Not(Box::new(condition))),
1058                            Box::new(result),
1059                        )),
1060                    );
1061                }
1062                result
1063            }
1064
1065            SvaExpr::SyncAcceptOn { condition, body } => {
1066                // sync_accept_on(C) P — like accept_on but C sampled at clock ticks only
1067                // In single-clock bounded model: same as accept_on
1068                let c = self.translate(condition, t);
1069                let p = self.translate(body, t);
1070                BoundedExpr::Or(Box::new(c), Box::new(p))
1071            }
1072
1073            SvaExpr::SyncRejectOn { condition, body } => {
1074                // sync_reject_on(C) P — like reject_on but C sampled at clock ticks only
1075                let c = self.translate(condition, t);
1076                let p = self.translate(body, t);
1077                BoundedExpr::And(Box::new(BoundedExpr::Not(Box::new(c))), Box::new(p))
1078            }
1079
1080            // ── Sprint 5: Sequence-level AND & OR ──
1081            SvaExpr::SequenceAnd(left, right) => {
1082                // IEEE 16.9.5 Thread semantics: both start at t, both must match,
1083                // composite ends at whichever finishes LAST (max endpoint).
1084                let left_matches = self.translate_sequence(left, t);
1085                let right_matches = self.translate_sequence(right, t);
1086                let mut outer: Option<BoundedExpr> = None;
1087                for lm in &left_matches {
1088                    for rm in &right_matches {
1089                        // Both conditions must hold; composite length = max
1090                        let _composite_length = lm.length.max(rm.length);
1091                        let both = BoundedExpr::And(
1092                            Box::new(lm.condition.clone()),
1093                            Box::new(rm.condition.clone()),
1094                        );
1095                        outer = Some(match outer {
1096                            None => both,
1097                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(both)),
1098                        });
1099                    }
1100                }
1101                outer.unwrap_or(BoundedExpr::Bool(false))
1102            }
1103
1104            SvaExpr::SequenceOr(left, right) => {
1105                // IEEE 16.9.7 Union semantics: at least one matches,
1106                // composite match set is the union of both.
1107                let left_matches = self.translate_sequence(left, t);
1108                let right_matches = self.translate_sequence(right, t);
1109                let mut outer: Option<BoundedExpr> = None;
1110                for m in left_matches.iter().chain(right_matches.iter()) {
1111                    outer = Some(match outer {
1112                        None => m.condition.clone(),
1113                        Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(m.condition.clone())),
1114                    });
1115                }
1116                outer.unwrap_or(BoundedExpr::Bool(false))
1117            }
1118
1119            // ── Sprint 7: Assertion Directives ──
1120            SvaExpr::ImmediateAssert { expression, .. } => {
1121                // Immediate assert → combinational check at each timestep
1122                self.translate(expression, t)
1123            }
1124
1125            // ── Sprint 13: Complex Data Types ──
1126            SvaExpr::FieldAccess { signal, field } => {
1127                let sig = self.translate(signal, t);
1128                // Field access → create a derived variable name
1129                match &sig {
1130                    BoundedExpr::Var(name) => {
1131                        let field_var =
1132                            format!("{}.{}", name.split('@').next().unwrap_or(name), field);
1133                        let var_name = format!("{}@{}", field_var, t);
1134                        self.declarations.insert(var_name.clone());
1135                        BoundedExpr::Var(var_name)
1136                    }
1137                    _ => sig, // fallback
1138                }
1139            }
1140
1141            SvaExpr::EnumLiteral { value, .. } => {
1142                // Enum literal → integer constant or uninterpreted
1143                BoundedExpr::Var(value.clone())
1144            }
1145
1146            // ── Sprint 14: Endpoint Methods ──
1147            SvaExpr::Triggered(name) => {
1148                let var_name = format!("{}.triggered@{}", name, t);
1149                self.declarations.insert(var_name.clone());
1150                BoundedExpr::Var(var_name)
1151            }
1152
1153            SvaExpr::Matched(name) => {
1154                let var_name = format!("{}.matched@{}", name, t);
1155                self.declarations.insert(var_name.clone());
1156                BoundedExpr::Var(var_name)
1157            }
1158
1159            // ── Sprint 15: Bitwise Operators ──
1160            SvaExpr::BitAnd(l, r) => {
1161                let left = self.translate(l, t);
1162                let right = self.translate(r, t);
1163                BoundedExpr::BitVecBinary {
1164                    op: BitVecBoundedOp::And,
1165                    left: Box::new(left),
1166                    right: Box::new(right),
1167                }
1168            }
1169
1170            SvaExpr::BitOr(l, r) => {
1171                let left = self.translate(l, t);
1172                let right = self.translate(r, t);
1173                BoundedExpr::BitVecBinary {
1174                    op: BitVecBoundedOp::Or,
1175                    left: Box::new(left),
1176                    right: Box::new(right),
1177                }
1178            }
1179
1180            SvaExpr::BitXor(l, r) => {
1181                let left = self.translate(l, t);
1182                let right = self.translate(r, t);
1183                BoundedExpr::BitVecBinary {
1184                    op: BitVecBoundedOp::Xor,
1185                    left: Box::new(left),
1186                    right: Box::new(right),
1187                }
1188            }
1189
1190            SvaExpr::BitNot(inner) => {
1191                let i = self.translate(inner, t);
1192                BoundedExpr::BitVecBinary {
1193                    op: BitVecBoundedOp::Not,
1194                    left: Box::new(i.clone()),
1195                    right: Box::new(i),
1196                }
1197            }
1198
1199            SvaExpr::ReductionAnd(inner) => {
1200                let sig = self.translate(inner, t);
1201                BoundedExpr::Apply {
1202                    name: "reduction_and".to_string(),
1203                    args: vec![sig],
1204                }
1205            }
1206
1207            SvaExpr::ReductionOr(inner) => {
1208                let sig = self.translate(inner, t);
1209                BoundedExpr::Apply {
1210                    name: "reduction_or".to_string(),
1211                    args: vec![sig],
1212                }
1213            }
1214
1215            SvaExpr::ReductionXor(inner) => {
1216                let sig = self.translate(inner, t);
1217                BoundedExpr::Apply {
1218                    name: "reduction_xor".to_string(),
1219                    args: vec![sig],
1220                }
1221            }
1222
1223            SvaExpr::BitSelect { signal, index } => {
1224                let s = self.translate(signal, t);
1225                let i = self.translate(index, t);
1226                BoundedExpr::ArraySelect {
1227                    array: Box::new(s),
1228                    index: Box::new(i),
1229                }
1230            }
1231
1232            SvaExpr::PartSelect { signal, high, low } => {
1233                let s = self.translate(signal, t);
1234                BoundedExpr::BitVecExtract {
1235                    high: *high,
1236                    low: *low,
1237                    operand: Box::new(s),
1238                }
1239            }
1240
1241            SvaExpr::Concat(items) => {
1242                if items.len() < 2 {
1243                    return items
1244                        .first()
1245                        .map(|i| self.translate(i, t))
1246                        .unwrap_or(BoundedExpr::Bool(false));
1247                }
1248                let mut result = self.translate(&items[0], t);
1249                for item in &items[1..] {
1250                    let r = self.translate(item, t);
1251                    result = BoundedExpr::BitVecConcat(Box::new(result), Box::new(r));
1252                }
1253                result
1254            }
1255
1256            // ── Sprint 10: Local Variables ──
1257            SvaExpr::SequenceAction {
1258                expression,
1259                assignments,
1260            } => {
1261                // The expression must hold, and all assignments capture values at this tick.
1262                // IEEE 16.10: assignments bind local variables to values at this timestep.
1263                // v = data_in at tick t → v resolves to data_in@t in subsequent references.
1264                let expr_cond = self.translate(expression, t);
1265                for (name, rhs) in assignments {
1266                    let bound_value = self.translate(rhs, t);
1267                    self.local_bindings.insert(name.clone(), bound_value);
1268                }
1269                expr_cond
1270            }
1271
1272            SvaExpr::LocalVar(name) => {
1273                // IEEE 16.10: Local variable reference resolves to the value captured
1274                // at assignment time, not the current timestep.
1275                if let Some(bound_value) = self.local_bindings.get(name) {
1276                    bound_value.clone()
1277                } else {
1278                    // Fallback: if no binding exists, create a timestep-specific variable
1279                    let var_name = format!("{}@{}", name, t);
1280                    self.declarations.insert(var_name.clone());
1281                    BoundedExpr::Var(var_name)
1282                }
1283            }
1284
1285            // ── Sprint 18: const' cast ──
1286            SvaExpr::ConstCast(inner) => {
1287                // IEEE 16.14.6.1: const'(expr) freezes the value at assertion queue time.
1288                // In an implication, the queue time is the antecedent's timestep.
1289                let freeze_t = self.queue_timestep.unwrap_or(t);
1290                self.translate(inner, freeze_t)
1291            }
1292
1293            // ── Sprint 12: Multi-Clock ──
1294            SvaExpr::Clocked { body, clock, .. } => {
1295                // In multi-clock BMC, each clock gets its own timestep domain.
1296                // For now, tag the variables with the clock domain name.
1297                // This enables downstream multi-clock analysis to distinguish domains.
1298                let inner = self.translate(body, t);
1299                // Wrap with clock domain context — variables in this subtree
1300                // are in the clock domain. We tag this by prefixing declarations.
1301                for decl in self.declarations.clone() {
1302                    if !decl.contains("__clk_") {
1303                        let tagged = format!("__clk_{}__{}", clock, decl);
1304                        self.declarations.insert(tagged);
1305                    }
1306                }
1307                inner
1308            }
1309
1310            // ── Sprint 23: IEEE 1800-2023 ──
1311            SvaExpr::ArrayMap { .. } => {
1312                BoundedExpr::Unsupported("array map with unknown size".to_string())
1313            }
1314            SvaExpr::TypeThis => BoundedExpr::Unsupported("type(this) in class scope".to_string()),
1315            SvaExpr::RealConst(_) => {
1316                // Real constants are used in checker assume constraints (e.g., r > 1.5)
1317                // They participate in Z3 Real arithmetic directly
1318                BoundedExpr::Unsupported("real constant outside checker context".to_string())
1319            }
1320        }
1321    }
1322
1323    /// Translate an SvaExpr as a SEQUENCE, returning all possible match endpoints.
1324    ///
1325    /// Unlike `translate()` which returns a single BoundedExpr, this returns the
1326    /// set of (condition, length) pairs representing all possible matches.
1327    /// This is the foundation for proper IEEE 1800 sequence-level operators:
1328    /// - SequenceAnd: both match, composite at max endpoint
1329    /// - SequenceOr: union of match sets
1330    /// - Intersect: both match at SAME length
1331    /// - first_match: only shortest match
1332    /// - throughout / within: desugared via intersect
1333    pub fn translate_sequence(&mut self, expr: &SvaExpr, t: u32) -> Vec<SequenceMatch> {
1334        match expr {
1335            // --- Delay: ##N or ##[min:max] ---
1336            SvaExpr::Delay { body, min, max } => {
1337                match max {
1338                    // Unified convention: None = unbounded ($), Some(n) = bounded
1339                    Some(max_val) if max_val == min => {
1340                        // Exact delay ##N: single offset at min
1341                        let body_matches = self.translate_sequence(body, t + min);
1342                        body_matches
1343                            .into_iter()
1344                            .map(|bm| SequenceMatch {
1345                                condition: bm.condition,
1346                                length: min + bm.length,
1347                            })
1348                            .collect()
1349                    }
1350                    Some(max_val) => {
1351                        // Range delay ##[min:max]: one possible match per offset
1352                        let mut matches = Vec::new();
1353                        for offset in *min..=*max_val {
1354                            if t + offset > t + self.bound {
1355                                break;
1356                            }
1357                            let body_matches = self.translate_sequence(body, t + offset);
1358                            for bm in body_matches {
1359                                matches.push(SequenceMatch {
1360                                    condition: bm.condition,
1361                                    length: offset + bm.length,
1362                                });
1363                            }
1364                        }
1365                        if matches.is_empty() {
1366                            matches.push(SequenceMatch {
1367                                condition: BoundedExpr::Bool(false),
1368                                length: *min,
1369                            });
1370                        }
1371                        matches
1372                    }
1373                    None => {
1374                        // Unbounded delay ##[min:$]: clamp to bound
1375                        let mut matches = Vec::new();
1376                        for offset in *min..=self.bound {
1377                            if t + offset > t + self.bound {
1378                                break;
1379                            }
1380                            let body_matches = self.translate_sequence(body, t + offset);
1381                            for bm in body_matches {
1382                                matches.push(SequenceMatch {
1383                                    condition: bm.condition,
1384                                    length: offset + bm.length,
1385                                });
1386                            }
1387                        }
1388                        if matches.is_empty() {
1389                            matches.push(SequenceMatch {
1390                                condition: BoundedExpr::Bool(false),
1391                                length: *min,
1392                            });
1393                        }
1394                        matches
1395                    }
1396                }
1397            }
1398
1399            // --- Repetition: [*N] or [*min:max] ---
1400            SvaExpr::Repetition { body, min, max } => {
1401                let effective_max = match max {
1402                    Some(m) => *m,
1403                    None => (*min).max(1) + self.bound,
1404                };
1405                let mut all_matches = Vec::new();
1406                for count in *min..=effective_max {
1407                    if count > self.bound + 1 {
1408                        break;
1409                    }
1410                    if count == 0 {
1411                        // [*0] matches immediately (empty sequence)
1412                        all_matches.push(SequenceMatch {
1413                            condition: BoundedExpr::Bool(true),
1414                            length: 0,
1415                        });
1416                        continue;
1417                    }
1418                    // For count N: body must match N consecutive times.
1419                    // The existing translate() evaluates body at offsets 0..N.
1420                    // Length = N - 1 (last match at offset N-1).
1421                    let total_length = count - 1;
1422                    if t + total_length > t + self.bound {
1423                        break;
1424                    }
1425                    let mut cond: Option<BoundedExpr> = None;
1426                    for offset in 0..count {
1427                        let b = self.translate(body, t + offset);
1428                        cond = Some(match cond {
1429                            None => b,
1430                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
1431                        });
1432                    }
1433                    all_matches.push(SequenceMatch {
1434                        condition: cond.unwrap_or(BoundedExpr::Bool(true)),
1435                        length: total_length,
1436                    });
1437                }
1438                if all_matches.is_empty() {
1439                    all_matches.push(SequenceMatch {
1440                        condition: BoundedExpr::Bool(false),
1441                        length: 0,
1442                    });
1443                }
1444                all_matches
1445            }
1446
1447            // --- Sequence concatenation via Implication (a ##N b) ---
1448            // In the parser, `a ##N b` → Implication { ante: a, cons: Delay{b,N,None}, overlapping: true }
1449            // In sequence context, this is conjunction, not material implication.
1450            SvaExpr::Implication {
1451                antecedent,
1452                consequent,
1453                overlapping,
1454            } => {
1455                let ante_matches = self.translate_sequence(antecedent, t);
1456                let mut all_matches = Vec::new();
1457                for am in &ante_matches {
1458                    let gap = if *overlapping { 0u32 } else { 1u32 };
1459                    let cons_start = t + am.length + gap;
1460                    if cons_start > t + self.bound {
1461                        continue;
1462                    }
1463                    let cons_matches = self.translate_sequence(consequent, cons_start);
1464                    for cm in &cons_matches {
1465                        let total_length = am.length + gap + cm.length;
1466                        if total_length > self.bound {
1467                            continue;
1468                        }
1469                        all_matches.push(SequenceMatch {
1470                            condition: BoundedExpr::And(
1471                                Box::new(am.condition.clone()),
1472                                Box::new(cm.condition.clone()),
1473                            ),
1474                            length: total_length,
1475                        });
1476                    }
1477                }
1478                if all_matches.is_empty() {
1479                    all_matches.push(SequenceMatch {
1480                        condition: BoundedExpr::Bool(false),
1481                        length: 0,
1482                    });
1483                }
1484                all_matches
1485            }
1486
1487            // --- Goto repetition: [->N] ---
1488            SvaExpr::GotoRepetition { body, count } => {
1489                if *count == 0 {
1490                    return vec![SequenceMatch {
1491                        condition: BoundedExpr::Bool(true),
1492                        length: 0,
1493                    }];
1494                }
1495                if *count > self.bound {
1496                    return vec![SequenceMatch {
1497                        condition: BoundedExpr::Bool(false),
1498                        length: 0,
1499                    }];
1500                }
1501                let combos = combinations(self.bound, *count);
1502                let mut matches = Vec::new();
1503                for combo in combos {
1504                    let end_pos = combo.last().copied().unwrap_or(0);
1505                    let mut conj: Option<BoundedExpr> = None;
1506                    for &pos in &combo {
1507                        let b = self.translate(body, t + pos);
1508                        conj = Some(match conj {
1509                            None => b,
1510                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(b)),
1511                        });
1512                    }
1513                    matches.push(SequenceMatch {
1514                        condition: conj.unwrap_or(BoundedExpr::Bool(true)),
1515                        length: end_pos,
1516                    });
1517                }
1518                matches
1519            }
1520
1521            // --- Non-consecutive repetition: [=N] ---
1522            SvaExpr::NonConsecRepetition { body, min, max } => {
1523                let effective_max = match max {
1524                    Some(m) => *m,
1525                    None => self.bound,
1526                };
1527                if *min > self.bound {
1528                    return vec![SequenceMatch {
1529                        condition: BoundedExpr::Bool(false),
1530                        length: 0,
1531                    }];
1532                }
1533                let capped_max = effective_max.min(self.bound);
1534                let all_positions: Vec<u32> = (1..=self.bound).collect();
1535                let mut all_matches = Vec::new();
1536                for count in *min..=capped_max {
1537                    let combos = combinations(self.bound, count);
1538                    for combo in combos {
1539                        let mut conj: Option<BoundedExpr> = None;
1540                        for &pos in &all_positions {
1541                            let b = self.translate(body, t + pos);
1542                            let term = if combo.contains(&pos) {
1543                                b
1544                            } else {
1545                                BoundedExpr::Not(Box::new(b))
1546                            };
1547                            conj = Some(match conj {
1548                                None => term,
1549                                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(term)),
1550                            });
1551                        }
1552                        // Non-consecutive can end anywhere within the bound
1553                        all_matches.push(SequenceMatch {
1554                            condition: conj.unwrap_or(BoundedExpr::Bool(true)),
1555                            length: self.bound,
1556                        });
1557                    }
1558                }
1559                if all_matches.is_empty() {
1560                    all_matches.push(SequenceMatch {
1561                        condition: BoundedExpr::Bool(true),
1562                        length: 0,
1563                    });
1564                }
1565                all_matches
1566            }
1567
1568            // --- Strong/Weak: forward to inner ---
1569            SvaExpr::Strong(inner) | SvaExpr::Weak(inner) => self.translate_sequence(inner, t),
1570
1571            // --- FirstMatch: only the shortest-length match (IEEE 16.9.8) ---
1572            SvaExpr::FirstMatch(inner) => {
1573                let matches = self.translate_sequence(inner, t);
1574                if matches.is_empty() {
1575                    return vec![SequenceMatch {
1576                        condition: BoundedExpr::Bool(false),
1577                        length: 0,
1578                    }];
1579                }
1580                let min_length = matches.iter().map(|m| m.length).min().unwrap_or(0);
1581                matches
1582                    .into_iter()
1583                    .filter(|m| m.length == min_length)
1584                    .collect()
1585            }
1586
1587            // --- Intersect: length-matching (IEEE 16.9.6) ---
1588            SvaExpr::Intersect { left, right } => {
1589                let left_matches = self.translate_sequence(left, t);
1590                let right_matches = self.translate_sequence(right, t);
1591                let mut combined = Vec::new();
1592                for lm in &left_matches {
1593                    for rm in &right_matches {
1594                        if lm.length == rm.length {
1595                            combined.push(SequenceMatch {
1596                                condition: BoundedExpr::And(
1597                                    Box::new(lm.condition.clone()),
1598                                    Box::new(rm.condition.clone()),
1599                                ),
1600                                length: lm.length,
1601                            });
1602                        }
1603                    }
1604                }
1605                if combined.is_empty() {
1606                    combined.push(SequenceMatch {
1607                        condition: BoundedExpr::Bool(false),
1608                        length: 0,
1609                    });
1610                }
1611                combined
1612            }
1613
1614            // --- SequenceAnd: thread semantics (IEEE 16.9.5) ---
1615            SvaExpr::SequenceAnd(left, right) => {
1616                let left_matches = self.translate_sequence(left, t);
1617                let right_matches = self.translate_sequence(right, t);
1618                let mut combined = Vec::new();
1619                for lm in &left_matches {
1620                    for rm in &right_matches {
1621                        combined.push(SequenceMatch {
1622                            condition: BoundedExpr::And(
1623                                Box::new(lm.condition.clone()),
1624                                Box::new(rm.condition.clone()),
1625                            ),
1626                            length: lm.length.max(rm.length),
1627                        });
1628                    }
1629                }
1630                if combined.is_empty() {
1631                    combined.push(SequenceMatch {
1632                        condition: BoundedExpr::Bool(false),
1633                        length: 0,
1634                    });
1635                }
1636                combined
1637            }
1638
1639            // --- SequenceOr: union semantics (IEEE 16.9.7) ---
1640            SvaExpr::SequenceOr(left, right) => {
1641                let mut left_matches = self.translate_sequence(left, t);
1642                let right_matches = self.translate_sequence(right, t);
1643                left_matches.extend(right_matches);
1644                if left_matches.is_empty() {
1645                    left_matches.push(SequenceMatch {
1646                        condition: BoundedExpr::Bool(false),
1647                        length: 0,
1648                    });
1649                }
1650                left_matches
1651            }
1652
1653            // --- All other expressions: atomic match at length 0 ---
1654            _ => {
1655                vec![SequenceMatch {
1656                    condition: self.translate(expr, t),
1657                    length: 0,
1658                }]
1659            }
1660        }
1661    }
1662
1663    /// Translate a top-level SVA property: conjoin over all timesteps [0, bound).
1664    /// This models G(property) — the property must hold at every reachable state.
1665    pub fn translate_property(&mut self, expr: &SvaExpr) -> TranslateResult {
1666        let mut result: Option<BoundedExpr> = None;
1667        for t in 0..self.bound {
1668            let step = self.translate(expr, t);
1669            result = Some(match result {
1670                None => step,
1671                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(step)),
1672            });
1673        }
1674        let expr = result.unwrap_or(BoundedExpr::Bool(true));
1675        let declarations: Vec<String> = self.declarations.iter().cloned().collect();
1676        TranslateResult { expr, declarations }
1677    }
1678
1679    /// Translate a concurrent assertion directive (IEEE 16.14).
1680    ///
1681    /// Returns a `DirectiveResult` with the translated expression and the directive's
1682    /// semantic role (check, constraint, or reachability query).
1683    pub fn translate_directive(
1684        &mut self,
1685        directive: &super::sva_model::SvaDirective,
1686    ) -> DirectiveResult {
1687        use super::sva_model::SvaDirectiveKind;
1688
1689        // First apply disable_iff if present
1690        let effective_property = if let Some(ref disable_cond) = directive.disable_iff {
1691            SvaExpr::DisableIff {
1692                condition: Box::new(disable_cond.clone()),
1693                body: Box::new(directive.property.clone()),
1694            }
1695        } else {
1696            directive.property.clone()
1697        };
1698
1699        let translated = self.translate_property(&effective_property);
1700
1701        match directive.kind {
1702            SvaDirectiveKind::Assert => DirectiveResult {
1703                expr: translated.expr,
1704                declarations: translated.declarations,
1705                role: DirectiveRole::Check,
1706            },
1707            SvaDirectiveKind::Assume | SvaDirectiveKind::Restrict => DirectiveResult {
1708                expr: translated.expr,
1709                declarations: translated.declarations,
1710                role: DirectiveRole::Constraint,
1711            },
1712            SvaDirectiveKind::Cover => DirectiveResult {
1713                expr: translated.expr,
1714                declarations: translated.declarations,
1715                role: DirectiveRole::Reachability,
1716            },
1717            SvaDirectiveKind::CoverSequence => DirectiveResult {
1718                expr: translated.expr,
1719                declarations: translated.declarations,
1720                role: DirectiveRole::ReachabilityMultiple,
1721            },
1722        }
1723    }
1724}
1725
1726/// The semantic role of a directive in formal verification.
1727#[derive(Debug, Clone, PartialEq)]
1728pub enum DirectiveRole {
1729    /// Assert: check property holds (negate and check UNSAT)
1730    Check,
1731    /// Assume/Restrict: add as solver constraint
1732    Constraint,
1733    /// Cover property: check reachability (SAT check, not UNSAT)
1734    Reachability,
1735    /// Cover sequence: count ALL matches (multiplicity)
1736    ReachabilityMultiple,
1737}
1738
1739/// Generate all k-element subsets of {1, 2, ..., n}.
1740/// Used for combinatorial expansion of goto/non-consecutive repetitions.
1741fn combinations(n: u32, k: u32) -> Vec<Vec<u32>> {
1742    if k == 0 {
1743        return vec![vec![]];
1744    }
1745    if k > n {
1746        return vec![];
1747    }
1748    let mut result = Vec::new();
1749    fn helper(start: u32, n: u32, k: u32, current: &mut Vec<u32>, result: &mut Vec<Vec<u32>>) {
1750        if current.len() == k as usize {
1751            result.push(current.clone());
1752            return;
1753        }
1754        for i in start..=n {
1755            current.push(i);
1756            helper(i + 1, n, k, current, result);
1757            current.pop();
1758        }
1759    }
1760    helper(1, n, k, &mut Vec::new(), &mut result);
1761    result
1762}
1763
1764/// Count the number of Or-leaves in a BoundedExpr tree.
1765pub fn count_or_leaves(e: &BoundedExpr) -> usize {
1766    match e {
1767        BoundedExpr::Or(left, right) => count_or_leaves(left) + count_or_leaves(right),
1768        _ => 1,
1769    }
1770}
1771
1772/// Count the number of And-leaves in a BoundedExpr tree.
1773pub fn count_and_leaves(e: &BoundedExpr) -> usize {
1774    match e {
1775        BoundedExpr::And(left, right) => count_and_leaves(left) + count_and_leaves(right),
1776        _ => 1,
1777    }
1778}
1779
1780/// Collect all signal names from declarations in a BoundedExpr tree.
1781fn collect_vars_from_bounded(expr: &BoundedExpr, vars: &mut std::collections::HashSet<String>) {
1782    match expr {
1783        BoundedExpr::Var(name) => {
1784            vars.insert(name.clone());
1785        }
1786        BoundedExpr::And(l, r)
1787        | BoundedExpr::Or(l, r)
1788        | BoundedExpr::Implies(l, r)
1789        | BoundedExpr::Eq(l, r)
1790        | BoundedExpr::Lt(l, r)
1791        | BoundedExpr::Gt(l, r)
1792        | BoundedExpr::Lte(l, r)
1793        | BoundedExpr::Gte(l, r)
1794        | BoundedExpr::BitVecConcat(l, r) => {
1795            collect_vars_from_bounded(l, vars);
1796            collect_vars_from_bounded(r, vars);
1797        }
1798        BoundedExpr::Not(inner) => collect_vars_from_bounded(inner, vars),
1799        BoundedExpr::BitVecVar(name, _) => {
1800            vars.insert(name.clone());
1801        }
1802        BoundedExpr::BitVecBinary { left, right, .. }
1803        | BoundedExpr::IntBinary { left, right, .. }
1804        | BoundedExpr::Comparison { left, right, .. } => {
1805            collect_vars_from_bounded(left, vars);
1806            collect_vars_from_bounded(right, vars);
1807        }
1808        BoundedExpr::BitVecExtract { operand, .. } => collect_vars_from_bounded(operand, vars),
1809        BoundedExpr::ArraySelect { array, index } => {
1810            collect_vars_from_bounded(array, vars);
1811            collect_vars_from_bounded(index, vars);
1812        }
1813        BoundedExpr::ArrayStore {
1814            array,
1815            index,
1816            value,
1817        } => {
1818            collect_vars_from_bounded(array, vars);
1819            collect_vars_from_bounded(index, vars);
1820            collect_vars_from_bounded(value, vars);
1821        }
1822        BoundedExpr::BitVecIte { cond, then, else_ } => {
1823            collect_vars_from_bounded(cond, vars);
1824            collect_vars_from_bounded(then, vars);
1825            collect_vars_from_bounded(else_, vars);
1826        }
1827        BoundedExpr::ForAll { body, .. } | BoundedExpr::Exists { body, .. } => {
1828            collect_vars_from_bounded(body, vars);
1829        }
1830        BoundedExpr::Apply { args, .. } => {
1831            for arg in args {
1832                collect_vars_from_bounded(arg, vars);
1833            }
1834        }
1835        BoundedExpr::Bool(_)
1836        | BoundedExpr::Int(_)
1837        | BoundedExpr::BitVecConst { .. }
1838        | BoundedExpr::Unsupported(_) => {}
1839    }
1840}
1841
1842/// Public wrapper for collect_vars_from_bounded (for testing).
1843pub fn collect_vars_from_bounded_pub(
1844    expr: &BoundedExpr,
1845    vars: &mut std::collections::HashSet<String>,
1846) {
1847    collect_vars_from_bounded(expr, vars);
1848}
1849
1850/// Translate a BoundedExpr (timestep-unrolled) into a VerifyExpr (Z3-ready).
1851///
1852/// This is the bridge from the compile crate to the verify crate.
1853/// Both SVA and FOL translate to BoundedExpr first; this function makes
1854/// them consumable by the Z3 solver for semantic equivalence checking.
1855#[cfg(feature = "verification")]
1856pub fn bounded_to_verify(expr: &BoundedExpr) -> logicaffeine_verify::VerifyExpr {
1857    use logicaffeine_verify::{VerifyExpr, VerifyOp};
1858    match expr {
1859        BoundedExpr::Var(name) => VerifyExpr::Var(name.clone()),
1860        BoundedExpr::Bool(b) => VerifyExpr::Bool(*b),
1861        BoundedExpr::Int(i) => VerifyExpr::Int(*i),
1862        BoundedExpr::And(l, r) => {
1863            VerifyExpr::binary(VerifyOp::And, bounded_to_verify(l), bounded_to_verify(r))
1864        }
1865        BoundedExpr::Or(l, r) => {
1866            VerifyExpr::binary(VerifyOp::Or, bounded_to_verify(l), bounded_to_verify(r))
1867        }
1868        BoundedExpr::Not(e) => VerifyExpr::not(bounded_to_verify(e)),
1869        BoundedExpr::Implies(l, r) => VerifyExpr::binary(
1870            VerifyOp::Implies,
1871            bounded_to_verify(l),
1872            bounded_to_verify(r),
1873        ),
1874        BoundedExpr::Eq(l, r) => {
1875            VerifyExpr::binary(VerifyOp::Eq, bounded_to_verify(l), bounded_to_verify(r))
1876        }
1877        BoundedExpr::Lt(l, r) => {
1878            VerifyExpr::binary(VerifyOp::Lt, bounded_to_verify(l), bounded_to_verify(r))
1879        }
1880        BoundedExpr::Gt(l, r) => {
1881            VerifyExpr::binary(VerifyOp::Gt, bounded_to_verify(l), bounded_to_verify(r))
1882        }
1883        BoundedExpr::Lte(l, r) => {
1884            VerifyExpr::binary(VerifyOp::Lte, bounded_to_verify(l), bounded_to_verify(r))
1885        }
1886        BoundedExpr::Gte(l, r) => {
1887            VerifyExpr::binary(VerifyOp::Gte, bounded_to_verify(l), bounded_to_verify(r))
1888        }
1889        BoundedExpr::Unsupported(_) => VerifyExpr::Bool(false),
1890        // `BitVecIte` is an our-SAT-only primitive (the CGRA mux tile is lowered bit-by-bit in
1891        // `bitblast`). The fabric proofs never route it through Z3, and VerifyExpr has no BV-ite;
1892        // fail CLOSED here (a `false` can only make a Z3 check fail, never falsely pass).
1893        BoundedExpr::BitVecIte { .. } => VerifyExpr::Bool(false),
1894
1895        // ---- Multi-sorted extensions ----
1896        BoundedExpr::BitVecConst { width, value } => VerifyExpr::bv_const(*width, *value),
1897        // Encode the bitvector width into the variable name (`name_bv<width>`), the convention
1898        // the Z3 equivalence encoder uses to recover a var's width. Dropping the width let the
1899        // encoder default to 8 — silently checking the wrong width for non-8-bit obligations,
1900        // and crashing (null AST) when a sized constant forced a width mismatch.
1901        BoundedExpr::BitVecVar(name, width) => VerifyExpr::Var(format!("{name}_bv{width}")),
1902        BoundedExpr::BitVecBinary { op, left, right } => {
1903            use logicaffeine_verify::BitVecOp;
1904            let vop = match op {
1905                BitVecBoundedOp::And => BitVecOp::And,
1906                BitVecBoundedOp::Or => BitVecOp::Or,
1907                BitVecBoundedOp::Xor => BitVecOp::Xor,
1908                BitVecBoundedOp::Not => BitVecOp::Not,
1909                BitVecBoundedOp::Shl => BitVecOp::Shl,
1910                BitVecBoundedOp::Shr => BitVecOp::Shr,
1911                BitVecBoundedOp::AShr => BitVecOp::AShr,
1912                BitVecBoundedOp::Add => BitVecOp::Add,
1913                BitVecBoundedOp::Sub => BitVecOp::Sub,
1914                BitVecBoundedOp::Mul => BitVecOp::Mul,
1915                BitVecBoundedOp::ULt => BitVecOp::ULt,
1916                BitVecBoundedOp::SLt => BitVecOp::SLt,
1917                BitVecBoundedOp::Eq => BitVecOp::Eq,
1918            };
1919            VerifyExpr::bv_binary(vop, bounded_to_verify(left), bounded_to_verify(right))
1920        }
1921        BoundedExpr::BitVecExtract { high, low, operand } => VerifyExpr::BitVecExtract {
1922            high: *high,
1923            low: *low,
1924            operand: Box::new(bounded_to_verify(operand)),
1925        },
1926        BoundedExpr::BitVecConcat(l, r) => VerifyExpr::BitVecConcat(
1927            Box::new(bounded_to_verify(l)),
1928            Box::new(bounded_to_verify(r)),
1929        ),
1930        BoundedExpr::ArraySelect { array, index } => VerifyExpr::Select {
1931            array: Box::new(bounded_to_verify(array)),
1932            index: Box::new(bounded_to_verify(index)),
1933        },
1934        BoundedExpr::ArrayStore {
1935            array,
1936            index,
1937            value,
1938        } => VerifyExpr::Store {
1939            array: Box::new(bounded_to_verify(array)),
1940            index: Box::new(bounded_to_verify(index)),
1941            value: Box::new(bounded_to_verify(value)),
1942        },
1943        BoundedExpr::IntBinary { op, left, right } => {
1944            let vop = match op {
1945                ArithBoundedOp::Add => VerifyOp::Add,
1946                ArithBoundedOp::Sub => VerifyOp::Sub,
1947                ArithBoundedOp::Mul => VerifyOp::Mul,
1948                ArithBoundedOp::Div => VerifyOp::Div,
1949            };
1950            VerifyExpr::binary(vop, bounded_to_verify(left), bounded_to_verify(right))
1951        }
1952        BoundedExpr::Comparison { op, left, right } => {
1953            let vop = match op {
1954                CmpBoundedOp::Gt => VerifyOp::Gt,
1955                CmpBoundedOp::Lt => VerifyOp::Lt,
1956                CmpBoundedOp::Gte => VerifyOp::Gte,
1957                CmpBoundedOp::Lte => VerifyOp::Lte,
1958            };
1959            VerifyExpr::binary(vop, bounded_to_verify(left), bounded_to_verify(right))
1960        }
1961        BoundedExpr::ForAll { var, sort, body } => {
1962            use logicaffeine_verify::VerifyType;
1963            let ty = match sort {
1964                BoundedSort::Bool => VerifyType::Bool,
1965                BoundedSort::Int => VerifyType::Int,
1966                BoundedSort::BitVec(w) => VerifyType::BitVector(*w),
1967                BoundedSort::Real => VerifyType::Real,
1968            };
1969            VerifyExpr::forall(vec![(var.clone(), ty)], bounded_to_verify(body))
1970        }
1971        BoundedExpr::Exists { var, sort, body } => {
1972            use logicaffeine_verify::VerifyType;
1973            let ty = match sort {
1974                BoundedSort::Bool => VerifyType::Bool,
1975                BoundedSort::Int => VerifyType::Int,
1976                BoundedSort::BitVec(w) => VerifyType::BitVector(*w),
1977                BoundedSort::Real => VerifyType::Real,
1978            };
1979            VerifyExpr::exists(vec![(var.clone(), ty)], bounded_to_verify(body))
1980        }
1981        BoundedExpr::Apply { name, args } => VerifyExpr::Apply {
1982            name: name.clone(),
1983            args: args.iter().map(bounded_to_verify).collect(),
1984        },
1985    }
1986}
1987
1988/// Extract signal names from a BoundedExpr by collecting all Var names
1989/// and stripping the @timestep suffix.
1990pub fn extract_signal_names(result: &TranslateResult) -> Vec<String> {
1991    let mut signals: HashSet<String> = HashSet::new();
1992    for decl in &result.declarations {
1993        if let Some(at_pos) = decl.find('@') {
1994            signals.insert(decl[..at_pos].to_string());
1995        } else {
1996            signals.insert(decl.clone());
1997        }
1998    }
1999    signals.into_iter().collect()
2000}