# Chapter 7c — Synthesis With a Proof Attached: `#ved_u1`
Chapter 5 turned a Sparkle declaration into Verilog with
`#synthesizeVerilog`. In that chapter you trust the compiler: nothing
checks that the module it built computes what your declaration says.
Chapter 7 proved two *Lean functions* equal, but the compiler was not part
of that proof.
This chapter covers a command that closes that gap for small designs:
```text
#ved_u1 delay8
```
It compiles `delay8` the same way `#synthesizeVerilog` does. It returns
the IR module **only together with a kernel-checked theorem**. The theorem
says that the module's outputs equal the declaration's Signal outputs at
every cycle. It covers every input stream whose values fit their widths,
with reset held at 0, and every arrangement of the body that assigns each
wire before reading it (§7c.2, §7c.4). It is a statement about the IR
module, not about the printed Verilog. If no such theorem can be built,
the command refuses and returns nothing.
> **Status (research release, snapshot `2bcf256b`).**
>
> - The commands live in `Tools/VedU1Entry.lean`, `Tools/VedU1Deep.lean`
> and the related `Tools/Ved*.lean` entries. These are library targets
> of the Sparkle repository, not part of the default build or the
> `Sparkle` umbrella. You use them with `import Tools.VedU1Entry`
> inside the repository.
> - This chapter teaches the single-output `#ved_u1` on small examples.
> At the snapshot the family also covers: several registers built by
> `Signal.loop`; several outputs (a `×`-tree of signals or a structure,
> one port per leaf); a result `Signal d (A × B)` packed into one port
> (`#ved_u1_packed`); modules with memories (`#ved_u1_mem`); a parent with
> instances (`#ved_u2_hier`); and `#ved_write_checked`, which writes
> exactly the checked design. Their statements differ from `U1Stmt`
> (see [PerCircuitVerification](../../research/PerCircuitVerification.md)).
> - **Scope of the release.** 243 of the 327 command rows of the
> fixed inventory are strict; the other 84 carry no claim. The 327 are
> command rows, not IPs. The production gate is **not** met. See the
> [research release](../../research/README.md) and the
> [row-by-row table](../../research/appendix/F-AllCommandRows.md).
> - Everything outside the covered scope is *refused*, never accepted
> with a weaker claim.
## The overall picture: what is proved where
The figure follows `delay8` (§7c.1) from the Lean declaration to the
tools that consume the SystemVerilog. Solid arrows are the compiler's
steps. Dotted links are theorems. A step with no dotted link has no
theorem; it is checked by tests at most.
```mermaid
flowchart TD
F["delay8
Lean declaration (Signal)"]
M["IR module delay8.ved_mod
from synthesizeCombinational"]
O["optimised IR
optimizeModule"]
T["SystemVerilog text
shipping printer (partial def)"]
P["tree parsed back
shipping parser"]
A["SV syntax tree
emitAstExpr (total copy)"]
L["IR expression again
lowerT (total copy)"]
S["SystemVerilog model
runModuleSV (SVSemantics)"]
H["yosys, FPGA, C simulator"]
F -->|synthesise| M
M -->|optimise| O
O -->|print| T
T -->|parse back| P
T -->|consumed by| H
M -->|"one expression"| A
A -->|lower| L
F <-.->|"① delay8.ved_u1: PROVED
same outputs at every cycle"| M
M <-.->|"② delay8_certified: PROVED for the fixed seed seed8
IR run = SV model run"| S
M <-.->|"③ roundtrip_sem: PROVED for SFrag expressions
width and value kept"| L
classDef proved fill:#e6f4ea,stroke:#1e7e34
classDef open fill:#fdecea,stroke:#b3261e
class F,M,S,A,L proved
class O,T,P,H open
```
| | Between | Theorem | What it gives | Section |
|---|---|---|---|---|
| ① | the declaration and the IR module | `delay8.ved_u1` | the same outputs at every cycle, for every input stream that fits the widths, with reset held at 0 | §7c.1–§7c.6 |
| ② | the IR module and the SystemVerilog model | `delay8_certified` | for the example's fixed seed `seed8` (the stream 5, 9, 9, 3, 7, clipped to the widths): the run of the IR equals the run of the SystemVerilog model, for every cycle count and every state | §7c.10 |
| ③ | an IR expression and `(emitAstExpr wof e).bind lowerT` | `roundtrip_sem` | the syntax tree, lowered back, keeps the width and the value, for expressions in the fragment `SFrag`. It is about the tree, not the printed text | §7c.10 |
What the figure does not connect (red boxes):
- **① and ② are two theorems, not one.** They use different width
functions (§7c.10), so they do not chain into one statement from
`delay8` to the SystemVerilog model.
- **The optimiser.** `optimizeModule` has no theorem. ① and ② are about
the module before it.
- **The printed text.** ② and ③ are about total copies of the printer
(`emitAssigns`/`emitRegs`, `emitAstExpr`) and of the lowering
(`lowerT`), not about the text. The shipping printer is a
`partial def`, so no proof can compute with it. `#guard` checks tie
it to the copies on listed inputs only.
- **Text to tree.** Printing the text and parsing it back with the
shipping parser has no theorem: it is checked on listed inputs only
(§7c.10, "Text to tree"). It also loses facts: an asynchronous and a
synchronous reset print differently, but parse to the same tree.
- **The tools.** yosys, the FPGA flow and the C simulator have no
theorem; co-simulation tests only.
The command blocks below are shown as `text` because they need the VED
tools. The real, CI-checked versions are in `Tests/Ved/U1EntryCheck.lean`
and `Tests/Ved/U1DeepCheck.lean`. §7c.4 has a cell you can run with plain
`import Sparkle`.
## 7c.1 Running it
A one-register delay of an 8-bit input:
```text
import Tools.VedU1Entry
open Sparkle.Core.Domain Sparkle.Core.Signal
def delay8 (x : Signal defaultDomain (BitVec 8)) : Signal defaultDomain (BitVec 8) :=
Signal.register 0#8 x
#ved_u1 delay8
```
The command prints the theorem's name and its axioms, then the module:
```text
VED U1 OK delay8.ved_u1: [Classical.choice, Quot.sound, propext]
{ name := "delay8",
inputs := [{ name := "_gen_x", ty := bitVector 8 },
{ name := "clk", ty := bit }, { name := "rst", ty := bit }],
outputs := [{ name := "out", ty := bitVector 8 }],
wires := [{ name := "_gen_x", ty := bitVector 8 },
{ name := "_gen_out", ty := bitVector 8 }],
body := [register "_gen_out" "clk" ("rst", synchronous) (ref "_gen_x") 0,
assign "out" (ref "_gen_out")],
... }
```
(The output is abbreviated here. The exact text is pinned with
`#guard_msgs` in `Tests/Ved/U1EntryCheck.lean`.)
After an accepted run, five constants exist next to your declaration:
| Constant | What it is |
|---|---|
| `delay8.ved_mod` | the module `synthesizeCombinational` returned, as a closed term |
| `delay8.ved_contract` | the port correspondence: which module port is which binder or output |
| `delay8.ved_outs` | the output ports |
| `delay8.ved_body` | one well-ordered arrangement of the body (proof data only, see §7c.4) |
| `delay8.ved_u1` | the theorem |
The theorem is stated about **your** constant, not about a copy:
```text
open Tools.VedU1Contract in
example : U1Stmt delay8.ved_contract delay8.ved_mod delay8 := delay8.ved_u1
```
There is no rule by name that forbids reusing a proof. What the entry
checks is the type: the theorem it adds must have exactly the expected
statement `U1Stmt f.ved_contract f.ved_mod f`, and the kernel checks the
proof against that type. `Tests/Ved/U1EntryCheck.lean` records the two
cases separately:
- **An old proof is refused.** Passing `delay8b.ved_u1` (or
`delay8k.ved_u1`) as the proof for `delay8` is refused at `[proof]`.
That theorem talks about `delay8b`'s own module and contract, so its type
is not `delay8`'s statement (`ctlProofB`, `ctlProofK`).
- **A new proof of a same-meaning artifact is accepted.** `delay8b`'s
module is a different artifact with the same meaning. Checking it
against `delay8`'s statement with a freshly generated proof is accepted
(`ctlArtB`). The IR contract has no "module name = declaration name"
condition.
That the entry returns the module of its *own* synthesis run is a property
of `#ved_u1` (it passes that module to the checker unchanged), not of the
statement.
## 7c.2 What the theorem says
`U1Stmt c m f` is a conjunction of five parts (`Tools/VedU1Contract.lean`):
| Part | Meaning | How it is proved |
|---|---|---|
| `CorrStmt c` | The port table read from `f`'s **type** matches the contract: one name per binder and per output, and all names distinct and different from `clk`/`rst`. | `decide` |
| `ShapeStmt c m` | The module's inputs are the table's ports in binder order with their widths, then `clk` and `rst`. Its outputs are the table's outputs. There are no memories and no instances. | `decide` |
| `WidthStmt c m` | Wire names are distinct. Every data input has a wire declaration of its port's width. Every register has a scalar wire declaration. | `decide` |
| `OrderStmt m` | The body is a well-formed netlist with an order in which every wire is assigned before it is read (§7c.4). | `decide` on the arrangement `ved_body` |
| `OutputsStmt c m f` | The behaviour statement below. | generated script, checked by the kernel |
The behaviour part, slightly simplified:
```text
∀ input streams ins,
InputsOk c m ins → -- every data input fits its width; reset held at 0
∀ K, -- run K cycles from the initial state st0
runModule … b … K (st0 c m) … = some envs ∧
∀ t < K, ∀ output o,
envs[t] o = (f applied to the input signals of ins) at cycle t, observed at o
```
Some points to read carefully:
- **Inputs.**
- Any input stream is covered, as long as each value fits its declared
width.
- The clock's value is left free: it is quantified, not fixed.
- The reset is held at 0. Runs with reset asserted are outside the
statement.
- **Initial state.** `st0` starts every register at its declared initial
value.
- **The run.** `runModule` is the IR semantics in `Sparkle/IR/Semantics.lean`.
It is a total Lean function, so the kernel can evaluate it.
- **The right-hand side.** It is computed from `f` itself (`srcOf c f`): the
declaration is applied to the input signals, then its output is read at
cycle `t`.
- **The body `b`.** It ranges over every well-ordered arrangement of the
module body. §7c.4 explains why.
## 7c.3 What the command does, step by step
`#ved_u1 f` returns the module only if every step below succeeds:
1. **Read the table.** It reads the port table from `f`'s type. A
declaration with several outputs is handled by the multi-output rule
(one port per leaf of the result); shapes the rule does not cover are
refused here, before synthesis (`[multi-output]` or `[table]`).
2. **Synthesise once.** It calls `synthesizeCombinational f`, the same
function `#synthesizeVerilog` calls, exactly once.
3. **Register the artifact.** It registers the module as `f.ved_mod`. It
then checks that this closed term evaluates back to the very value
synthesis returned (`[artifact]`).
4. **Find an order.** It looks for a well-ordered arrangement of the body
and checks it with `OrderOk` (`[order]`).
5. **State the theorem.** It builds the expected statement
`U1Stmt f.ved_contract f.ved_mod f` (`[type]`).
6. **Prove it.** It elaborates a generated proof script against that
statement (`[proof]`). Errors are never turned into `sorry`.
7. **Kernel check.** It adds the theorem to the kernel synchronously, then
re-reads the stored type and compares it with step 5 (`[kernel]`,
`[type]`).
8. **Strict audit.** It runs the strict audit (`[audit]`). The audit
accepts only `propext`, `Classical.choice` and `Quot.sound`. It
rejects `native_decide` (`Lean.ofReduceBool`) and any other axiom.
When a step fails:
- **The report.** Failures are reported as `VED U1 REFUSED f [stage]: …`.
Inside the checker (steps 3–8), any other exception is reported as
`[checker]`. Not every failure takes this form: an interrupt is never
caught, and a heartbeat or recursion-limit error raised while reading the
table or during synthesis propagates as its own error.
- **The rollback.** The checker saves the elaboration state when it starts,
which is after synthesis. On a failure it restores that state. The
constants it added (`ved_mod`, `ved_contract`, `ved_outs`, `ved_body`,
`ved_u1`, and anything a failed kernel step left) and its messages
disappear. Constants that existed before are not deleted; the state just
goes back to the checker's start.
- **What is not restored.** Anything synthesis did before the checker
started: the environment before `synthesizeCombinational`, `IO.Ref`s and
caches, and files.
The proof script is **untrusted**. The kernel and the audit are what make
the result trustworthy, not the script generator.
## 7c.4 Why statement order does not matter
A circuit is a set of wires driven at the same time. The order in which
the assignments are written down carries no meaning. In Verilog,
```text
assign c = b;
assign b = a;
```
is the same circuit as the two lines swapped.
Sparkle's IR semantics, however, evaluates the body **once, top to
bottom** (`evalAssigns`). When a wire is read before its assignment, the
read sees the value from the starting environment. You can see this with
plain `import Sparkle`:
```lean
import Sparkle
open Sparkle.IR.AST Sparkle.IR.Semantics
namespace Notebooks.Ch07c
/-- Start: input `a` is 5, every other wire 0. -/
def env0 : Env := fun n => if n = "a" then 5 else 0
/-- Every name is 8 bits wide. -/
def we8 : WEnv := fun _ => 8
/-- `b := a; c := b`: each wire is assigned before it is read. -/
def fwd : List Stmt := [.assign "b" (.ref "a"), .assign "c" (.ref "b")]
/-- The same two assignments, swapped. -/
def bwd : List Stmt := [.assign "c" (.ref "b"), .assign "b" (.ref "a")]
-- one top-to-bottom pass: `c` is 5 in one order, 0 in the other
#guard (evalAssigns we8 (fun _ _ => 0) fwd env0).map (· "c") == some 5
#guard (evalAssigns we8 (fun _ _ => 0) bwd env0).map (· "c") == some 0
-- `woCheck` tells the two apart: only `fwd` assigns before reading
#guard Sparkle.IR.Reorder.woCheck [] fwd
#guard !Sparkle.IR.Reorder.woCheck [] bwd
```
Sparkle's compiler does emit bodies like `bwd` for some `circuit do`
blocks. An example is the accumulator `accK9` in
`Tests/Ved/U1DeepCheck.lean`:
```text
_tmp_op_a_2 := _tmp_loop_body_7[7:0] -- read here
...
_tmp_loop_body_7 := _tmp_a_5 -- assigned here
out := _tmp_op_a_2
```
As continuous assignments, these lines mean the same in any order:
swapping two `assign` statements does not change a netlist. (This is a
remark about statement order only. U1 says nothing about the correctness
of the Verilog that is printed for this design.) A theorem about the IR
body *in its printed order*, read with the one-pass `evalAssigns`, would be
false here although the order of the assignments carries no meaning. So
the U1 statement is about the body as a netlist, not about one listing of
it:
- **The well-ordered arrangements.**
- `WO [] b` holds when `b` assigns every wire before reading it.
- `OutputsStmt` speaks about **every** permutation `b` of the body with
`WO [] b`.
- **They all agree.** `runModule_perm` (`Sparkle/IR/ReorderInvariance.lean`)
proves that all such arrangements give the same run. So the statement
does not depend on which one you pick.
- **One arrangement must exist.** `OrderStmt` requires it, checked in the
kernel by `OrderOk`. `OrderOk` also rules out bodies that have no
order-free meaning:
- a combinational cycle;
- an assignment that reads its own target;
- a read of a name that is neither an input, a register, nor assigned;
- an output with no driver;
- an assignment to an input;
- a name that is both assigned and a register output;
- duplicate register or memory names.
With these rules, the starting value of the environment never stands in
for a missing driver.
- **The module is not reordered.** The arrangement the checker found is
stored as proof data (`f.ved_body`). The module you get back is exactly
what synthesis returned. If no arrangement exists, the command refuses
with `[order]`.
- **The in-order reading is still available.** When the printed order is
already well-ordered, `outputs_body` gives the in-order statement over
`m.body` itself.
## 7c.5 How the proof is built
Both commands prove `OutputsStmt` in the same three moves:
1. **Pick the checked arrangement.**
`outputs_of_order b0 (h : OrderOk m b0 = true)` reduces the statement
over *every* well-ordered arrangement to the one arrangement `b0 =
f.ved_body`.
2. **Induct over cycles.** `outputs_of_step` turns the claim for all `K`
cycles into an induction. You supply an invariant `R` between the
module's register state and the cycle number, and prove two things:
- `R` holds at cycle 0 for `st0`;
- one `stepModule` of `b0` from a state satisfying `R` produces the
right outputs for that cycle and a next state that satisfies `R`
again.
The time direction (`runModule` counts cycles down; streams count up)
is handled once inside `outputs_of_step` (`seedFwd_time`).
3. **Prove one symbolic cycle.** The module's syntax is fixed, but the
step is not a closed computation: the inputs `ins`, the cycle `s`, the
state `st` and the memories are all universally quantified. The
generated script unfolds `stepModule` on the fixed body with `simp`,
which leaves arithmetic over those variables, and closes it with the
input-width bounds and `omega`.
The two commands differ in where the invariant and the per-cycle facts
come from:
- **`#ved_u1`** builds the script itself. It covers register-free bodies
(the invariant is just `True`) and one-register delays (the invariant
is "the register holds the declaration's output at the current
cycle").
- **`#ved_u1_deep`** reuses what `#verify_elab_deep` already proved about
the declaration (see [`docs/VED.md`](../../VED.md#what-ved-is)):
```text
#verify_elab_deep accK9
#ved_u1_deep accK9
```
- **The facts it uses.** It uses only the standard-axiom facts
`_deep_trace`, `_deep_next`, `_deep_inits` and `_deep_out`. These
relate the Signal to the reified circuit `Cdo`.
- **The invariant.** "The module's register equals `Cdo.irState` at the
same cycle."
- **What it does not use.** `#verify_elab_deep`'s IR replay theorems
(`_deep_signal_run`, `_deep_regstep`, …) rely on `native_decide`, and
are not used. The strict audit would reject them anyway.
## 7c.6 How we know it is not vacuous
An accepted run is only interesting if wrong modules are refused.
`Tests/Ved/U1EntryCheck.lean` feeds the checker the real declaration
together with a **mutated** module. Each mutation must be refused at the
named stage, and none of the names the checker registers (`ved_mod`,
`ved_contract`, `ved_outs`, `ved_body`, `ved_u1` for that run) may be left
in the environment:
| Mutation of `delay8`'s module | Refused at |
|---|---|
| register initial value 0 → 5 | `[proof]` |
| output reads the input instead of the register | `[proof]` |
| output port widened to 9 bits | `[proof]` |
| register fed from a constant | `[proof]` |
| output's driver removed | `[order]` |
| an assignment to the data input added | `[order]` |
| `ident8`'s module put into `delay8`'s statement | `[proof]` |
For some of these, the test also proves in the kernel that the statement is
**false**, not just that the script gave up. For example, the identity
does not implement the delay:
```text
theorem ident_not_delay : ¬ U1Stmt delay8.ved_contract delay8.ved_mod ident8
```
The witness is an input of 1 at every cycle. At cycle 0 the register
gives 0 but the identity gives 1.
`Tests/Ved/U1DeepCheck.lean` does the same for the deep route. It also
checks that the accepted theorem's dependency closure contains no
`native_decide` auxiliary. And it confirms that `accK9`'s body, in its
printed order, is *not* well-ordered:
```text
example : Sparkle.IR.Reorder.woCheck [] accK9.ved_mod.body = false := by decide
```
The theorem is accepted all the same, by §7c.4.
## 7c.7 What it does not claim
- **The artifact.** The guarantee is about the module
`synthesizeCombinational` returned. The Verilog that
`#synthesizeVerilog` prints goes through `optimizeModule` and the
printer, and is not covered. Neither is the C simulator.
- **Scope.**
- This chapter's statement `U1Stmt` has no memories and no instances;
memories, packed ports and hierarchies have their own statements
(`MemStmt`, `PackedStmt`, `U2HStmt` / `U2HRStmt`).
- Runs with reset held at 0.
- **Coverage.** 243 of 327 command rows are strict at the snapshot; that
is not a claim that the IP library is verified, and the 327 are rows,
not IPs.
- **Other stages.** Nothing is proved about the optimiser, the printed
SystemVerilog or hardware: see the guarantee ladder in the
[research README](../../research/README.md#the-guarantee-ladder).
- **The general compiler theorem** is a different, paused effort
([the general theorem](../../research/CompilerGeneralTheorem.md)); this chapter's
per-circuit theorem is not a soundness theorem of the compiler.
## 7c.8 Running the checks yourself
```bash
lake build Tests.Ved.U1ContractCheck # the statement, toy instances, order controls
lake build Tests.Ved.U1EntryCheck # #ved_u1 runs and mutation controls
lake build Tests.Ved.U1DeepCheck # #ved_u1_deep on accK9 / natInit5
```
CI builds the same targets in `.github/workflows/ved-run.yml`, on every supported Lean version. The design
notes are in [`docs/VED.md`](../../VED.md#single-module); the reproduction
steps of the whole release are in
[Appendix C](../../research/appendix/C-Reproduction.md).
For a step-by-step tutorial on writing circuits whose proofs go through (a register, two
extensions, a small change that makes the automatic proof stop, and the ways past it that
this snapshot supports), see
[Writing circuits whose proofs go through](../../research/ProofFriendlyCircuits.md).
## 7c.9 The same input on both sides: numbers
§7c.2 states the theorem for every input stream. This section fixes **one** stream and
computes both sides of the theorem by hand. Every number below is pinned in
[`Ex7_TwoSides.lean`](../../research/examples/tutorial/Ex7_TwoSides.lean):
```bash
lake build Tools.VedU1Entry
lake env lean docs/research/examples/tutorial/Ex7_TwoSides.lean ; echo "exit $?"
```
**Which checkout.** These examples are newer than the research snapshot `3af3889f`, which does not
contain them, and neither does the tag `v0.2.0`; check out `a97a0def` (the squash of pull
request #190 on `main`, the first commit that has them) or a later commit such as the tag `v0.2.1`, and run
them there, with Lean 4.32.1. They were first checked on the code of `fcb33734`; from there to
`a97a0def` nothing under `Sparkle/` or `Tools/` changed (`git diff --stat fcb33734 a97a0def --
Sparkle Tools` is empty), only `IP/Bus/I2CHW.lean` and `IP/Net/MemcachedHW.lean`, which the examples
do not use.
The checks on `delay8.ved_mod` and `delay8.ved_contract` are `by decide +kernel`, not `#guard`:
`#ved_u1` adds these two constants without compiled code, so `#guard` cannot call them.
The kernel evaluates the statement; there is no `native_decide`.
### The input
One function `ins : Nat → String → Nat`: time, then port name, gives a number.
```text
t 0 1 2 3 4
_gen_x 5 9 9 3 7
rst 0 0 0 0 0
clk 0 0 0 0 0 (the theorem lets clk be anything)
```
### DSL side
`PTy.sig` turns the numbers of one port into a `Signal`. For an 8-bit port, the value at `t` is
`BitVec.ofNat 8 (ins t "_gen_x")`: `5#8, 9#8, 9#8, 3#8, 7#8`. For a `Bool` port it is
`ins t n != 0`. `applyIns` gives `delay8` that signal. `srcOf … "out" t` observes the result
as a number:
```text
t 0 1 2 3 4
srcOf … "out" 0 5 9 9 3
```
### IR side
`st0` puts the register `_gen_out` at its init value, 0. `runModule` counts its cycle index
**down**, so `seedFwd m 5 ins j` reads `ins (5 - 1 - j)`:
```text
j 0 1 2 3 4
stream time 4 - j 4 3 2 1 0
_gen_x fed by seedFwd 7 3 9 9 5
```
The run starts at j = 4 (the first entry of the trace). Trace position `t` therefore sees
stream time `t`. The run, per cycle:
```text
t 0 1 2 3 4
_gen_x 5 9 9 3 7
_gen_out 0 5 9 9 3 (register, before the clock edge of this cycle)
out 0 5 9 9 3
```
### Both in one table, and the theorem at this input
```text
t 0 1 2 3 4
_gen_x 5 9 9 3 7
DSL srcOf 0 5 9 9 3
IR out 0 5 9 9 3
```
The file checks that the two lists are equal. It then proves `InputsOk` for this `ins` (every
value fits 8 bits; `rst` is 0) and instantiates `delay8.ved_u1` at it (`delay8_at_ins5`): the run
does not fail, and `out` at t = 0..4 is 0, 5, 9, 9, 3. The theorem is this table, for all
streams in `InputsOk` and all K.
### Inputs outside `InputsOk`
Two streams the theorem does not cover (the file proves `¬ InputsOk` for both):
| Stream | `delay8` DSL `out` | `delay8` IR `out` |
|---|---|---|
| `_gen_x` = 5, 9, **300**, 3, 7 | 0, 5, 9, 44, 3 | 0, 5, 9, 44, 3 |
| `_gen_x` = 5, 9, 9, 3, 7 and **`rst` = 1 at t = 2** | 0, 5, 9, 9, 3 | 0, 5, 9, **0**, 3 |
* **300 on an 8-bit port.** `BitVec.ofNat 8 300 = 44` on the DSL side. The IR keeps 300 on the
input wire and masks it where the register stores it (`_gen_out` = 44 at t = 3). So `delay8`
still agrees. A circuit that reads the input directly does not. For `pass8 x = x` the
DSL gives 5, 9, 44, 3, 7 and the IR gives 5, 9, **300**, 3, 7: the first difference is at
t = 2. For `eq44 x = (x === 44)` the DSL gives 0, 0, **1**, 0, 0 and the IR 0, 0, **0**, 0, 0.
`add8` with `a` = 300, `b` = 1 happens to agree (45 on both sides), because the IR masks the
sum. Whether an out-of-range value matters depends on the circuit; the theorem does not look,
and excludes it.
* **`rst` = 1.** `Signal.register` has no reset input, so the DSL ignores `rst`. The IR register
has a synchronous reset: at t = 2 it loads 0 instead of `_gen_x`. `out` is 0 at t = 3 on the IR
side and 9 on the DSL side. The first difference is at t = 3.
This is why `InputsOk` is in the statement: outside it the two sides may differ.
### More circuits
Same method, same file.
```text
enReg8 t 0 1 2 3 4 5
en 1 0 1 1 0 0
x 5 9 9 3 7 1
DSL out 0 5 5 9 3 3
IR out 0 5 5 9 3 3
counter8 t 0 1 2 3 4 5
en 1 1 0 1 1 1
DSL out 0 1 2 2 3 4
IR out 0 1 2 2 3 4 (well-ordered arrangement)
add8 t 0 1 2 3 4
a 100 200 250 255 1
b 50 55 5 1 255
DSL out 150 255 255 0 0
IR out 150 255 255 0 0
```
`add8` wraps at t = 3: 255 + 1 = 256, which is 0 in 8 bits.
`counter8` shows why the theorem speaks about *every well-ordered arrangement* of the body
(§7c.4). The body as the synthesizer lists it reads a wire before assigning it. Run in that
order, `out` is 0, 0, 0, 0, 0, 0. Run in a well-ordered arrangement, it is 0, 1, 2, 2, 3, 4. The
file checks both.
## 7c.10 From the IR to SystemVerilog: proved cases and not-proved cases
`delay8.ved_u1` stops at the IR (§7c.7). The step from the IR to SystemVerilog has other
theorems, for a fragment. This section runs both kinds of case. Every text, width, value and
verdict below is pinned in
[`Ex8_Roundtrip.lean`](../../research/examples/tutorial/Ex8_Roundtrip.lean):
```bash
lake build Tools.VedU1Entry Tools.SVParser.RoundtripProof
lake env lean docs/research/examples/tutorial/Ex8_Roundtrip.lean ; echo "exit $?"
```
**Which checkout.** These examples are newer than the research snapshot `3af3889f`, which does not
contain them, and neither does the tag `v0.2.0`; check out `a97a0def` (the squash of pull
request #190 on `main`, the first commit that has them) or a later commit such as the tag `v0.2.1`, and run
them there, with Lean 4.32.1. They were first checked on the code of `fcb33734`; from there to
`a97a0def` nothing under `Sparkle/` or `Tools/` changed (`git diff --stat fcb33734 a97a0def --
Sparkle Tools` is empty), only `IP/Bus/I2CHW.lean` and `IP/Net/MemcachedHW.lean`, which the examples
do not use.
Widths used: `a`, `b` are 8 bits, `s` is 1 bit, `w16` is 16 bits, `w40` is 40 bits.
### Proved: three expressions
The theorem is `roundtrip_sem` (`Tools/SVParser/RoundtripProof.lean`): if an IR expression is
in the fragment `SFrag`, then emitting it (`emitAstExpr`) and lowering the result back
(`lowerT`) gives an expression with the same width and the same value.
| IR expression | `sfragCheck` | emitted text | width, value at a=200, b=100, s=0 |
|---|---|---|---|
| `a + b` | true | `(a + b)` | 8, 44 (300 mod 256) |
| `s ? a : b` (arms 8 and 8 bits) | true | `(s ? a : b)` | 8, 100 |
| `a[5:2]` (in range for 8 bits) | true | `a[5:2]` | 4, 2 |
For each, the file builds `SFrag` from its constructors (`sfrag_add`, `sfrag_mux`,
`sfrag_slice`) and applies `roundtrip_sem` (`add_roundtrip`, `mux_roundtrip`,
`slice_roundtrip`). The theorem gives: width kept, value kept, in every bounded environment.
Here the lowered tree is even identical to the original. `#print axioms` lists the standard
three.
One module: `delay8`. `seqCheck` on its body returns `true`. The theorem is
`certified_forward_trace_module`; it has two hypotheses, written out for `delay8`:
1. `hchk`: `seqCheck (moduleWof delayMod) (weOf (moduleWof delayMod)) delayMod.body = true`
(`delay8_seqCheck`);
2. `hseed`: every environment the seed produces fits the declared widths, for every time and
every state (`seed8_bounded`). The file's seed takes the stream 5, 9, 9, 3, 7 and clips
every value to its width. The clipping is needed because the hypothesis speaks about every
state, not only the reachable ones.
The conclusion (`delay8_certified`): the emitter produces its three programs, and for every
cycle count, every state and every memory, the IR run equals the run of the SystemVerilog
model (`Tools/SVParser/SVSemantics.lean`). Run for 5 cycles, both give:
```text
t 0 1 2 3 4
_gen_x 5 9 9 3 7
_gen_out 0 5 9 9 3
out 0 5 9 9 3 IR and SystemVerilog model: equal
```
The text the shipping emitter prints for the module is pinned in the file (an `always_ff`
with `if (rst) _gen_out <= 8'd0; else _gen_out <= _gen_x;` and `assign out = _gen_out;`).
This theorem and `delay8.ved_u1` are **not one theorem**. They read different width functions:
`ved_u1` uses `declWidth` (wire table only), this one `weOf (moduleWof m)` (wires, inputs and
outputs). They give 0 and 8 for `out`, and 0 and 1 for `clk`.
### Not proved: outside the fragment
| IR expression | `SFrag` / `sfragCheck` | what the emitter prints | what is not guaranteed |
|---|---|---|---|
| `~w40` (`not` of 40 bits) | false (`SFrag.not` needs width ≤ 32) | `(40'(w40 ^ 40'd1099511627775))` | `roundtrip_sem` is silent. The module-level predicate `sf4Check` accepts it. |
| `s ? a : w16` (arms 8 and 16 bits) | false | `(s ? a : w16)` | that the emitted ternary keeps the IR's width |
| `a[11:4]` (past bit 7 of an 8-bit `a`) | false | `8'((a) >> 4)` | that the emitted shift-and-cast agrees with the IR slice |
| `~unknown` (no declared width) | false | `~(unknown)` | everything: an unpinned `~` (see below) |
What the file shows for each:
* **Mux, different arm widths.** With s = 0 the IR mux passes `w16` through unmasked: value
4660, but the width it reports is the then-arm's, 8, and 4660 does not fit 8 bits. The
SystemVerilog model gives the ternary width 16. Same value, two widths. `SFrag.mux` rules
this out by requiring equal arm widths. `sf4Check` also rejects it.
* **Out-of-range slice.** At a = 200 the IR gives 12 (200 >> 4). The file does not compare it
with the model; there is no theorem for this shape.
* **`~w40`.** At w40 = 1 the IR gives 1099511627774 (2^40 − 2), and so does the model. That is
one input, not a theorem for `roundtrip_sem`.
**Text to tree.** The tree is printed as text and parsed back by the shipping parser.
`roundtrip_sem` is about the tree before printing. For `s ? a : b` the text is `(s ? a : b)`,
and the parser returns the same tree: a check on this input only. A concrete loss in this
step: a register with an asynchronous reset and one with a synchronous reset print as
different text, and the parser makes the same tree of both (it keeps only the first `posedge`).
The reset kind is re-detected later from the shape of the `if`.
**Shipping `partial def`s.** `Sparkle.Backend.Verilog.emitExpr` is `partial`: Lean makes it
`opaque`, with no unfolding equation (`emitExpr.eq_1` does not exist; both facts are pinned), so
no proof can compute with it. The theorems are about total copies (`emitAstExpr`, `lowerT`).
What ties a copy to the shipping function is `#guard`s: about 50 expressions in
`Tools/SVParser/EmitAst.lean`. They do not cover any expression that is not on that list. The
file adds a sweep of 1304 expressions (8 leaves; `not` and `neg` of each leaf; 12 binary
operators over all leaf pairs; all muxes over leaves). For all 1304, the shipping text parsed
back equals the copy's tree. Of the 1304, 679 are in the proved fragment. The sweep is depth
1 only: no deeper trees, slices, concats, other widths, statements or modules.
**Bugs of this class.** Three are named in
[ReadingTheTheorem §6](../../research/ReadingTheTheorem.md#6-from-the-module-to-systemverilog-proved-for-a-fragment-tested-beyond-it):
| Bug | Where it was | What the file shows for that shape | What checks it today |
|---|---|---|---|
| `~` widened by context (Test 58) | the emitted Verilog | `~a` with known width prints `(8'(a ^ 8'd255))`; with unknown width it still prints `~(unknown)`. The unknown-width case is outside `SFrag` and `sf4Check`. | `ParserTest` Test 58 (one module: no `~(` in the output), the XiangShan co-simulation, the yosys gate. No proof. |
| dropped slice offset (Tests 51, 57, 60) | the C simulator only: Tests 51 and 57 record that the IR and the re-emitted Verilog were correct | `d138[137:69]` is in `SFrag` (`sliceRefKeep`); the text keeps `[137:69]`, and `roundtrip_sem` gives width 69 | the C simulator has no theorem; co-simulation tests only |
| concat element width (MiscModule, HPTW; bench/xiangshan/README.md) | the emitted Verilog: concat elements are self-determined, so an operator element needs a width pin | `{a & b, b}` prints `{8'((a & b)), b}`; it is in `SFrag` (`concatCons`); width 16, value 2058 at a=12, b=10, kept. With an operator element of unknown width, the text is `{(a & unknown), b}`: no cast, outside `SFrag` and `sf4Check` | `ParserTest`, XiangShan co-simulation. No proof for the unknown-width case. |
Test 52 (a wide concat narrower than its destination) is a different bug, also in the C
simulator. For the slice-offset bug, the proved fragment covers the IR-level shape; the bug
itself was elsewhere. For the other two (`~`, concat element width), the proved fragment
excludes exactly the unknown-width input that still prints unpinned.
```lean
end Notebooks.Ch07c
```