aver-cert 0.1.2

Independent artifact certificate engine and verifier for Aver WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
fn render_expr_fragment_cert(c: &Cert) -> String {
    // The two Int comparison faces discharge entirely inside the wall
    // (`intCmpBool_claim_discharges` / `intSelect_claim_discharges`): the
    // checked face pins their whole meaning, so there is no producer semantic
    // premise and no bespoke proof declaration to emit. This test precedes the
    // audited-generic one because their source types (Int, Int -> Bool) sit
    // inside that gate while their PLAN calls a runtime helper the generic
    // fragment grammar refuses.
    if c.int_cmp_face().is_some() {
        return String::new();
    }
    // Audited integer/Bool source fragments emit only their option-(b)
    // semantic bridge in `Certificate.lean`.
    if expr_fragment_uses_audited_generic(c) {
        return String::new();
    }
    if let Some(face) = c.int_add_face() {
        return render_expr_fragment_int_add_cert(c, face);
    }
    // Projection-faced fragments are discharged in `Final.cert` through the
    // audited direct-projection generic and emit no bespoke proof declarations.
    if c.project_face().is_some() {
        return String::new();
    }
    // Record-parameter fragments discharge through the wall's checked record
    // face (`recordParam_claim_discharges`) and emit no bespoke proof
    // declarations. Falling to the generic body renderer would emit a bogus
    // `{name}_simulates` over `verbatimRepr` (and, for an Int-carrier field
    // read, panic in the value renderer on the user struct projection).
    if c.record_param_face().is_some() {
        return String::new();
    }
    if let Some(face) = c.vector_get_face() {
        return render_expr_fragment_vector_get_cert(c, face);
    }
    let c = c.inner();
    let Cert::ExprFragment {
        name,
        self_idx,
        carrier,
        plan,
        ..
    } = c
    else {
        unreachable!()
    };
    let binders = plan
        .params
        .iter()
        .enumerate()
        .map(|(i, ty)| format!("(a{i} : {})", ty.lean_dom_type()))
        .collect::<Vec<_>>()
        .join(" ");
    let theorem_args = (0..plan.params.len())
        .map(|i| format!("a{i}"))
        .collect::<Vec<_>>();
    let input_list = expr_fragment_arg_list(plan, |i, ty| {
        ty.lean_arg_repr(&format!("a{i}"), &carrier.to_string())
    });
    let result = expr_fragment_wval_expr(plan, &|idx, _ty| format!("a{idx}"));
    let evalset = format!("wFuncN, wRunF, {name}Code, {name}Host, f, b32, popArgs, initLocals");
    let proof_tactic = expr_fragment_simp_tactic(plan, &evalset);
    let model_args = (0..plan.params.len())
        .map(|i| expr_fragment_dom_accessor("p", i, plan.params.len()))
        .collect::<Vec<_>>()
        .join(" ");
    let model_args = if model_args.is_empty() {
        String::new()
    } else {
        format!(" {model_args}")
    };
    let cod_repr = expr_fragment_cod_repr(plan.result);
    format!(
        r#"/-! ### {name} — expr-fragment-v1 certificate (carrier type {carrier}) -/

/-- The verifier-checked plan is an `expr-fragment-v1`: a typed, ordered,
    non-recursive wasm fragment with no runtime host calls. -/
theorem {name}_wasm_certified (S : CarrierSpec {carrier}) :
    ∀ (fuel : Nat) {binders},
      wFuncN {name}Code {name}Host (fuel + 1) {self_idx} {input_list}
        = some ({result}) := by
  intro fuel {intro_args}
{proof_tactic}

#print axioms {name}_wasm_certified

def {name}HostRef : HostTbl := {name}Host

theorem {name}_simulates : AverCert.Schema.Obligation.holds {name}Ob := by
  intro S add sub mul stringEq stringConcat toIndex cmp eq hadd hsub hmul hStringEq hStringConcat _hToIndex _hCmp _hEq fuel p vs w hrepr hrun
  simp only [{name}Ob, AverCert.Schema.Obligation.holds] at hrun ⊢
  subst hrepr
  cases fuel with
  | zero => simp [wFuncN] at hrun
  | succ f =>
      rw [{name}_wasm_certified S f{model_args}] at hrun
      simp only [Option.some.injEq] at hrun
      subst hrun
      simp [{cod_repr}]
"#,
        intro_args = theorem_args.join(" "),
    )
}

/// The fused vector-read proof: the obligation discharges through the wall's
/// generic template theorem, specialised to this claim's byte-derived holes
/// and the plan-lowered code table. The to-index contract hypothesis comes
/// straight from the obligation denotation's sixth host-contract slot.
fn render_expr_fragment_vector_get_cert(c: &Cert, face: FragVectorGetOrDefaultFace) -> String {
    let name = c.name();
    let carrier = c.carrier();
    let self_idx = c.self_idx();
    format!(
        r#"/-! ### {name} — fused vector-read certificate (carrier type {carrier}) -/

theorem {name}_simulates : AverCert.Schema.Obligation.holds AverCert.{name}Ob := by
  intro S add sub mul stringEq stringConcat toIndex cmp eq _hadd _hsub _hmul _hStringEq
    _hStringConcat hToIndex _hCmp _hEq fuel p vs w hDom hRun
  obtain ⟨v, i⟩ := p
  exact AverCert.StandardFace.vectorGetOrDefault_simulates_model
    {carrier} {to_index_idx} {box_idx} {arr_ty} ({d} : Int) (by decide) S toIndex hToIndex
    CertModule.{name}Code {self_idx} rfl fuel v i vs w hDom hRun

#print axioms {name}_simulates
"#,
        to_index_idx = face.to_index_idx,
        box_idx = face.box_idx,
        arr_ty = face.arr_ty,
        d = face.default,
    )
}

/// The straight-line integer proof face for a host-call expr fragment
/// `add(param0, box(k))`: the SAME theorem shapes (and closer) the legacy
/// straight-line class ships, stated over the plan-lowered code table. The
/// obligation covers ALL representations under the named add contract — no
/// weakening relative to the legacy class.
fn render_expr_fragment_int_add_cert(c: &Cert, face: FragIntAddFace) -> String {
    let name = c.name();
    let self_idx = c.self_idx();
    let carrier = c.carrier();
    let k = face.k;
    let g1 = k + 3;
    let g2 = k - 5;
    format!(
        r#"/-! ### {name} — expr-fragment-v1 certificate (carrier type {carrier}, straight-line integer face) -/

/-- The plan-lowered body of `{name}` maps any representation of `n` to a
    representation of `n + {k}`, for ALL `n : ℤ`, under the named runtime
    contract `hadd` (carrier add = exact integer addition on represented values). -/
theorem {name}_wasm_certified
    (S : ReprSpec {carrier})
    (add : List WVal → Option WVal)
    (hadd : ∀ a b va vb, S.Repr a va → S.Repr b vb →
          ∃ w, add [va, vb] = some w ∧ S.Repr (a + b) w) :
    ∀ (n : Int) (v : WVal), S.Repr n v →
      ∃ w, wFuncN {name}Code ({name}Host add) 1 {self_idx} [v] = some w ∧ S.Repr (n + {k}) w := by
  intro n v hv
  obtain ⟨w, hw, hrepr⟩ := hadd n {k} v (carrierSmall {carrier} {k}) hv (S.smallIntro {k})
  refine ⟨w, ?_, hrepr⟩
  simp only [wFuncN, {name}Code, {name}Host, boxRef, carrierSmall, initLocals,
    wRunF, popArgs, List.getElem?_cons_zero, List.length, List.take, List.drop,
    List.reverse, List.replicate, if_true, reduceIte]
  simp only [carrierSmall] at hw
  simp [hw]

#print axioms {name}_wasm_certified

/-- Consumer-facing composition: whatever the bytes return represents the
    model value `n + {k}` (faithfulness law ∘ simulation). -/
theorem {name}_wasm_faithful
    (S : ReprSpec {carrier})
    (add : List WVal → Option WVal)
    (hadd : ∀ a b va vb, S.Repr a va → S.Repr b vb →
          ∃ w, add [va, vb] = some w ∧ S.Repr (a + b) w) :
    ∀ (n : Int) (v : WVal), S.Repr n v →
      ∃ w m, wFuncN {name}Code ({name}Host add) 1 {self_idx} [v] = some w ∧ S.Repr m w ∧ m = n + {k} :=
  fun n v hv =>
    let ⟨w, hrun, hrepr⟩ := {name}_wasm_certified S add hadd n v hv
    ⟨w, n + {k}, hrun, hrepr, rfl⟩

#print axioms {name}_wasm_faithful

-- anti-vacuity: the emitted body actually RUNS on concrete inputs.
def {name}HostRef : HostTbl := {name}Host (addRef {carrier})
example :
    ((wFuncN {name}Code {name}HostRef 4 {self_idx} [carrierSmall {carrier} 3]).bind carrierToInt)
      = some ({g1}) := by native_decide
example :
    ((wFuncN {name}Code {name}HostRef 4 {self_idx} [carrierSmall {carrier} (-5)]).bind carrierToInt)
      = some ({g2}) := by native_decide

/-- Schema-shaped simulation obligation for `{name}` (composed by the single
    final theorem). Partial correctness over any fuel and representation. -/
theorem {name}_simulates : AverCert.Schema.Obligation.holds {name}Ob := by
  intro S add sub mul stringEq stringConcat toIndex cmp eq hadd hsub hmul hStringEq hStringConcat _hToIndex _hCmp _hEq fuel ns vs w hrepr hrun
  simp only [{name}Ob, AverCert.Schema.Obligation.holds] at hrun ⊢
  obtain ⟨hrepr, harity⟩ := hrepr
  cases hrepr with
  | nil =>
      simp at harity
  | cons hv htail =>
    rename_i n v ns vs
    cases htail with
    | nil =>
      cases fuel with
      | zero => simp only [wFuncN, reduceCtorEq] at hrun
      | succ f =>
        rcases hc : add [v, carrierSmall {carrier} ({k})] with _ | r
        · simp [wFuncN, wRunF, {name}Code, {name}Host, boxRef, popArgs, initLocals, hc] at hrun
        · simp [wFuncN, wRunF, {name}Code, {name}Host, boxRef, popArgs, initLocals, hc] at hrun
          subst hrun
          simpa [AverCert.Schema.intRepr] using hadd n ({k}) v (carrierSmall {carrier} ({k})) r hv (S.smallIntro ({k})) hc
    | cons _ _ =>
      simp at harity
"#
    )
}

fn expr_fragment_cod_repr(ty: FragTy) -> &'static str {
    match ty {
        FragTy::F64 => "AverCert.Schema.floatBitsRepr",
        FragTy::BoolI32 => "AverCert.Schema.boolRepr",
        FragTy::IntCarrier | FragTy::I64 | FragTy::RawI32 | FragTy::Ref | FragTy::AdtRef => {
            "AverCert.Schema.verbatimRepr"
        }
    }
}

fn expr_fragment_arg_list<F>(plan: &ExprFragmentPlan, mut arg: F) -> String
where
    F: FnMut(usize, FragTy) -> String,
{
    let args = plan
        .params
        .iter()
        .enumerate()
        .map(|(i, ty)| arg(i, *ty))
        .collect::<Vec<_>>();
    format!("[{}]", args.join(", "))
}

fn expr_fragment_wval_expr<F>(plan: &ExprFragmentPlan, local: &F) -> String
where
    F: Fn(u32, FragTy) -> String,
{
    let root = plan.body.node(plan.body.result).expect("fragment root exists");
    let value = expr_fragment_value_expr(&plan.body, plan.body.result, local);
    match root.ty {
        FragTy::F64 => format!(".f64v ({value})"),
        FragTy::BoolI32 => format!("b32 ({value})"),
        FragTy::IntCarrier | FragTy::I64 | FragTy::RawI32 | FragTy::Ref | FragTy::AdtRef => {
            unreachable!("expr-fragment root must be a certified result type")
        }
    }
}

fn expr_fragment_value_expr<F>(block: &FragBlock, id: FragValueId, local: &F) -> String
where
    F: Fn(u32, FragTy) -> String,
{
    let node = block.node(id).expect("fragment node exists");
    match node.ty {
        FragTy::BoolI32 => expr_fragment_bool_expr(block, id, local),
        FragTy::RawI32 => expr_fragment_i32_expr(block, id, local),
        _ => expr_fragment_typed_value_expr(block, id, local),
    }
}

fn expr_fragment_typed_value_expr<F>(block: &FragBlock, id: FragValueId, local: &F) -> String
where
    F: Fn(u32, FragTy) -> String,
{
    let node = block.node(id).expect("fragment node exists");
    match &node.kind {
        FragNodeKind::Local { index } => local(*index, node.ty),
        FragNodeKind::ConstBool(v) => v.to_string(),
        FragNodeKind::ConstI64(k) => lean_int_lit(*k),
        FragNodeKind::ConstI32(k) => k.to_string(),
        FragNodeKind::ConstF64(bits) => lean_u64_hex(*bits),
        FragNodeKind::StructGet {
            field, receiver, ..
        } => {
            let recv = expr_fragment_value_expr(block, *receiver, local);
            match field {
                0 => recv,
                // `expr-fragment-v1`'s Int face is stated over canonical
                // `carrierSmall`, whose limbs field is null and sign is 0.
                1 => "WVal.null".to_string(),
                2 => "0".to_string(),
                _ => unreachable!("unsupported carrier field in fragment"),
            }
        }
        FragNodeKind::StructGetUser { .. } => {
            unreachable!("user struct projection is rendered by the projection face, not the generic value renderer")
        }
        FragNodeKind::VectorGetOrDefault { .. } => {
            unreachable!("the fused vector read is rendered by its own face, not the generic value renderer")
        }
        FragNodeKind::RefIsNull { value } => {
            let v = expr_fragment_value_expr(block, *value, local);
            format!("{v} = WVal.null")
        }
        FragNodeKind::Prim { op, args } => {
            match op {
                FragPrim::F64Add => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("(Float.ofBits ({lhs}) + Float.ofBits ({rhs})).toBits")
                }
                FragPrim::F64Mul => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("(Float.ofBits ({lhs}) * Float.ofBits ({rhs})).toBits")
                }
                FragPrim::F64Le => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("Float.ofBits ({lhs}) <= Float.ofBits ({rhs})")
                }
                // `f64.ge` is stated as the swapped `<=`, exactly the shape the
                // wall interpreter gives `.f64Ge` (`b32 (f b <= f a)`) and the
                // same convention `i64.ge_s` already uses. It is an IEEE ordered
                // comparison in both directions, so a NaN operand makes it false
                // — the identical NaN posture as `f64.le`.
                FragPrim::F64Ge => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("Float.ofBits ({rhs}) <= Float.ofBits ({lhs})")
                }
                FragPrim::F64Lt => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("Float.ofBits ({lhs}) < Float.ofBits ({rhs})")
                }
                // `f64.gt` is stated as the swapped `<`, matching the wall
                // interpreter's `.f64Gt` clause (`b32 (f b < f a)`) and the
                // swapped-relation convention `f64.ge`/`i64.ge_s` already use.
                FragPrim::F64Gt => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("Float.ofBits ({rhs}) < Float.ofBits ({lhs})")
                }
                // `f64.eq` is stated with Bool-valued `==` (`Float.beq`, the
                // extern IEEE comparison), NEVER with propositional `=`:
                // `Float` has no lawful `DecidableEq`, and `Float.ofBits b =
                // Float.ofBits b` holds for a NaN pattern while `f64.eq`
                // returns 0 for it. `==` is exactly the wall interpreter's
                // `.f64Eq` clause (`b32 (f a == f b)`).
                FragPrim::F64Eq => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("Float.ofBits ({lhs}) == Float.ofBits ({rhs})")
                }
                FragPrim::I64Eq => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("({lhs}) = ({rhs})")
                }
                FragPrim::I64LeS => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("({lhs}) <= ({rhs})")
                }
                FragPrim::I64LtS => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("({lhs}) < ({rhs})")
                }
                FragPrim::I64GeS => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("({rhs}) <= ({lhs})")
                }
                // Swapped `<`, the same convention `i64.ge_s` uses for `>=`,
                // matching the wall interpreter's `.i64GtS` clause.
                FragPrim::I64GtS => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("({rhs}) < ({lhs})")
                }
                FragPrim::I32Eq => {
                    let lhs = expr_fragment_i32_expr(block, args[0], local);
                    let rhs = expr_fragment_i32_expr(block, args[1], local);
                    format!("(({lhs}) = ({rhs}))")
                }
                FragPrim::I32LtS => {
                    let lhs = expr_fragment_i32_expr(block, args[0], local);
                    let rhs = expr_fragment_i32_expr(block, args[1], local);
                    format!("({lhs}) < ({rhs})")
                }
                FragPrim::I32GtS => {
                    let lhs = expr_fragment_i32_expr(block, args[0], local);
                    let rhs = expr_fragment_i32_expr(block, args[1], local);
                    format!("({lhs}) > ({rhs})")
                }
                FragPrim::I32GeS => {
                    let lhs = expr_fragment_i32_expr(block, args[0], local);
                    let rhs = expr_fragment_i32_expr(block, args[1], local);
                    format!("({lhs}) \u{2265} ({rhs})")
                }
                FragPrim::I32And => {
                    let lhs = expr_fragment_value_expr(block, args[0], local);
                    let rhs = expr_fragment_value_expr(block, args[1], local);
                    format!("(({lhs}) \u{2227} ({rhs}))")
                }
            }
        }
        FragNodeKind::HostCall { .. } => {
            unreachable!("host-free expr-fragment value renderer does not handle host calls")
        }
        FragNodeKind::SelfCall { .. } => {
            unreachable!("self-call is rendered by the fuel-recursion face, not the generic value renderer")
        }
        FragNodeKind::If {
            cond,
            then_block,
            else_block,
        } => {
            let c = expr_fragment_bool_expr(block, *cond, local);
            let t = expr_fragment_value_expr(then_block, then_block.result, local);
            let e = expr_fragment_value_expr(else_block, else_block.result, local);
            format!("if ({c}) then ({t}) else ({e})")
        }
    }
}

fn expr_fragment_bool_expr<F>(block: &FragBlock, id: FragValueId, local: &F) -> String
where
    F: Fn(u32, FragTy) -> String,
{
    let node = block.node(id).expect("fragment node exists");
    match &node.kind {
        FragNodeKind::Local { index } => local(*index, node.ty),
        FragNodeKind::ConstBool(v) => v.to_string(),
        FragNodeKind::RefIsNull { value } => {
            if matches!(
                block.node(*value).map(|node| &node.kind),
                Some(FragNodeKind::StructGet { field: 1, .. })
            ) {
                "true".to_string()
            } else {
                let v = expr_fragment_value_expr(block, *value, local);
                format!("{v} = WVal.null")
            }
        }
        FragNodeKind::Prim { op, args } => match op {
            FragPrim::F64Le => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("Float.ofBits ({lhs}) <= Float.ofBits ({rhs})")
            }
            FragPrim::F64Ge => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("Float.ofBits ({rhs}) <= Float.ofBits ({lhs})")
            }
            FragPrim::F64Lt => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("Float.ofBits ({lhs}) < Float.ofBits ({rhs})")
            }
            FragPrim::F64Gt => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("Float.ofBits ({rhs}) < Float.ofBits ({lhs})")
            }
            FragPrim::F64Eq => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("Float.ofBits ({lhs}) == Float.ofBits ({rhs})")
            }
            FragPrim::I64Eq => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("({lhs}) = ({rhs})")
            }
            FragPrim::I64LeS => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("({lhs}) <= ({rhs})")
            }
            FragPrim::I64LtS => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("({lhs}) < ({rhs})")
            }
            FragPrim::I64GeS => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("({rhs}) <= ({lhs})")
            }
            FragPrim::I64GtS => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("({rhs}) < ({lhs})")
            }
            FragPrim::I32Eq => {
                let lhs = expr_fragment_i32_expr(block, args[0], local);
                let rhs = expr_fragment_i32_expr(block, args[1], local);
                format!("decide (({lhs}) = ({rhs}))")
            }
            FragPrim::I32LtS => {
                let lhs = expr_fragment_i32_expr(block, args[0], local);
                let rhs = expr_fragment_i32_expr(block, args[1], local);
                format!("({lhs}) < ({rhs})")
            }
            FragPrim::I32GtS => {
                let lhs = expr_fragment_i32_expr(block, args[0], local);
                let rhs = expr_fragment_i32_expr(block, args[1], local);
                format!("({lhs}) > ({rhs})")
            }
            FragPrim::I32GeS => {
                let lhs = expr_fragment_i32_expr(block, args[0], local);
                let rhs = expr_fragment_i32_expr(block, args[1], local);
                format!("({lhs}) \u{2265} ({rhs})")
            }
            // Both operands are `BoolI32` by the checker's strict typing, so
            // the source reading is plain conjunction of the operand readings
            // (matching the wall interpreter's {0,1}-domain `.i32And` clause).
            FragPrim::I32And => {
                let lhs = expr_fragment_value_expr(block, args[0], local);
                let rhs = expr_fragment_value_expr(block, args[1], local);
                format!("(({lhs}) \u{2227} ({rhs}))")
            }
            FragPrim::F64Add | FragPrim::F64Mul => {
                unreachable!("numeric primitive cannot produce BoolI32")
            }
        },
        FragNodeKind::If {
            cond,
            then_block,
            else_block,
        } => {
            let c = expr_fragment_bool_expr(block, *cond, local);
            let t = expr_fragment_bool_expr(then_block, then_block.result, local);
            let e = expr_fragment_bool_expr(else_block, else_block.result, local);
            format!("if ({c}) then ({t}) else ({e})")
        }
        FragNodeKind::ConstI64(_)
        | FragNodeKind::ConstI32(_)
        | FragNodeKind::ConstF64(_)
        | FragNodeKind::HostCall { .. }
        | FragNodeKind::SelfCall { .. }
        | FragNodeKind::StructGet { .. }
        | FragNodeKind::StructGetUser { .. }
        | FragNodeKind::VectorGetOrDefault { .. } => unreachable!("node is not BoolI32"),
    }
}

fn expr_fragment_i32_expr<F>(block: &FragBlock, id: FragValueId, local: &F) -> String
where
    F: Fn(u32, FragTy) -> String,
{
    let node = block.node(id).expect("fragment node exists");
    match node.ty {
        FragTy::RawI32 => expr_fragment_typed_value_expr(block, id, local),
        FragTy::BoolI32 => {
            let b = expr_fragment_bool_expr(block, id, local);
            format!("if ({b}) then (1 : Int) else (0 : Int)")
        }
        _ => unreachable!("node is not an i32 value"),
    }
}

fn expr_fragment_simp_tactic(plan: &ExprFragmentPlan, evalset: &str) -> String {
    let mut steps = plan
        .params
        .iter()
        .enumerate()
        .filter(|(_, ty)| **ty == FragTy::BoolI32)
        .map(|(i, _)| format!("cases a{i}"))
        .collect::<Vec<_>>();
    let mut conds = Vec::new();
    collect_expr_fragment_conditions(&plan.body, &|idx, _ty| format!("a{idx}"), &mut conds);
    for (i, cond) in conds.iter().enumerate() {
        steps.push(format!("by_cases h{i} : {cond}"));
    }
    let hints = if conds.is_empty() {
        String::new()
    } else {
        format!(
            ", {}",
            (0..conds.len())
                .map(|i| format!("h{i}"))
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    if steps.is_empty() {
        format!("  simp [{evalset}, carrierSmall, ge_iff_le]")
    } else {
        format!(
            "  {} <;> simp [{evalset}, carrierSmall, ge_iff_le{hints}]",
            steps.join(" <;> ")
        )
    }
}

fn collect_expr_fragment_conditions<F>(block: &FragBlock, local: &F, out: &mut Vec<String>)
where
    F: Fn(u32, FragTy) -> String,
{
    for node in &block.nodes {
        match &node.kind {
            FragNodeKind::Prim {
                op:
                    FragPrim::F64Le
                    | FragPrim::F64Ge
                    | FragPrim::F64Lt
                    | FragPrim::F64Gt
                    | FragPrim::F64Eq
                    | FragPrim::I64Eq
                    | FragPrim::I64LeS
                    | FragPrim::I64LtS
                    | FragPrim::I64GeS
                    | FragPrim::I64GtS
                    | FragPrim::I32Eq
                    | FragPrim::I32LtS
                    | FragPrim::I32GtS,
                ..
            } => {
                let cond = expr_fragment_value_expr(block, node.id, local);
                if !out.contains(&cond) {
                    out.push(cond);
                }
            }
            FragNodeKind::If {
                then_block,
                else_block,
                ..
            } => {
                collect_expr_fragment_conditions(then_block, local, out);
                collect_expr_fragment_conditions(else_block, local, out);
            }
            _ => {}
        }
    }
}

fn lean_u64_hex(bits: u64) -> String {
    format!("0x{bits:016x}")
}