Skip to main content

logicaffeine_compile/codegen_sva/
rtl.rs

1//! RTL / transition-system bounded model checking — including multi-bit (bitvector) registers.
2//!
3//! A [`TransitionSystem`] is the classic `(registers, property)` model of synchronous
4//! hardware: each [`Register`] has a width, an initial value, and a next-state expression
5//! over the CURRENT state; a safety property must hold in every reachable state. 1-bit
6//! registers are control/FSM bits; wider registers are datapath, handled through the
7//! bit-blaster. This module time-indexes the model (`r` → `r@t`), lowers it through the
8//! certified prover seam ([`super::sva_to_proof::bounded_to_proof`]), and drives
9//! [`logicaffeine_proof::bmc`]. Pure Rust, certified, Z3-free.
10//!
11//! [`parse_transition_system`] ingests a synthesizable Verilog subset (multi-bit `reg`,
12//! `initial`, one `always @(posedge clk)` block, `assert property`) with a typed (bool /
13//! bitvector) expression parser. Unsupported constructs error out — never a silent
14//! mis-parse.
15
16use super::sva_to_proof::bounded_to_proof;
17use super::sva_to_verify::{BitVecBoundedOp, BoundedExpr};
18use logicaffeine_proof::bmc::{self, BmcOutcome, InductionOutcome};
19use logicaffeine_proof::sat::{find_model, prove_unsat, ModelOutcome, UnsatOutcome};
20use logicaffeine_proof::ProofExpr;
21use std::collections::HashMap;
22
23/// A next-state function: a direct expression, or a guarded `if/else` (from RTL reset/mux
24/// logic). Guards reference the current state and free inputs.
25#[derive(Debug, Clone)]
26pub enum NextState {
27    Simple(BoundedExpr),
28    Ite {
29        cond: BoundedExpr,
30        then_: Box<NextState>,
31        else_: Box<NextState>,
32    },
33}
34
35/// A hardware register: a width, an optional initial value, and its next-state function.
36#[derive(Debug, Clone)]
37pub struct Register {
38    pub name: String,
39    /// Bit width. `1` is a Boolean control bit; `>1` is a bitvector datapath register.
40    pub width: u32,
41    /// Initial (reset) value, masked to `width`; `None` means a FREE initial state (BMC
42    /// explores all start values — the reset-as-free-input model).
43    pub init: Option<u64>,
44    /// Next-state function over the current (unindexed) state and free inputs.
45    pub next: NextState,
46}
47
48/// A synchronous transition system over Boolean and bitvector registers.
49#[derive(Debug, Clone)]
50pub struct TransitionSystem {
51    pub registers: Vec<Register>,
52    /// The safety property that must hold in every reachable state (unindexed, boolean).
53    pub property: BoundedExpr,
54}
55
56fn mask(width: u32) -> u64 {
57    if width >= 64 {
58        u64::MAX
59    } else {
60        (1u64 << width) - 1
61    }
62}
63
64impl TransitionSystem {
65    /// Bounded model check: is a state violating `property` reachable within `max_k` steps?
66    pub fn bmc(&self, max_k: u32) -> BmcOutcome {
67        if self.lowered_init().is_none()
68            || self.lowered_trans(0).is_none()
69            || self.lowered_property(0).is_none()
70        {
71            return BmcOutcome::Unsupported;
72        }
73        let init = self.lowered_init().unwrap();
74        bmc::find_counterexample(
75            &init,
76            &|t| self.lowered_trans(t).unwrap(),
77            &|t| self.lowered_property(t).unwrap(),
78            max_k,
79        )
80    }
81
82    /// Prove (by k-induction) that `property` holds in EVERY reachable state.
83    pub fn prove_invariant(&self, k: u32) -> InductionOutcome {
84        if self.lowered_init().is_none()
85            || self.lowered_trans(0).is_none()
86            || self.lowered_property(0).is_none()
87        {
88            return InductionOutcome::Unsupported;
89        }
90        let init = self.lowered_init().unwrap();
91        bmc::prove_invariant(
92            &init,
93            &|t| self.lowered_trans(t).unwrap(),
94            &|t| self.lowered_property(t).unwrap(),
95            k,
96        )
97    }
98
99    /// A concrete witnessing execution: a model of `init ∧ trans(0..steps)` with NO property
100    /// negation. For a deterministic controller this is the unique real run from the initial
101    /// state — used to ANIMATE the proven-safe machine, which (by construction) has no
102    /// counterexample to show. Returns the `signal@t` bit assignments of the run, or `None` if
103    /// the obligation leaves the supported fragment.
104    pub fn witness_trace(&self, steps: u32) -> Option<Vec<(String, bool)>> {
105        let mut acc = self.lowered_init()?;
106        for t in 0..steps {
107            let tr = self.lowered_trans(t)?;
108            acc = ProofExpr::And(Box::new(acc), Box::new(tr));
109        }
110        match find_model(&acc) {
111            ModelOutcome::Sat(model) => Some(model),
112            _ => None,
113        }
114    }
115
116    fn lowered_init(&self) -> Option<ProofExpr> {
117        // Only registers with a declared initial value are constrained; the rest are free.
118        let parts: Vec<BoundedExpr> = self
119            .registers
120            .iter()
121            .filter_map(|r| r.init.map(|v| reg_init_eq(&r.name, r.width, v)))
122            .collect();
123        bounded_to_proof(&conj(parts))
124    }
125
126    fn lowered_trans(&self, t: u32) -> Option<ProofExpr> {
127        let parts = self.registers.iter().map(|r| reg_next_eq(r, t)).collect();
128        bounded_to_proof(&conj(parts))
129    }
130
131    fn lowered_property(&self, t: u32) -> Option<ProofExpr> {
132        bounded_to_proof(&time_index(&self.property, t))
133    }
134}
135
136/// `reg@0 = init` as a bounded obligation (boolean equality for 1-bit, `bveq` for wider).
137fn reg_init_eq(name: &str, width: u32, init: u64) -> BoundedExpr {
138    let at0 = format!("{name}@0");
139    if width == 1 {
140        let v = BoundedExpr::Var(at0);
141        if init & 1 == 1 {
142            v
143        } else {
144            BoundedExpr::Not(Box::new(v))
145        }
146    } else {
147        BoundedExpr::BitVecBinary {
148            op: BitVecBoundedOp::Eq,
149            left: Box::new(BoundedExpr::BitVecVar(at0, width)),
150            right: Box::new(BoundedExpr::BitVecConst {
151                width,
152                value: init & mask(width),
153            }),
154        }
155    }
156}
157
158/// `reg@(t+1) = value` as a bounded obligation (boolean equality for 1-bit, `bveq` for wider).
159fn reg_eq_value(name: &str, width: u32, t: u32, rhs: BoundedExpr) -> BoundedExpr {
160    let at_next = format!("{name}@{}", t + 1);
161    if width == 1 {
162        BoundedExpr::Eq(Box::new(BoundedExpr::Var(at_next)), Box::new(rhs))
163    } else {
164        BoundedExpr::BitVecBinary {
165            op: BitVecBoundedOp::Eq,
166            left: Box::new(BoundedExpr::BitVecVar(at_next, width)),
167            right: Box::new(rhs),
168        }
169    }
170}
171
172/// `reg@(t+1) = next(state@t)` as a bounded obligation, expanding guarded updates into
173/// `(cond → reg@(t+1)=then) ∧ (¬cond → reg@(t+1)=else)` (no bitvector-mux node needed).
174fn reg_next_eq(r: &Register, t: u32) -> BoundedExpr {
175    next_constraint(&r.name, r.width, t, &r.next)
176}
177
178fn next_constraint(name: &str, width: u32, t: u32, ns: &NextState) -> BoundedExpr {
179    match ns {
180        NextState::Simple(e) => reg_eq_value(name, width, t, time_index(e, t)),
181        NextState::Ite { cond, then_, else_ } => {
182            let c = time_index(cond, t);
183            BoundedExpr::And(
184                Box::new(BoundedExpr::Implies(
185                    Box::new(c.clone()),
186                    Box::new(next_constraint(name, width, t, then_)),
187                )),
188                Box::new(BoundedExpr::Implies(
189                    Box::new(BoundedExpr::Not(Box::new(c))),
190                    Box::new(next_constraint(name, width, t, else_)),
191                )),
192            )
193        }
194    }
195}
196
197fn conj(mut parts: Vec<BoundedExpr>) -> BoundedExpr {
198    match parts.len() {
199        0 => BoundedExpr::Bool(true),
200        1 => parts.pop().unwrap(),
201        _ => {
202            let mut acc = parts.pop().unwrap();
203            while let Some(p) = parts.pop() {
204                acc = BoundedExpr::And(Box::new(p), Box::new(acc));
205            }
206            acc
207        }
208    }
209}
210
211/// Replace every (unindexed) register reference with its `name@t` form, recursively.
212fn time_index(e: &BoundedExpr, t: u32) -> BoundedExpr {
213    let ri = |x: &BoundedExpr| Box::new(time_index(x, t));
214    match e {
215        BoundedExpr::Var(n) => BoundedExpr::Var(format!("{n}@{t}")),
216        BoundedExpr::BitVecVar(n, w) => BoundedExpr::BitVecVar(format!("{n}@{t}"), *w),
217        BoundedExpr::Bool(_) | BoundedExpr::Int(_) | BoundedExpr::BitVecConst { .. } => e.clone(),
218        BoundedExpr::Not(x) => BoundedExpr::Not(ri(x)),
219        BoundedExpr::And(a, b) => BoundedExpr::And(ri(a), ri(b)),
220        BoundedExpr::Or(a, b) => BoundedExpr::Or(ri(a), ri(b)),
221        BoundedExpr::Implies(a, b) => BoundedExpr::Implies(ri(a), ri(b)),
222        BoundedExpr::Eq(a, b) => BoundedExpr::Eq(ri(a), ri(b)),
223        BoundedExpr::Lt(a, b) => BoundedExpr::Lt(ri(a), ri(b)),
224        BoundedExpr::Gt(a, b) => BoundedExpr::Gt(ri(a), ri(b)),
225        BoundedExpr::Lte(a, b) => BoundedExpr::Lte(ri(a), ri(b)),
226        BoundedExpr::Gte(a, b) => BoundedExpr::Gte(ri(a), ri(b)),
227        BoundedExpr::BitVecBinary { op, left, right } => BoundedExpr::BitVecBinary {
228            op: op.clone(),
229            left: ri(left),
230            right: ri(right),
231        },
232        BoundedExpr::BitVecExtract { high, low, operand } => BoundedExpr::BitVecExtract {
233            high: *high,
234            low: *low,
235            operand: ri(operand),
236        },
237        BoundedExpr::BitVecConcat(a, b) => BoundedExpr::BitVecConcat(ri(a), ri(b)),
238        BoundedExpr::Comparison { op, left, right } => BoundedExpr::Comparison {
239            op: op.clone(),
240            left: ri(left),
241            right: ri(right),
242        },
243        other => other.clone(),
244    }
245}
246
247// ── Verilog → TransitionSystem ──────────────────────────────────────────────────────────
248
249/// A Verilog parse error (kept distinct so the BMC layer can surface it verbatim).
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct RtlParseError {
252    pub message: String,
253}
254
255fn perr<T>(msg: impl Into<String>) -> Result<T, RtlParseError> {
256    Err(RtlParseError {
257        message: msg.into(),
258    })
259}
260
261#[derive(Debug, Clone, PartialEq)]
262enum Tok {
263    Ident(String),
264    /// A numeric literal: value plus optional explicit bit width (`4'd5` → (5, Some(4))).
265    Num(u64, Option<u32>),
266    Sym(String),
267}
268
269fn tokenize(src: &str) -> Result<Vec<Tok>, RtlParseError> {
270    let b = src.as_bytes();
271    let mut toks = Vec::new();
272    let mut i = 0;
273    while i < b.len() {
274        let c = b[i] as char;
275        if c.is_whitespace() {
276            i += 1;
277            continue;
278        }
279        if c == '/' && i + 1 < b.len() && b[i + 1] == b'/' {
280            while i < b.len() && b[i] != b'\n' {
281                i += 1;
282            }
283            continue;
284        }
285        if c == '/' && i + 1 < b.len() && b[i + 1] == b'*' {
286            i += 2;
287            while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {
288                i += 1;
289            }
290            i += 2;
291            continue;
292        }
293        if c.is_ascii_alphabetic() || c == '_' {
294            let start = i;
295            while i < b.len() && ((b[i] as char).is_ascii_alphanumeric() || b[i] == b'_') {
296                i += 1;
297            }
298            toks.push(Tok::Ident(src[start..i].to_string()));
299            continue;
300        }
301        if c.is_ascii_digit() {
302            let start = i;
303            while i < b.len() && (b[i] as char).is_ascii_digit() {
304                i += 1;
305            }
306            let size_digits = &src[start..i];
307            if i < b.len() && b[i] == b'\'' {
308                // Sized literal `<size>'<base><value>`.
309                i += 1;
310                let base = if i < b.len() {
311                    let ch = b[i] as char;
312                    i += 1;
313                    ch.to_ascii_lowercase()
314                } else {
315                    return perr("malformed sized literal");
316                };
317                let vstart = i;
318                while i < b.len() && ((b[i] as char).is_ascii_alphanumeric() || b[i] == b'_') {
319                    i += 1;
320                }
321                let vstr: String = src[vstart..i].chars().filter(|c| *c != '_').collect();
322                let radix = match base {
323                    'b' => 2,
324                    'o' => 8,
325                    'd' => 10,
326                    'h' => 16,
327                    _ => return perr(format!("unsupported literal base '{base}'")),
328                };
329                let value = u64::from_str_radix(&vstr, radix).map_err(|_| RtlParseError {
330                    message: format!("bad literal value '{vstr}'"),
331                })?;
332                let width: u32 = size_digits.parse().map_err(|_| RtlParseError {
333                    message: format!("bad literal size '{size_digits}'"),
334                })?;
335                toks.push(Tok::Num(value, Some(width)));
336            } else {
337                let value: u64 = size_digits.parse().map_err(|_| RtlParseError {
338                    message: format!("bad number '{size_digits}'"),
339                })?;
340                toks.push(Tok::Num(value, None));
341            }
342            continue;
343        }
344        let two = if i + 1 < b.len() { &src[i..i + 2] } else { "" };
345        if matches!(two, "==" | "!=" | "<=" | ">=" | "&&" | "||" | "<<" | ">>") {
346            toks.push(Tok::Sym(two.to_string()));
347            i += 2;
348            continue;
349        }
350        let one = &src[i..i + 1];
351        if "()[]{};:@~&|^=<>!,+-*".contains(one) {
352            toks.push(Tok::Sym(one.to_string()));
353            i += 1;
354            continue;
355        }
356        return perr(format!("unexpected character '{c}'"));
357    }
358    Ok(toks)
359}
360
361/// A typed sub-expression: Boolean, a width-`w` bitvector, or an unsized literal whose width
362/// is determined by context.
363#[derive(Clone)]
364enum Typed {
365    Bool(BoundedExpr),
366    Bv(BoundedExpr, u32),
367    Num(u64),
368}
369
370impl Typed {
371    /// Coerce to a `w`-bit bitvector (or a Boolean when `w == 1`).
372    fn as_width(self, w: u32) -> Result<BoundedExpr, RtlParseError> {
373        match self {
374            Typed::Bv(e, ew) if ew == w => Ok(e),
375            Typed::Bv(_, ew) => perr(format!("width mismatch: expected {w}, got {ew}")),
376            Typed::Num(v) if w == 1 => Ok(BoundedExpr::Bool(v & 1 == 1)),
377            Typed::Num(v) => Ok(BoundedExpr::BitVecConst {
378                width: w,
379                value: v & mask(w),
380            }),
381            Typed::Bool(e) if w == 1 => Ok(e),
382            Typed::Bool(_) => perr(format!("expected a {w}-bit value, got a Boolean")),
383        }
384    }
385    /// Coerce to a Boolean (a wider value is "non-zero").
386    fn as_bool(self) -> Result<BoundedExpr, RtlParseError> {
387        match self {
388            Typed::Bool(e) => Ok(e),
389            Typed::Num(v) => Ok(BoundedExpr::Bool(v != 0)),
390            Typed::Bv(e, w) => Ok(BoundedExpr::Not(Box::new(BoundedExpr::BitVecBinary {
391                op: BitVecBoundedOp::Eq,
392                left: Box::new(e),
393                right: Box::new(BoundedExpr::BitVecConst { width: w, value: 0 }),
394            }))),
395        }
396    }
397    fn width_hint(&self) -> Option<u32> {
398        match self {
399            Typed::Bv(_, w) => Some(*w),
400            Typed::Bool(_) => Some(1),
401            Typed::Num(_) => None,
402        }
403    }
404}
405
406/// Bring two operands to a common bitvector width (at least one must be sized).
407fn bv_pair(a: Typed, b: Typed) -> Result<(BoundedExpr, BoundedExpr, u32), RtlParseError> {
408    let w = a.width_hint().or_else(|| b.width_hint());
409    let w = match w {
410        Some(w) if w >= 1 => w,
411        _ => return perr("ambiguous width: at least one operand must be sized"),
412    };
413    Ok((a.as_width(w)?, b.as_width(w)?, w))
414}
415
416fn bx(e: BoundedExpr) -> Box<BoundedExpr> {
417    Box::new(e)
418}
419
420struct Parser<'a> {
421    t: &'a [Tok],
422    i: usize,
423    widths: HashMap<String, u32>,
424}
425
426impl<'a> Parser<'a> {
427    fn peek(&self) -> Option<&Tok> {
428        self.t.get(self.i)
429    }
430    fn is_sym(&self, s: &str) -> bool {
431        matches!(self.peek(), Some(Tok::Sym(x)) if x == s)
432    }
433    fn is_kw(&self, k: &str) -> bool {
434        matches!(self.peek(), Some(Tok::Ident(x)) if x == k)
435    }
436    fn eat_sym(&mut self, s: &str) -> Result<(), RtlParseError> {
437        if self.is_sym(s) {
438            self.i += 1;
439            Ok(())
440        } else {
441            perr(format!("expected '{s}', found {:?}", self.peek()))
442        }
443    }
444    fn eat_kw(&mut self, k: &str) -> Result<(), RtlParseError> {
445        if self.is_kw(k) {
446            self.i += 1;
447            Ok(())
448        } else {
449            perr(format!("expected '{k}', found {:?}", self.peek()))
450        }
451    }
452    fn ident(&mut self) -> Result<String, RtlParseError> {
453        match self.peek() {
454            Some(Tok::Ident(n)) => {
455                let n = n.clone();
456                self.i += 1;
457                Ok(n)
458            }
459            other => perr(format!("expected identifier, found {other:?}")),
460        }
461    }
462    fn num(&mut self) -> Result<u64, RtlParseError> {
463        match self.peek() {
464            Some(Tok::Num(v, _)) => {
465                let v = *v;
466                self.i += 1;
467                Ok(v)
468            }
469            other => perr(format!("expected a number, found {other:?}")),
470        }
471    }
472
473    // Typed expression grammar (Verilog precedence, low→high):
474    // || , && , | , ^ , & , ==/!= , </<=/>/>= , +/- , * , unary ~/! , primary.
475    fn expr(&mut self) -> Result<Typed, RtlParseError> {
476        self.p_lor()
477    }
478    fn p_lor(&mut self) -> Result<Typed, RtlParseError> {
479        let mut a = self.p_land()?;
480        while self.is_sym("||") {
481            self.i += 1;
482            let b = self.p_land()?;
483            a = Typed::Bool(BoundedExpr::Or(bx(a.as_bool()?), bx(b.as_bool()?)));
484        }
485        Ok(a)
486    }
487    fn p_land(&mut self) -> Result<Typed, RtlParseError> {
488        let mut a = self.p_bor()?;
489        while self.is_sym("&&") {
490            self.i += 1;
491            let b = self.p_bor()?;
492            a = Typed::Bool(BoundedExpr::And(bx(a.as_bool()?), bx(b.as_bool()?)));
493        }
494        Ok(a)
495    }
496    fn p_bor(&mut self) -> Result<Typed, RtlParseError> {
497        let mut a = self.p_bxor()?;
498        while self.is_sym("|") {
499            self.i += 1;
500            let b = self.p_bxor()?;
501            a = self.bitwise(
502                a,
503                b,
504                |x, y| BoundedExpr::Or(bx(x), bx(y)),
505                BitVecBoundedOp::Or,
506            )?;
507        }
508        Ok(a)
509    }
510    fn p_bxor(&mut self) -> Result<Typed, RtlParseError> {
511        let mut a = self.p_band()?;
512        while self.is_sym("^") {
513            self.i += 1;
514            let b = self.p_band()?;
515            a = self.bitwise(
516                a,
517                b,
518                |x, y| BoundedExpr::Not(bx(BoundedExpr::Eq(bx(x), bx(y)))),
519                BitVecBoundedOp::Xor,
520            )?;
521        }
522        Ok(a)
523    }
524    fn p_band(&mut self) -> Result<Typed, RtlParseError> {
525        let mut a = self.p_eq()?;
526        while self.is_sym("&") {
527            self.i += 1;
528            let b = self.p_eq()?;
529            a = self.bitwise(
530                a,
531                b,
532                |x, y| BoundedExpr::And(bx(x), bx(y)),
533                BitVecBoundedOp::And,
534            )?;
535        }
536        Ok(a)
537    }
538    fn p_eq(&mut self) -> Result<Typed, RtlParseError> {
539        let mut a = self.p_rel()?;
540        while self.is_sym("==") || self.is_sym("!=") {
541            let neq = self.is_sym("!=");
542            self.i += 1;
543            let b = self.p_rel()?;
544            let eq = self.equality(a, b)?;
545            a = Typed::Bool(if neq { BoundedExpr::Not(bx(eq)) } else { eq });
546        }
547        Ok(a)
548    }
549    fn p_rel(&mut self) -> Result<Typed, RtlParseError> {
550        let mut a = self.p_add()?;
551        while self.is_sym("<") || self.is_sym(">") || self.is_sym("<=") || self.is_sym(">=") {
552            let op = match self.peek() {
553                Some(Tok::Sym(s)) => s.clone(),
554                _ => unreachable!(),
555            };
556            self.i += 1;
557            let b = self.p_add()?;
558            let (l, r, _w) = bv_pair(a, b)?;
559            // Unsigned magnitude comparisons via the bit-blaster's ULt.
560            let ult = |x: BoundedExpr, y: BoundedExpr| BoundedExpr::BitVecBinary {
561                op: BitVecBoundedOp::ULt,
562                left: bx(x),
563                right: bx(y),
564            };
565            let res = match op.as_str() {
566                "<" => ult(l, r),
567                ">" => ult(r, l),
568                "<=" => BoundedExpr::Not(bx(ult(r, l))),
569                ">=" => BoundedExpr::Not(bx(ult(l, r))),
570                _ => unreachable!(),
571            };
572            a = Typed::Bool(res);
573        }
574        Ok(a)
575    }
576    fn p_add(&mut self) -> Result<Typed, RtlParseError> {
577        let mut a = self.p_mul()?;
578        while self.is_sym("+") || self.is_sym("-") {
579            let sub = self.is_sym("-");
580            self.i += 1;
581            let b = self.p_mul()?;
582            let (l, r, w) = bv_pair(a, b)?;
583            a = Typed::Bv(
584                BoundedExpr::BitVecBinary {
585                    op: if sub {
586                        BitVecBoundedOp::Sub
587                    } else {
588                        BitVecBoundedOp::Add
589                    },
590                    left: bx(l),
591                    right: bx(r),
592                },
593                w,
594            );
595        }
596        Ok(a)
597    }
598    fn p_mul(&mut self) -> Result<Typed, RtlParseError> {
599        let mut a = self.p_unary()?;
600        while self.is_sym("*") {
601            self.i += 1;
602            let b = self.p_unary()?;
603            let (l, r, w) = bv_pair(a, b)?;
604            a = Typed::Bv(
605                BoundedExpr::BitVecBinary {
606                    op: BitVecBoundedOp::Mul,
607                    left: bx(l),
608                    right: bx(r),
609                },
610                w,
611            );
612        }
613        Ok(a)
614    }
615    fn p_unary(&mut self) -> Result<Typed, RtlParseError> {
616        if self.is_sym("!") {
617            self.i += 1;
618            return Ok(Typed::Bool(BoundedExpr::Not(bx(self
619                .p_unary()?
620                .as_bool()?))));
621        }
622        if self.is_sym("~") {
623            self.i += 1;
624            let inner = self.p_unary()?;
625            return Ok(match inner {
626                Typed::Bool(e) => Typed::Bool(BoundedExpr::Not(bx(e))),
627                Typed::Bv(e, w) => Typed::Bv(
628                    BoundedExpr::BitVecBinary {
629                        op: BitVecBoundedOp::Not,
630                        left: bx(e.clone()),
631                        right: bx(e),
632                    },
633                    w,
634                ),
635                Typed::Num(_) => return perr("'~' needs a sized operand"),
636            });
637        }
638        self.p_primary()
639    }
640    fn p_primary(&mut self) -> Result<Typed, RtlParseError> {
641        if self.is_sym("(") {
642            self.i += 1;
643            let e = self.expr()?;
644            self.eat_sym(")")?;
645            return Ok(e);
646        }
647        match self.peek() {
648            Some(Tok::Num(v, w)) => {
649                let (v, w) = (*v, *w);
650                self.i += 1;
651                Ok(match w {
652                    None => Typed::Num(v),
653                    Some(1) => Typed::Bool(BoundedExpr::Bool(v & 1 == 1)),
654                    Some(w) => Typed::Bv(
655                        BoundedExpr::BitVecConst {
656                            width: w,
657                            value: v & mask(w),
658                        },
659                        w,
660                    ),
661                })
662            }
663            Some(Tok::Ident(n)) => {
664                let n = n.clone();
665                self.i += 1;
666                match self.widths.get(&n).copied() {
667                    Some(1) | None => Ok(Typed::Bool(BoundedExpr::Var(n))),
668                    Some(w) => Ok(Typed::Bv(BoundedExpr::BitVecVar(n, w), w)),
669                }
670            }
671            other => perr(format!("expected an expression, found {other:?}")),
672        }
673    }
674
675    /// Bitwise `&`/`|`/`^`: Boolean on Boolean operands, bit-blasted on bitvectors.
676    fn bitwise(
677        &self,
678        a: Typed,
679        b: Typed,
680        bool_op: fn(BoundedExpr, BoundedExpr) -> BoundedExpr,
681        bv_op: BitVecBoundedOp,
682    ) -> Result<Typed, RtlParseError> {
683        match (&a, &b) {
684            (Typed::Bv(..), _) | (_, Typed::Bv(..)) => {
685                let (l, r, w) = bv_pair(a, b)?;
686                Ok(Typed::Bv(
687                    BoundedExpr::BitVecBinary {
688                        op: bv_op,
689                        left: bx(l),
690                        right: bx(r),
691                    },
692                    w,
693                ))
694            }
695            _ => Ok(Typed::Bool(bool_op(a.as_bool()?, b.as_bool()?))),
696        }
697    }
698
699    /// `==` (the `!=` caller negates): biconditional on Booleans, `bveq` on bitvectors.
700    fn equality(&self, a: Typed, b: Typed) -> Result<BoundedExpr, RtlParseError> {
701        match (&a, &b) {
702            (Typed::Bv(..), _) | (_, Typed::Bv(..)) => {
703                let (l, r, _w) = bv_pair(a, b)?;
704                Ok(BoundedExpr::BitVecBinary {
705                    op: BitVecBoundedOp::Eq,
706                    left: bx(l),
707                    right: bx(r),
708                })
709            }
710            _ => Ok(BoundedExpr::Eq(bx(a.as_bool()?), bx(b.as_bool()?))),
711        }
712    }
713
714    fn skip_to_semi(&mut self) -> Result<(), RtlParseError> {
715        while !self.is_sym(";") {
716            if self.peek().is_none() {
717                return perr("expected ';' before end of input");
718            }
719            self.i += 1;
720        }
721        self.i += 1;
722        Ok(())
723    }
724    fn skip_balanced_parens(&mut self) -> Result<(), RtlParseError> {
725        self.eat_sym("(")?;
726        let mut depth = 1;
727        while depth > 0 {
728            match self.peek() {
729                None => return perr("unbalanced '(' in port list"),
730                Some(Tok::Sym(s)) if s == "(" => depth += 1,
731                Some(Tok::Sym(s)) if s == ")" => depth -= 1,
732                _ => {}
733            }
734            self.i += 1;
735        }
736        Ok(())
737    }
738
739    /// Parse `[hi:lo]` and return the width `hi - lo + 1`.
740    fn parse_range_width(&mut self) -> Result<u32, RtlParseError> {
741        self.eat_sym("[")?;
742        let hi = self.num()? as i64;
743        self.eat_sym(":")?;
744        let lo = self.num()? as i64;
745        self.eat_sym("]")?;
746        if hi < lo {
747            return perr("register range must be [hi:lo] with hi >= lo");
748        }
749        Ok((hi - lo + 1) as u32)
750    }
751
752    /// Parse an `always` body into per-register next-state functions, honoring `if/else`
753    /// (a register unassigned in a branch holds its prior value).
754    fn parse_block(&mut self) -> Result<HashMap<String, NextState>, RtlParseError> {
755        let mut map = HashMap::new();
756        if self.is_kw("begin") {
757            self.i += 1;
758            while !self.is_kw("end") {
759                if self.peek().is_none() {
760                    return perr("missing 'end' in always block");
761                }
762                self.parse_stmt(&mut map)?;
763            }
764            self.i += 1;
765        } else {
766            self.parse_stmt(&mut map)?;
767        }
768        Ok(map)
769    }
770
771    fn parse_stmt(&mut self, map: &mut HashMap<String, NextState>) -> Result<(), RtlParseError> {
772        if self.is_kw("if") {
773            self.i += 1;
774            self.eat_sym("(")?;
775            let cond = self.expr()?.as_bool()?;
776            self.eat_sym(")")?;
777            let then_map = self.parse_block()?;
778            let else_map = if self.is_kw("else") {
779                self.i += 1;
780                self.parse_block()?
781            } else {
782                HashMap::new()
783            };
784            let mut names: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
785            names.extend(then_map.keys().cloned());
786            names.extend(else_map.keys().cloned());
787            for n in names {
788                let w = self.widths.get(&n).copied().unwrap_or(1);
789                let hold = if w == 1 {
790                    NextState::Simple(BoundedExpr::Var(n.clone()))
791                } else {
792                    NextState::Simple(BoundedExpr::BitVecVar(n.clone(), w))
793                };
794                let prior = map.get(&n).cloned().unwrap_or(hold);
795                let then_ns = then_map.get(&n).cloned().unwrap_or_else(|| prior.clone());
796                let else_ns = else_map.get(&n).cloned().unwrap_or(prior);
797                map.insert(
798                    n,
799                    NextState::Ite {
800                        cond: cond.clone(),
801                        then_: Box::new(then_ns),
802                        else_: Box::new(else_ns),
803                    },
804                );
805            }
806            Ok(())
807        } else {
808            let n = self.ident()?;
809            let w = self.widths.get(&n).copied().unwrap_or(1);
810            if self.is_sym("<=") {
811                self.i += 1;
812            } else {
813                self.eat_sym("=")?;
814            }
815            let e = self.expr()?.as_width(w)?;
816            self.eat_sym(";")?;
817            map.insert(n, NextState::Simple(e));
818            Ok(())
819        }
820    }
821}
822
823/// Parse a synthesizable Verilog module into a [`TransitionSystem`]. Errors (never silently
824/// mis-parses) on anything outside the supported subset.
825pub fn parse_transition_system(src: &str) -> Result<TransitionSystem, RtlParseError> {
826    let toks = tokenize(src)?;
827    // First pass: collect register widths so the expression parser is correctly typed.
828    // First pass: collect the width of every declared signal (reg/input/output/wire,
829    // wherever declared — including the port list) so the expression parser is correctly
830    // typed. Inputs are free variables; only `reg`s become registers (second pass).
831    let is_decl_kw = |s: &str| matches!(s, "reg" | "input" | "output" | "wire");
832    let mut widths: HashMap<String, u32> = HashMap::new();
833    {
834        let mut j = 0;
835        while j < toks.len() {
836            if matches!(&toks[j], Tok::Ident(k) if is_decl_kw(k)) {
837                j += 1;
838                let mut w = 1u32;
839                if matches!(toks.get(j), Some(Tok::Sym(s)) if s == "[") {
840                    let mut tmp = Parser {
841                        t: &toks,
842                        i: j,
843                        widths: HashMap::new(),
844                    };
845                    w = tmp.parse_range_width()?;
846                    j = tmp.i;
847                }
848                // Comma-separated names — but stop at the next declaration keyword (port
849                // lists read `input clk, input rst`, not `input clk, rst`).
850                loop {
851                    match toks.get(j) {
852                        Some(Tok::Ident(n)) if !is_decl_kw(n) => {
853                            widths.insert(n.clone(), w);
854                            j += 1;
855                        }
856                        _ => break,
857                    }
858                    if matches!(toks.get(j), Some(Tok::Sym(s)) if s == ",") {
859                        j += 1;
860                        continue;
861                    }
862                    break;
863                }
864            } else {
865                j += 1;
866            }
867        }
868    }
869
870    let mut p = Parser {
871        t: &toks,
872        i: 0,
873        widths,
874    };
875    p.eat_kw("module")?;
876    let _name = p.ident()?;
877    if p.is_sym("(") {
878        p.skip_balanced_parens()?;
879    }
880    p.eat_sym(";")?;
881
882    let mut order: Vec<String> = Vec::new();
883    let mut init: HashMap<String, u64> = HashMap::new();
884    let mut next: HashMap<String, NextState> = HashMap::new();
885    let mut property: Option<BoundedExpr> = None;
886
887    loop {
888        match p.peek() {
889            None => return perr("unexpected end of input (missing 'endmodule')"),
890            Some(Tok::Ident(k)) if k == "endmodule" => {
891                p.i += 1;
892                break;
893            }
894            Some(Tok::Ident(k)) if k == "reg" => {
895                p.i += 1;
896                if p.is_sym("[") {
897                    let _ = p.parse_range_width()?;
898                }
899                loop {
900                    let n = p.ident()?;
901                    if !order.contains(&n) {
902                        order.push(n);
903                    }
904                    if p.is_sym(",") {
905                        p.i += 1;
906                        continue;
907                    }
908                    break;
909                }
910                p.eat_sym(";")?;
911            }
912            Some(Tok::Ident(k)) if k == "input" || k == "output" || k == "wire" => {
913                p.skip_to_semi()?;
914            }
915            Some(Tok::Ident(k)) if k == "initial" => {
916                p.i += 1;
917                let mut one = |p: &mut Parser| -> Result<(), RtlParseError> {
918                    let n = p.ident()?;
919                    p.eat_sym("=")?;
920                    let v = p.num()?;
921                    p.eat_sym(";")?;
922                    init.insert(n, v);
923                    Ok(())
924                };
925                if p.is_kw("begin") {
926                    p.i += 1;
927                    while !p.is_kw("end") {
928                        if p.peek().is_none() {
929                            return perr("missing 'end' for initial block");
930                        }
931                        one(&mut p)?;
932                    }
933                    p.i += 1;
934                } else {
935                    one(&mut p)?;
936                }
937            }
938            Some(Tok::Ident(k)) if k == "always" => {
939                p.i += 1;
940                p.eat_sym("@")?;
941                p.eat_sym("(")?;
942                p.eat_kw("posedge")?;
943                let _clk = p.ident()?;
944                p.eat_sym(")")?;
945                let block = p.parse_block()?;
946                for (n, ns) in block {
947                    next.insert(n, ns);
948                }
949            }
950            Some(Tok::Ident(k)) if k == "assert" => {
951                p.i += 1;
952                p.eat_kw("property")?;
953                p.eat_sym("(")?;
954                if p.is_sym("@") {
955                    p.i += 1;
956                    p.eat_sym("(")?;
957                    p.eat_kw("posedge")?;
958                    let _ = p.ident()?;
959                    p.eat_sym(")")?;
960                }
961                let e = p.expr()?.as_bool()?;
962                p.eat_sym(")")?;
963                p.eat_sym(";")?;
964                property = Some(e);
965            }
966            Some(_) => p.skip_to_semi()?,
967        }
968    }
969
970    if order.is_empty() {
971        return perr("no registers found");
972    }
973    let property = match property {
974        Some(p) => p,
975        None => return perr("no 'assert property' found"),
976    };
977
978    let mut registers = Vec::with_capacity(order.len());
979    for name in &order {
980        let width = p.widths.get(name).copied().unwrap_or(1);
981        // `initial` is optional: absent ⇒ a free initial state (reset-as-free-input).
982        let init_val = init.get(name).map(|v| *v & mask(width));
983        let next_ns = next.remove(name).unwrap_or_else(|| {
984            // A register with no update holds its value.
985            if width == 1 {
986                NextState::Simple(BoundedExpr::Var(name.clone()))
987            } else {
988                NextState::Simple(BoundedExpr::BitVecVar(name.clone(), width))
989            }
990        });
991        registers.push(Register {
992            name: name.clone(),
993            width,
994            init: init_val,
995            next: next_ns,
996        });
997    }
998
999    Ok(TransitionSystem {
1000        registers,
1001        property,
1002    })
1003}
1004
1005/// Emit a synthesizable Verilog SOFT-CORE for the reversible ALU datapath (corner 5, phase 3) — the
1006/// register-VM's `RevAdd` charge-recovery core as RTL: a `width`-bit register advanced by `step` each
1007/// clock. `q := (q + step) mod 2^width` is a PERMUTATION of the state space (a cyclic reversible
1008/// datapath whose reverse module is the `−step` decrement), and the emitted text is real synthesizable
1009/// Verilog — [`parse_transition_system`] accepts it and BMC / k-induction discharge its obligations.
1010/// This is the round-tripping HDL twin of the software `RevAdd`; the full VM-datapath soft-core + a
1011/// VM↔RTL SMT equivalence are the larger MAKE_A_CHIP build this slice opens.
1012pub fn emit_reversible_alu_verilog(width: u32, step: u64) -> String {
1013    let hi = width - 1;
1014    let max = if width >= 64 {
1015        u64::MAX
1016    } else {
1017        (1u64 << width) - 1
1018    };
1019    format!(
1020        "module rev_alu(input clk);\n  reg [{hi}:0] q;\n  initial q = 0;\n  always @(posedge clk) q <= q + {width}'d{step};\n  assert property (q <= {width}'d{max});\nendmodule"
1021    )
1022}
1023
1024/// Emit the reversible `RevAdd` DATAPATH as synthesizable Verilog — a `width`-bit accumulator advanced
1025/// by a data INPUT each clock (`q := (q + delta) mod 2^width`), the genuine charge-recovery ALU slice
1026/// (its reverse is `q := q − delta`). For every fixed `delta` the clocked transition is a bijection in
1027/// `q`. Unlike the constant-step [`emit_reversible_alu_verilog`], this is the real datapath the VM's
1028/// `RevAdd` maps to; `benchmarks/silicon/` synthesizes + place-and-routes the 32-bit form on an ECP5 FPGA.
1029pub fn emit_reversible_datapath_verilog(width: u32) -> String {
1030    let hi = width - 1;
1031    format!(
1032        "module rev_alu(input clk, input [{hi}:0] delta, output reg [{hi}:0] q);\n  initial q = 0;\n  always @(posedge clk) q <= q + delta;\n  assert property (q == q);\nendmodule"
1033    )
1034}
1035
1036/// Emit the LOGOS reversible ALU CORE as synthesizable Verilog — the abelian charge-recovery datapath
1037/// of the VM: two `width`-bit registers `a`,`b` and a 3-bit opcode selecting `RevAdd`/`RevSub`/`RevXor`/
1038/// `RevNeg`/`RevSwap`. For every fixed opcode the transition on `(a,b)` is a BIJECTION, so the whole ALU
1039/// runs backward with zero erased bits. The 32-bit form place-and-routes on a Lattice ECP5 (ULX3S) via
1040/// `scripts/synth-soft-core.sh` (`benchmarks/silicon/rev_alu_core.v`): 336 LUTs + 64 FFs at ~136 MHz.
1041pub fn emit_reversible_alu_core_verilog(width: u32) -> String {
1042    let hi = width - 1;
1043    format!(
1044        "module rev_alu_core(input clk, input [2:0] op, output reg [{hi}:0] a, output reg [{hi}:0] b);\n\
1045         \x20 initial begin a = 0; b = 0; end\n\
1046         \x20 always @(posedge clk) begin\n\
1047         \x20   case (op)\n\
1048         \x20     3'd0: a <= a + b;\n\
1049         \x20     3'd1: a <= a - b;\n\
1050         \x20     3'd2: a <= a ^ b;\n\
1051         \x20     3'd3: a <= (~a) + {width}'d1;\n\
1052         \x20     3'd4: begin a <= b; b <= a; end\n\
1053         \x20     default: ;\n\
1054         \x20   endcase\n\
1055         \x20 end\n\
1056         endmodule"
1057    )
1058}
1059
1060/// Emit the ISA **opcode decoder** for the reversible core — the silicon FRONT-END that turns a wire
1061/// opcode BYTE (the exact byte [`crate::vm::binisa::encode_program`] puts on the wire) into the
1062/// reversible ALU's 3-bit control select plus a `core` valid flag. The `case` labels are DERIVED from
1063/// [`crate::vm::binisa::opcode`], so the decoder and the wire format share ONE source of truth: the
1064/// byte the network carries is the byte the chip decodes, with no translation layer. Compose with
1065/// [`emit_reversible_alu_core_verilog`] — wire `isa_core_decoder.sel → rev_alu_core.op`.
1066pub fn emit_isa_core_decoder_verilog() -> String {
1067    use crate::vm::binisa::opcode;
1068    use crate::vm::Op;
1069    let core = [
1070        (Op::RevAdd { place: 0, delta: 0 }, "RevAdd"),
1071        (Op::RevSub { place: 0, delta: 0 }, "RevSub"),
1072        (Op::RevXor { place: 0, delta: 0 }, "RevXor"),
1073        (Op::RevNeg { place: 0 }, "RevNeg"),
1074        (Op::RevSwap { a: 0, b: 0 }, "RevSwap"),
1075    ];
1076    let mut arms = String::new();
1077    for (op, name) in &core {
1078        let code = opcode(op);
1079        arms.push_str(&format!(
1080            "\x20     8'd{code}: begin sel = 3'd{code}; core = 1'b1; end  // {name}\n"
1081        ));
1082    }
1083    // An UNRECOGNISED wire byte decodes to an ALU-identity select (`3'd7` hits the ALU's `default: ;`)
1084    // and asserts `core = 0`: an illegal opcode is an inert no-op on the reversible state, never a
1085    // silent RevAdd. Correct ISA hygiene — a corrupt byte cannot perturb the datapath.
1086    format!(
1087        "module isa_core_decoder(input [7:0] opcode, output reg [2:0] sel, output reg core);\n\
1088         \x20 always @(*) begin\n\
1089         \x20   case (opcode)\n\
1090         {arms}\
1091         \x20     default: begin sel = 3'd7; core = 1'b0; end\n\
1092         \x20   endcase\n\
1093         \x20 end\n\
1094         endmodule"
1095    )
1096}
1097
1098/// Emit the GENERAL INTEGER ALU datapath — the combinational functional unit that executes the
1099/// arithmetic / bitwise / signed-comparison ops straight off a WIRE OPCODE BYTE. The `case` labels are
1100/// the stable `binisa` opcodes (one source of truth with the wire format), so the ALU decodes the same
1101/// bytes the network carries. Each operation is proven correct by our own certified SAT (the identity
1102/// battery `the_general_alu_datapath_is_proven_correct_by_our_sat`); comparisons are SIGNED (matching
1103/// the VM's i64 semantics) and yield 0/1. This is the ratchet frontier grown from the reversible core.
1104pub fn emit_alu_datapath_verilog(width: u32) -> String {
1105    use crate::vm::binisa::opcode;
1106    use crate::vm::Op;
1107    let hi = width - 1;
1108    let add = opcode(&Op::Add {
1109        dst: 0,
1110        lhs: 0,
1111        rhs: 0,
1112    });
1113    let addassign = opcode(&Op::AddAssign { dst: 0, src: 0 });
1114    let sub = opcode(&Op::Sub {
1115        dst: 0,
1116        lhs: 0,
1117        rhs: 0,
1118    });
1119    let mul = opcode(&Op::Mul {
1120        dst: 0,
1121        lhs: 0,
1122        rhs: 0,
1123    });
1124    // Div / ExactDiv / Mod / FloorDiv are NOT in the combinational ALU: division is inherently
1125    // sequential, so the soft-core issues those opcodes to the shared iterative `shared_divider`
1126    // (a ~26x LUT saving). DivPow2 stays here — it is a cheap round-toward-zero arithmetic shift.
1127    let divpow2 = opcode(&Op::DivPow2 {
1128        dst: 0,
1129        lhs: 0,
1130        k: 0,
1131    });
1132    let xor = opcode(&Op::BitXor {
1133        dst: 0,
1134        lhs: 0,
1135        rhs: 0,
1136    });
1137    let and = opcode(&Op::BitAnd {
1138        dst: 0,
1139        lhs: 0,
1140        rhs: 0,
1141    });
1142    let or = opcode(&Op::BitOr {
1143        dst: 0,
1144        lhs: 0,
1145        rhs: 0,
1146    });
1147    let not = opcode(&Op::Not { dst: 0, src: 0 });
1148    let shl = opcode(&Op::Shl {
1149        dst: 0,
1150        lhs: 0,
1151        rhs: 0,
1152    });
1153    let shr = opcode(&Op::Shr {
1154        dst: 0,
1155        lhs: 0,
1156        rhs: 0,
1157    });
1158    // The shift COUNT is masked to the value width (`b[log2(W)-1:0]`), matching the VM's
1159    // `wrapping_shl/shr(b as u32)` which masks the count mod the word width. `Shr` is ARITHMETIC.
1160    let cnt_hi = width.trailing_zeros().saturating_sub(1);
1161    let lt = opcode(&Op::Lt {
1162        dst: 0,
1163        lhs: 0,
1164        rhs: 0,
1165    });
1166    let gt = opcode(&Op::Gt {
1167        dst: 0,
1168        lhs: 0,
1169        rhs: 0,
1170    });
1171    let lte = opcode(&Op::LtEq {
1172        dst: 0,
1173        lhs: 0,
1174        rhs: 0,
1175    });
1176    let gte = opcode(&Op::GtEq {
1177        dst: 0,
1178        lhs: 0,
1179        rhs: 0,
1180    });
1181    let eq = opcode(&Op::Eq {
1182        dst: 0,
1183        lhs: 0,
1184        rhs: 0,
1185    });
1186    let neq = opcode(&Op::NotEq {
1187        dst: 0,
1188        lhs: 0,
1189        rhs: 0,
1190    });
1191    format!(
1192        "module alu(input [7:0] opcode, input [{hi}:0] a, input [{hi}:0] b, output reg [{hi}:0] y);\n\
1193         \x20 always @(*) begin\n\
1194         \x20   case (opcode)\n\
1195         \x20     8'd{add}: y = a + b;\n\
1196         \x20     8'd{addassign}: y = a + b;\n\
1197         \x20     8'd{sub}: y = a - b;\n\
1198         \x20     8'd{mul}: y = a * b;\n\
1199         \x20     8'd{divpow2}: y = a[{hi}] ? ($signed($signed(a) + (({width}'d1 << b[{cnt_hi}:0]) - {width}'d1)) >>> b[{cnt_hi}:0]) : ($signed(a) >>> b[{cnt_hi}:0]);\n\
1200         \x20     8'd{xor}: y = a ^ b;\n\
1201         \x20     8'd{and}: y = a & b;\n\
1202         \x20     8'd{or}: y = a | b;\n\
1203         \x20     8'd{not}: y = ~a;\n\
1204         \x20     8'd{shl}: y = a << b[{cnt_hi}:0];\n\
1205         \x20     8'd{shr}: y = $signed(a) >>> b[{cnt_hi}:0];\n\
1206         \x20     8'd{lt}: y = ($signed(a) < $signed(b)) ? 1 : 0;\n\
1207         \x20     8'd{gt}: y = ($signed(a) > $signed(b)) ? 1 : 0;\n\
1208         \x20     8'd{lte}: y = ($signed(a) <= $signed(b)) ? 1 : 0;\n\
1209         \x20     8'd{gte}: y = ($signed(a) >= $signed(b)) ? 1 : 0;\n\
1210         \x20     8'd{eq}: y = (a == b) ? 1 : 0;\n\
1211         \x20     8'd{neq}: y = (a != b) ? 1 : 0;\n\
1212         \x20     8'd226: y = a + b;\n\
1213         \x20     8'd227: y = a - b;\n\
1214         \x20     8'd228: y = a * b;\n\
1215         \x20     default: y = {width}'d0;\n\
1216         \x20   endcase\n\
1217         \x20 end\n\
1218         endmodule"
1219    )
1220}
1221
1222/// Emit the SHARED ITERATIVE DIVIDER — one sequential restoring divider that computes signed
1223/// quotient AND remainder, replacing the ~24,600-cell COMBINATIONAL `$signed(a)/$signed(b)` +
1224/// `$signed(a)%$signed(b)` the ALU instantiates per-op (Div/Mod/FloorDiv). It costs 833 LUT / 204 FF
1225/// placed-and-routed on the ECP5-85K at ~100 MHz — a ~26× LUT drop vs the ~22,000-LUT combinational
1226/// divide, the lever that fits the full 113-op CPU under 83,640. Truncated (round-toward-zero)
1227/// semantics matching the VM: quotient sign = sign(a)^sign(b), remainder sign = sign(a); b==0 →
1228/// q=r=0. One 1-bit/cycle restoring loop over |a|/|b| (W cycles) then a sign fixup; the soft-core
1229/// pulses `start` and stalls until `done`. The module is Verilog-parameterized (default W=32;
1230/// instantiate #(.W(64)) for the BigInt lane), so this emitter is the single source for the on-disk
1231/// `shared_divider.v`, proven == the combinational oracle by iverilog ([`emit_shared_divider_testbench`]).
1232pub fn emit_shared_divider_verilog() -> String {
1233    include_str!("shared_divider.v").to_string()
1234}
1235
1236/// Emit the divider's self-checking testbench: drive the sequential `shared_divider`, wait for
1237/// `done`, and check quotient+remainder against the combinational `$signed` div/mod oracle over
1238/// every sign/edge case plus a 4000-pair pseudo-random sweep. PASS iff all match.
1239pub fn emit_shared_divider_testbench() -> String {
1240    include_str!("tb_shared_divider.v").to_string()
1241}
1242
1243/// Emit a yosys synthesis FLOW (`.ys`) that takes the reversible soft-core RTL to a gate-level netlist
1244/// (corner 5, phase 5). This is the tape-out-ready boundary produced IN-REPO: the synthesizable,
1245/// formally-verified reversible RTL ([`emit_reversible_alu_verilog`]) PLUS this flow. Executing it needs
1246/// the external `yosys` synthesizer (not installed here); mapping the generic gate set to an
1247/// adiabatic / charge-recovery PDK and running a foundry are the physical tape-out steps beyond
1248/// software. The flow reads the module, elaborates, techmaps, maps to a generic gate library, and
1249/// writes the gate-level netlist + a resource report.
1250pub fn emit_yosys_tapeout_flow(module: &str, rtl_file: &str) -> String {
1251    format!(
1252        "# LOGOS reversible soft-core — tape-out synthesis flow.  Run with:  yosys {module}.ys\n\
1253         read_verilog {rtl_file}\n\
1254         hierarchy -check -top {module}\n\
1255         proc; opt; fsm; opt; memory; opt\n\
1256         techmap; opt\n\
1257         # Generic gate mapping; a reversible/adiabatic PDK (charge-recovery cells) replaces this for silicon.\n\
1258         abc -g AND,OR,XOR,NAND,NOR\n\
1259         opt; clean\n\
1260         write_verilog {module}_netlist.v\n\
1261         stat\n"
1262    )
1263}
1264
1265/// LOGICAL EQUIVALENCE CHECK (corner 5, phase 3) — discharged by OUR OWN certified SAT, not yosys's
1266/// SAT or Z3. Parse the soft-core RTL, extract register `reg`'s next-state, and prove it equals `spec`
1267/// (the VM op's datapath function) for EVERY input by refuting the miter `rtl_next ≠ spec` with
1268/// [`logicaffeine_proof::sat::prove_unsat`] — a bit-blasted CDCL refutation, the LEC "back-check". This
1269/// is the equivalence a tool like yosys `equiv` runs on its internal SAT, done here on ours. Returns
1270/// `Some(true)` iff the RTL datapath is equivalent to the VM spec, `Some(false)` if a differing input
1271/// exists, `None` if the RTL / next-state / miter can't be lowered to the bit-blaster.
1272pub fn lec_next_state_matches_vm(rtl: &str, reg: &str, spec: BoundedExpr) -> Option<bool> {
1273    let ts = parse_transition_system(rtl).ok()?;
1274    let r = ts.registers.iter().find(|r| r.name == reg)?;
1275    let rtl_next = match &r.next {
1276        NextState::Simple(e) => e.clone(),
1277        NextState::Ite { .. } => return None,
1278    };
1279    // The miter: are the RTL datapath and the VM spec EVER unequal? Equivalent iff that is UNSAT.
1280    let miter = BoundedExpr::Eq(Box::new(rtl_next), Box::new(spec));
1281    let p = super::bitblast::lower_bool(&miter)?;
1282    Some(prove_unsat(&ProofExpr::Not(Box::new(p))) == UnsatOutcome::Refuted)
1283}
1284
1285#[cfg(test)]
1286#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/rtl/tests.rs"]
1287mod tests;