Skip to main content

logicaffeine_compile/codegen_sva/
sva_model.rs

1//! SVA Semantic Model
2//!
3//! Provides an AST for a subset of SystemVerilog Assertions, a parser
4//! for that subset, and structural equivalence checking.
5//!
6//! This model enables the Z3 semantic equivalence pipeline:
7//! FOL (from LOGOS) ↔ SVA (from LLM) checked for structural match.
8
9/// SVA expression AST — models a useful subset of SystemVerilog Assertions.
10#[derive(Debug, Clone)]
11pub enum SvaExpr {
12    /// Signal reference: `req`, `ack`, `data_out`
13    Signal(String),
14    /// Integer constant with bit width: `8'hFF`
15    Const(u64, u32),
16    /// Rising edge: `$rose(sig)`
17    Rose(Box<SvaExpr>),
18    /// Falling edge: `$fell(sig)`
19    Fell(Box<SvaExpr>),
20    /// Past value: `$past(sig, n)`
21    Past(Box<SvaExpr>, u32),
22    /// Conjunction: `a && b`
23    And(Box<SvaExpr>, Box<SvaExpr>),
24    /// Disjunction: `a || b`
25    Or(Box<SvaExpr>, Box<SvaExpr>),
26    /// Negation: `!a`
27    Not(Box<SvaExpr>),
28    /// Equality: `a == b`
29    Eq(Box<SvaExpr>, Box<SvaExpr>),
30    /// SVA implication: `a |-> b` (overlapping) or `a |=> b` (non-overlapping)
31    Implication {
32        antecedent: Box<SvaExpr>,
33        consequent: Box<SvaExpr>,
34        overlapping: bool,
35    },
36    /// Delay: `##[min:max] body`
37    Delay {
38        body: Box<SvaExpr>,
39        min: u32,
40        max: Option<u32>,
41    },
42    /// Sequence repetition: `body[*N]` or `body[*min:max]`
43    Repetition {
44        body: Box<SvaExpr>,
45        min: u32,
46        max: Option<u32>, // None = unbounded ($)
47    },
48    /// Strong eventually: `s_eventually(body)`
49    SEventually(Box<SvaExpr>),
50    /// Strong always: `s_always(body)`
51    SAlways(Box<SvaExpr>),
52    /// Stable: `$stable(sig)` — signal unchanged from previous cycle
53    Stable(Box<SvaExpr>),
54    /// Changed: `$changed(sig)` — signal changed from previous cycle
55    Changed(Box<SvaExpr>),
56    /// Disable condition: `disable iff (cond) body`
57    DisableIff {
58        condition: Box<SvaExpr>,
59        body: Box<SvaExpr>,
60    },
61    /// Next time: `nexttime(body)` or `nexttime[N](body)`
62    Nexttime(Box<SvaExpr>, u32),
63    /// Conditional property: `if (cond) P else Q`
64    IfElse {
65        condition: Box<SvaExpr>,
66        then_expr: Box<SvaExpr>,
67        else_expr: Box<SvaExpr>,
68    },
69    // ── IEEE 1800 Extended Constructs (Sprint 1B) ──
70    /// Inequality: `a != b`
71    NotEq(Box<SvaExpr>, Box<SvaExpr>),
72    /// Less than: `a < b`
73    LessThan(Box<SvaExpr>, Box<SvaExpr>),
74    /// Greater than: `a > b`
75    GreaterThan(Box<SvaExpr>, Box<SvaExpr>),
76    /// Less or equal: `a <= b`
77    LessEqual(Box<SvaExpr>, Box<SvaExpr>),
78    /// Greater or equal: `a >= b`
79    GreaterEqual(Box<SvaExpr>, Box<SvaExpr>),
80    /// Ternary: `cond ? a : b`
81    Ternary {
82        condition: Box<SvaExpr>,
83        then_expr: Box<SvaExpr>,
84        else_expr: Box<SvaExpr>,
85    },
86    /// Throughout: `sig throughout seq` — signal holds during entire sequence
87    Throughout {
88        signal: Box<SvaExpr>,
89        sequence: Box<SvaExpr>,
90    },
91    /// Within: `seq1 within seq2` — first sequence completes within second
92    Within {
93        inner: Box<SvaExpr>,
94        outer: Box<SvaExpr>,
95    },
96    /// First match: `first_match(seq)` — matches at first completion
97    FirstMatch(Box<SvaExpr>),
98    /// Intersect: `seq1 intersect seq2` — both sequences match with same length
99    Intersect {
100        left: Box<SvaExpr>,
101        right: Box<SvaExpr>,
102    },
103    // ── IEEE 1800 System Functions (Audit) ──
104    /// At most one bit set: `$onehot0(sig)` — popcount ≤ 1
105    OneHot0(Box<SvaExpr>),
106    /// Exactly one bit set: `$onehot(sig)` — popcount = 1
107    OneHot(Box<SvaExpr>),
108    /// Population count: `$countones(sig)` — returns integer
109    CountOnes(Box<SvaExpr>),
110    /// X/Z detection: `$isunknown(sig)` — always false in 2-state formal
111    IsUnknown(Box<SvaExpr>),
112    /// Sampled value: `$sampled(sig)` — identity in synchronous formal
113    Sampled(Box<SvaExpr>),
114    /// Bit width: `$bits(sig)` — returns integer
115    Bits(Box<SvaExpr>),
116    /// Ceiling log2: `$clog2(val)` — minimum bits to represent val
117    Clog2(Box<SvaExpr>),
118    // ── IEEE 1800 System Functions (Sprint 13) ──
119    /// Generalized bit counting: `$countbits(sig, '0', '1', ...)` (IEEE 20.9)
120    CountBits(Box<SvaExpr>, Vec<char>),
121    /// Parameter bound check: `$isunbounded(param)` (IEEE 20.9)
122    IsUnbounded(Box<SvaExpr>),
123    // ── Advanced Sequences (Audit) ──
124    /// Goto repetition: `sig[->N]` — N non-consecutive matches
125    GotoRepetition {
126        body: Box<SvaExpr>,
127        count: u32,
128    },
129    /// Non-consecutive repetition: `sig[=N]` or `sig[=min:max]`
130    NonConsecRepetition {
131        body: Box<SvaExpr>,
132        min: u32,
133        max: Option<u32>,
134    },
135    // ── Property Abort Operators (Audit) ──
136    /// Accept on: `accept_on(cond) body` — property passes if cond true
137    AcceptOn {
138        condition: Box<SvaExpr>,
139        body: Box<SvaExpr>,
140    },
141    /// Reject on: `reject_on(cond) body` — property fails if cond true
142    RejectOn {
143        condition: Box<SvaExpr>,
144        body: Box<SvaExpr>,
145    },
146    // ── Property Connectives (Sprint 1, IEEE 16.12.3-8) ──
147    /// Property negation: `not property_expr` (IEEE 16.12.3)
148    /// Distinct from boolean `!` — negates temporal property evaluation.
149    /// Flips strength: not(weak) → strong, not(strong) → weak (IEEE 16.12.15).
150    PropertyNot(Box<SvaExpr>),
151    /// Property implication: `p implies q` (IEEE 16.12.8)
152    /// Distinct from sequence `|->` — property-level `not p or q`.
153    PropertyImplies(Box<SvaExpr>, Box<SvaExpr>),
154    /// Property biconditional: `p iff q` (IEEE 16.12.8)
155    /// Equivalent to `(p implies q) and (q implies p)`.
156    PropertyIff(Box<SvaExpr>, Box<SvaExpr>),
157    // ── LTL Temporal Operators (Sprint 2, IEEE 16.12.11-13) ──
158    /// Weak unbounded always: `always p` (IEEE 16.12.11)
159    /// Passes if trace ends (weak semantics).
160    Always(Box<SvaExpr>),
161    /// Weak bounded always: `always [m:n] p` (IEEE 16.12.11)
162    /// max=None means $ (weak allows $).
163    AlwaysBounded {
164        body: Box<SvaExpr>,
165        min: u32,
166        max: Option<u32>,
167    },
168    /// Strong bounded always: `s_always [m:n] p` (IEEE 16.12.11)
169    /// All ticks must exist. NO $ allowed.
170    SAlwaysBounded {
171        body: Box<SvaExpr>,
172        min: u32,
173        max: u32,
174    },
175    /// Weak bounded eventually: `eventually [m:n] p` (IEEE 16.12.13)
176    /// Range must be bounded (no $).
177    EventuallyBounded {
178        body: Box<SvaExpr>,
179        min: u32,
180        max: u32,
181    },
182    /// Strong bounded eventually: `s_eventually [m:n] p` (IEEE 16.12.13)
183    /// CAN use $ (max=None means $).
184    SEventuallyBounded {
185        body: Box<SvaExpr>,
186        min: u32,
187        max: Option<u32>,
188    },
189    /// Until operator with 4 variants (IEEE 16.12.12):
190    /// `p until q` (weak, non-overlapping)
191    /// `p s_until q` (strong, non-overlapping)
192    /// `p until_with q` (weak, overlapping)
193    /// `p s_until_with q` (strong, overlapping)
194    Until {
195        lhs: Box<SvaExpr>,
196        rhs: Box<SvaExpr>,
197        strong: bool,
198        inclusive: bool,
199    },
200    // ── Strong/Weak, Advanced Temporal & Sync Abort (Sprint 3, IEEE 16.12.2, 16.12.9-10, 16.12.14, 16.12.16) ──
201    /// Strong sequence: `strong(seq)` (IEEE 16.12.2) — match must exist within bound
202    Strong(Box<SvaExpr>),
203    /// Weak sequence: `weak(seq)` (IEEE 16.12.2) — no match needed if bound exhausted
204    Weak(Box<SvaExpr>),
205    /// Strong nexttime: `s_nexttime(body)` or `s_nexttime[N](body)` (IEEE 16.12.10)
206    SNexttime(Box<SvaExpr>, u32),
207    /// Followed-by: `seq #-# prop` (overlapping) or `seq #=# prop` (non-overlapping) (IEEE 16.12.9)
208    FollowedBy {
209        antecedent: Box<SvaExpr>,
210        consequent: Box<SvaExpr>,
211        overlapping: bool,
212    },
213    /// Property case: `case(expr) val: prop; ... default: prop; endcase` (IEEE 16.12.16)
214    PropertyCase {
215        expression: Box<SvaExpr>,
216        items: Vec<(Vec<SvaExpr>, Box<SvaExpr>)>,
217        default: Option<Box<SvaExpr>>,
218    },
219    /// Synchronous accept abort: `sync_accept_on(cond) body` (IEEE 16.12.14)
220    SyncAcceptOn {
221        condition: Box<SvaExpr>,
222        body: Box<SvaExpr>,
223    },
224    /// Synchronous reject abort: `sync_reject_on(cond) body` (IEEE 16.12.14)
225    SyncRejectOn {
226        condition: Box<SvaExpr>,
227        body: Box<SvaExpr>,
228    },
229    // ── Sequence-Level AND & OR (Sprint 5, IEEE 16.9.5, 16.9.7) ──
230    /// Sequence AND: both operands match, composite ends at whichever finishes last
231    SequenceAnd(Box<SvaExpr>, Box<SvaExpr>),
232    /// Sequence OR: at least one matches, composite match set is union
233    SequenceOr(Box<SvaExpr>, Box<SvaExpr>),
234    // ── Assertion Directives (Sprint 7, IEEE 16.2-4, 16.14) ──
235    /// Immediate assertion: `assert(expr)`, `assert #0(expr)`, `assert final(expr)`
236    ImmediateAssert {
237        expression: Box<SvaExpr>,
238        deferred: Option<ImmediateDeferred>,
239    },
240    // ── Complex Data Types (Sprint 13, IEEE 16.6, 20.9) ──
241    /// Field access: `req.addr` or `req.header.id`
242    FieldAccess {
243        signal: Box<SvaExpr>,
244        field: String,
245    },
246    /// Enum literal: `ST_READ` or `state_t::READ`
247    EnumLiteral {
248        type_name: Option<String>,
249        value: String,
250    },
251    // ── Endpoint Methods (Sprint 14, IEEE 16.9.11) ──
252    /// Triggered endpoint: `seq_name.triggered`
253    Triggered(String),
254    /// Matched endpoint: `seq_name.matched`
255    Matched(String),
256    // ── Bitwise Operators (Sprint 15, IEEE 16.6) ──
257    BitAnd(Box<SvaExpr>, Box<SvaExpr>),
258    BitOr(Box<SvaExpr>, Box<SvaExpr>),
259    BitXor(Box<SvaExpr>, Box<SvaExpr>),
260    BitNot(Box<SvaExpr>),
261    ReductionAnd(Box<SvaExpr>),
262    ReductionOr(Box<SvaExpr>),
263    ReductionXor(Box<SvaExpr>),
264    BitSelect {
265        signal: Box<SvaExpr>,
266        index: Box<SvaExpr>,
267    },
268    PartSelect {
269        signal: Box<SvaExpr>,
270        high: u32,
271        low: u32,
272    },
273    Concat(Vec<SvaExpr>),
274    // ── Local Variables (Sprint 10, IEEE 16.10) ──
275    /// Sequence match with local variable assignments:
276    /// `(expr, v = rhs, w = rhs2)` — expression matches AND variables assigned
277    SequenceAction {
278        expression: Box<SvaExpr>,
279        assignments: Vec<(String, Box<SvaExpr>)>,
280    },
281    /// Local variable reference within a sequence/property
282    LocalVar(String),
283    // ── Let Construct (Sprint 16, IEEE 11.12) ──
284    /// const' cast: `const'(expr)` — freezes value at queue time
285    ConstCast(Box<SvaExpr>),
286    // ── Multi-Clock (Sprint 12, IEEE 16.13) ──
287    /// Clocked expression: `@(posedge clk) body` — preserves clock annotation for multi-clock
288    Clocked {
289        clock: String,
290        edge: ClockEdge,
291        body: Box<SvaExpr>,
292    },
293    // ── IEEE 1800-2023 Additions (Sprint 23) ──
294    /// Array map method: `A.map(x) with (expr)` (IEEE 7.12, 2023)
295    ArrayMap {
296        array: Box<SvaExpr>,
297        iterator: String,
298        with_expr: Box<SvaExpr>,
299    },
300    /// Type operator: `type(this)` (IEEE 6.23, 2023)
301    TypeThis,
302    /// Real literal constant: `1.5`, `1.2E3` (IEEE 5.7.2, 2023)
303    RealConst(f64),
304}
305
306/// Clock edge type
307#[derive(Debug, Clone, PartialEq)]
308pub enum ClockEdge {
309    Posedge,
310    Negedge,
311    Edge, // any edge
312}
313
314/// Deferred assertion timing (IEEE 16.4)
315#[derive(Debug, Clone, PartialEq)]
316pub enum ImmediateDeferred {
317    /// `#0` — observed region
318    Observed,
319    /// `final` — final simulation phase
320    Final,
321}
322
323/// Assertion directive kind (IEEE 16.14)
324#[derive(Debug, Clone, PartialEq)]
325pub enum SvaDirectiveKind {
326    Assert,
327    Assume,
328    Cover,
329    CoverSequence,
330    Restrict,
331}
332
333/// A concurrent assertion directive (IEEE 16.14)
334#[derive(Debug, Clone)]
335pub struct SvaDirective {
336    pub kind: SvaDirectiveKind,
337    pub property: SvaExpr,
338    pub label: Option<String>,
339    pub clock: Option<String>,
340    pub disable_iff: Option<SvaExpr>,
341    pub action_pass: Option<String>,
342    pub action_fail: Option<String>,
343}
344
345/// Port type for named sequence/property declarations (IEEE 16.8, 16.12)
346#[derive(Debug, Clone, PartialEq)]
347pub enum SvaPortType {
348    Untyped,
349    Bit,
350    Sequence,
351    Property,
352}
353
354/// A port in a named sequence or property declaration
355#[derive(Debug, Clone)]
356pub struct SvaPort {
357    pub name: String,
358    pub port_type: SvaPortType,
359    pub default: Option<SvaExpr>,
360}
361
362/// Named sequence declaration (IEEE 16.8)
363#[derive(Debug, Clone)]
364pub struct SequenceDecl {
365    pub name: String,
366    pub ports: Vec<SvaPort>,
367    pub body: SvaExpr,
368}
369
370/// Named property declaration (IEEE 16.12)
371#[derive(Debug, Clone)]
372pub struct PropertyDecl {
373    pub name: String,
374    pub ports: Vec<SvaPort>,
375    pub body: SvaExpr,
376}
377
378/// Let declaration (IEEE 11.12) — pure expression substitution
379#[derive(Debug, Clone)]
380pub struct LetDecl {
381    pub name: String,
382    pub ports: Vec<SvaPort>,
383    pub body: SvaExpr,
384}
385
386/// Dist weight kind (IEEE 18.5.4)
387#[derive(Debug, Clone, PartialEq)]
388pub enum DistKind {
389    /// `:=` — weight per value
390    PerValue,
391    /// `:/` — weight distributed across range
392    PerRange,
393}
394
395/// A dist item — value or range with weight
396#[derive(Debug, Clone)]
397pub struct DistItem {
398    pub min: u64,
399    pub max: Option<u64>,
400    pub weight: u64,
401    pub kind: DistKind,
402}
403
404/// Checker declaration (IEEE Chapter 17)
405#[derive(Debug, Clone)]
406pub struct CheckerDecl {
407    pub name: String,
408    pub ports: Vec<SvaPort>,
409    pub rand_vars: Vec<RandVar>,
410    pub assertions: Vec<SvaDirective>,
411}
412
413/// Type discriminant for random variables (IEEE 17.7, extended in 2023)
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub enum RandVarType {
416    /// Bitvector with width: `rand bit [N-1:0]`
417    BitVec(u32),
418    /// IEEE 754 double: `rand real` (IEEE 1800-2023)
419    Real,
420}
421
422/// Random variable in a checker (IEEE 17.7)
423#[derive(Debug, Clone)]
424pub struct RandVar {
425    pub name: String,
426    pub var_type: RandVarType,
427    pub is_const: bool,
428}
429
430/// Resolve a sequence instance by substituting actuals for formals.
431pub fn resolve_sequence_instance(
432    decls: &[SequenceDecl],
433    name: &str,
434    args: &[SvaExpr],
435) -> Result<SvaExpr, SvaParseError> {
436    let decl = decls
437        .iter()
438        .find(|d| d.name == name)
439        .ok_or_else(|| SvaParseError {
440            message: format!("undeclared sequence: '{}'", name),
441        })?;
442
443    let expected = decl.ports.len();
444    let provided = args.len();
445    // Count ports without defaults to determine minimum args
446    let min_args = decl.ports.iter().filter(|p| p.default.is_none()).count();
447    if provided < min_args || provided > expected {
448        return Err(SvaParseError {
449            message: format!(
450                "sequence '{}' expects {}-{} arguments, got {}",
451                name, min_args, expected, provided
452            ),
453        });
454    }
455
456    let mut result = decl.body.clone();
457    for (i, port) in decl.ports.iter().enumerate() {
458        let actual = if i < args.len() {
459            args[i].clone()
460        } else if let Some(ref default) = port.default {
461            default.clone()
462        } else {
463            return Err(SvaParseError {
464                message: format!(
465                    "missing argument for port '{}' in sequence '{}'",
466                    port.name, name
467                ),
468            });
469        };
470        result = substitute_signal(&result, &port.name, &actual);
471    }
472    Ok(result)
473}
474
475/// Substitute all occurrences of signal `name` with `replacement` in an expression.
476/// Handles all 78 SvaExpr variants recursively.
477fn substitute_signal(expr: &SvaExpr, name: &str, replacement: &SvaExpr) -> SvaExpr {
478    let sub = |e: &SvaExpr| Box::new(substitute_signal(e, name, replacement));
479    let sub_vec = |v: &[SvaExpr]| {
480        v.iter()
481            .map(|e| substitute_signal(e, name, replacement))
482            .collect::<Vec<_>>()
483    };
484
485    match expr {
486        // ── Terminals ──
487        SvaExpr::Signal(s) if s == name => replacement.clone(),
488        SvaExpr::Signal(_) | SvaExpr::Const(_, _) => expr.clone(),
489        SvaExpr::LocalVar(s) if s == name => replacement.clone(),
490        SvaExpr::LocalVar(_) => expr.clone(),
491        SvaExpr::Triggered(s) => SvaExpr::Triggered(s.clone()),
492        SvaExpr::Matched(s) => SvaExpr::Matched(s.clone()),
493        SvaExpr::EnumLiteral { type_name, value } => SvaExpr::EnumLiteral {
494            type_name: type_name.clone(),
495            value: value.clone(),
496        },
497
498        // ── Unary wrappers ──
499        SvaExpr::Rose(inner) => SvaExpr::Rose(sub(inner)),
500        SvaExpr::Fell(inner) => SvaExpr::Fell(sub(inner)),
501        SvaExpr::Not(inner) => SvaExpr::Not(sub(inner)),
502        SvaExpr::Stable(inner) => SvaExpr::Stable(sub(inner)),
503        SvaExpr::Changed(inner) => SvaExpr::Changed(sub(inner)),
504        SvaExpr::SEventually(inner) => SvaExpr::SEventually(sub(inner)),
505        SvaExpr::SAlways(inner) => SvaExpr::SAlways(sub(inner)),
506        SvaExpr::Always(inner) => SvaExpr::Always(sub(inner)),
507        SvaExpr::FirstMatch(inner) => SvaExpr::FirstMatch(sub(inner)),
508        SvaExpr::Strong(inner) => SvaExpr::Strong(sub(inner)),
509        SvaExpr::Weak(inner) => SvaExpr::Weak(sub(inner)),
510        SvaExpr::PropertyNot(inner) => SvaExpr::PropertyNot(sub(inner)),
511        SvaExpr::OneHot0(inner) => SvaExpr::OneHot0(sub(inner)),
512        SvaExpr::OneHot(inner) => SvaExpr::OneHot(sub(inner)),
513        SvaExpr::CountOnes(inner) => SvaExpr::CountOnes(sub(inner)),
514        SvaExpr::IsUnknown(inner) => SvaExpr::IsUnknown(sub(inner)),
515        SvaExpr::Sampled(inner) => SvaExpr::Sampled(sub(inner)),
516        SvaExpr::Bits(inner) => SvaExpr::Bits(sub(inner)),
517        SvaExpr::Clog2(inner) => SvaExpr::Clog2(sub(inner)),
518        SvaExpr::IsUnbounded(inner) => SvaExpr::IsUnbounded(sub(inner)),
519        SvaExpr::BitNot(inner) => SvaExpr::BitNot(sub(inner)),
520        SvaExpr::ReductionAnd(inner) => SvaExpr::ReductionAnd(sub(inner)),
521        SvaExpr::ReductionOr(inner) => SvaExpr::ReductionOr(sub(inner)),
522        SvaExpr::ReductionXor(inner) => SvaExpr::ReductionXor(sub(inner)),
523        SvaExpr::ConstCast(inner) => SvaExpr::ConstCast(sub(inner)),
524
525        // ── Unary with extra data ──
526        SvaExpr::Past(inner, n) => SvaExpr::Past(sub(inner), *n),
527        SvaExpr::Nexttime(inner, n) => SvaExpr::Nexttime(sub(inner), *n),
528        SvaExpr::SNexttime(inner, n) => SvaExpr::SNexttime(sub(inner), *n),
529        SvaExpr::CountBits(inner, chars) => SvaExpr::CountBits(sub(inner), chars.clone()),
530        SvaExpr::GotoRepetition { body, count } => SvaExpr::GotoRepetition {
531            body: sub(body),
532            count: *count,
533        },
534
535        // ── Binary ──
536        SvaExpr::And(l, r) => SvaExpr::And(sub(l), sub(r)),
537        SvaExpr::Or(l, r) => SvaExpr::Or(sub(l), sub(r)),
538        SvaExpr::Eq(l, r) => SvaExpr::Eq(sub(l), sub(r)),
539        SvaExpr::NotEq(l, r) => SvaExpr::NotEq(sub(l), sub(r)),
540        SvaExpr::LessThan(l, r) => SvaExpr::LessThan(sub(l), sub(r)),
541        SvaExpr::GreaterThan(l, r) => SvaExpr::GreaterThan(sub(l), sub(r)),
542        SvaExpr::LessEqual(l, r) => SvaExpr::LessEqual(sub(l), sub(r)),
543        SvaExpr::GreaterEqual(l, r) => SvaExpr::GreaterEqual(sub(l), sub(r)),
544        SvaExpr::PropertyImplies(l, r) => SvaExpr::PropertyImplies(sub(l), sub(r)),
545        SvaExpr::PropertyIff(l, r) => SvaExpr::PropertyIff(sub(l), sub(r)),
546        SvaExpr::SequenceAnd(l, r) => SvaExpr::SequenceAnd(sub(l), sub(r)),
547        SvaExpr::SequenceOr(l, r) => SvaExpr::SequenceOr(sub(l), sub(r)),
548        SvaExpr::BitAnd(l, r) => SvaExpr::BitAnd(sub(l), sub(r)),
549        SvaExpr::BitOr(l, r) => SvaExpr::BitOr(sub(l), sub(r)),
550        SvaExpr::BitXor(l, r) => SvaExpr::BitXor(sub(l), sub(r)),
551
552        // ── Struct-like with named fields ──
553        SvaExpr::Implication {
554            antecedent,
555            consequent,
556            overlapping,
557        } => SvaExpr::Implication {
558            antecedent: sub(antecedent),
559            consequent: sub(consequent),
560            overlapping: *overlapping,
561        },
562        SvaExpr::Delay { body, min, max } => SvaExpr::Delay {
563            body: sub(body),
564            min: *min,
565            max: *max,
566        },
567        SvaExpr::Repetition { body, min, max } => SvaExpr::Repetition {
568            body: sub(body),
569            min: *min,
570            max: *max,
571        },
572        SvaExpr::NonConsecRepetition { body, min, max } => SvaExpr::NonConsecRepetition {
573            body: sub(body),
574            min: *min,
575            max: *max,
576        },
577        SvaExpr::DisableIff { condition, body } => SvaExpr::DisableIff {
578            condition: sub(condition),
579            body: sub(body),
580        },
581        SvaExpr::IfElse {
582            condition,
583            then_expr,
584            else_expr,
585        } => SvaExpr::IfElse {
586            condition: sub(condition),
587            then_expr: sub(then_expr),
588            else_expr: sub(else_expr),
589        },
590        SvaExpr::Ternary {
591            condition,
592            then_expr,
593            else_expr,
594        } => SvaExpr::Ternary {
595            condition: sub(condition),
596            then_expr: sub(then_expr),
597            else_expr: sub(else_expr),
598        },
599        SvaExpr::Throughout { signal, sequence } => SvaExpr::Throughout {
600            signal: sub(signal),
601            sequence: sub(sequence),
602        },
603        SvaExpr::Within { inner, outer } => SvaExpr::Within {
604            inner: sub(inner),
605            outer: sub(outer),
606        },
607        SvaExpr::Intersect { left, right } => SvaExpr::Intersect {
608            left: sub(left),
609            right: sub(right),
610        },
611        SvaExpr::AcceptOn { condition, body } => SvaExpr::AcceptOn {
612            condition: sub(condition),
613            body: sub(body),
614        },
615        SvaExpr::RejectOn { condition, body } => SvaExpr::RejectOn {
616            condition: sub(condition),
617            body: sub(body),
618        },
619        SvaExpr::SyncAcceptOn { condition, body } => SvaExpr::SyncAcceptOn {
620            condition: sub(condition),
621            body: sub(body),
622        },
623        SvaExpr::SyncRejectOn { condition, body } => SvaExpr::SyncRejectOn {
624            condition: sub(condition),
625            body: sub(body),
626        },
627        SvaExpr::FollowedBy {
628            antecedent,
629            consequent,
630            overlapping,
631        } => SvaExpr::FollowedBy {
632            antecedent: sub(antecedent),
633            consequent: sub(consequent),
634            overlapping: *overlapping,
635        },
636        SvaExpr::Until {
637            lhs,
638            rhs,
639            strong,
640            inclusive,
641        } => SvaExpr::Until {
642            lhs: sub(lhs),
643            rhs: sub(rhs),
644            strong: *strong,
645            inclusive: *inclusive,
646        },
647        SvaExpr::AlwaysBounded { body, min, max } => SvaExpr::AlwaysBounded {
648            body: sub(body),
649            min: *min,
650            max: *max,
651        },
652        SvaExpr::SAlwaysBounded { body, min, max } => SvaExpr::SAlwaysBounded {
653            body: sub(body),
654            min: *min,
655            max: *max,
656        },
657        SvaExpr::EventuallyBounded { body, min, max } => SvaExpr::EventuallyBounded {
658            body: sub(body),
659            min: *min,
660            max: *max,
661        },
662        SvaExpr::SEventuallyBounded { body, min, max } => SvaExpr::SEventuallyBounded {
663            body: sub(body),
664            min: *min,
665            max: *max,
666        },
667        SvaExpr::FieldAccess { signal, field } => SvaExpr::FieldAccess {
668            signal: sub(signal),
669            field: field.clone(),
670        },
671        SvaExpr::BitSelect { signal, index } => SvaExpr::BitSelect {
672            signal: sub(signal),
673            index: sub(index),
674        },
675        SvaExpr::PartSelect { signal, high, low } => SvaExpr::PartSelect {
676            signal: sub(signal),
677            high: *high,
678            low: *low,
679        },
680        SvaExpr::ImmediateAssert {
681            expression,
682            deferred,
683        } => SvaExpr::ImmediateAssert {
684            expression: sub(expression),
685            deferred: deferred.clone(),
686        },
687
688        // ── Vec children ──
689        SvaExpr::Concat(items) => SvaExpr::Concat(sub_vec(items)),
690
691        // ── Complex structures ──
692        SvaExpr::PropertyCase {
693            expression,
694            items,
695            default,
696        } => SvaExpr::PropertyCase {
697            expression: sub(expression),
698            items: items
699                .iter()
700                .map(|(vals, prop)| (sub_vec(vals), sub(prop)))
701                .collect(),
702            default: default.as_ref().map(|d| sub(d)),
703        },
704        SvaExpr::SequenceAction {
705            expression,
706            assignments,
707        } => SvaExpr::SequenceAction {
708            expression: sub(expression),
709            assignments: assignments
710                .iter()
711                .map(|(var_name, rhs)| (var_name.clone(), sub(rhs)))
712                .collect(),
713        },
714        SvaExpr::Clocked { clock, edge, body } => SvaExpr::Clocked {
715            clock: clock.clone(),
716            edge: edge.clone(),
717            body: sub(body),
718        },
719        SvaExpr::ArrayMap {
720            array,
721            iterator,
722            with_expr,
723        } => SvaExpr::ArrayMap {
724            array: sub(array),
725            iterator: iterator.clone(),
726            with_expr: sub(with_expr),
727        },
728        SvaExpr::TypeThis => SvaExpr::TypeThis,
729        SvaExpr::RealConst(v) => SvaExpr::RealConst(*v),
730    }
731}
732
733/// Parse error for SVA subset.
734#[derive(Debug)]
735pub struct SvaParseError {
736    pub message: String,
737}
738
739impl std::fmt::Display for SvaParseError {
740    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
741        write!(f, "SVA parse error: {}", self.message)
742    }
743}
744
745/// Parse a concurrent assertion directive (IEEE 16.14).
746///
747/// Handles: `assert property(...)`, `assume property(...)`, `cover property(...)`,
748/// `cover sequence(...)`, `restrict property(...)`.
749/// Optionally prefixed by a label: `label: assert property(...)`.
750/// Optionally contains action blocks: `assert property(p) $info("ok"); else $error("fail");`
751pub fn parse_sva_directive(input: &str) -> Result<SvaDirective, SvaParseError> {
752    let input = input.trim().trim_end_matches(';');
753    let input = input.trim();
754
755    // Check for label prefix: `label: directive...`
756    let (label, rest) = if let Some(colon_pos) = input.find(':') {
757        let potential_label = input[..colon_pos].trim();
758        // Only treat as label if it's a simple identifier (no spaces, no keywords)
759        if !potential_label.is_empty()
760            && potential_label
761                .chars()
762                .all(|c| c.is_alphanumeric() || c == '_')
763            && !potential_label.starts_with("assert")
764            && !potential_label.starts_with("assume")
765            && !potential_label.starts_with("cover")
766            && !potential_label.starts_with("restrict")
767        {
768            (
769                Some(potential_label.to_string()),
770                input[colon_pos + 1..].trim(),
771            )
772        } else {
773            (None, input)
774        }
775    } else {
776        (None, input)
777    };
778
779    // Determine directive kind
780    let (kind, after_kind) = if rest.starts_with("assert property") {
781        (
782            SvaDirectiveKind::Assert,
783            rest["assert property".len()..].trim(),
784        )
785    } else if rest.starts_with("assume property") {
786        (
787            SvaDirectiveKind::Assume,
788            rest["assume property".len()..].trim(),
789        )
790    } else if rest.starts_with("cover sequence") {
791        (
792            SvaDirectiveKind::CoverSequence,
793            rest["cover sequence".len()..].trim(),
794        )
795    } else if rest.starts_with("cover property") {
796        (
797            SvaDirectiveKind::Cover,
798            rest["cover property".len()..].trim(),
799        )
800    } else if rest.starts_with("restrict property") {
801        (
802            SvaDirectiveKind::Restrict,
803            rest["restrict property".len()..].trim(),
804        )
805    } else {
806        return Err(SvaParseError {
807            message: format!("expected assertion directive, got: '{}'", rest),
808        });
809    };
810
811    // Parse the property expression in parentheses
812    if !after_kind.starts_with('(') {
813        return Err(SvaParseError {
814            message: format!(
815                "expected '(' after directive keyword, got: '{}'",
816                after_kind
817            ),
818        });
819    }
820    let close = find_balanced_close(after_kind, 0).ok_or_else(|| SvaParseError {
821        message: "unbalanced parentheses in directive".to_string(),
822    })?;
823    let prop_str = &after_kind[1..close];
824    let after_prop = after_kind[close + 1..].trim();
825
826    // Parse optional clock: @(posedge clk)
827    let (clock, prop_rest) = if prop_str.trim().starts_with("@(") {
828        if let Some(clock_close) = prop_str.find(')') {
829            let clock_str = prop_str[2..clock_close].trim().to_string();
830            (Some(clock_str), prop_str[clock_close + 1..].trim())
831        } else {
832            (None, prop_str.trim())
833        }
834    } else {
835        (None, prop_str.trim())
836    };
837
838    // Parse optional disable iff
839    let (disable_iff, prop_body) = if prop_rest.starts_with("disable iff") {
840        let after_disable = prop_rest["disable iff".len()..].trim();
841        if after_disable.starts_with('(') {
842            if let Some(di_close) = find_balanced_close(after_disable, 0) {
843                let di_str = &after_disable[1..di_close];
844                let body = after_disable[di_close + 1..].trim();
845                (Some(parse_sva(di_str)?), body)
846            } else {
847                (None, prop_rest)
848            }
849        } else {
850            (None, prop_rest)
851        }
852    } else {
853        (None, prop_rest)
854    };
855
856    let property = parse_sva(prop_body)?;
857
858    // Parse optional action blocks after the closing paren
859    let mut action_pass = None;
860    let mut action_fail = None;
861    let remaining = after_prop;
862    if !remaining.is_empty() {
863        // Look for `else` keyword to separate pass/fail, but skip occurrences
864        // inside string literals (both regular "..." and triple-quoted """...""").
865        if let Some(else_pos) = find_else_outside_strings(remaining) {
866            let pass_part = remaining[..else_pos].trim();
867            let fail_part = remaining[else_pos + 4..].trim();
868            if !pass_part.is_empty() {
869                action_pass = Some(pass_part.trim_end_matches(';').trim().to_string());
870            }
871            if !fail_part.is_empty() {
872                action_fail = Some(fail_part.trim_end_matches(';').trim().to_string());
873            }
874        } else if remaining.starts_with("$") || remaining.starts_with("else") {
875            let part = remaining.trim_end_matches(';').trim();
876            if remaining.starts_with("else") {
877                action_fail = Some(part["else".len()..].trim().to_string());
878            } else {
879                action_pass = Some(part.to_string());
880            }
881        }
882    }
883
884    // Restrict property cannot have action blocks (IEEE 16.14.4)
885    if kind == SvaDirectiveKind::Restrict && (action_pass.is_some() || action_fail.is_some()) {
886        return Err(SvaParseError {
887            message: "restrict property cannot have action blocks".to_string(),
888        });
889    }
890
891    Ok(SvaDirective {
892        kind,
893        property,
894        label,
895        clock,
896        disable_iff,
897        action_pass,
898        action_fail,
899    })
900}
901
902/// Parse a subset of SVA text into an SvaExpr.
903///
904/// Supports: signals, `$rose()`, `$fell()`, `s_eventually()`,
905/// `!()`, `&&`, `||`, `==`, `|->`, `|=>`.
906pub fn parse_sva(input: &str) -> Result<SvaExpr, SvaParseError> {
907    let input = input.trim();
908
909    // Parse clock sensitivity prefix: @(posedge clk), @(negedge clk), @(edge clk)
910    // IEEE 16.13: preserve clock annotation as Clocked variant for multi-clock support
911    if input.starts_with("@(") {
912        if let Some(pos) = input.find(')') {
913            let clock_spec = input[2..pos].trim();
914            let rest = input[pos + 1..].trim();
915
916            let (edge, clock_name) = if clock_spec.starts_with("posedge ") {
917                (ClockEdge::Posedge, clock_spec[8..].trim().to_string())
918            } else if clock_spec.starts_with("negedge ") {
919                (ClockEdge::Negedge, clock_spec[8..].trim().to_string())
920            } else if clock_spec.starts_with("edge ") {
921                (ClockEdge::Edge, clock_spec[5..].trim().to_string())
922            } else {
923                // Unknown edge type — treat as posedge
924                (ClockEdge::Posedge, clock_spec.to_string())
925            };
926
927            let body = parse_toplevel(rest)?;
928            return Ok(SvaExpr::Clocked {
929                clock: clock_name,
930                edge,
931                body: Box::new(body),
932            });
933        }
934    }
935
936    parse_toplevel(input)
937}
938
939fn parse_toplevel(input: &str) -> Result<SvaExpr, SvaParseError> {
940    let input = input.trim();
941
942    // Immediate assertions: assert(expr), assert #0(expr), assert final(expr) (Sprint 7)
943    if input.starts_with("assert ") || input.starts_with("assert(") || input.starts_with("assert#")
944    {
945        let rest = input["assert".len()..].trim();
946        if rest.starts_with("#0") {
947            let body = rest[2..].trim();
948            if body.starts_with('(') {
949                if let Some(close) = find_balanced_close(body, 0) {
950                    let inner = &body[1..close];
951                    return Ok(SvaExpr::ImmediateAssert {
952                        expression: Box::new(parse_implication(inner)?),
953                        deferred: Some(ImmediateDeferred::Observed),
954                    });
955                }
956            }
957        } else if rest.starts_with("final") {
958            let body = rest[5..].trim();
959            if body.starts_with('(') {
960                if let Some(close) = find_balanced_close(body, 0) {
961                    let inner = &body[1..close];
962                    return Ok(SvaExpr::ImmediateAssert {
963                        expression: Box::new(parse_implication(inner)?),
964                        deferred: Some(ImmediateDeferred::Final),
965                    });
966                }
967            }
968        } else if rest.starts_with('(') {
969            if let Some(close) = find_balanced_close(rest, 0) {
970                let inner = &rest[1..close];
971                return Ok(SvaExpr::ImmediateAssert {
972                    expression: Box::new(parse_implication(inner)?),
973                    deferred: None,
974                });
975            }
976        }
977    }
978
979    // sync_accept_on(cond) body — synchronous property abort (Sprint 3)
980    if input.starts_with("sync_accept_on") {
981        let rest = input["sync_accept_on".len()..].trim();
982        if rest.starts_with('(') {
983            if let Some(close) = find_balanced_close(rest, 0) {
984                let cond = &rest[1..close];
985                let body = rest[close + 1..].trim();
986                return Ok(SvaExpr::SyncAcceptOn {
987                    condition: Box::new(parse_implication(cond)?),
988                    body: Box::new(parse_toplevel(body)?),
989                });
990            }
991        }
992    }
993
994    // sync_reject_on(cond) body — synchronous property abort (Sprint 3)
995    if input.starts_with("sync_reject_on") {
996        let rest = input["sync_reject_on".len()..].trim();
997        if rest.starts_with('(') {
998            if let Some(close) = find_balanced_close(rest, 0) {
999                let cond = &rest[1..close];
1000                let body = rest[close + 1..].trim();
1001                return Ok(SvaExpr::SyncRejectOn {
1002                    condition: Box::new(parse_implication(cond)?),
1003                    body: Box::new(parse_toplevel(body)?),
1004                });
1005            }
1006        }
1007    }
1008
1009    // accept_on(cond) body — property abort operators
1010    if input.starts_with("accept_on") {
1011        let rest = input["accept_on".len()..].trim();
1012        if rest.starts_with('(') {
1013            if let Some(close) = find_balanced_close(rest, 0) {
1014                let cond = &rest[1..close];
1015                let body = rest[close + 1..].trim();
1016                return Ok(SvaExpr::AcceptOn {
1017                    condition: Box::new(parse_implication(cond)?),
1018                    body: Box::new(parse_toplevel(body)?),
1019                });
1020            }
1021        }
1022    }
1023
1024    // reject_on(cond) body
1025    if input.starts_with("reject_on") {
1026        let rest = input["reject_on".len()..].trim();
1027        if rest.starts_with('(') {
1028            if let Some(close) = find_balanced_close(rest, 0) {
1029                let cond = &rest[1..close];
1030                let body = rest[close + 1..].trim();
1031                return Ok(SvaExpr::RejectOn {
1032                    condition: Box::new(parse_implication(cond)?),
1033                    body: Box::new(parse_toplevel(body)?),
1034                });
1035            }
1036        }
1037    }
1038
1039    // disable iff (cond) body — must be checked before implication
1040    if input.starts_with("disable iff") {
1041        let rest = input["disable iff".len()..].trim();
1042        if rest.starts_with('(') {
1043            if let Some(close) = find_balanced_close(rest, 0) {
1044                let cond = &rest[1..close];
1045                let body = rest[close + 1..].trim();
1046                return Ok(SvaExpr::DisableIff {
1047                    condition: Box::new(parse_implication(cond)?),
1048                    body: Box::new(parse_implication(body)?),
1049                });
1050            }
1051        }
1052    }
1053
1054    // if (cond) P else Q — must be checked before implication
1055    if input.starts_with("if ") || input.starts_with("if(") {
1056        let rest = input[2..].trim();
1057        if rest.starts_with('(') {
1058            if let Some(close) = find_balanced_close(rest, 0) {
1059                let cond = &rest[1..close];
1060                let after_cond = rest[close + 1..].trim();
1061                if let Some(else_pos) = find_else_keyword(after_cond) {
1062                    let then_part = after_cond[..else_pos].trim();
1063                    let else_part = after_cond[else_pos + 4..].trim();
1064                    return Ok(SvaExpr::IfElse {
1065                        condition: Box::new(parse_implication(cond)?),
1066                        then_expr: Box::new(parse_implication(then_part)?),
1067                        else_expr: Box::new(parse_implication(else_part)?),
1068                    });
1069                } else {
1070                    return Ok(SvaExpr::IfElse {
1071                        condition: Box::new(parse_implication(cond)?),
1072                        then_expr: Box::new(parse_implication(after_cond)?),
1073                        else_expr: Box::new(SvaExpr::Signal("1".to_string())),
1074                    });
1075                }
1076            }
1077        }
1078    }
1079
1080    parse_implication(input)
1081}
1082
1083fn parse_implication(input: &str) -> Result<SvaExpr, SvaParseError> {
1084    // Check for |-> or |=> or #-# or #=#
1085    // Scan not inside parentheses
1086    let mut depth = 0i32;
1087    let chars: Vec<char> = input.chars().collect();
1088    for i in 0..chars.len().saturating_sub(2) {
1089        match chars[i] {
1090            '(' => depth += 1,
1091            ')' => depth -= 1,
1092            '|' if depth == 0 => {
1093                if i + 2 < chars.len() && chars[i + 1] == '-' && chars[i + 2] == '>' {
1094                    let lhs = input[..i].trim();
1095                    let rhs = input[i + 3..].trim();
1096                    return Ok(SvaExpr::Implication {
1097                        antecedent: Box::new(parse_property_implies(lhs)?),
1098                        consequent: Box::new(parse_property_implies(rhs)?),
1099                        overlapping: true,
1100                    });
1101                }
1102                if i + 2 < chars.len() && chars[i + 1] == '=' && chars[i + 2] == '>' {
1103                    let lhs = input[..i].trim();
1104                    let rhs = input[i + 3..].trim();
1105                    return Ok(SvaExpr::Implication {
1106                        antecedent: Box::new(parse_property_implies(lhs)?),
1107                        consequent: Box::new(parse_property_implies(rhs)?),
1108                        overlapping: false,
1109                    });
1110                }
1111            }
1112            // #-# (followed-by overlapping) and #=# (followed-by non-overlapping)
1113            '#' if depth == 0 && i + 2 < chars.len() => {
1114                if chars[i + 1] == '-' && chars[i + 2] == '#' {
1115                    let lhs = input[..i].trim();
1116                    let rhs = input[i + 3..].trim();
1117                    if !lhs.is_empty() {
1118                        return Ok(SvaExpr::FollowedBy {
1119                            antecedent: Box::new(parse_property_implies(lhs)?),
1120                            consequent: Box::new(parse_property_implies(rhs)?),
1121                            overlapping: true,
1122                        });
1123                    }
1124                }
1125                if chars[i + 1] == '=' && chars[i + 2] == '#' {
1126                    let lhs = input[..i].trim();
1127                    let rhs = input[i + 3..].trim();
1128                    if !lhs.is_empty() {
1129                        return Ok(SvaExpr::FollowedBy {
1130                            antecedent: Box::new(parse_property_implies(lhs)?),
1131                            consequent: Box::new(parse_property_implies(rhs)?),
1132                            overlapping: false,
1133                        });
1134                    }
1135                }
1136            }
1137            _ => {}
1138        }
1139    }
1140    parse_property_implies(input)
1141}
1142
1143/// Parse property-level `implies` (IEEE 16.12.8).
1144/// Lower precedence than `iff`, higher than `|->` / `|=>`.
1145fn parse_property_implies(input: &str) -> Result<SvaExpr, SvaParseError> {
1146    let input = input.trim();
1147    if let Some(pos) = find_keyword_at_depth_0(input, "implies") {
1148        let lhs = input[..pos].trim();
1149        let rhs = input[pos + 7..].trim();
1150        return Ok(SvaExpr::PropertyImplies(
1151            Box::new(parse_property_iff(lhs)?),
1152            Box::new(parse_property_implies(rhs)?), // right-associative
1153        ));
1154    }
1155    parse_property_iff(input)
1156}
1157
1158/// Parse property-level `iff` (IEEE 16.12.8).
1159/// Higher precedence than `implies`, lower than `until`.
1160fn parse_property_iff(input: &str) -> Result<SvaExpr, SvaParseError> {
1161    let input = input.trim();
1162    if let Some(pos) = find_keyword_at_depth_0(input, "iff") {
1163        let lhs = input[..pos].trim();
1164        let rhs = input[pos + 3..].trim();
1165        return Ok(SvaExpr::PropertyIff(
1166            Box::new(parse_until(lhs)?),
1167            Box::new(parse_property_iff(rhs)?), // right-associative
1168        ));
1169    }
1170    parse_until(input)
1171}
1172
1173/// Parse `until` / `s_until` / `until_with` / `s_until_with` (IEEE 16.12.12).
1174/// Higher precedence than `iff`, lower than `||`.
1175fn parse_until(input: &str) -> Result<SvaExpr, SvaParseError> {
1176    let input = input.trim();
1177    // Check in order: longest keywords first to avoid partial matches
1178    for (keyword, strong, inclusive) in &[
1179        ("s_until_with", true, true),
1180        ("until_with", false, true),
1181        ("s_until", true, false),
1182        ("until", false, false),
1183    ] {
1184        if let Some(pos) = find_keyword_at_depth_0(input, keyword) {
1185            let lhs = input[..pos].trim();
1186            let rhs = input[pos + keyword.len()..].trim();
1187            return Ok(SvaExpr::Until {
1188                lhs: Box::new(parse_or(lhs)?),
1189                rhs: Box::new(parse_until(rhs)?), // right-associative
1190                strong: *strong,
1191                inclusive: *inclusive,
1192            });
1193        }
1194    }
1195    parse_or(input)
1196}
1197
1198fn parse_or(input: &str) -> Result<SvaExpr, SvaParseError> {
1199    let mut depth = 0i32;
1200    let chars: Vec<char> = input.chars().collect();
1201    for i in 0..chars.len().saturating_sub(1) {
1202        match chars[i] {
1203            '(' => depth += 1,
1204            ')' => depth -= 1,
1205            '|' if depth == 0 && i + 1 < chars.len() && chars[i + 1] == '|' => {
1206                let lhs = input[..i].trim();
1207                let rhs = input[i + 2..].trim();
1208                return Ok(SvaExpr::Or(
1209                    Box::new(parse_seq_ops(lhs)?),
1210                    Box::new(parse_or(rhs)?),
1211                ));
1212            }
1213            _ => {}
1214        }
1215    }
1216    parse_seq_ops(input)
1217}
1218
1219/// Parse sequence-level operators: `and`, `or`, `throughout`, `within`, `intersect`.
1220/// `and` / `or` are sequence-level (thread/union semantics), distinct from `&&` / `||`.
1221/// These bind tighter than `||` but looser than `&&`.
1222fn parse_seq_ops(input: &str) -> Result<SvaExpr, SvaParseError> {
1223    let input_trimmed = input.trim();
1224
1225    // Check for keyword operators at depth 0
1226    // Must scan for these as whole words (not inside identifiers)
1227    // Check `throughout`, `within`, `intersect` first (higher precedence than `and`/`or`)
1228    for keyword in &["throughout", "within", "intersect"] {
1229        if let Some(pos) = find_keyword_at_depth_0(input_trimmed, keyword) {
1230            let lhs = input_trimmed[..pos].trim();
1231            let rhs = input_trimmed[pos + keyword.len()..].trim();
1232            return match *keyword {
1233                "throughout" => Ok(SvaExpr::Throughout {
1234                    signal: Box::new(parse_and(lhs)?),
1235                    sequence: Box::new(parse_and(rhs)?),
1236                }),
1237                "within" => Ok(SvaExpr::Within {
1238                    inner: Box::new(parse_and(lhs)?),
1239                    outer: Box::new(parse_and(rhs)?),
1240                }),
1241                "intersect" => Ok(SvaExpr::Intersect {
1242                    left: Box::new(parse_and(lhs)?),
1243                    right: Box::new(parse_and(rhs)?),
1244                }),
1245                _ => unreachable!(),
1246            };
1247        }
1248    }
1249
1250    // Sequence-level `or` (IEEE 16.9.7) — union semantics
1251    // Check before `and` since `or` has lower precedence
1252    if let Some(pos) = find_keyword_at_depth_0(input_trimmed, "or") {
1253        let lhs = input_trimmed[..pos].trim();
1254        let rhs = input_trimmed[pos + 2..].trim();
1255        return Ok(SvaExpr::SequenceOr(
1256            Box::new(parse_seq_and(lhs)?),
1257            Box::new(parse_seq_ops(rhs)?), // right-associative
1258        ));
1259    }
1260
1261    parse_seq_and(input)
1262}
1263
1264/// Parse sequence-level `and` (IEEE 16.9.5) — thread semantics.
1265/// Higher precedence than sequence `or`, lower than `&&`.
1266fn parse_seq_and(input: &str) -> Result<SvaExpr, SvaParseError> {
1267    let input_trimmed = input.trim();
1268    if let Some(pos) = find_keyword_at_depth_0(input_trimmed, "and") {
1269        let lhs = input_trimmed[..pos].trim();
1270        let rhs = input_trimmed[pos + 3..].trim();
1271        return Ok(SvaExpr::SequenceAnd(
1272            Box::new(parse_and(lhs)?),
1273            Box::new(parse_seq_and(rhs)?), // right-associative
1274        ));
1275    }
1276    parse_and(input)
1277}
1278
1279/// Find a keyword at parenthesis depth 0, respecting word boundaries.
1280fn find_keyword_at_depth_0(input: &str, keyword: &str) -> Option<usize> {
1281    let mut depth = 0i32;
1282    let bytes = input.as_bytes();
1283    let klen = keyword.len();
1284    for i in 0..input.len() {
1285        match bytes[i] {
1286            b'(' => depth += 1,
1287            b')' => depth -= 1,
1288            _ if depth == 0 && i + klen <= input.len() => {
1289                if &input[i..i + klen] == keyword {
1290                    // Check word boundaries
1291                    let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
1292                    let after_ok =
1293                        i + klen >= input.len() || !bytes[i + klen].is_ascii_alphanumeric();
1294                    if before_ok && after_ok {
1295                        return Some(i);
1296                    }
1297                }
1298            }
1299            _ => {}
1300        }
1301    }
1302    None
1303}
1304
1305fn parse_and(input: &str) -> Result<SvaExpr, SvaParseError> {
1306    let mut depth = 0i32;
1307    let chars: Vec<char> = input.chars().collect();
1308    for i in 0..chars.len().saturating_sub(1) {
1309        match chars[i] {
1310            '(' => depth += 1,
1311            ')' => depth -= 1,
1312            '&' if depth == 0 && i + 1 < chars.len() && chars[i + 1] == '&' => {
1313                let lhs = input[..i].trim();
1314                let rhs = input[i + 2..].trim();
1315                return Ok(SvaExpr::And(
1316                    Box::new(parse_sequence(lhs)?),
1317                    Box::new(parse_and(rhs)?),
1318                ));
1319            }
1320            _ => {}
1321        }
1322    }
1323    parse_sequence(input)
1324}
1325
1326/// Parse infix sequence concatenation: `req ##N ack` or `req ##[min:max] ack`.
1327/// In IEEE 1800, `##` between two expressions is a sequence delay operator.
1328/// This binds tighter than `&&` but looser than `==`/`!=`.
1329fn parse_sequence(input: &str) -> Result<SvaExpr, SvaParseError> {
1330    let input = input.trim();
1331    let bytes = input.as_bytes();
1332    let mut depth = 0i32;
1333
1334    // Scan for infix `##` at depth 0 (not at position 0 — that's prefix delay)
1335    // Start from i=0 to track parens, but only match ## when i > 0
1336    for i in 0..input.len().saturating_sub(1) {
1337        match bytes[i] {
1338            b'(' => {
1339                depth += 1;
1340                continue;
1341            }
1342            b')' => {
1343                depth -= 1;
1344                continue;
1345            }
1346            b'#' if depth == 0 && i > 0 && i + 1 < input.len() && bytes[i + 1] == b'#' => {
1347                // Found `##` not at start — this is infix sequence concatenation
1348                let lhs = input[..i].trim();
1349                if lhs.is_empty() {
1350                    continue;
1351                }
1352                let delay_and_rhs = &input[i..]; // starts with "##..."
1353                                                 // Parse the delay part: ##N or ##[min:max]
1354                let rest = &delay_and_rhs[2..];
1355                if rest.starts_with('[') {
1356                    // ##[min:max] rhs
1357                    if let Some(bracket_end) = rest.find(']') {
1358                        let range_str = &rest[1..bracket_end];
1359                        let rhs = rest[bracket_end + 1..].trim();
1360                        let parts: Vec<&str> = range_str.split(':').collect();
1361                        if parts.len() == 2 {
1362                            let min = parts[0].trim().parse::<u32>().unwrap_or(0);
1363                            let max_str = parts[1].trim();
1364                            let max = if max_str == "$" {
1365                                None // $ = unbounded
1366                            } else {
1367                                Some(max_str.parse::<u32>().unwrap_or(0))
1368                            };
1369                            return Ok(SvaExpr::Implication {
1370                                antecedent: Box::new(parse_eq(lhs)?),
1371                                consequent: Box::new(SvaExpr::Delay {
1372                                    body: Box::new(parse_sequence(rhs)?),
1373                                    min,
1374                                    max,
1375                                }),
1376                                overlapping: true,
1377                            });
1378                        }
1379                    }
1380                } else {
1381                    // ##N rhs — exact delay
1382                    let mut num_end = 0;
1383                    for c in rest.chars() {
1384                        if c.is_ascii_digit() {
1385                            num_end += 1;
1386                        } else {
1387                            break;
1388                        }
1389                    }
1390                    if num_end > 0 {
1391                        let n = rest[..num_end].parse::<u32>().unwrap_or(0);
1392                        let rhs = rest[num_end..].trim();
1393                        return Ok(SvaExpr::Implication {
1394                            antecedent: Box::new(parse_eq(lhs)?),
1395                            consequent: Box::new(SvaExpr::Delay {
1396                                body: Box::new(parse_sequence(rhs)?),
1397                                min: n,
1398                                max: Some(n), // exact: min == max
1399                            }),
1400                            overlapping: true,
1401                        });
1402                    }
1403                }
1404            }
1405            _ => {}
1406        }
1407    }
1408    parse_eq(input)
1409}
1410
1411fn parse_eq(input: &str) -> Result<SvaExpr, SvaParseError> {
1412    let mut depth = 0i32;
1413    let chars: Vec<char> = input.chars().collect();
1414    let len = chars.len();
1415
1416    // Scan for ternary: `cond ? then : else` (lowest precedence in this group)
1417    for i in 0..len {
1418        match chars[i] {
1419            '(' => depth += 1,
1420            ')' => depth -= 1,
1421            '?' if depth == 0 => {
1422                let cond = input[..i].trim();
1423                let rest = &input[i + 1..];
1424                // Find the matching ':'
1425                let mut d2 = 0i32;
1426                for j in 0..rest.len() {
1427                    match rest.as_bytes()[j] {
1428                        b'(' => d2 += 1,
1429                        b')' => d2 -= 1,
1430                        b':' if d2 == 0 => {
1431                            let then_part = rest[..j].trim();
1432                            let else_part = rest[j + 1..].trim();
1433                            return Ok(SvaExpr::Ternary {
1434                                condition: Box::new(parse_eq(cond)?),
1435                                then_expr: Box::new(parse_eq(then_part)?),
1436                                else_expr: Box::new(parse_eq(else_part)?),
1437                            });
1438                        }
1439                        _ => {}
1440                    }
1441                }
1442            }
1443            _ => {}
1444        }
1445    }
1446
1447    depth = 0;
1448    // Scan for comparison operators: ==, !=, <=, >=, <, >
1449    // Must check two-char operators before single-char ones
1450    // Track both () and [] depth so [-> and [= don't conflict with < and >
1451    for i in 0..len {
1452        match chars[i] {
1453            '(' | '[' => depth += 1,
1454            ')' | ']' => depth -= 1,
1455            _ if depth != 0 => {}
1456            '!' if i + 1 < len && chars[i + 1] == '=' => {
1457                let lhs = input[..i].trim();
1458                let rhs = input[i + 2..].trim();
1459                return Ok(SvaExpr::NotEq(
1460                    Box::new(parse_unary(lhs)?),
1461                    Box::new(parse_unary(rhs)?),
1462                ));
1463            }
1464            '=' if i + 1 < len && chars[i + 1] == '=' => {
1465                let lhs = input[..i].trim();
1466                let rhs = input[i + 2..].trim();
1467                return Ok(SvaExpr::Eq(
1468                    Box::new(parse_unary(lhs)?),
1469                    Box::new(parse_unary(rhs)?),
1470                ));
1471            }
1472            '<' if i + 1 < len && chars[i + 1] == '=' => {
1473                let lhs = input[..i].trim();
1474                let rhs = input[i + 2..].trim();
1475                return Ok(SvaExpr::LessEqual(
1476                    Box::new(parse_unary(lhs)?),
1477                    Box::new(parse_unary(rhs)?),
1478                ));
1479            }
1480            '>' if i + 1 < len && chars[i + 1] == '=' => {
1481                let lhs = input[..i].trim();
1482                let rhs = input[i + 2..].trim();
1483                return Ok(SvaExpr::GreaterEqual(
1484                    Box::new(parse_unary(lhs)?),
1485                    Box::new(parse_unary(rhs)?),
1486                ));
1487            }
1488            '<' if depth == 0 => {
1489                let lhs = input[..i].trim();
1490                let rhs = input[i + 1..].trim();
1491                return Ok(SvaExpr::LessThan(
1492                    Box::new(parse_unary(lhs)?),
1493                    Box::new(parse_unary(rhs)?),
1494                ));
1495            }
1496            '>' if depth == 0 => {
1497                let lhs = input[..i].trim();
1498                let rhs = input[i + 1..].trim();
1499                return Ok(SvaExpr::GreaterThan(
1500                    Box::new(parse_unary(lhs)?),
1501                    Box::new(parse_unary(rhs)?),
1502                ));
1503            }
1504            _ => {}
1505        }
1506    }
1507    parse_unary(input)
1508}
1509
1510fn parse_unary(input: &str) -> Result<SvaExpr, SvaParseError> {
1511    let input = input.trim();
1512
1513    // strong(seq) — sequence must complete within bound (Sprint 3)
1514    if let Some(result) = try_parse_function_call(input, "strong", |inner| {
1515        Ok(SvaExpr::Strong(Box::new(parse_implication(inner)?)))
1516    })? {
1517        return Ok(result);
1518    }
1519
1520    // weak(seq) — sequence may not complete (Sprint 3)
1521    if let Some(result) = try_parse_function_call(input, "weak", |inner| {
1522        Ok(SvaExpr::Weak(Box::new(parse_implication(inner)?)))
1523    })? {
1524        return Ok(result);
1525    }
1526
1527    // s_nexttime[N](body) — with explicit count (Sprint 3)
1528    if input.starts_with("s_nexttime[") {
1529        if let Some(bracket_end) = input.find(']') {
1530            let n_str = &input[11..bracket_end];
1531            if let Ok(n) = n_str.parse::<u32>() {
1532                let rest = input[bracket_end + 1..].trim();
1533                if rest.starts_with('(') {
1534                    if let Some(close) = find_balanced_close(rest, 0) {
1535                        let inner = &rest[1..close];
1536                        return Ok(SvaExpr::SNexttime(
1537                            Box::new(parse_implication(inner.trim())?),
1538                            n,
1539                        ));
1540                    }
1541                }
1542            }
1543        }
1544    }
1545
1546    // s_nexttime(body) — default count = 1 (Sprint 3)
1547    if let Some(result) = try_parse_function_call(input, "s_nexttime", |inner| {
1548        Ok(SvaExpr::SNexttime(Box::new(parse_implication(inner)?), 1))
1549    })? {
1550        return Ok(result);
1551    }
1552
1553    // Property negation: `not expr` (IEEE 16.12.3)
1554    // Must be before `!` check. `not` is a keyword (word boundary checked).
1555    if input.starts_with("not ") || input.starts_with("not(") {
1556        let rest = input[3..].trim();
1557        return Ok(SvaExpr::PropertyNot(Box::new(parse_unary(rest)?)));
1558    }
1559
1560    // always [m:n] body — bounded weak always (IEEE 16.12.11)
1561    // Must check before `always ` (unbounded) to avoid consuming the bracket
1562    if input.starts_with("always [") || input.starts_with("always[") {
1563        let rest = input["always".len()..].trim();
1564        if rest.starts_with('[') {
1565            if let Some(bracket_end) = rest.find(']') {
1566                let range_str = &rest[1..bracket_end];
1567                let body_str = rest[bracket_end + 1..].trim();
1568                let parts: Vec<&str> = range_str.split(':').collect();
1569                if parts.len() == 2 {
1570                    let min = parts[0].trim().parse::<u32>().map_err(|_| SvaParseError {
1571                        message: format!("invalid always min: '{}'", parts[0]),
1572                    })?;
1573                    let max_str = parts[1].trim();
1574                    let max = if max_str == "$" {
1575                        None // weak allows $
1576                    } else {
1577                        Some(max_str.parse::<u32>().map_err(|_| SvaParseError {
1578                            message: format!("invalid always max: '{}'", max_str),
1579                        })?)
1580                    };
1581                    return Ok(SvaExpr::AlwaysBounded {
1582                        body: Box::new(parse_unary(body_str)?),
1583                        min,
1584                        max,
1585                    });
1586                }
1587            }
1588        }
1589    }
1590
1591    // always body — unbounded weak always (IEEE 16.12.11)
1592    if input.starts_with("always ") || input.starts_with("always(") {
1593        let rest = input["always".len()..].trim();
1594        return Ok(SvaExpr::Always(Box::new(parse_unary(rest)?)));
1595    }
1596
1597    // s_always [m:n] body — bounded strong always (IEEE 16.12.11)
1598    // Must check BEFORE the existing s_always() function-call parse
1599    if input.starts_with("s_always [") || input.starts_with("s_always[") {
1600        let rest = input["s_always".len()..].trim();
1601        if rest.starts_with('[') {
1602            if let Some(bracket_end) = rest.find(']') {
1603                let range_str = &rest[1..bracket_end];
1604                let body_str = rest[bracket_end + 1..].trim();
1605                let parts: Vec<&str> = range_str.split(':').collect();
1606                if parts.len() == 2 {
1607                    let min = parts[0].trim().parse::<u32>().map_err(|_| SvaParseError {
1608                        message: format!("invalid s_always min: '{}'", parts[0]),
1609                    })?;
1610                    let max_str = parts[1].trim();
1611                    if max_str == "$" {
1612                        return Err(SvaParseError {
1613                            message: "s_always range must be bounded ($ not allowed)".to_string(),
1614                        });
1615                    }
1616                    let max = max_str.parse::<u32>().map_err(|_| SvaParseError {
1617                        message: format!("invalid s_always max: '{}'", max_str),
1618                    })?;
1619                    return Ok(SvaExpr::SAlwaysBounded {
1620                        body: Box::new(parse_unary(body_str)?),
1621                        min,
1622                        max,
1623                    });
1624                }
1625            }
1626        }
1627    }
1628
1629    // eventually [m:n] body — bounded weak eventually (IEEE 16.12.13)
1630    if input.starts_with("eventually [") || input.starts_with("eventually[") {
1631        let rest = input["eventually".len()..].trim();
1632        if rest.starts_with('[') {
1633            if let Some(bracket_end) = rest.find(']') {
1634                let range_str = &rest[1..bracket_end];
1635                let body_str = rest[bracket_end + 1..].trim();
1636                let parts: Vec<&str> = range_str.split(':').collect();
1637                if parts.len() == 2 {
1638                    let min = parts[0].trim().parse::<u32>().map_err(|_| SvaParseError {
1639                        message: format!("invalid eventually min: '{}'", parts[0]),
1640                    })?;
1641                    let max_str = parts[1].trim();
1642                    if max_str == "$" {
1643                        return Err(SvaParseError {
1644                            message: "weak eventually range must be bounded ($ not allowed)"
1645                                .to_string(),
1646                        });
1647                    }
1648                    let max = max_str.parse::<u32>().map_err(|_| SvaParseError {
1649                        message: format!("invalid eventually max: '{}'", max_str),
1650                    })?;
1651                    return Ok(SvaExpr::EventuallyBounded {
1652                        body: Box::new(parse_unary(body_str)?),
1653                        min,
1654                        max,
1655                    });
1656                }
1657            }
1658        }
1659    }
1660
1661    // s_eventually [m:n] body — bounded strong eventually (IEEE 16.12.13)
1662    // Must check BEFORE the existing s_eventually() function-call parse
1663    if input.starts_with("s_eventually [") || input.starts_with("s_eventually[") {
1664        let rest = input["s_eventually".len()..].trim();
1665        if rest.starts_with('[') {
1666            if let Some(bracket_end) = rest.find(']') {
1667                let range_str = &rest[1..bracket_end];
1668                let body_str = rest[bracket_end + 1..].trim();
1669                let parts: Vec<&str> = range_str.split(':').collect();
1670                if parts.len() == 2 {
1671                    let min = parts[0].trim().parse::<u32>().map_err(|_| SvaParseError {
1672                        message: format!("invalid s_eventually min: '{}'", parts[0]),
1673                    })?;
1674                    let max_str = parts[1].trim();
1675                    let max = if max_str == "$" {
1676                        None // strong eventually CAN use $
1677                    } else {
1678                        Some(max_str.parse::<u32>().map_err(|_| SvaParseError {
1679                            message: format!("invalid s_eventually max: '{}'", max_str),
1680                        })?)
1681                    };
1682                    return Ok(SvaExpr::SEventuallyBounded {
1683                        body: Box::new(parse_unary(body_str)?),
1684                        min,
1685                        max,
1686                    });
1687                }
1688            }
1689        }
1690    }
1691
1692    // Delay: ##N body or ##[min:max] body or ##[*] or ##[+]
1693    if input.starts_with("##") {
1694        let rest = &input[2..];
1695        if rest.starts_with('[') {
1696            // Check for ##[*] and ##[+] shorthands first
1697            // Convention: max: None = unbounded ($), max: Some(n) = bounded
1698            if rest.starts_with("[*]") {
1699                let body_str = rest[3..].trim();
1700                return Ok(SvaExpr::Delay {
1701                    body: Box::new(parse_unary(body_str)?),
1702                    min: 0,
1703                    max: None, // [*] = [0:$]
1704                });
1705            }
1706            if rest.starts_with("[+]") {
1707                let body_str = rest[3..].trim();
1708                return Ok(SvaExpr::Delay {
1709                    body: Box::new(parse_unary(body_str)?),
1710                    min: 1,
1711                    max: None, // [+] = [1:$]
1712                });
1713            }
1714            // ##[min:max] body
1715            if let Some(bracket_end) = rest.find(']') {
1716                let range_str = &rest[1..bracket_end];
1717                let body_str = rest[bracket_end + 1..].trim();
1718                let parts: Vec<&str> = range_str.split(':').collect();
1719                if parts.len() == 2 {
1720                    let min = parts[0].trim().parse::<u32>().map_err(|_| SvaParseError {
1721                        message: format!("invalid delay min: '{}'", parts[0]),
1722                    })?;
1723                    let max_str = parts[1].trim();
1724                    let max = if max_str == "$" {
1725                        None // $ = unbounded
1726                    } else {
1727                        Some(max_str.parse::<u32>().map_err(|_| SvaParseError {
1728                            message: format!("invalid delay max: '{}'", max_str),
1729                        })?)
1730                    };
1731                    return Ok(SvaExpr::Delay {
1732                        body: Box::new(parse_unary(body_str)?),
1733                        min,
1734                        max,
1735                    });
1736                }
1737            }
1738        } else {
1739            // ##N body — exact delay
1740            let mut num_end = 0;
1741            for c in rest.chars() {
1742                if c.is_ascii_digit() {
1743                    num_end += 1;
1744                } else {
1745                    break;
1746                }
1747            }
1748            if num_end > 0 {
1749                let n = rest[..num_end].parse::<u32>().map_err(|_| SvaParseError {
1750                    message: format!("invalid delay number: '{}'", &rest[..num_end]),
1751                })?;
1752                let body_str = rest[num_end..].trim();
1753                return Ok(SvaExpr::Delay {
1754                    body: Box::new(parse_unary(body_str)?),
1755                    min: n,
1756                    max: Some(n), // exact delay: min == max
1757                });
1758            }
1759        }
1760    }
1761
1762    // Negation: !(...)
1763    if input.starts_with('!') {
1764        let inner = input[1..].trim();
1765        let inner = strip_parens(inner);
1766        return Ok(SvaExpr::Not(Box::new(parse_implication(inner)?)));
1767    }
1768
1769    // IEEE 1800 system functions — $onehot0 BEFORE $onehot (prefix clarity)
1770    if let Some(result) = try_parse_function_call(input, "$onehot0", |inner| {
1771        Ok(SvaExpr::OneHot0(Box::new(parse_implication(inner)?)))
1772    })? {
1773        return Ok(result);
1774    }
1775
1776    if let Some(result) = try_parse_function_call(input, "$onehot", |inner| {
1777        Ok(SvaExpr::OneHot(Box::new(parse_implication(inner)?)))
1778    })? {
1779        return Ok(result);
1780    }
1781
1782    if let Some(result) = try_parse_function_call(input, "$countones", |inner| {
1783        Ok(SvaExpr::CountOnes(Box::new(parse_implication(inner)?)))
1784    })? {
1785        return Ok(result);
1786    }
1787
1788    if let Some(result) = try_parse_function_call(input, "$isunknown", |inner| {
1789        Ok(SvaExpr::IsUnknown(Box::new(parse_implication(inner)?)))
1790    })? {
1791        return Ok(result);
1792    }
1793
1794    if let Some(result) = try_parse_function_call(input, "$sampled", |inner| {
1795        Ok(SvaExpr::Sampled(Box::new(parse_implication(inner)?)))
1796    })? {
1797        return Ok(result);
1798    }
1799
1800    if let Some(result) = try_parse_function_call(input, "$bits", |inner| {
1801        Ok(SvaExpr::Bits(Box::new(parse_implication(inner)?)))
1802    })? {
1803        return Ok(result);
1804    }
1805
1806    if let Some(result) = try_parse_function_call(input, "$clog2", |inner| {
1807        Ok(SvaExpr::Clog2(Box::new(parse_implication(inner)?)))
1808    })? {
1809        return Ok(result);
1810    }
1811
1812    // $countbits(sig, '0', '1', ...) — generalized bit counting (IEEE 20.9)
1813    if input.starts_with("$countbits(") {
1814        if let Some(close) = find_balanced_close(input, "$countbits".len()) {
1815            let inner = &input["$countbits".len() + 1..close];
1816            // Parse: first arg is signal, rest are control chars
1817            let parts: Vec<&str> = inner.split(',').collect();
1818            if !parts.is_empty() {
1819                let sig = parse_implication(parts[0].trim())?;
1820                let mut control_chars = Vec::new();
1821                for part in &parts[1..] {
1822                    let trimmed = part.trim().trim_matches('\'');
1823                    if let Some(c) = trimmed.chars().next() {
1824                        control_chars.push(c);
1825                    }
1826                }
1827                return Ok(SvaExpr::CountBits(Box::new(sig), control_chars));
1828            }
1829        }
1830    }
1831
1832    // $isunbounded(param) — parameter bound check (IEEE 20.9)
1833    if let Some(result) = try_parse_function_call(input, "$isunbounded", |inner| {
1834        Ok(SvaExpr::IsUnbounded(Box::new(parse_implication(inner)?)))
1835    })? {
1836        return Ok(result);
1837    }
1838
1839    // $rose(...), $fell(...), $stable(...), $changed(...), s_eventually(...), $nexttime(...)
1840    // Use balanced paren matching so "$fell(sda) && scl" correctly parses $fell(sda) only
1841    if let Some(result) = try_parse_function_call(input, "$rose", |inner| {
1842        Ok(SvaExpr::Rose(Box::new(parse_implication(inner)?)))
1843    })? {
1844        return Ok(result);
1845    }
1846
1847    if let Some(result) = try_parse_function_call(input, "$fell", |inner| {
1848        Ok(SvaExpr::Fell(Box::new(parse_implication(inner)?)))
1849    })? {
1850        return Ok(result);
1851    }
1852
1853    if let Some(result) = try_parse_function_call(input, "$stable", |inner| {
1854        Ok(SvaExpr::Stable(Box::new(parse_implication(inner)?)))
1855    })? {
1856        return Ok(result);
1857    }
1858
1859    if let Some(result) = try_parse_function_call(input, "$changed", |inner| {
1860        Ok(SvaExpr::Changed(Box::new(parse_implication(inner)?)))
1861    })? {
1862        return Ok(result);
1863    }
1864
1865    if let Some(result) = try_parse_function_call(input, "s_eventually", |inner| {
1866        Ok(SvaExpr::SEventually(Box::new(parse_implication(inner)?)))
1867    })? {
1868        return Ok(result);
1869    }
1870
1871    if let Some(result) = try_parse_function_call(input, "s_always", |inner| {
1872        Ok(SvaExpr::SAlways(Box::new(parse_implication(inner)?)))
1873    })? {
1874        return Ok(result);
1875    }
1876
1877    // nexttime[N](body) — with explicit count
1878    if input.starts_with("nexttime[") {
1879        if let Some(bracket_end) = input.find(']') {
1880            let n_str = &input[9..bracket_end];
1881            if let Ok(n) = n_str.parse::<u32>() {
1882                let rest = input[bracket_end + 1..].trim();
1883                if rest.starts_with('(') {
1884                    if let Some(close) = find_balanced_close(rest, 0) {
1885                        let inner = &rest[1..close];
1886                        return Ok(SvaExpr::Nexttime(
1887                            Box::new(parse_implication(inner.trim())?),
1888                            n,
1889                        ));
1890                    }
1891                }
1892            }
1893        }
1894    }
1895
1896    // nexttime(body) — default count = 1
1897    if let Some(result) = try_parse_function_call(input, "nexttime", |inner| {
1898        Ok(SvaExpr::Nexttime(Box::new(parse_implication(inner)?), 1))
1899    })? {
1900        return Ok(result);
1901    }
1902
1903    if let Some(result) = try_parse_function_call(input, "$nexttime", |inner| {
1904        Ok(SvaExpr::Nexttime(Box::new(parse_implication(inner)?), 1))
1905    })? {
1906        return Ok(result);
1907    }
1908
1909    if let Some(result) = try_parse_function_call(input, "first_match", |inner| {
1910        Ok(SvaExpr::FirstMatch(Box::new(parse_implication(inner)?)))
1911    })? {
1912        return Ok(result);
1913    }
1914
1915    if let Some(result) = try_parse_function_call(input, "$past", |inner| {
1916        // $past(sig, n) — parse the signal and count
1917        if let Some(comma) = inner.find(',') {
1918            let sig = inner[..comma].trim();
1919            let n_str = inner[comma + 1..].trim();
1920            let n = n_str.parse::<u32>().unwrap_or(1);
1921            Ok(SvaExpr::Past(Box::new(parse_atom(sig)?), n))
1922        } else {
1923            Ok(SvaExpr::Past(Box::new(parse_atom(inner)?), 1))
1924        }
1925    })? {
1926        return Ok(result);
1927    }
1928
1929    // Parenthesized expression
1930    if input.starts_with('(') && input.ends_with(')') {
1931        return parse_implication(&input[1..input.len() - 1]);
1932    }
1933
1934    parse_atom(input)
1935}
1936
1937/// Find the `else` keyword in action block text, skipping occurrences inside
1938/// string literals (both regular `"..."` and triple-quoted `"""..."""`).
1939/// Returns the byte offset of the `else` keyword, or None if not found outside strings.
1940fn find_else_outside_strings(input: &str) -> Option<usize> {
1941    let bytes = input.as_bytes();
1942    let len = bytes.len();
1943    let mut i = 0;
1944    while i < len {
1945        // Check for triple-quoted string: """..."""
1946        if i + 2 < len && bytes[i] == b'"' && bytes[i + 1] == b'"' && bytes[i + 2] == b'"' {
1947            i += 3; // skip opening """
1948            while i < len {
1949                if bytes[i] == b'\\' && i + 1 < len {
1950                    i += 2; // skip escape sequence
1951                } else if i + 2 < len
1952                    && bytes[i] == b'"'
1953                    && bytes[i + 1] == b'"'
1954                    && bytes[i + 2] == b'"'
1955                {
1956                    i += 3; // skip closing """
1957                    break;
1958                } else {
1959                    i += 1;
1960                }
1961            }
1962            continue;
1963        }
1964        // Check for regular string: "..."
1965        if bytes[i] == b'"' {
1966            i += 1; // skip opening "
1967            while i < len {
1968                if bytes[i] == b'\\' && i + 1 < len {
1969                    i += 2; // skip escape sequence
1970                } else if bytes[i] == b'"' {
1971                    i += 1; // skip closing "
1972                    break;
1973                } else {
1974                    i += 1;
1975                }
1976            }
1977            continue;
1978        }
1979        // Check for `else` keyword at word boundary
1980        if i + 4 <= len && &input[i..i + 4] == "else" {
1981            // Verify it's at a word boundary (not part of a larger identifier)
1982            let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
1983            let after_ok = i + 4 >= len || !bytes[i + 4].is_ascii_alphanumeric();
1984            if before_ok && after_ok {
1985                return Some(i);
1986            }
1987        }
1988        i += 1;
1989    }
1990    None
1991}
1992
1993/// Find the closing paren that balances the opening paren at `start`.
1994/// Returns the index of the closing ')' relative to the input string.
1995fn find_balanced_close(input: &str, start: usize) -> Option<usize> {
1996    let chars: Vec<char> = input.chars().collect();
1997    let mut depth = 0i32;
1998    for i in start..chars.len() {
1999        match chars[i] {
2000            '(' => depth += 1,
2001            ')' => {
2002                depth -= 1;
2003                if depth == 0 {
2004                    return Some(i);
2005                }
2006            }
2007            _ => {}
2008        }
2009    }
2010    None
2011}
2012
2013/// Try to parse a function call like `$rose(expr)` with balanced parens.
2014/// If the input starts with `prefix(`, extracts the balanced inner expression,
2015/// parses it with the provided closure, and returns the result.
2016/// If there's content after the closing paren, this returns None so the caller
2017/// can try parsing at a higher level (e.g., `$rose(sig) && other` should be
2018/// parsed as And($rose(sig), other) at the And level, not here).
2019fn try_parse_function_call<F>(
2020    input: &str,
2021    prefix: &str,
2022    parse_inner: F,
2023) -> Result<Option<SvaExpr>, SvaParseError>
2024where
2025    F: FnOnce(&str) -> Result<SvaExpr, SvaParseError>,
2026{
2027    let full_prefix = format!("{}(", prefix);
2028    if !input.starts_with(&full_prefix) {
2029        return Ok(None);
2030    }
2031    let paren_start = full_prefix.len() - 1; // index of '('
2032    if let Some(close) = find_balanced_close(input, paren_start) {
2033        let inner = &input[full_prefix.len()..close];
2034        let remaining = input[close + 1..].trim();
2035        if remaining.is_empty() {
2036            // Simple case: $rose(sig) with nothing after
2037            return Ok(Some(parse_inner(inner.trim())?));
2038        }
2039        // There's stuff after the closing paren (e.g., "$rose(sig) && other")
2040        // Parse just the function call, then let the caller handle the rest
2041        // We can't handle this at the unary level — return None so the
2042        // expression gets reparsed at the binary operator level.
2043        // But we need to handle it: wrap as atom.
2044        // Actually, re-parse the entire input through the binary operators:
2045        // The issue is that "$fell(sda) && scl" is at the AND level, not unary.
2046        // So we parse just "$fell(sda)" as the left side of AND.
2047        return Ok(None);
2048    }
2049    Err(SvaParseError {
2050        message: format!("unbalanced parens in {}", prefix),
2051    })
2052}
2053
2054/// Find the position of the top-level "else" keyword (not inside parens).
2055fn find_else_keyword(input: &str) -> Option<usize> {
2056    let mut depth = 0i32;
2057    let bytes = input.as_bytes();
2058    for i in 0..input.len().saturating_sub(3) {
2059        match bytes[i] {
2060            b'(' => depth += 1,
2061            b')' => depth -= 1,
2062            b'e' if depth == 0 => {
2063                if input[i..].starts_with("else") {
2064                    // Check word boundary
2065                    let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
2066                    let after_ok = i + 4 >= input.len() || !bytes[i + 4].is_ascii_alphanumeric();
2067                    if before_ok && after_ok {
2068                        return Some(i);
2069                    }
2070                }
2071            }
2072            _ => {}
2073        }
2074    }
2075    None
2076}
2077
2078fn parse_atom(input: &str) -> Result<SvaExpr, SvaParseError> {
2079    let input = input.trim();
2080    if input.is_empty() {
2081        return Err(SvaParseError {
2082            message: "empty expression".to_string(),
2083        });
2084    }
2085
2086    // Check for [+] repetition shorthand: signal[+] ≡ signal[*1:$]
2087    if let Some(bracket_pos) = input.find("[+]") {
2088        let signal_part = input[..bracket_pos].trim();
2089        let body = parse_atom(signal_part)?;
2090        return Ok(SvaExpr::Repetition {
2091            body: Box::new(body),
2092            min: 1,
2093            max: None,
2094        });
2095    }
2096
2097    // Check for repetition: signal[*N] or signal[*min:max] or signal[*]
2098    if let Some(bracket_pos) = input.find("[*") {
2099        let signal_part = input[..bracket_pos].trim();
2100        let rep_part = &input[bracket_pos + 2..];
2101        if let Some(close_bracket) = rep_part.find(']') {
2102            let range_str = &rep_part[..close_bracket].trim();
2103            // [*] shorthand ≡ [*0:$]
2104            if range_str.is_empty() {
2105                let body = parse_atom(signal_part)?;
2106                return Ok(SvaExpr::Repetition {
2107                    body: Box::new(body),
2108                    min: 0,
2109                    max: None,
2110                });
2111            }
2112            let body = parse_atom(signal_part)?;
2113            if let Some(colon) = range_str.find(':') {
2114                let min_str = range_str[..colon].trim();
2115                let max_str = range_str[colon + 1..].trim();
2116                let min = min_str.parse::<u32>().map_err(|_| SvaParseError {
2117                    message: format!("invalid repetition min: '{}'", min_str),
2118                })?;
2119                let max = if max_str == "$" {
2120                    None
2121                } else {
2122                    Some(max_str.parse::<u32>().map_err(|_| SvaParseError {
2123                        message: format!("invalid repetition max: '{}'", max_str),
2124                    })?)
2125                };
2126                return Ok(SvaExpr::Repetition {
2127                    body: Box::new(body),
2128                    min,
2129                    max,
2130                });
2131            } else {
2132                // Exact repetition: [*N]
2133                let n = range_str.trim().parse::<u32>().map_err(|_| SvaParseError {
2134                    message: format!("invalid repetition count: '{}'", range_str),
2135                })?;
2136                return Ok(SvaExpr::Repetition {
2137                    body: Box::new(body),
2138                    min: n,
2139                    max: Some(n),
2140                });
2141            }
2142        }
2143    }
2144
2145    // Goto repetition: signal[->N]
2146    if let Some(bracket_pos) = input.find("[->") {
2147        let signal_part = input[..bracket_pos].trim();
2148        let rep_part = &input[bracket_pos + 3..];
2149        if let Some(close_bracket) = rep_part.find(']') {
2150            let count_str = rep_part[..close_bracket].trim();
2151            let count = count_str.parse::<u32>().map_err(|_| SvaParseError {
2152                message: format!("invalid goto repetition count: '{}'", count_str),
2153            })?;
2154            return Ok(SvaExpr::GotoRepetition {
2155                body: Box::new(parse_atom(signal_part)?),
2156                count,
2157            });
2158        }
2159    }
2160
2161    // Non-consecutive repetition: signal[=N] or signal[=min:max] or signal[=min:$]
2162    if let Some(bracket_pos) = input.find("[=") {
2163        let signal_part = input[..bracket_pos].trim();
2164        let rep_part = &input[bracket_pos + 2..];
2165        if let Some(close_bracket) = rep_part.find(']') {
2166            let range_str = &rep_part[..close_bracket];
2167            let body = parse_atom(signal_part)?;
2168            if let Some(colon) = range_str.find(':') {
2169                let min = range_str[..colon]
2170                    .trim()
2171                    .parse::<u32>()
2172                    .map_err(|_| SvaParseError {
2173                        message: format!(
2174                            "invalid non-consec repetition min: '{}'",
2175                            &range_str[..colon]
2176                        ),
2177                    })?;
2178                let max_str = range_str[colon + 1..].trim();
2179                let max = if max_str == "$" {
2180                    None
2181                } else {
2182                    Some(max_str.parse::<u32>().map_err(|_| SvaParseError {
2183                        message: format!("invalid non-consec repetition max: '{}'", max_str),
2184                    })?)
2185                };
2186                return Ok(SvaExpr::NonConsecRepetition {
2187                    body: Box::new(body),
2188                    min,
2189                    max,
2190                });
2191            } else {
2192                let n = range_str.trim().parse::<u32>().map_err(|_| SvaParseError {
2193                    message: format!("invalid non-consec repetition count: '{}'", range_str),
2194                })?;
2195                return Ok(SvaExpr::NonConsecRepetition {
2196                    body: Box::new(body),
2197                    min: n,
2198                    max: Some(n),
2199                });
2200            }
2201        }
2202    }
2203
2204    // IEEE 1800-2023 5.7.2: Real literal constants (e.g., 1.5, 1.2E3, 1.30e-2)
2205    // Must have digit on each side of decimal point (.12 and 9. are invalid)
2206    if (input.contains('.') || input.contains('e') || input.contains('E'))
2207        && input.chars().next().map_or(false, |c| c.is_ascii_digit())
2208    {
2209        if let Ok(v) = input.parse::<f64>() {
2210            return Ok(SvaExpr::RealConst(v));
2211        }
2212    }
2213
2214    // Check if it's a number (plain or Verilog-style width'd value)
2215    if let Ok(n) = input.parse::<u64>() {
2216        return Ok(SvaExpr::Const(n, 32));
2217    }
2218    // Verilog numeric literal: N'd M or N'hXX etc.
2219    if let Some(tick_pos) = input.find('\'') {
2220        let width_str = &input[..tick_pos];
2221        let rest = &input[tick_pos + 1..];
2222        if let Ok(width) = width_str.parse::<u32>() {
2223            let (radix, value_str) = if rest.starts_with('d') || rest.starts_with('D') {
2224                (10, &rest[1..])
2225            } else if rest.starts_with('h') || rest.starts_with('H') {
2226                (16, &rest[1..])
2227            } else if rest.starts_with('b') || rest.starts_with('B') {
2228                (2, &rest[1..])
2229            } else if rest.starts_with('o') || rest.starts_with('O') {
2230                (8, &rest[1..])
2231            } else {
2232                (10, rest)
2233            };
2234            if let Ok(value) = u64::from_str_radix(value_str, radix) {
2235                return Ok(SvaExpr::Const(value, width));
2236            }
2237        }
2238    }
2239
2240    // IEEE 1800-2023: type(this) construct (IEEE 6.23)
2241    if input == "type(this)" {
2242        return Ok(SvaExpr::TypeThis);
2243    }
2244
2245    // IEEE 1800-2023: A.map(x) with (expr) — array map method (IEEE 7.12)
2246    if let Some(dot_map_pos) = input.find(".map(") {
2247        let array_part = &input[..dot_map_pos].trim();
2248        let after_map = &input[dot_map_pos + 5..]; // skip ".map("
2249                                                   // Find closing paren for iterator args
2250        if let Some(iter_close) = after_map.find(')') {
2251            let iter_part = after_map[..iter_close].trim();
2252            let iterator = if iter_part.is_empty() {
2253                "item".to_string() // default iterator name per IEEE 7.12
2254            } else {
2255                // May have iterator and optional index arg: "x" or "x, i"
2256                iter_part
2257                    .split(',')
2258                    .next()
2259                    .unwrap_or("item")
2260                    .trim()
2261                    .to_string()
2262            };
2263            let after_iter_close = after_map[iter_close + 1..].trim();
2264            // Expect `with (expr)`
2265            if after_iter_close.starts_with("with") {
2266                let with_body = after_iter_close["with".len()..].trim();
2267                let with_expr_str = strip_parens(with_body);
2268                let array_expr = parse_atom(array_part)?;
2269                let with_expr = parse_sva(with_expr_str)?;
2270                return Ok(SvaExpr::ArrayMap {
2271                    array: Box::new(array_expr),
2272                    iterator,
2273                    with_expr: Box::new(with_expr),
2274                });
2275            }
2276        }
2277    }
2278
2279    // Must be a signal name
2280    if input.chars().all(|c| c.is_alphanumeric() || c == '_') {
2281        return Ok(SvaExpr::Signal(input.to_string()));
2282    }
2283
2284    Err(SvaParseError {
2285        message: format!("unexpected token: '{}'", input),
2286    })
2287}
2288
2289/// Render an SvaExpr back to valid SVA text.
2290/// Closes the round-trip: parse_sva(text) → SvaExpr → sva_expr_to_string → text.
2291pub fn sva_expr_to_string(expr: &SvaExpr) -> String {
2292    match expr {
2293        SvaExpr::Signal(name) => name.clone(),
2294        SvaExpr::Const(value, width) => format!("{}'d{}", width, value),
2295        SvaExpr::Rose(inner) => format!("$rose({})", sva_expr_to_string(inner)),
2296        SvaExpr::Fell(inner) => format!("$fell({})", sva_expr_to_string(inner)),
2297        SvaExpr::Past(inner, n) => format!("$past({}, {})", sva_expr_to_string(inner), n),
2298        SvaExpr::And(left, right) => {
2299            format!(
2300                "({} && {})",
2301                sva_expr_to_string(left),
2302                sva_expr_to_string(right)
2303            )
2304        }
2305        SvaExpr::Or(left, right) => {
2306            format!(
2307                "({} || {})",
2308                sva_expr_to_string(left),
2309                sva_expr_to_string(right)
2310            )
2311        }
2312        SvaExpr::Not(inner) => format!("!({})", sva_expr_to_string(inner)),
2313        SvaExpr::Eq(left, right) => {
2314            format!(
2315                "({} == {})",
2316                sva_expr_to_string(left),
2317                sva_expr_to_string(right)
2318            )
2319        }
2320        SvaExpr::Implication {
2321            antecedent,
2322            consequent,
2323            overlapping,
2324        } => {
2325            let op = if *overlapping { "|->" } else { "|=>" };
2326            format!(
2327                "{} {} {}",
2328                sva_expr_to_string(antecedent),
2329                op,
2330                sva_expr_to_string(consequent)
2331            )
2332        }
2333        SvaExpr::Delay { body, min, max } => match (min, max) {
2334            // Unified convention: None = unbounded ($), Some(n) = bounded
2335            (0, None) => format!("##[*] {}", sva_expr_to_string(body)),
2336            (1, None) => format!("##[+] {}", sva_expr_to_string(body)),
2337            (_, None) => format!("##[{}:$] {}", min, sva_expr_to_string(body)),
2338            (_, Some(max_val)) if min == max_val => {
2339                format!("##{} {}", min, sva_expr_to_string(body))
2340            }
2341            (_, Some(max_val)) => format!("##[{}:{}] {}", min, max_val, sva_expr_to_string(body)),
2342        },
2343        SvaExpr::Repetition { body, min, max } => {
2344            let body_str = sva_expr_to_string(body);
2345            match (min, max) {
2346                (0, None) => format!("{}[*]", body_str),
2347                (1, None) => format!("{}[+]", body_str),
2348                (_, Some(m)) if *m == *min => format!("{}[*{}]", body_str, min),
2349                (_, Some(m)) => format!("{}[*{}:{}]", body_str, min, m),
2350                (_, None) => format!("{}[*{}:$]", body_str, min),
2351            }
2352        }
2353        SvaExpr::SEventually(inner) => format!("s_eventually({})", sva_expr_to_string(inner)),
2354        SvaExpr::SAlways(inner) => format!("s_always({})", sva_expr_to_string(inner)),
2355        SvaExpr::Stable(inner) => format!("$stable({})", sva_expr_to_string(inner)),
2356        SvaExpr::Changed(inner) => format!("$changed({})", sva_expr_to_string(inner)),
2357        SvaExpr::Nexttime(inner, n) => {
2358            if *n == 1 {
2359                format!("nexttime({})", sva_expr_to_string(inner))
2360            } else {
2361                format!("nexttime[{}]({})", n, sva_expr_to_string(inner))
2362            }
2363        }
2364        SvaExpr::DisableIff { condition, body } => {
2365            format!(
2366                "disable iff ({}) {}",
2367                sva_expr_to_string(condition),
2368                sva_expr_to_string(body)
2369            )
2370        }
2371        SvaExpr::IfElse {
2372            condition,
2373            then_expr,
2374            else_expr,
2375        } => {
2376            format!(
2377                "if ({}) {} else {}",
2378                sva_expr_to_string(condition),
2379                sva_expr_to_string(then_expr),
2380                sva_expr_to_string(else_expr),
2381            )
2382        }
2383        // IEEE 1800 extended (Sprint 1B)
2384        SvaExpr::NotEq(l, r) => format!("({} != {})", sva_expr_to_string(l), sva_expr_to_string(r)),
2385        SvaExpr::LessThan(l, r) => {
2386            format!("({} < {})", sva_expr_to_string(l), sva_expr_to_string(r))
2387        }
2388        SvaExpr::GreaterThan(l, r) => {
2389            format!("({} > {})", sva_expr_to_string(l), sva_expr_to_string(r))
2390        }
2391        SvaExpr::LessEqual(l, r) => {
2392            format!("({} <= {})", sva_expr_to_string(l), sva_expr_to_string(r))
2393        }
2394        SvaExpr::GreaterEqual(l, r) => {
2395            format!("({} >= {})", sva_expr_to_string(l), sva_expr_to_string(r))
2396        }
2397        SvaExpr::Ternary {
2398            condition,
2399            then_expr,
2400            else_expr,
2401        } => {
2402            format!(
2403                "{} ? {} : {}",
2404                sva_expr_to_string(condition),
2405                sva_expr_to_string(then_expr),
2406                sva_expr_to_string(else_expr),
2407            )
2408        }
2409        SvaExpr::Throughout { signal, sequence } => {
2410            format!(
2411                "{} throughout ({})",
2412                sva_expr_to_string(signal),
2413                sva_expr_to_string(sequence),
2414            )
2415        }
2416        SvaExpr::Within { inner, outer } => {
2417            format!(
2418                "({}) within ({})",
2419                sva_expr_to_string(inner),
2420                sva_expr_to_string(outer),
2421            )
2422        }
2423        SvaExpr::FirstMatch(inner) => format!("first_match({})", sva_expr_to_string(inner)),
2424        SvaExpr::Intersect { left, right } => {
2425            format!(
2426                "({}) intersect ({})",
2427                sva_expr_to_string(left),
2428                sva_expr_to_string(right),
2429            )
2430        }
2431        // IEEE 1800 system functions (Audit)
2432        SvaExpr::OneHot0(inner) => format!("$onehot0({})", sva_expr_to_string(inner)),
2433        SvaExpr::OneHot(inner) => format!("$onehot({})", sva_expr_to_string(inner)),
2434        SvaExpr::CountOnes(inner) => format!("$countones({})", sva_expr_to_string(inner)),
2435        SvaExpr::IsUnknown(inner) => format!("$isunknown({})", sva_expr_to_string(inner)),
2436        SvaExpr::Sampled(inner) => format!("$sampled({})", sva_expr_to_string(inner)),
2437        SvaExpr::Bits(inner) => format!("$bits({})", sva_expr_to_string(inner)),
2438        SvaExpr::Clog2(inner) => format!("$clog2({})", sva_expr_to_string(inner)),
2439        SvaExpr::CountBits(inner, chars) => {
2440            let char_args: Vec<String> = chars.iter().map(|c| format!("'{}'", c)).collect();
2441            format!(
2442                "$countbits({}, {})",
2443                sva_expr_to_string(inner),
2444                char_args.join(", ")
2445            )
2446        }
2447        SvaExpr::IsUnbounded(inner) => format!("$isunbounded({})", sva_expr_to_string(inner)),
2448        // Advanced sequences (Audit)
2449        SvaExpr::GotoRepetition { body, count } => {
2450            format!("{}[->{}]", sva_expr_to_string(body), count)
2451        }
2452        SvaExpr::NonConsecRepetition { body, min, max } => {
2453            let body_str = sva_expr_to_string(body);
2454            match max {
2455                Some(m) if *m == *min => format!("{}[={}]", body_str, min),
2456                Some(m) => format!("{}[={}:{}]", body_str, min, m),
2457                None => format!("{}[={}:$]", body_str, min),
2458            }
2459        }
2460        // Property abort operators (Audit)
2461        SvaExpr::AcceptOn { condition, body } => {
2462            format!(
2463                "accept_on({}) {}",
2464                sva_expr_to_string(condition),
2465                sva_expr_to_string(body)
2466            )
2467        }
2468        SvaExpr::RejectOn { condition, body } => {
2469            format!(
2470                "reject_on({}) {}",
2471                sva_expr_to_string(condition),
2472                sva_expr_to_string(body)
2473            )
2474        }
2475        // Property connectives (Sprint 1, IEEE 16.12.3-8)
2476        SvaExpr::PropertyNot(inner) => format!("not {}", sva_expr_to_string(inner)),
2477        SvaExpr::PropertyImplies(l, r) => {
2478            format!(
2479                "{} implies {}",
2480                sva_expr_to_string(l),
2481                sva_expr_to_string(r)
2482            )
2483        }
2484        SvaExpr::PropertyIff(l, r) => {
2485            format!("{} iff {}", sva_expr_to_string(l), sva_expr_to_string(r))
2486        }
2487        // LTL temporal operators (Sprint 2)
2488        SvaExpr::Always(inner) => format!("always({})", sva_expr_to_string(inner)),
2489        SvaExpr::AlwaysBounded { body, min, max } => match max {
2490            Some(m) => format!("always [{}:{}] {}", min, m, sva_expr_to_string(body)),
2491            None => format!("always [{}:$] {}", min, sva_expr_to_string(body)),
2492        },
2493        SvaExpr::SAlwaysBounded { body, min, max } => {
2494            format!("s_always [{}:{}] {}", min, max, sva_expr_to_string(body))
2495        }
2496        SvaExpr::EventuallyBounded { body, min, max } => {
2497            format!("eventually [{}:{}] {}", min, max, sva_expr_to_string(body))
2498        }
2499        SvaExpr::SEventuallyBounded { body, min, max } => match max {
2500            Some(m) => format!("s_eventually [{}:{}] {}", min, m, sva_expr_to_string(body)),
2501            None => format!("s_eventually [{}:$] {}", min, sva_expr_to_string(body)),
2502        },
2503        SvaExpr::Until {
2504            lhs,
2505            rhs,
2506            strong,
2507            inclusive,
2508        } => {
2509            let op = match (strong, inclusive) {
2510                (false, false) => "until",
2511                (true, false) => "s_until",
2512                (false, true) => "until_with",
2513                (true, true) => "s_until_with",
2514            };
2515            format!(
2516                "{} {} {}",
2517                sva_expr_to_string(lhs),
2518                op,
2519                sva_expr_to_string(rhs)
2520            )
2521        }
2522        // Sprint 3
2523        SvaExpr::Strong(inner) => format!("strong({})", sva_expr_to_string(inner)),
2524        SvaExpr::Weak(inner) => format!("weak({})", sva_expr_to_string(inner)),
2525        SvaExpr::SNexttime(inner, n) => {
2526            if *n == 1 {
2527                format!("s_nexttime({})", sva_expr_to_string(inner))
2528            } else {
2529                format!("s_nexttime[{}]({})", n, sva_expr_to_string(inner))
2530            }
2531        }
2532        SvaExpr::FollowedBy {
2533            antecedent,
2534            consequent,
2535            overlapping,
2536        } => {
2537            let op = if *overlapping { "#-#" } else { "#=#" };
2538            format!(
2539                "{} {} {}",
2540                sva_expr_to_string(antecedent),
2541                op,
2542                sva_expr_to_string(consequent)
2543            )
2544        }
2545        SvaExpr::PropertyCase {
2546            expression,
2547            items,
2548            default,
2549        } => {
2550            let mut s = format!("case({})", sva_expr_to_string(expression));
2551            for (vals, prop) in items {
2552                let vs: Vec<String> = vals.iter().map(sva_expr_to_string).collect();
2553                s.push_str(&format!(
2554                    " {}: {};",
2555                    vs.join(", "),
2556                    sva_expr_to_string(prop)
2557                ));
2558            }
2559            if let Some(d) = default {
2560                s.push_str(&format!(" default: {};", sva_expr_to_string(d)));
2561            }
2562            s.push_str(" endcase");
2563            s
2564        }
2565        SvaExpr::SyncAcceptOn { condition, body } => {
2566            format!(
2567                "sync_accept_on({}) {}",
2568                sva_expr_to_string(condition),
2569                sva_expr_to_string(body)
2570            )
2571        }
2572        SvaExpr::SyncRejectOn { condition, body } => {
2573            format!(
2574                "sync_reject_on({}) {}",
2575                sva_expr_to_string(condition),
2576                sva_expr_to_string(body)
2577            )
2578        }
2579        // Sprint 5
2580        SvaExpr::SequenceAnd(l, r) => {
2581            format!(
2582                "({}) and ({})",
2583                sva_expr_to_string(l),
2584                sva_expr_to_string(r)
2585            )
2586        }
2587        SvaExpr::SequenceOr(l, r) => {
2588            format!("({}) or ({})", sva_expr_to_string(l), sva_expr_to_string(r))
2589        }
2590        // Sprint 7
2591        SvaExpr::ImmediateAssert {
2592            expression,
2593            deferred,
2594        } => match deferred {
2595            None => format!("assert({})", sva_expr_to_string(expression)),
2596            Some(ImmediateDeferred::Observed) => {
2597                format!("assert #0({})", sva_expr_to_string(expression))
2598            }
2599            Some(ImmediateDeferred::Final) => {
2600                format!("assert final({})", sva_expr_to_string(expression))
2601            }
2602        },
2603        // Sprint 13
2604        SvaExpr::FieldAccess { signal, field } => {
2605            format!("{}.{}", sva_expr_to_string(signal), field)
2606        }
2607        SvaExpr::EnumLiteral {
2608            type_name: Some(t),
2609            value,
2610        } => format!("{}::{}", t, value),
2611        SvaExpr::EnumLiteral {
2612            type_name: None,
2613            value,
2614        } => value.clone(),
2615        // Sprint 14
2616        SvaExpr::Triggered(name) => format!("{}.triggered", name),
2617        SvaExpr::Matched(name) => format!("{}.matched", name),
2618        // Sprint 15
2619        SvaExpr::BitAnd(l, r) => format!("({} & {})", sva_expr_to_string(l), sva_expr_to_string(r)),
2620        SvaExpr::BitOr(l, r) => format!("({} | {})", sva_expr_to_string(l), sva_expr_to_string(r)),
2621        SvaExpr::BitXor(l, r) => format!("({} ^ {})", sva_expr_to_string(l), sva_expr_to_string(r)),
2622        SvaExpr::BitNot(inner) => format!("~{}", sva_expr_to_string(inner)),
2623        SvaExpr::ReductionAnd(inner) => format!("&{}", sva_expr_to_string(inner)),
2624        SvaExpr::ReductionOr(inner) => format!("|{}", sva_expr_to_string(inner)),
2625        SvaExpr::ReductionXor(inner) => format!("^{}", sva_expr_to_string(inner)),
2626        SvaExpr::BitSelect { signal, index } => format!(
2627            "{}[{}]",
2628            sva_expr_to_string(signal),
2629            sva_expr_to_string(index)
2630        ),
2631        SvaExpr::PartSelect { signal, high, low } => {
2632            format!("{}[{}:{}]", sva_expr_to_string(signal), high, low)
2633        }
2634        SvaExpr::Concat(items) => {
2635            let parts: Vec<String> = items.iter().map(sva_expr_to_string).collect();
2636            format!("{{{}}}", parts.join(", "))
2637        }
2638        // Sprint 18
2639        SvaExpr::SequenceAction {
2640            expression,
2641            assignments,
2642        } => {
2643            let assigns: Vec<String> = assignments
2644                .iter()
2645                .map(|(name, rhs)| format!("{} = {}", name, sva_expr_to_string(rhs)))
2646                .collect();
2647            format!(
2648                "({}, {})",
2649                sva_expr_to_string(expression),
2650                assigns.join(", ")
2651            )
2652        }
2653        SvaExpr::LocalVar(name) => name.clone(),
2654        SvaExpr::ConstCast(inner) => format!("const'({})", sva_expr_to_string(inner)),
2655        SvaExpr::Clocked { clock, edge, body } => {
2656            let edge_str = match edge {
2657                ClockEdge::Posedge => "posedge",
2658                ClockEdge::Negedge => "negedge",
2659                ClockEdge::Edge => "edge",
2660            };
2661            format!("@({} {}) {}", edge_str, clock, sva_expr_to_string(body))
2662        }
2663        // Sprint 23 (IEEE 1800-2023)
2664        SvaExpr::ArrayMap {
2665            array,
2666            iterator,
2667            with_expr,
2668        } => {
2669            format!(
2670                "{}.map({}) with ({})",
2671                sva_expr_to_string(array),
2672                iterator,
2673                sva_expr_to_string(with_expr)
2674            )
2675        }
2676        SvaExpr::TypeThis => "type(this)".to_string(),
2677        SvaExpr::RealConst(v) => format!("{}", v),
2678    }
2679}
2680
2681fn strip_parens(input: &str) -> &str {
2682    let input = input.trim();
2683    if input.starts_with('(') && input.ends_with(')') {
2684        &input[1..input.len() - 1]
2685    } else {
2686        input
2687    }
2688}
2689
2690/// Check if two SvaExpr trees are structurally equivalent.
2691pub fn sva_exprs_structurally_equivalent(a: &SvaExpr, b: &SvaExpr) -> bool {
2692    match (a, b) {
2693        (SvaExpr::Signal(sa), SvaExpr::Signal(sb)) => sa == sb,
2694        (SvaExpr::Const(va, wa), SvaExpr::Const(vb, wb)) => va == vb && wa == wb,
2695        (SvaExpr::Rose(ia), SvaExpr::Rose(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2696        (SvaExpr::Fell(ia), SvaExpr::Fell(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2697        (SvaExpr::Past(ia, na), SvaExpr::Past(ib, nb)) => {
2698            na == nb && sva_exprs_structurally_equivalent(ia, ib)
2699        }
2700        (SvaExpr::And(la, ra), SvaExpr::And(lb, rb)) => {
2701            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2702        }
2703        (SvaExpr::Or(la, ra), SvaExpr::Or(lb, rb)) => {
2704            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2705        }
2706        (SvaExpr::Not(ia), SvaExpr::Not(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2707        (SvaExpr::Eq(la, ra), SvaExpr::Eq(lb, rb)) => {
2708            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2709        }
2710        (
2711            SvaExpr::Implication {
2712                antecedent: aa,
2713                consequent: ca,
2714                overlapping: oa,
2715            },
2716            SvaExpr::Implication {
2717                antecedent: ab,
2718                consequent: cb,
2719                overlapping: ob,
2720            },
2721        ) => {
2722            oa == ob
2723                && sva_exprs_structurally_equivalent(aa, ab)
2724                && sva_exprs_structurally_equivalent(ca, cb)
2725        }
2726        (
2727            SvaExpr::Delay {
2728                body: ba,
2729                min: mna,
2730                max: mxa,
2731            },
2732            SvaExpr::Delay {
2733                body: bb,
2734                min: mnb,
2735                max: mxb,
2736            },
2737        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2738        (
2739            SvaExpr::Repetition {
2740                body: ba,
2741                min: mna,
2742                max: mxa,
2743            },
2744            SvaExpr::Repetition {
2745                body: bb,
2746                min: mnb,
2747                max: mxb,
2748            },
2749        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2750        (SvaExpr::SEventually(ia), SvaExpr::SEventually(ib)) => {
2751            sva_exprs_structurally_equivalent(ia, ib)
2752        }
2753        (SvaExpr::SAlways(ia), SvaExpr::SAlways(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2754        (SvaExpr::Stable(ia), SvaExpr::Stable(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2755        (SvaExpr::Changed(ia), SvaExpr::Changed(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2756        (SvaExpr::Nexttime(ia, na), SvaExpr::Nexttime(ib, nb)) => {
2757            na == nb && sva_exprs_structurally_equivalent(ia, ib)
2758        }
2759        (
2760            SvaExpr::DisableIff {
2761                condition: ca,
2762                body: ba,
2763            },
2764            SvaExpr::DisableIff {
2765                condition: cb,
2766                body: bb,
2767            },
2768        ) => sva_exprs_structurally_equivalent(ca, cb) && sva_exprs_structurally_equivalent(ba, bb),
2769        (
2770            SvaExpr::IfElse {
2771                condition: ca,
2772                then_expr: ta,
2773                else_expr: ea,
2774            },
2775            SvaExpr::IfElse {
2776                condition: cb,
2777                then_expr: tb,
2778                else_expr: eb,
2779            },
2780        ) => {
2781            sva_exprs_structurally_equivalent(ca, cb)
2782                && sva_exprs_structurally_equivalent(ta, tb)
2783                && sva_exprs_structurally_equivalent(ea, eb)
2784        }
2785        // IEEE 1800 extended (Sprint 1B)
2786        (SvaExpr::NotEq(la, ra), SvaExpr::NotEq(lb, rb)) => {
2787            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2788        }
2789        (SvaExpr::LessThan(la, ra), SvaExpr::LessThan(lb, rb)) => {
2790            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2791        }
2792        (SvaExpr::GreaterThan(la, ra), SvaExpr::GreaterThan(lb, rb)) => {
2793            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2794        }
2795        (SvaExpr::LessEqual(la, ra), SvaExpr::LessEqual(lb, rb)) => {
2796            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2797        }
2798        (SvaExpr::GreaterEqual(la, ra), SvaExpr::GreaterEqual(lb, rb)) => {
2799            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2800        }
2801        (
2802            SvaExpr::Ternary {
2803                condition: ca,
2804                then_expr: ta,
2805                else_expr: ea,
2806            },
2807            SvaExpr::Ternary {
2808                condition: cb,
2809                then_expr: tb,
2810                else_expr: eb,
2811            },
2812        ) => {
2813            sva_exprs_structurally_equivalent(ca, cb)
2814                && sva_exprs_structurally_equivalent(ta, tb)
2815                && sva_exprs_structurally_equivalent(ea, eb)
2816        }
2817        (
2818            SvaExpr::Throughout {
2819                signal: sa,
2820                sequence: qa,
2821            },
2822            SvaExpr::Throughout {
2823                signal: sb,
2824                sequence: qb,
2825            },
2826        ) => sva_exprs_structurally_equivalent(sa, sb) && sva_exprs_structurally_equivalent(qa, qb),
2827        (
2828            SvaExpr::Within {
2829                inner: ia,
2830                outer: oa,
2831            },
2832            SvaExpr::Within {
2833                inner: ib,
2834                outer: ob,
2835            },
2836        ) => sva_exprs_structurally_equivalent(ia, ib) && sva_exprs_structurally_equivalent(oa, ob),
2837        (SvaExpr::FirstMatch(ia), SvaExpr::FirstMatch(ib)) => {
2838            sva_exprs_structurally_equivalent(ia, ib)
2839        }
2840        (
2841            SvaExpr::Intersect {
2842                left: la,
2843                right: ra,
2844            },
2845            SvaExpr::Intersect {
2846                left: lb,
2847                right: rb,
2848            },
2849        ) => sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb),
2850        // IEEE 1800 system functions (Audit)
2851        (SvaExpr::OneHot0(ia), SvaExpr::OneHot0(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2852        (SvaExpr::OneHot(ia), SvaExpr::OneHot(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2853        (SvaExpr::CountOnes(ia), SvaExpr::CountOnes(ib)) => {
2854            sva_exprs_structurally_equivalent(ia, ib)
2855        }
2856        (SvaExpr::IsUnknown(ia), SvaExpr::IsUnknown(ib)) => {
2857            sva_exprs_structurally_equivalent(ia, ib)
2858        }
2859        (SvaExpr::Sampled(ia), SvaExpr::Sampled(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2860        (SvaExpr::Bits(ia), SvaExpr::Bits(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2861        (SvaExpr::Clog2(ia), SvaExpr::Clog2(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2862        (SvaExpr::CountBits(ia, ca), SvaExpr::CountBits(ib, cb)) => {
2863            ca == cb && sva_exprs_structurally_equivalent(ia, ib)
2864        }
2865        (SvaExpr::IsUnbounded(ia), SvaExpr::IsUnbounded(ib)) => {
2866            sva_exprs_structurally_equivalent(ia, ib)
2867        }
2868        // Advanced sequences (Audit)
2869        (
2870            SvaExpr::GotoRepetition {
2871                body: ba,
2872                count: ca,
2873            },
2874            SvaExpr::GotoRepetition {
2875                body: bb,
2876                count: cb,
2877            },
2878        ) => ca == cb && sva_exprs_structurally_equivalent(ba, bb),
2879        (
2880            SvaExpr::NonConsecRepetition {
2881                body: ba,
2882                min: mna,
2883                max: mxa,
2884            },
2885            SvaExpr::NonConsecRepetition {
2886                body: bb,
2887                min: mnb,
2888                max: mxb,
2889            },
2890        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2891        // Property abort operators (Audit)
2892        (
2893            SvaExpr::AcceptOn {
2894                condition: ca,
2895                body: ba,
2896            },
2897            SvaExpr::AcceptOn {
2898                condition: cb,
2899                body: bb,
2900            },
2901        ) => sva_exprs_structurally_equivalent(ca, cb) && sva_exprs_structurally_equivalent(ba, bb),
2902        (
2903            SvaExpr::RejectOn {
2904                condition: ca,
2905                body: ba,
2906            },
2907            SvaExpr::RejectOn {
2908                condition: cb,
2909                body: bb,
2910            },
2911        ) => sva_exprs_structurally_equivalent(ca, cb) && sva_exprs_structurally_equivalent(ba, bb),
2912        // Property connectives (Sprint 1)
2913        (SvaExpr::PropertyNot(ia), SvaExpr::PropertyNot(ib)) => {
2914            sva_exprs_structurally_equivalent(ia, ib)
2915        }
2916        (SvaExpr::PropertyImplies(la, ra), SvaExpr::PropertyImplies(lb, rb)) => {
2917            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2918        }
2919        (SvaExpr::PropertyIff(la, ra), SvaExpr::PropertyIff(lb, rb)) => {
2920            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
2921        }
2922        // LTL temporal operators (Sprint 2)
2923        (SvaExpr::Always(ia), SvaExpr::Always(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2924        (
2925            SvaExpr::AlwaysBounded {
2926                body: ba,
2927                min: mna,
2928                max: mxa,
2929            },
2930            SvaExpr::AlwaysBounded {
2931                body: bb,
2932                min: mnb,
2933                max: mxb,
2934            },
2935        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2936        (
2937            SvaExpr::SAlwaysBounded {
2938                body: ba,
2939                min: mna,
2940                max: mxa,
2941            },
2942            SvaExpr::SAlwaysBounded {
2943                body: bb,
2944                min: mnb,
2945                max: mxb,
2946            },
2947        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2948        (
2949            SvaExpr::EventuallyBounded {
2950                body: ba,
2951                min: mna,
2952                max: mxa,
2953            },
2954            SvaExpr::EventuallyBounded {
2955                body: bb,
2956                min: mnb,
2957                max: mxb,
2958            },
2959        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2960        (
2961            SvaExpr::SEventuallyBounded {
2962                body: ba,
2963                min: mna,
2964                max: mxa,
2965            },
2966            SvaExpr::SEventuallyBounded {
2967                body: bb,
2968                min: mnb,
2969                max: mxb,
2970            },
2971        ) => mna == mnb && mxa == mxb && sva_exprs_structurally_equivalent(ba, bb),
2972        (
2973            SvaExpr::Until {
2974                lhs: la,
2975                rhs: ra,
2976                strong: sa,
2977                inclusive: ia,
2978            },
2979            SvaExpr::Until {
2980                lhs: lb,
2981                rhs: rb,
2982                strong: sb,
2983                inclusive: ib,
2984            },
2985        ) => {
2986            sa == sb
2987                && ia == ib
2988                && sva_exprs_structurally_equivalent(la, lb)
2989                && sva_exprs_structurally_equivalent(ra, rb)
2990        }
2991        // Sprint 3
2992        (SvaExpr::Strong(ia), SvaExpr::Strong(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2993        (SvaExpr::Weak(ia), SvaExpr::Weak(ib)) => sva_exprs_structurally_equivalent(ia, ib),
2994        (SvaExpr::SNexttime(ia, na), SvaExpr::SNexttime(ib, nb)) => {
2995            na == nb && sva_exprs_structurally_equivalent(ia, ib)
2996        }
2997        (
2998            SvaExpr::FollowedBy {
2999                antecedent: aa,
3000                consequent: ca,
3001                overlapping: oa,
3002            },
3003            SvaExpr::FollowedBy {
3004                antecedent: ab,
3005                consequent: cb,
3006                overlapping: ob,
3007            },
3008        ) => {
3009            oa == ob
3010                && sva_exprs_structurally_equivalent(aa, ab)
3011                && sva_exprs_structurally_equivalent(ca, cb)
3012        }
3013        (
3014            SvaExpr::PropertyCase {
3015                expression: ea,
3016                items: ia,
3017                default: da,
3018            },
3019            SvaExpr::PropertyCase {
3020                expression: eb,
3021                items: ib,
3022                default: db,
3023            },
3024        ) => {
3025            sva_exprs_structurally_equivalent(ea, eb)
3026                && ia.len() == ib.len()
3027                && ia.iter().zip(ib.iter()).all(|((va, pa), (vb, pb))| {
3028                    va.len() == vb.len()
3029                        && va
3030                            .iter()
3031                            .zip(vb.iter())
3032                            .all(|(a, b)| sva_exprs_structurally_equivalent(a, b))
3033                        && sva_exprs_structurally_equivalent(pa, pb)
3034                })
3035                && match (da, db) {
3036                    (Some(a), Some(b)) => sva_exprs_structurally_equivalent(a, b),
3037                    (None, None) => true,
3038                    _ => false,
3039                }
3040        }
3041        (
3042            SvaExpr::SyncAcceptOn {
3043                condition: ca,
3044                body: ba,
3045            },
3046            SvaExpr::SyncAcceptOn {
3047                condition: cb,
3048                body: bb,
3049            },
3050        ) => sva_exprs_structurally_equivalent(ca, cb) && sva_exprs_structurally_equivalent(ba, bb),
3051        (
3052            SvaExpr::SyncRejectOn {
3053                condition: ca,
3054                body: ba,
3055            },
3056            SvaExpr::SyncRejectOn {
3057                condition: cb,
3058                body: bb,
3059            },
3060        ) => sva_exprs_structurally_equivalent(ca, cb) && sva_exprs_structurally_equivalent(ba, bb),
3061        // Sprint 5
3062        (SvaExpr::SequenceAnd(la, ra), SvaExpr::SequenceAnd(lb, rb)) => {
3063            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
3064        }
3065        (SvaExpr::SequenceOr(la, ra), SvaExpr::SequenceOr(lb, rb)) => {
3066            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
3067        }
3068        // Sprint 7
3069        (
3070            SvaExpr::ImmediateAssert {
3071                expression: ea,
3072                deferred: da,
3073            },
3074            SvaExpr::ImmediateAssert {
3075                expression: eb,
3076                deferred: db,
3077            },
3078        ) => da == db && sva_exprs_structurally_equivalent(ea, eb),
3079        // Sprint 13
3080        (
3081            SvaExpr::FieldAccess {
3082                signal: sa,
3083                field: fa,
3084            },
3085            SvaExpr::FieldAccess {
3086                signal: sb,
3087                field: fb,
3088            },
3089        ) => fa == fb && sva_exprs_structurally_equivalent(sa, sb),
3090        (
3091            SvaExpr::EnumLiteral {
3092                type_name: ta,
3093                value: va,
3094            },
3095            SvaExpr::EnumLiteral {
3096                type_name: tb,
3097                value: vb,
3098            },
3099        ) => ta == tb && va == vb,
3100        // Sprint 14
3101        (SvaExpr::Triggered(a), SvaExpr::Triggered(b)) => a == b,
3102        (SvaExpr::Matched(a), SvaExpr::Matched(b)) => a == b,
3103        // Sprint 15
3104        (SvaExpr::BitAnd(la, ra), SvaExpr::BitAnd(lb, rb)) => {
3105            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
3106        }
3107        (SvaExpr::BitOr(la, ra), SvaExpr::BitOr(lb, rb)) => {
3108            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
3109        }
3110        (SvaExpr::BitXor(la, ra), SvaExpr::BitXor(lb, rb)) => {
3111            sva_exprs_structurally_equivalent(la, lb) && sva_exprs_structurally_equivalent(ra, rb)
3112        }
3113        (SvaExpr::BitNot(ia), SvaExpr::BitNot(ib)) => sva_exprs_structurally_equivalent(ia, ib),
3114        (SvaExpr::ReductionAnd(ia), SvaExpr::ReductionAnd(ib)) => {
3115            sva_exprs_structurally_equivalent(ia, ib)
3116        }
3117        (SvaExpr::ReductionOr(ia), SvaExpr::ReductionOr(ib)) => {
3118            sva_exprs_structurally_equivalent(ia, ib)
3119        }
3120        (SvaExpr::ReductionXor(ia), SvaExpr::ReductionXor(ib)) => {
3121            sva_exprs_structurally_equivalent(ia, ib)
3122        }
3123        (
3124            SvaExpr::BitSelect {
3125                signal: sa,
3126                index: ia,
3127            },
3128            SvaExpr::BitSelect {
3129                signal: sb,
3130                index: ib,
3131            },
3132        ) => sva_exprs_structurally_equivalent(sa, sb) && sva_exprs_structurally_equivalent(ia, ib),
3133        (
3134            SvaExpr::PartSelect {
3135                signal: sa,
3136                high: ha,
3137                low: la,
3138            },
3139            SvaExpr::PartSelect {
3140                signal: sb,
3141                high: hb,
3142                low: lb,
3143            },
3144        ) => ha == hb && la == lb && sva_exprs_structurally_equivalent(sa, sb),
3145        (SvaExpr::Concat(ia), SvaExpr::Concat(ib)) => {
3146            ia.len() == ib.len()
3147                && ia
3148                    .iter()
3149                    .zip(ib.iter())
3150                    .all(|(a, b)| sva_exprs_structurally_equivalent(a, b))
3151        }
3152        // Sprint 18
3153        (
3154            SvaExpr::SequenceAction {
3155                expression: ea,
3156                assignments: aa,
3157            },
3158            SvaExpr::SequenceAction {
3159                expression: eb,
3160                assignments: ab,
3161            },
3162        ) => {
3163            sva_exprs_structurally_equivalent(ea, eb)
3164                && aa.len() == ab.len()
3165                && aa.iter().zip(ab.iter()).all(|((na, ra), (nb, rb))| {
3166                    na == nb && sva_exprs_structurally_equivalent(ra, rb)
3167                })
3168        }
3169        (SvaExpr::LocalVar(a), SvaExpr::LocalVar(b)) => a == b,
3170        (SvaExpr::ConstCast(ia), SvaExpr::ConstCast(ib)) => {
3171            sva_exprs_structurally_equivalent(ia, ib)
3172        }
3173        (
3174            SvaExpr::Clocked {
3175                clock: ca,
3176                edge: ea,
3177                body: ba,
3178            },
3179            SvaExpr::Clocked {
3180                clock: cb,
3181                edge: eb,
3182                body: bb,
3183            },
3184        ) => ca == cb && ea == eb && sva_exprs_structurally_equivalent(ba, bb),
3185        // Sprint 23 (IEEE 1800-2023)
3186        (
3187            SvaExpr::ArrayMap {
3188                array: aa,
3189                iterator: ia,
3190                with_expr: wa,
3191            },
3192            SvaExpr::ArrayMap {
3193                array: ab,
3194                iterator: ib,
3195                with_expr: wb,
3196            },
3197        ) => {
3198            ia == ib
3199                && sva_exprs_structurally_equivalent(aa, ab)
3200                && sva_exprs_structurally_equivalent(wa, wb)
3201        }
3202        (SvaExpr::TypeThis, SvaExpr::TypeThis) => true,
3203        (SvaExpr::RealConst(a), SvaExpr::RealConst(b)) => a.to_bits() == b.to_bits(),
3204        _ => false,
3205    }
3206}
3207
3208// ═══════════════════════════════════════════════════════════════════════════
3209// Elaboration Pass — Default Clocking & Disable Iff (IEEE 16.15-16)
3210// ═══════════════════════════════════════════════════════════════════════════
3211
3212/// Context for elaborating directives with default clocking and disable iff.
3213/// IEEE 16.15: `default clocking` applies to all assertions in scope that
3214/// lack an explicit clock. IEEE 16.16: `default disable iff` applies the
3215/// reset condition to all assertions lacking explicit `disable iff`.
3216#[derive(Debug, Clone, Default)]
3217pub struct ElaborationContext {
3218    pub default_clocking: Option<String>,
3219    pub default_disable_iff: Option<SvaExpr>,
3220}
3221
3222/// Elaborate a set of directives by applying default clocking and disable iff.
3223///
3224/// IEEE 16.15-16: For each directive:
3225/// - If it lacks an explicit clock and a default clocking exists, apply the default.
3226/// - If it lacks an explicit disable_iff and a default disable_iff exists, wrap
3227///   the property body in `DisableIff { condition, body }`.
3228/// - Explicit annotations override defaults (no clobbering).
3229pub fn elaborate_directives(
3230    directives: &[SvaDirective],
3231    ctx: &ElaborationContext,
3232) -> Vec<SvaDirective> {
3233    directives
3234        .iter()
3235        .map(|d| {
3236            let mut elaborated = d.clone();
3237
3238            // Apply default clock if missing
3239            if elaborated.clock.is_none() {
3240                if let Some(ref default_clk) = ctx.default_clocking {
3241                    elaborated.clock = Some(default_clk.clone());
3242                }
3243            }
3244
3245            // Apply default disable iff if missing
3246            if elaborated.disable_iff.is_none() {
3247                if let Some(ref default_dis) = ctx.default_disable_iff {
3248                    elaborated.disable_iff = Some(default_dis.clone());
3249                }
3250            }
3251
3252            elaborated
3253        })
3254        .collect()
3255}
3256
3257/// Resolve `let` declarations by inlining expression substitution.
3258/// IEEE 11.12: `let` is pure expression substitution with no temporal semantics.
3259pub fn resolve_let_instance(
3260    decls: &[LetDecl],
3261    name: &str,
3262    args: &[SvaExpr],
3263) -> Result<SvaExpr, SvaParseError> {
3264    let decl = decls
3265        .iter()
3266        .find(|d| d.name == name)
3267        .ok_or_else(|| SvaParseError {
3268            message: format!("undeclared let: '{}'", name),
3269        })?;
3270
3271    let required_count = decl.ports.iter().filter(|p| p.default.is_none()).count();
3272    if args.len() < required_count || args.len() > decl.ports.len() {
3273        return Err(SvaParseError {
3274            message: format!(
3275                "let '{}' expects {} to {} arguments, got {}",
3276                name,
3277                required_count,
3278                decl.ports.len(),
3279                args.len()
3280            ),
3281        });
3282    }
3283
3284    let mut result = decl.body.clone();
3285    for (i, port) in decl.ports.iter().enumerate() {
3286        let actual = if i < args.len() {
3287            args[i].clone()
3288        } else {
3289            port.default.clone().ok_or_else(|| SvaParseError {
3290                message: format!(
3291                    "missing required argument '{}' for let '{}'",
3292                    port.name, name
3293                ),
3294            })?
3295        };
3296        result = substitute_signal(&result, &port.name, &actual);
3297    }
3298    Ok(result)
3299}
3300
3301/// Translate dist items into range constraints for formal verification.
3302/// IEEE 16.14.2: In formal mode, `dist` ≡ `inside` (range restriction only).
3303pub fn translate_dist_to_ranges(items: &[DistItem]) -> Vec<(u64, u64)> {
3304    items
3305        .iter()
3306        .map(|item| {
3307            let max = item.max.unwrap_or(item.min);
3308            (item.min, max)
3309        })
3310        .collect()
3311}
3312
3313/// Validate dist list is non-empty.
3314pub fn validate_dist(items: &[DistItem]) -> Result<(), SvaParseError> {
3315    if items.is_empty() {
3316        return Err(SvaParseError {
3317            message: "empty dist list".to_string(),
3318        });
3319    }
3320    Ok(())
3321}
3322
3323/// Resolve a checker instance by binding ports into its assertions.
3324pub fn resolve_checker(
3325    checker: &CheckerDecl,
3326    port_bindings: &[(String, SvaExpr)],
3327) -> Result<Vec<SvaDirective>, SvaParseError> {
3328    checker
3329        .assertions
3330        .iter()
3331        .map(|directive| {
3332            let mut resolved_prop = directive.property.clone();
3333            for (port_name, actual) in port_bindings {
3334                resolved_prop = substitute_signal(&resolved_prop, port_name, actual);
3335            }
3336            Ok(SvaDirective {
3337                kind: directive.kind.clone(),
3338                property: resolved_prop,
3339                label: directive.label.clone(),
3340                clock: directive.clock.clone(),
3341                disable_iff: directive.disable_iff.clone(),
3342                action_pass: directive.action_pass.clone(),
3343                action_fail: directive.action_fail.clone(),
3344            })
3345        })
3346        .collect()
3347}
3348
3349/// Get checker's random variable quantifier structure.
3350/// Returns (const_rand_vars, per_timestep_rand_vars).
3351pub fn checker_quantifier_structure(checker: &CheckerDecl) -> (Vec<&RandVar>, Vec<&RandVar>) {
3352    let const_vars: Vec<&RandVar> = checker.rand_vars.iter().filter(|v| v.is_const).collect();
3353    let nonconst_vars: Vec<&RandVar> = checker.rand_vars.iter().filter(|v| !v.is_const).collect();
3354    (const_vars, nonconst_vars)
3355}