Repository navigation
Expand file tree
/
Copy pathIRInterpreter.lean
More file actions
6055 lines (5610 loc) · 291 KB
/
Copy pathIRInterpreter.lean
File metadata and controls
6055 lines (5610 loc) · 291 KB
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/-
IRInterpreter: Execution semantics for IR (Yul-based intermediate representation)
This defines how IR contracts execute, enabling proofs that spec→IR compilation preserves semantics.
Key differences from SpecInterpreter:
- IR uses Yul expressions (ident, call) instead of high-level Spec expressions (storage, param)
- IR has explicit variables and assignment instead of automatic scoping
- IR is lower-level but simpler to reason about than full spec interpreter
All functions in this module are **total** (no `partial` annotations):
- Expression evaluators use structural recursion on expression size (exprSize/exprsSize)
- Statement executors use an explicit fuel parameter
-/
import Compiler.IR
import Compiler.CompilationModel
import Compiler.Proofs.IRGeneration.IRRuntimeTypes
import Compiler.Proofs.IRGeneration.IRStorageWord
import Compiler.Proofs.MappingSlot
import Compiler.Proofs.YulGeneration.LogNames
import Compiler.Proofs.IRGeneration.Returndata
import Compiler.Proofs.YulGeneration.Backends.EvmYulLeanBuiltinSemantics
import Compiler.Proofs.YulGeneration.Backends.EvmYulLeanPureBuiltinLemmas
import Compiler.Keccak.Sponge
import Verity.Core
-- The Layer A log-cross-cast theorems (IRStmtPreservesObsAt_of_log0..log4)
-- use `simp` with `applyYulLogCall?` and other simp lemmas that the
-- `linter.unusedSimpArgs` may flag as unused even when load-bearing,
-- because they're consumed by simp's match-reduction rather than direct
-- rewrites. Disable for this file, matching the precedent in
-- Compiler.Proofs.IRGeneration.Function.lean (line 11).
set_option linter.unusedSimpArgs false
namespace Compiler.Proofs.IRGeneration
open Compiler
open Compiler.Yul
open Verity.Core
open Compiler.Proofs
export Compiler.Proofs.YulGeneration (isYulLogName)
/-! Size measures for termination proofs. -/
mutual
def exprSize : YulExpr → Nat
| .call _ args => exprsSize args + 2
| _ => 1
def exprsSize : List YulExpr → Nat
| [] => 0
| e :: es => exprSize e + exprsSize es + 1
end
private theorem exprSize_lt_exprsSize_cons (e : YulExpr) (es : List YulExpr) :
exprSize e < exprsSize (e :: es) := by
simp only [exprsSize]
omega
private theorem exprsSize_tail_lt_exprsSize_cons (e : YulExpr) (es : List YulExpr) :
exprsSize es < exprsSize (e :: es) := by
simp only [exprsSize]
omega
private theorem exprsSize_lt_exprSize_call (func : String) (args : List YulExpr) :
exprsSize args < exprSize (.call func args) := by
simp [exprSize]
private theorem exprs_head_measure_decreases (fuel : Nat) (e : YulExpr) (es : List YulExpr) :
Prod.Lex (fun x y => x < y) (fun x y => x < y)
(fuel, exprSize e) (fuel, exprsSize (e :: es)) := by
rw [Prod.lex_iff]
exact Or.inr ⟨rfl, exprSize_lt_exprsSize_cons e es⟩
private theorem exprs_tail_measure_decreases (fuel : Nat) (e : YulExpr) (es : List YulExpr) :
Prod.Lex (fun x y => x < y) (fun x y => x < y)
(fuel, exprsSize es) (fuel, exprsSize (e :: es)) := by
rw [Prod.lex_iff]
exact Or.inr ⟨rfl, exprsSize_tail_lt_exprsSize_cons e es⟩
private theorem expr_call_measure_decreases (fuel : Nat) (func : String) (args : List YulExpr) :
Prod.Lex (fun x y => x < y) (fun x y => x < y)
(fuel, exprsSize args + 1) (fuel, exprSize (.call func args)) := by
rw [Prod.lex_iff]
simp [exprSize]
private theorem pairLex_same_fst_succ (a b : Nat) :
Prod.Lex (fun x y => x < y) (fun x y => x < y) (a, b) (a, b + 1) := by
rw [Prod.lex_iff]
omega
private theorem internal_call_measure_decreases (fuel measure : Nat) :
Prod.Lex (fun x y => x < y) (fun x y => x < y) (fuel, 0) (fuel.succ, measure + 1) := by
rw [Prod.lex_iff]
exact Or.inl (Nat.lt_succ_self fuel)
/-! ## Execution State Helpers -/
def byteWordCount (size : Nat) : Nat :=
(size + 31) / 32
/-- Word reads wrap the byte offset mod `2^256`, matching EVM `UInt256`
address arithmetic (compiled code computes scratch offsets with the wrapping
`add` builtin, so reads must land on the same keys as the stores). -/
def memorySliceWords (memory : Nat → Nat) (offset size : Nat) : List Nat :=
(List.range (byteWordCount size)).map
(fun i => memory ((offset + i * 32) % Compiler.Constants.evmModulus))
/-- Big-endian 32-byte encoding of a proof-IR memory word. -/
def irWordToBytesBE (word : Nat) : ByteArray :=
⟨((List.range 32).map
(fun index => UInt8.ofNat ((word / (256 ^ (31 - index))) % 256))).toArray⟩
/-- Exact byte slice read by `keccak256(offset, size)` from the proof IR's
word-addressed memory. Verity emits word-aligned memory regions, so each
successive cell is based at `offset + 32 * index`; the final cell is truncated
to the requested byte length. -/
def irMemorySliceBytesBE (memory : Nat → Nat) (offset size : Nat) : ByteArray :=
let bytes := (memorySliceWords memory offset size).foldl
(fun acc word => acc ++ irWordToBytesBE word)
ByteArray.empty
bytes.extract 0 size
/-- Proof-side model of `keccak256(offset, size)` over linear memory, using
the in-tree Ethereum Keccak implementation on the exact requested byte slice. -/
def abstractKeccakMemorySlice (memory : Nat → Nat) (offset size : Nat) : Nat :=
KeccakEngine.byteArrayToNatBE
(KeccakEngine.keccak256 (irMemorySliceBytesBE memory offset size)) %
Compiler.Constants.evmModulus
/-- Read the word-aligned memory payload that a Yul `log*` instruction records.
The proof IR models log data at word granularity, so byte sizes are truncated to
complete 32-byte words. -/
def yulLogDataWords (memory : Nat → Nat) (offset size : Nat) : List Nat :=
(List.range (size / 32)).map
(fun i => memory ((offset + i * 32) % Compiler.Constants.evmModulus))
/-- Canonical proof-side encoding of a Yul log entry: topics followed by the
word-aligned data payload. -/
def encodeYulLogEvent (memory : Nat → Nat) (offset size : Nat)
(topics : List Nat) : List Nat :=
topics ++ yulLogDataWords memory offset size
def IRState.appendYulLog (s : IRState) (offset size : Nat)
(topics : List Nat) : IRState :=
{ s with events := s.events ++ [encodeYulLogEvent s.memory offset size topics] }
def applyYulLogCall? (state : IRState) (func : String)
(argVals : List Nat) : Option IRState :=
match func, argVals with
| "log0", [offset, size] =>
some (state.appendYulLog offset size [])
| "log1", [offset, size, topic0] =>
some (state.appendYulLog offset size [topic0])
| "log2", [offset, size, topic0, topic1] =>
some (state.appendYulLog offset size [topic0, topic1])
| "log3", [offset, size, topic0, topic1, topic2] =>
some (state.appendYulLog offset size [topic0, topic1, topic2])
| "log4", [offset, size, topic0, topic1, topic2, topic3] =>
some (state.appendYulLog offset size [topic0, topic1, topic2, topic3])
| _, _ => none
@[simp] theorem applyYulLogCall?_log0
(state : IRState) (offset size : Nat) :
applyYulLogCall? state "log0" [offset, size] =
some (state.appendYulLog offset size []) := rfl
@[simp] theorem applyYulLogCall?_log1
(state : IRState) (offset size topic0 : Nat) :
applyYulLogCall? state "log1" [offset, size, topic0] =
some (state.appendYulLog offset size [topic0]) := rfl
@[simp] theorem applyYulLogCall?_log2
(state : IRState) (offset size topic0 topic1 : Nat) :
applyYulLogCall? state "log2" [offset, size, topic0, topic1] =
some (state.appendYulLog offset size [topic0, topic1]) := rfl
@[simp] theorem applyYulLogCall?_log3
(state : IRState) (offset size topic0 topic1 topic2 : Nat) :
applyYulLogCall? state "log3" [offset, size, topic0, topic1, topic2] =
some (state.appendYulLog offset size [topic0, topic1, topic2]) := rfl
@[simp] theorem applyYulLogCall?_log4
(state : IRState) (offset size topic0 topic1 topic2 topic3 : Nat) :
applyYulLogCall? state "log4" [offset, size, topic0, topic1, topic2, topic3] =
some (state.appendYulLog offset size [topic0, topic1, topic2, topic3]) := rfl
@[simp] theorem IRState.appendYulLog_events
(s : IRState) (offset size : Nat) (topics : List Nat) :
(s.appendYulLog offset size topics).events =
s.events ++ [encodeYulLogEvent s.memory offset size topics] := rfl
/-- Decoded internal helper definition from `IRContract.internalFunctions`. -/
structure IRInternalFunctionDef where
name : String
params : List String
rets : List String
body : List YulStmt
/-- View a stored internal-function statement as a decoded helper definition. -/
def irInternalFunctionDefOfStmt? : YulStmt → Option IRInternalFunctionDef
| .funcDef name params rets body => some { name, params, rets, body }
| _ => none
/-- Look up a helper function in the contract-local internal function table. -/
def findInternalFunction? (contract : IRContract) (name : String) :
Option IRInternalFunctionDef :=
(contract.internalFunctions.filterMap irInternalFunctionDefOfStmt?).find? (fun fn => fn.name = name)
/-- Helper-aware expression evaluation result, which can thread stateful helper-call
effects or propagate control-flow effects out of expression position. -/
inductive IRExprEvalResult
| value (value : Nat) (state : IRState)
| stop (state : IRState)
| return (value : Nat) (state : IRState)
| revert (state : IRState)
deriving Nonempty
/-- Helper-aware call / argument-list evaluation result, carrying either a list of
values or an early control-flow effect. -/
inductive IRValuesEvalResult
| values (values : List Nat) (state : IRState)
| stop (state : IRState)
| return (value : Nat) (state : IRState)
| revert (state : IRState)
deriving Nonempty
/-- Helper-aware statement execution result. `leave` is propagated explicitly so
internal Yul helper bodies can exit without aborting the whole external function. -/
inductive IRExecResultWithInternals
| continue (state : IRState)
| return (value : Nat) (state : IRState)
| stop (state : IRState)
| revert (state : IRState)
| leave (state : IRState)
deriving Nonempty
/-! ## IR Expression Evaluation (Total)
Expression evaluators use structural recursion on expression size, matching the
pattern already used by `evalYulExpr` in `Semantics.lean`. The `exprSize`/`exprsSize`
measures from Semantics.lean are reused.
-/
/-!
Runtime Yul mapping slots are derived via `keccak(baseSlot, key)`. IR proof
semantics call through `MappingSlot`; the active proof backend is `keccak`
(see `activeMappingSlotBackend`), so mapping addressing in `mappingSlot`/`sload`/
`sstore` follows Solidity's flat keccak-derived storage slots.
-/
mutual
/-- Evaluate a list of Yul expressions in the IR context.
Total: uses `exprsSize` for termination (structural recursion on expression tree). -/
def evalIRExprs (state : IRState) : List YulExpr → Option (List Nat)
| [] => some []
| e :: es => do
let v ← evalIRExpr state e
let vs ← evalIRExprs state es
pure (v :: vs)
termination_by es => exprsSize es
decreasing_by
all_goals
simp only [exprsSize]
omega
/-- Evaluate an IR function call by evaluating all arguments first, then dispatching.
Total: uses `exprsSize args + 1` for termination. Evaluating args decreases the measure.
NOTE: This function always evaluates all arguments via `evalIRExprs` before dispatching,
matching the structure of `evalYulCall` in Semantics.lean. For `sload`, mapping slot
routing uses `Compiler.Proofs.abstractDecodeMappingSlot` on the evaluated slot value
(not pattern-matching on the argument expression). This makes the function structurally
identical to the Yul version, enabling direct equivalence proofs without axioms. -/
def evalIRCall (state : IRState) (func : String) : List YulExpr → Option Nat
| args => do
let argVals ← evalIRExprs state args
if func = "tload" then
match argVals with
| [slot] => some (state.transientStorage (slot % Compiler.Constants.evmModulus))
| _ => none
else if func = "mload" then
match argVals with
| [offset] => some (state.memory offset)
| _ => none
else if func = "extcodesize" then
match argVals with
| [addr] => some (state.codeSize (addr % Compiler.Constants.addressModulus))
| _ => none
else if func = "returndatasize" then
match argVals with
| [] => some (32 * state.returndata.length % Compiler.Constants.evmModulus)
| _ => none
else if func = "keccak256" then
match argVals with
| [offset, size] => some (abstractKeccakMemorySlice state.memory offset size)
| _ => none
else
Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallWithEvmYulLeanContext
state.storage state.sender state.msgValue state.thisAddress state.blockTimestamp
state.blockNumber state.chainId state.blobBaseFee state.txOrigin state.selector state.calldata func argVals
termination_by args => exprsSize args + 1
decreasing_by
omega
/-- Evaluate a Yul expression in the IR context.
Total: uses `exprSize` for termination (structural recursion on expression tree). -/
def evalIRExpr (state : IRState) : YulExpr → Option Nat
| .lit n => some n
| .hex n => some n
| .str _ => none -- Strings not supported in our IR subset
| .ident name => state.getVar name
| .call func args => evalIRCall state func args
termination_by e => exprSize e
decreasing_by
simp [exprSize]
end -- mutual
@[simp] theorem evalIRCall_tload_singleton
(state : IRState) (argExpr : YulExpr) :
evalIRCall state "tload" [argExpr] =
(evalIRExpr state argExpr).bind
(fun slot => some (state.transientStorage (slot % Compiler.Constants.evmModulus))) := by
simp [evalIRCall, evalIRExprs]
cases evalIRExpr state argExpr with
| none => simp
| some val => simp
@[simp] theorem evalIRCall_mload_singleton
(state : IRState) (argExpr : YulExpr) :
evalIRCall state "mload" [argExpr] =
(evalIRExpr state argExpr).bind
(fun offset => some (state.memory offset)) := by
simp [evalIRCall, evalIRExprs]
cases evalIRExpr state argExpr with
| none => simp
| some val => simp
@[simp] theorem evalIRCall_extcodesize_singleton
(state : IRState) (argExpr : YulExpr) :
evalIRCall state "extcodesize" [argExpr] =
(evalIRExpr state argExpr).bind
(fun addr => some (state.codeSize (addr % Compiler.Constants.addressModulus))) := by
simp [evalIRCall, evalIRExprs]
cases evalIRExpr state argExpr with
| none => simp
| some val => simp
@[simp] theorem evalIRCall_returndatasize_nil
(state : IRState) :
evalIRCall state "returndatasize" [] =
some (32 * state.returndata.length % Compiler.Constants.evmModulus) := by
simp [evalIRCall, evalIRExprs]
@[simp] theorem evalIRExpr_returndatasize_nil
(state : IRState) :
evalIRExpr state (YulExpr.call "returndatasize" []) =
some (32 * state.returndata.length % Compiler.Constants.evmModulus) := by
simp [evalIRExpr]
@[simp] theorem evalIRCall_calldataload_singleton
(state : IRState) (argExpr : YulExpr) :
evalIRCall state "calldataload" [argExpr] =
(evalIRExpr state argExpr).bind
(fun offset => some (Compiler.Proofs.YulGeneration.calldataloadWord
state.selector state.calldata offset)) := by
simp [evalIRCall, evalIRExprs,
Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallWithEvmYulLeanContext,
Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallViaEvmYulLean]
cases evalIRExpr state argExpr with
| none => simp
| some val => simp
@[simp] theorem evalIRCall_sload_singleton
(state : IRState) (argExpr : YulExpr) :
evalIRCall state "sload" [argExpr] =
(evalIRExpr state argExpr).bind
(fun slot => some (Compiler.Proofs.abstractLoadStorageOrMapping state.storage slot).toNat) := by
simp [evalIRCall, evalIRExprs,
Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallWithEvmYulLeanContext,
Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallViaEvmYulLean,
Compiler.Proofs.abstractLoadStorageOrMapping]
cases evalIRExpr state argExpr with
| none => simp
| some val => simp
def restoreCallerVars (callerState calleeState : IRState) : IRState :=
{ calleeState with vars := callerState.vars }
def internalReturnValues (state : IRState) (retNames : List String) : List Nat :=
retNames.map (fun name => (state.getVar name).getD 0)
/-- Internal helper calls execute with a fresh local-variable frame. They keep the
caller's storage / memory / transaction context, but only helper params and
declared return slots are in scope at function entry. -/
def prepareInternalCalleeState
(callerState : IRState) (helper : IRInternalFunctionDef) (args : List Nat) : IRState :=
let paramBindings := helper.params.zip args
let retBindings := helper.rets.map (fun name => (name, 0))
{ callerState with vars := [] }.setVars (paramBindings ++ retBindings)
@[simp] theorem prepareInternalCalleeState_vars
(callerState : IRState) (helper : IRInternalFunctionDef) (args : List Nat) :
(prepareInternalCalleeState callerState helper args).vars =
({ callerState with vars := [] }.setVars
(helper.params.zip args ++ helper.rets.map (fun name => (name, 0)))).vars := by
simp only [prepareInternalCalleeState]
/-- Legacy IR-theorem compatibility subset for external bodies. This excludes the
helper-only Yul forms whose semantics differ from the current helper-free
interpreter target (`letMany`, `leave`, and `switch`) while still allowing
nested blocks, branches, and structurally compatible loops so the
conservative-extension theorem can talk about today's compiled external-body
shape explicitly. -/
inductive LegacyCompatibleExternalStmtList : List YulStmt → Prop
| nil :
LegacyCompatibleExternalStmtList []
| comment (msg : String) (rest : List YulStmt) :
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.comment msg :: rest)
| let_ (name : String) (value : YulExpr) (rest : List YulStmt) :
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.let_ name value :: rest)
| assign (name : String) (value : YulExpr) (rest : List YulStmt) :
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.assign name value :: rest)
| exprStmt (value : YulExpr) (rest : List YulStmt) :
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.exprStmt value :: rest)
| if_ (cond : YulExpr) (body rest : List YulStmt) :
LegacyCompatibleExternalStmtList body →
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.if_ cond body :: rest)
| block (body rest : List YulStmt) :
LegacyCompatibleExternalStmtList body →
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.block body :: rest)
| for_ (init : List YulStmt) (cond : YulExpr) (post body rest : List YulStmt) :
LegacyCompatibleExternalStmtList init →
LegacyCompatibleExternalStmtList post →
LegacyCompatibleExternalStmtList body →
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.for_ init cond post body :: rest)
| funcDef (name : String) (params rets : List String) (body rest : List YulStmt) :
LegacyCompatibleExternalStmtList body →
LegacyCompatibleExternalStmtList rest →
LegacyCompatibleExternalStmtList (.funcDef name params rets body :: rest)
abbrev LegacyCompatibleExternalStmt (stmt : YulStmt) : Prop :=
LegacyCompatibleExternalStmtList [stmt]
/-- Weaker compiled-side witness: only the externally callable function bodies
remain inside the current legacy-compatible Yul subset. This is the witness that
is plausibly derivable from supported external compile outputs even when the full
compiled contract still carries internal helper definitions. -/
def LegacyCompatibleExternalBodies (contract : IRContract) : Prop :=
∀ fn ∈ contract.functions, LegacyCompatibleExternalStmtList fn.body
mutual
/-- Evaluate a list of Yul expressions in the helper-aware IR context, threading
stateful internal helper effects left-to-right. -/
def evalIRExprsWithInternals
(contract : IRContract) (fuel : Nat) (state : IRState) :
List YulExpr → IRValuesEvalResult
| [] => .values [] state
| e :: es =>
match evalIRExprWithInternals contract fuel state e with
| .value v state' =>
match evalIRExprsWithInternals contract fuel state' es with
| .values vs state'' => .values (v :: vs) state''
| .stop state'' => .stop state''
| .return value state'' => .return value state''
| .revert state'' => .revert state''
| .stop state' => .stop state'
| .return value state' => .return value state'
| .revert state' => .revert state'
termination_by exprs => (fuel, exprsSize exprs)
decreasing_by
any_goals exact exprs_head_measure_decreases fuel e es
any_goals exact exprs_tail_measure_decreases fuel e es
/-- Execute a contract-local helper call, propagating control-flow effects and
restoring the caller's local variable frame on all non-revert exits. -/
def execIRInternalFunctionWithInternals
(contract : IRContract) :
Nat → IRState → IRInternalFunctionDef → List Nat → IRValuesEvalResult
| 0, callerState, _helper, _args => .revert callerState
| Nat.succ fuel', callerState, helper, args =>
if helper.params.length = args.length then
let calleeState := prepareInternalCalleeState callerState helper args
match execIRStmtsWithInternals contract fuel' calleeState helper.body with
| .continue finalState =>
.values (internalReturnValues finalState helper.rets)
(restoreCallerVars callerState finalState)
| .leave finalState =>
.values (internalReturnValues finalState helper.rets)
(restoreCallerVars callerState finalState)
| .stop finalState =>
.stop (restoreCallerVars callerState finalState)
| .return value finalState =>
.return value (restoreCallerVars callerState finalState)
| .revert _ =>
.revert callerState
else
.revert callerState
termination_by fuel => (fuel, 0)
decreasing_by all_goals simp_wf; all_goals omega
/-- Evaluate a Yul call in the helper-aware IR context. Builtins remain pure, while
internal helper calls execute through `IRContract.internalFunctions`. -/
def evalIRCallWithInternals
(contract : IRContract) (fuel : Nat) (state : IRState) (func : String) :
List YulExpr → IRValuesEvalResult
| args =>
match evalIRExprsWithInternals contract fuel state args with
| .values argVals state' =>
match findInternalFunction? contract func with
| some helper =>
match fuel with
| 0 => .revert state'
| Nat.succ fuel' =>
execIRInternalFunctionWithInternals contract fuel' state' helper argVals
| none =>
if func = "tload" then
match argVals with
| [slot] => .values [state'.transientStorage (slot % Compiler.Constants.evmModulus)] state'
| _ => .revert state'
else if func = "extcodesize" then
match argVals with
| [addr] => .values [state'.codeSize (addr % Compiler.Constants.addressModulus)] state'
| _ => .revert state'
else if func = "mload" then
match argVals with
| [offset] => .values [state'.memory offset] state'
| _ => .revert state'
else if func = "returndatasize" then
match argVals with
| [] => .values [32 * state'.returndata.length % Compiler.Constants.evmModulus] state'
| _ => .revert state'
else if func = "keccak256" then
match argVals with
| [offset, size] => .values [abstractKeccakMemorySlice state'.memory offset size] state'
| _ => .revert state'
else
match Compiler.Proofs.YulGeneration.Backends.evalBuiltinCallWithEvmYulLeanContext
state'.storage state'.sender state'.msgValue state'.thisAddress
state'.blockTimestamp state'.blockNumber state'.chainId state'.blobBaseFee
state'.txOrigin state'.selector state'.calldata func argVals with
| some value => .values [value] state'
| none => .revert state'
| .stop state' => .stop state'
| .return value state' => .return value state'
| .revert state' => .revert state'
termination_by args => (fuel, exprsSize args + 1)
decreasing_by
any_goals exact pairLex_same_fst_succ fuel (exprsSize args)
any_goals exact internal_call_measure_decreases fuel' _
/-- Evaluate a single expression in the helper-aware IR context. -/
def evalIRExprWithInternals
(contract : IRContract) (fuel : Nat) (state : IRState) :
YulExpr → IRExprEvalResult
| .lit n => .value n state
| .hex n => .value n state
| .str _ => .revert state
| .ident name =>
match state.getVar name with
| some value => .value value state
| none => .revert state
| .call func args =>
match evalIRCallWithInternals contract fuel state func args with
| .values [value] state' => .value value state'
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value state' => .return value state'
| .revert state' => .revert state'
termination_by expr => (fuel, exprSize expr)
decreasing_by
exact expr_call_measure_decreases fuel func args
/-- Execute a single Yul statement in the helper-aware IR context. -/
def execIRStmtWithInternals
(contract : IRContract) :
Nat → IRState → YulStmt → IRExecResultWithInternals
| _, state, .funcDef _ _ _ _ => .continue state
| 0, state, _ => .revert state
| Nat.succ fuel, state, stmt =>
match stmt with
| .comment _ => .continue state
| .let_ name value =>
match evalIRExprWithInternals contract fuel state value with
| .value v state' => .continue (state'.setVar name v)
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .letMany names value =>
match value with
| .call func args =>
match evalIRCallWithInternals contract fuel state func args with
| .values values state' =>
if names.length = values.length then
.continue (state'.setVars (names.zip values))
else
.revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| _ => .revert state
| .assign name value =>
match evalIRExprWithInternals contract fuel state value with
| .value v state' => .continue (state'.setVar name v)
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .leave => .leave state
| .exprStmt e =>
match e with
| .call "sstore" [slotExpr, valExpr] =>
match slotExpr with
| .call "mappingSlot" [baseExpr, keyExpr] =>
match evalIRExprWithInternals contract fuel state baseExpr with
| .value baseSlot state' =>
match evalIRExprWithInternals contract fuel state' keyExpr with
| .value key state'' =>
match evalIRExprWithInternals contract fuel state'' valExpr with
| .value val state''' =>
let updated := Compiler.Proofs.abstractStoreMappingEntry
state'''.storage baseSlot key val
.continue { state''' with storage := updated }
| .stop state''' => .stop state'''
| .return value' state''' => .return value' state'''
| .revert state''' => .revert state'''
| .stop state'' => .stop state''
| .return value' state'' => .return value' state''
| .revert state'' => .revert state''
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| _ =>
match evalIRExprsWithInternals contract fuel state [slotExpr, valExpr] with
| .values [slot, val] state' =>
let updated := Compiler.Proofs.abstractStoreStorageOrMapping state'.storage slot val
.continue { state' with storage := updated }
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "mstore" [offsetExpr, valExpr] =>
match evalIRExprsWithInternals contract fuel state [offsetExpr, valExpr] with
| .values [offset, val] state' =>
.continue (state'.writePhysicalMemoryValue
(Verity.Core.Uint256.ofNat offset).val val)
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "tstore" [offsetExpr, valExpr] =>
match evalIRExprsWithInternals contract fuel state [offsetExpr, valExpr] with
| .values [offset, val] state' =>
let offset := offset % Compiler.Constants.evmModulus
.continue {
state' with
transientStorage := fun o =>
if o = offset then val else state'.transientStorage o
}
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "calldatacopy" [dstExpr, srcExpr, sizeExpr] =>
match evalIRExprsWithInternals contract fuel state [dstExpr, srcExpr, sizeExpr] with
| .values [dst, src, size] state' =>
.continue {
state' with
memory := Compiler.Proofs.YulGeneration.calldatacopyMemory
state'.selector state'.calldata dst src size state'.memory
}
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "returndatacopy" [dstExpr, srcExpr, sizeExpr] =>
match evalIRExprsWithInternals contract fuel state [dstExpr, srcExpr, sizeExpr] with
| .values [dst, src, size] state' =>
if src + size ≤ 32 * state'.returndata.length then
.continue {
state' with
memory := Compiler.Proofs.IRGeneration.returndatacopyMemoryPadded
state'.returndata dst src size state'.memory
}
else .revert state'
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "stop" [] => .stop state
| .call "revert" [offsetExpr, sizeExpr] =>
match evalIRExprsWithInternals contract fuel state [offsetExpr, sizeExpr] with
| .values [_, _] state' => .revert state'
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "return" [offsetExpr, sizeExpr] =>
match evalIRExprsWithInternals contract fuel state [offsetExpr, sizeExpr] with
| .values [offset, size] state' =>
if size = 32 then
.return (state'.memory offset) state'
else
.return 0 state'
| .values _ state' => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call "invalid" [] => .revert state
| .call "selfdestruct" [addrExpr] =>
match evalIRExprsWithInternals contract fuel state [addrExpr] with
| .values _ state' => .stop state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .call func args =>
if isYulLogName func then
match evalIRExprsWithInternals contract fuel state args with
| .values argVals state' =>
match applyYulLogCall? state' func argVals with
| some next => .continue next
| none => .revert state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
else
-- Use evalIRCallWithInternals directly so that void internal
-- helpers (returning 0 values) succeed instead of reverting
-- through the single-value filter in evalIRExprWithInternals.
match evalIRCallWithInternals contract fuel state func args with
| .values _ state' => .continue state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| _ =>
match evalIRExprWithInternals contract fuel state e with
| .value _ state' => .continue state'
| .stop state' => .stop state'
| .return value' state' => .return value' state'
| .revert state' => .revert state'
| .if_ cond body =>
match evalIRExprWithInternals contract fuel state cond with
| .value condValue state' =>
if condValue ≠ 0 then
execIRStmtsWithInternals contract fuel state' body
else
.continue state'
| .stop state' => .stop state'
| .return value state' => .return value state'
| .revert state' => .revert state'
| .switch expr cases defaultCase =>
match evalIRExprWithInternals contract fuel state expr with
| .value switchValue state' =>
match cases.find? (·.1 == switchValue) with
| some (_, body) => execIRStmtsWithInternals contract fuel state' body
| none =>
match defaultCase with
| some body => execIRStmtsWithInternals contract fuel state' body
| none => .continue state'
| .stop state' => .stop state'
| .return value state' => .return value state'
| .revert state' => .revert state'
| .for_ init cond post body =>
match execIRStmtsWithInternals contract fuel state init with
| .continue state' =>
match evalIRExprWithInternals contract fuel state' cond with
| .value condValue state'' =>
if condValue ≠ 0 then
match execIRStmtsWithInternals contract fuel state'' body with
| .continue state''' =>
match execIRStmtsWithInternals contract fuel state''' post with
| .continue state'''' =>
execIRStmtWithInternals contract fuel state'''' (.for_ [] cond post body)
| .return value state'''' => .return value state''''
| .stop state'''' => .stop state''''
| .revert state'''' => .revert state''''
| .leave state'''' => .leave state''''
| .return value state''' => .return value state'''
| .stop state''' => .stop state'''
| .revert state''' => .revert state'''
| .leave state''' => .leave state'''
else
.continue state''
| .stop state'' => .stop state''
| .return value state'' => .return value state''
| .revert state'' => .revert state''
| .return value state' => .return value state'
| .stop state' => .stop state'
| .revert state' => .revert state'
| .leave state' => .leave state'
| .block stmts =>
execIRStmtsWithInternals contract fuel state stmts
| .funcDef _ _ _ _ => .continue state
termination_by fuel => (fuel, 0)
decreasing_by all_goals simp_wf; all_goals omega
/-- Execute a list of statements in the helper-aware IR context. -/
def execIRStmtsWithInternals
(contract : IRContract) (fuel : Nat) (state : IRState) :
List YulStmt → IRExecResultWithInternals
| [] => .continue state
| stmt :: rest =>
match fuel with
| 0 => .revert state
| Nat.succ fuel' =>
match execIRStmtWithInternals contract fuel' state stmt with
| .continue state' => execIRStmtsWithInternals contract fuel' state' rest
| .return value state' => .return value state'
| .stop state' => .stop state'
| .revert state' => .revert state'
| .leave state' => .leave state'
termination_by stmts => (fuel, stmts.length)
decreasing_by all_goals simp_wf; all_goals omega
end
theorem execIRStmtWithInternals_log0_of_eval_args
{contract : IRContract}
{fuel : Nat}
{state state' : IRState}
{args : List YulExpr}
{offset size : Nat}
(heval :
evalIRExprsWithInternals contract fuel state args =
.values [offset, size] state') :
execIRStmtWithInternals contract (Nat.succ fuel) state
(YulStmt.exprStmt (YulExpr.call "log0" args)) =
.continue (state'.appendYulLog offset size []) := by
simp [execIRStmtWithInternals, isYulLogName, heval]
theorem execIRStmtWithInternals_log1_of_eval_args
{contract : IRContract}
{fuel : Nat}
{state state' : IRState}
{args : List YulExpr}
{offset size topic0 : Nat}
(heval :
evalIRExprsWithInternals contract fuel state args =
.values [offset, size, topic0] state') :
execIRStmtWithInternals contract (Nat.succ fuel) state
(YulStmt.exprStmt (YulExpr.call "log1" args)) =
.continue (state'.appendYulLog offset size [topic0]) := by
simp [execIRStmtWithInternals, isYulLogName, heval]
theorem execIRStmtWithInternals_log2_of_eval_args
{contract : IRContract}
{fuel : Nat}
{state state' : IRState}
{args : List YulExpr}
{offset size topic0 topic1 : Nat}
(heval :
evalIRExprsWithInternals contract fuel state args =
.values [offset, size, topic0, topic1] state') :
execIRStmtWithInternals contract (Nat.succ fuel) state
(YulStmt.exprStmt (YulExpr.call "log2" args)) =
.continue (state'.appendYulLog offset size [topic0, topic1]) := by
simp [execIRStmtWithInternals, isYulLogName, heval]
theorem execIRStmtWithInternals_log3_of_eval_args
{contract : IRContract}
{fuel : Nat}
{state state' : IRState}
{args : List YulExpr}
{offset size topic0 topic1 topic2 : Nat}
(heval :
evalIRExprsWithInternals contract fuel state args =
.values [offset, size, topic0, topic1, topic2] state') :
execIRStmtWithInternals contract (Nat.succ fuel) state
(YulStmt.exprStmt (YulExpr.call "log3" args)) =
.continue (state'.appendYulLog offset size [topic0, topic1, topic2]) := by
simp [execIRStmtWithInternals, isYulLogName, heval]
theorem execIRStmtWithInternals_log4_of_eval_args
{contract : IRContract}
{fuel : Nat}
{state state' : IRState}
{args : List YulExpr}
{offset size topic0 topic1 topic2 topic3 : Nat}
(heval :
evalIRExprsWithInternals contract fuel state args =
.values [offset, size, topic0, topic1, topic2, topic3] state') :
execIRStmtWithInternals contract (Nat.succ fuel) state
(YulStmt.exprStmt (YulExpr.call "log4" args)) =
.continue (state'.appendYulLog offset size
[topic0, topic1, topic2, topic3]) := by
simp [execIRStmtWithInternals, isYulLogName, heval]
/-! ## Helper Scope Sanity Checks -/
/-- Helper bodies do not inherit caller-only locals. If a helper reads an
identifier that is neither a parameter nor a declared return slot, execution
fails against the fresh callee frame instead of silently seeing the caller's
binding. -/
theorem execIRInternalFunctionWithInternals_hides_caller_only_locals :
let callerState := (IRState.initial 0).setVar "callerOnly" 7
let helper : IRInternalFunctionDef :=
{ name := "helper"
params := []
rets := ["ret"]
body := [.assign "ret" (.ident "callerOnly")] }
let contract : IRContract :=
{ name := "C"
deploy := []
functions := []
usesMapping := false }
execIRInternalFunctionWithInternals contract 2 callerState helper [] =
.revert callerState := by
simp [execIRInternalFunctionWithInternals, prepareInternalCalleeState,
execIRStmtsWithInternals, execIRStmtWithInternals,
IRState.initial, IRState.setVar, IRState.setVars]
/-! ## IR Statement Execution (Fuel-Based, Total)
Statement executors use an explicit fuel parameter to ensure totality.
This eliminates the need for `partial def` and the corresponding
`execIRStmtsFuel_adequate` axiom. The fuel-based versions are now the
canonical definitions.
-/
/-- Result of executing IR statements -/
inductive IRExecResult
| continue (state : IRState)
| return (value : Nat) (state : IRState)
| stop (state : IRState)
| revert (state : IRState)
deriving Nonempty
mutual
/-- Execute a single Yul statement with fuel bound.
Total: uses explicit fuel parameter for recursion control.
When fuel is 0, execution reverts (safe fallback). -/
def execIRStmt : Nat → IRState → YulStmt → IRExecResult
| _, state, .funcDef _ _ _ _ => .continue state
| 0, state, _ => .revert state -- Out of fuel
| Nat.succ fuel, state, stmt =>
match stmt with
| .comment _ => .continue state
| .let_ name value =>
match evalIRExpr state value with
| some v => .continue (state.setVar name v)
| none => .revert state
| .letMany _ _ => .revert state
| .assign name value =>
match evalIRExpr state value with
| some v => .continue (state.setVar name v)
| none => .revert state
| .leave => .continue state
| .exprStmt e =>
match e with
| .call "sstore" [slotExpr, valExpr] =>
match slotExpr with
| .call "mappingSlot" [baseExpr, keyExpr] =>
match evalIRExpr state baseExpr, evalIRExpr state keyExpr, evalIRExpr state valExpr with
| some baseSlot, some key, some val =>
let updated := Compiler.Proofs.abstractStoreMappingEntry
state.storage baseSlot key val
.continue {
state with
storage := updated
}
| _, _, _ => .revert state
| _ =>
match evalIRExpr state slotExpr, evalIRExpr state valExpr with
| some slot, some val =>
let updated := Compiler.Proofs.abstractStoreStorageOrMapping
state.storage slot val
.continue {
state with
storage := updated
}
| _, _ => .revert state
| .call "mstore" [offsetExpr, valExpr] =>
match evalIRExpr state offsetExpr, evalIRExpr state valExpr with
| some offset, some val =>
.continue (state.writePhysicalMemoryValue (Verity.Core.Uint256.ofNat offset).val val)
| _, _ => .revert state
| .call "tstore" [offsetExpr, valExpr] =>
match evalIRExpr state offsetExpr, evalIRExpr state valExpr with
| some offset, some val =>
let offset := offset % Compiler.Constants.evmModulus
.continue {
state with
transientStorage := fun o =>
if o = offset then val else state.transientStorage o