-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTranslate.lean
More file actions
3987 lines (3786 loc) · 213 KB
/
Translate.lean
File metadata and controls
3987 lines (3786 loc) · 213 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
import Lean
import Compiler.Modules.ERC20
import Compiler.Modules.Precompiles
import Compiler.CompilationModel.InternalNaming
import Verity.Macro.Syntax
namespace Verity.Macro
open Lean
open Lean.Elab
open Lean.Elab.Command
set_option hygiene false
abbrev Term := TSyntax `term
abbrev Cmd := TSyntax `command
abbrev Ident := TSyntax `ident
abbrev DoSeq := TSyntax `Lean.Parser.Term.doSeq
inductive ValueType where
| uint256
| int256
| uint8
| address
| bytes32
| bool
| string
| bytes
| array (elemTy : ValueType)
| tuple (elemTys : List ValueType)
| unit
deriving Repr, BEq
inductive MappingKeyType where
| address
| uint256
deriving BEq
structure StructMemberDecl where
name : String
wordOffset : Nat
packed : Option (Nat × Nat) := none
deriving BEq
inductive StorageType where
| scalar (ty : ValueType)
| dynamicArray (elemTy : Compiler.CompilationModel.StorageArrayElemType)
| mappingAddressToUint256
| mapping2AddressToAddressToUint256
| mappingUintToUint256
| mappingChain (keyTypes : List MappingKeyType)
| mappingStruct (keyType : MappingKeyType) (members : List StructMemberDecl)
| mappingStruct2 (outerKey : MappingKeyType) (innerKey : MappingKeyType) (members : List StructMemberDecl)
deriving BEq
structure StorageFieldDecl where
ident : Ident
name : String
ty : StorageType
slotNum : Nat
structure ParamDecl where
ident : Ident
name : String
ty : ValueType
structure ErrorDecl where
ident : Ident
name : String
params : Array ValueType
structure ConstantDecl where
ident : Ident
name : String
ty : ValueType
body : Term
structure ImmutableDecl where
ident : Ident
name : String
ty : ValueType
body : Term
structure ExternalDecl where
ident : Ident
name : String
params : Array ValueType
returnTys : Array ValueType
structure LocalObligationDecl where
ident : Ident
name : String
obligation : String
proofStatus : Compiler.ProofStatus
inductive InitGuardDecl where
| initializer (fieldIdent : Ident) (fieldName : String)
| reinitializer (fieldIdent : Ident) (fieldName : String) (version : Nat)
structure FunctionDecl where
ident : Ident
name : String
params : Array ParamDecl
returnTy : ValueType
isPayable : Bool := false
isView : Bool := false
initGuard? : Option InitGuardDecl := none
localObligations : Array LocalObligationDecl := #[]
body : Term
structure ConstructorDecl where
params : Array ParamDecl
isPayable : Bool := false
localObligations : Array LocalObligationDecl := #[]
body : Term
private def strTerm (s : String) : Term := ⟨Syntax.mkStrLit s⟩
private def natTerm (n : Nat) : Term := ⟨Syntax.mkNumLit (toString n)⟩
private partial def expectTermListLiteral (stx : Term) : CommandElabM (Array Term) := do
match stx with
| `(term| [ $[$xs],* ]) => pure xs
| `(term| ($inner:term)) => expectTermListLiteral inner
| _ => throwErrorAt stx "expected list literal [..]"
private partial def collectTupleElems (stx : Syntax) : Array Syntax :=
if stx.isAtom then
#[]
else if stx.getKind == `null then
stx.getArgs.foldl (fun acc child => acc ++ collectTupleElems child) #[]
else
#[stx]
private def tupleElemsFromSyntax? (stx : Syntax) : Option (Array Syntax) :=
if stx.getKind == `Lean.Parser.Term.tuple then
some (collectTupleElems stx[1])
else
none
private partial def expectMappingKeyTerms (stx : Term) : CommandElabM (Array Term) := do
expectTermListLiteral stx
private partial def collectArrowChainTypes (stx : Term) : CommandElabM (List Term × Term) := do
match stx with
| `(term| $lhs:term → $rhs:term) =>
let (rest, resultTy) ← collectArrowChainTypes rhs
pure (lhs :: rest, resultTy)
| _ => pure ([], stx)
private def natFromSyntax (stx : Syntax) : CommandElabM Nat :=
match stx.isNatLit? with
| some n => pure n
| none => throwErrorAt stx "expected natural literal"
private partial def valueTypeFromSyntax (ty : Term) : CommandElabM ValueType := do
match ty with
| `(term| Uint256) => pure .uint256
| `(term| Int256) => pure .int256
| `(term| Uint8) => pure .uint8
| `(term| Address) => pure .address
| `(term| Bytes32) => pure .bytes32
| `(term| Bool) => pure .bool
| `(term| String) => pure .string
| `(term| Bytes) => pure .bytes
| `(term| Array $elemTy:term) =>
let elem ← valueTypeFromSyntax elemTy
match elem with
| .unit => throwErrorAt ty "unsupported type '{ty}'; Array Unit is not allowed"
| .array _ => throwErrorAt ty "unsupported type '{ty}'; nested arrays are not supported"
| _ => pure (.array elem)
| `(term| Tuple [ $[$elemTys:term],* ]) =>
let elems ← elemTys.mapM valueTypeFromSyntax
if elems.size < 2 then
throwErrorAt ty "tuple types must have at least 2 elements"
pure (.tuple elems.toList)
| `(term| Unit) => pure .unit
| _ => throwErrorAt ty "unsupported type '{ty}'; expected Uint256, Int256, Uint8, Address, Bytes32, Bool, String, Bytes, Array <type>, Tuple [...], or Unit"
private def storageTypeFromSyntax (ty : Term) : CommandElabM StorageType := do
let keyTypeFromSyntax (stx : Term) : CommandElabM MappingKeyType := do
match stx with
| `(term| Address) => pure .address
| `(term| Uint256) => pure .uint256
| _ => throwErrorAt stx "unsupported mapping key type; expected Address or Uint256"
let structMemberFromSyntax (stx : TSyntax `verityStructMember) : CommandElabM StructMemberDecl := do
match stx with
| `(verityStructMember| $name:ident @word $wordOffset:num) =>
pure {
name := toString name.getId
wordOffset := ← natFromSyntax wordOffset
}
| `(verityStructMember| $name:ident @word $wordOffset:num packed($offset:num,$width:num)) =>
pure {
name := toString name.getId
wordOffset := ← natFromSyntax wordOffset
packed := some (← natFromSyntax offset, ← natFromSyntax width)
}
| _ => throwErrorAt stx "invalid struct member declaration"
let storageArrayElemTypeFromValueType (elemTy : ValueType) : CommandElabM Compiler.CompilationModel.StorageArrayElemType :=
match elemTy with
| .uint256 => pure .uint256
| .address => pure .address
| .bool => pure .bool
| .bytes32 => pure .bytes32
| _ =>
throwErrorAt ty
s!"storage dynamic arrays currently support only one-word elements (Uint256, Address, Bool, Bytes32) on the macro path, got {reprStr (ValueType.array elemTy)}"
let (arrowArgs, arrowResult) ← collectArrowChainTypes ty
if !arrowArgs.isEmpty then
match arrowResult with
| `(term| Uint256) =>
let keyTypes ← arrowArgs.mapM keyTypeFromSyntax
match keyTypes with
| [.address] => pure .mappingAddressToUint256
| [.uint256] => pure .mappingUintToUint256
| [.address, .address] => pure .mapping2AddressToAddressToUint256
| _ => pure (.mappingChain keyTypes)
| _ =>
throwErrorAt ty "unsupported mapping value type; expected Uint256"
else
match ty with
| `(term| MappingStruct($keyTy:term,[ $[$members:verityStructMember],* ])) =>
pure <| .mappingStruct
(← keyTypeFromSyntax keyTy)
((← members.mapM structMemberFromSyntax).toList)
| `(term| MappingStruct2($outerKey:term,$innerKey:term,[ $[$members:verityStructMember],* ])) =>
pure <| .mappingStruct2
(← keyTypeFromSyntax outerKey)
(← keyTypeFromSyntax innerKey)
((← members.mapM structMemberFromSyntax).toList)
| _ => do
let vt ← valueTypeFromSyntax ty
match vt with
| .array elemTy => pure (.dynamicArray (← storageArrayElemTypeFromValueType elemTy))
| .tuple _ => throwErrorAt ty "storage fields cannot be Tuple; use mapping encodings"
| _ => pure (.scalar vt)
private def modelMappingKeyTypeTerm : MappingKeyType → CommandElabM Term
| .address => `(Compiler.CompilationModel.MappingKeyType.address)
| .uint256 => `(Compiler.CompilationModel.MappingKeyType.uint256)
private def storageTypeMappingKeyTypes? : StorageType → Option (List MappingKeyType)
| .mappingAddressToUint256 => some [.address]
| .mapping2AddressToAddressToUint256 => some [.address, .address]
| .mappingUintToUint256 => some [.uint256]
| .mappingChain keyTypes => some keyTypes
| _ => none
private def storageTypeMappingDepth? (ty : StorageType) : Option Nat :=
storageTypeMappingKeyTypes? ty |>.map List.length
private def storageKeyTypeContractTerm : MappingKeyType → CommandElabM Term
| .address => `(Address)
| .uint256 => `(Uint256)
private def modelStructMemberTerm (member : StructMemberDecl) : CommandElabM Term := do
let packedTerm ←
match member.packed with
| none => `(none)
| some (offset, width) =>
`(some { offset := $(natTerm offset), width := $(natTerm width) })
`(Compiler.CompilationModel.StructMember.mk
$(strTerm member.name)
$(natTerm member.wordOffset)
$packedTerm)
private def modelFieldTypeTerm (ty : StorageType) : CommandElabM Term :=
match ty with
| .scalar .uint256 => `(Compiler.CompilationModel.FieldType.uint256)
| .scalar .int256 => throwError "storage fields cannot be Int256; use Uint256 encoding"
| .scalar .uint8 => throwError "storage fields cannot be Uint8; use Uint256 encoding"
| .scalar .address => `(Compiler.CompilationModel.FieldType.address)
| .scalar .bytes32 => throwError "storage fields cannot be Bytes32; use Uint256 encoding"
| .scalar .bool => throwError "storage fields cannot be Bool; use Uint256 (0/1) encoding"
| .scalar .string => throwError "storage fields cannot be String; use Uint256 encoding"
| .scalar .bytes => throwError "storage fields cannot be Bytes; use Uint256 encoding"
| .scalar (.array _) => throwError "storage fields cannot be Array; use mapping encodings"
| .scalar (.tuple _) => throwError "storage fields cannot be Tuple; use mapping encodings"
| .scalar .unit => throwError "storage fields cannot be Unit"
| .dynamicArray .uint256 => `(Compiler.CompilationModel.FieldType.dynamicArray Compiler.CompilationModel.StorageArrayElemType.uint256)
| .dynamicArray .address => `(Compiler.CompilationModel.FieldType.dynamicArray Compiler.CompilationModel.StorageArrayElemType.address)
| .dynamicArray .bool => `(Compiler.CompilationModel.FieldType.dynamicArray Compiler.CompilationModel.StorageArrayElemType.bool)
| .dynamicArray .uint8 => `(Compiler.CompilationModel.FieldType.dynamicArray Compiler.CompilationModel.StorageArrayElemType.uint8)
| .dynamicArray .bytes32 => `(Compiler.CompilationModel.FieldType.dynamicArray Compiler.CompilationModel.StorageArrayElemType.bytes32)
| .mappingAddressToUint256 =>
`(Compiler.CompilationModel.FieldType.mappingTyped
(Compiler.CompilationModel.MappingType.simple Compiler.CompilationModel.MappingKeyType.address))
| .mapping2AddressToAddressToUint256 =>
`(Compiler.CompilationModel.FieldType.mappingTyped
(Compiler.CompilationModel.MappingType.nested
Compiler.CompilationModel.MappingKeyType.address
Compiler.CompilationModel.MappingKeyType.address))
| .mappingUintToUint256 =>
`(Compiler.CompilationModel.FieldType.mappingTyped
(Compiler.CompilationModel.MappingType.simple Compiler.CompilationModel.MappingKeyType.uint256))
| .mappingChain keyTypes => do
let keyTypeTerms := (← keyTypes.mapM modelMappingKeyTypeTerm).toArray
`(Compiler.CompilationModel.FieldType.mappingTyped
(Compiler.CompilationModel.MappingType.chain [ $[$keyTypeTerms],* ]))
| .mappingStruct keyType members => do
let keyTypeTerm ← modelMappingKeyTypeTerm keyType
let memberTerms := (← members.mapM modelStructMemberTerm).toArray
`(Compiler.CompilationModel.FieldType.mappingStruct $keyTypeTerm [ $[$memberTerms],* ])
| .mappingStruct2 outerKey innerKey members => do
let outerKeyTerm ← modelMappingKeyTypeTerm outerKey
let innerKeyTerm ← modelMappingKeyTypeTerm innerKey
let memberTerms := (← members.mapM modelStructMemberTerm).toArray
`(Compiler.CompilationModel.FieldType.mappingStruct2 $outerKeyTerm $innerKeyTerm [ $[$memberTerms],* ])
private partial def modelParamTypeTerm (ty : ValueType) : CommandElabM Term :=
match ty with
| .uint256 => `(Compiler.CompilationModel.ParamType.uint256)
| .int256 => `(Compiler.CompilationModel.ParamType.int256)
| .uint8 => `(Compiler.CompilationModel.ParamType.uint8)
| .address => `(Compiler.CompilationModel.ParamType.address)
| .bytes32 => `(Compiler.CompilationModel.ParamType.bytes32)
| .bool => `(Compiler.CompilationModel.ParamType.bool)
| .string => `(Compiler.CompilationModel.ParamType.string)
| .bytes => `(Compiler.CompilationModel.ParamType.bytes)
| .array elemTy => do
`(Compiler.CompilationModel.ParamType.array $(← modelParamTypeTerm elemTy))
| .tuple elemTys => do
let elemTerms ← elemTys.mapM modelParamTypeTerm
`(Compiler.CompilationModel.ParamType.tuple [ $[$elemTerms.toArray],* ])
| .unit => throwError "function parameters cannot be Unit"
private def modelReturnTypeTerm (ty : ValueType) : CommandElabM Term :=
match ty with
| .unit => `(none)
| .uint256 => `(some Compiler.CompilationModel.FieldType.uint256)
| .int256 => `(none)
| .uint8 => `(none)
| .address => `(some Compiler.CompilationModel.FieldType.address)
| .bytes32 => `(none)
| .bool => `(none)
| .string => `(none)
| .bytes => `(none)
| .array _ => `(none)
| .tuple _ => `(none)
private partial def modelReturnsTerm (ty : ValueType) : CommandElabM Term :=
match ty with
| .unit => `([])
| .uint256 => `([Compiler.CompilationModel.ParamType.uint256])
| .int256 => `([Compiler.CompilationModel.ParamType.int256])
| .uint8 => `([Compiler.CompilationModel.ParamType.uint8])
| .address => `([Compiler.CompilationModel.ParamType.address])
| .bytes32 => `([Compiler.CompilationModel.ParamType.bytes32])
| .bool => `([Compiler.CompilationModel.ParamType.bool])
| .string => `([Compiler.CompilationModel.ParamType.string])
| .bytes => `([Compiler.CompilationModel.ParamType.bytes])
| .array elemTy => do
`([Compiler.CompilationModel.ParamType.array $(← modelParamTypeTerm elemTy)])
| .tuple elemTys => do
let elemTerms ← elemTys.mapM modelParamTypeTerm
`([ $[$elemTerms.toArray],* ])
mutual
private partial def mkTupleContractType (elemTys : List ValueType) : CommandElabM Term := do
let rec go : List ValueType → CommandElabM Term
| [] => throwError "tuple types must have at least 2 elements"
| [ty] => contractValueTypeTerm ty
| ty :: rest => do
`(($(← contractValueTypeTerm ty) × $(← go rest)))
go elemTys
private partial def contractValueTypeTerm (ty : ValueType) : CommandElabM Term :=
match ty with
| .uint256 => `(Uint256)
| .int256 => `(Int256)
| .uint8 => `(Uint256)
| .address => `(Address)
| .bytes32 => `(Uint256)
| .bool => `(Bool)
| .string => `(String)
| .bytes => `(ByteArray)
| .array elemTy => do
`(Array $(← contractValueTypeTerm elemTy))
| .tuple elemTys => mkTupleContractType elemTys
| .unit => `(Unit)
end
private def parseStorageField (stx : Syntax) : CommandElabM StorageFieldDecl := do
match stx with
| `(verityStorageField| $name:ident : $ty:term := slot $slotNum:num) =>
pure {
ident := name
name := toString name.getId
ty := ← storageTypeFromSyntax ty
slotNum := ← natFromSyntax slotNum
}
| _ => throwErrorAt stx "invalid storage field declaration"
private def parseParam (stx : Syntax) : CommandElabM ParamDecl := do
match stx with
| `(verityParam| $name:ident : $ty:term) =>
pure {
ident := name
name := toString name.getId
ty := ← valueTypeFromSyntax ty
}
| _ => throwErrorAt stx "invalid parameter declaration"
private def parseError (stx : Syntax) : CommandElabM ErrorDecl := do
match stx with
| `(verityError| error $name:ident ($[$params:term],*)) =>
pure {
ident := name
name := toString name.getId
params := ← params.mapM valueTypeFromSyntax
}
| _ => throwErrorAt stx "invalid custom error declaration"
private def parseConstant (stx : Syntax) : CommandElabM ConstantDecl := do
match stx with
| `(verityConstant| $name:ident : $ty:term := $body:term) =>
pure {
ident := name
name := toString name.getId
ty := ← valueTypeFromSyntax ty
body := body
}
| _ => throwErrorAt stx "invalid constant declaration"
private def parseImmutable (stx : Syntax) : CommandElabM ImmutableDecl := do
match stx with
| `(verityImmutable| $name:ident : $ty:term := $body:term) =>
pure {
ident := name
name := toString name.getId
ty := ← valueTypeFromSyntax ty
body := body
}
| _ => throwErrorAt stx "invalid immutable declaration"
private def parseExternal (stx : Syntax) : CommandElabM ExternalDecl := do
match stx with
| `(verityExternal| external $name:ident ($[$params:term],*) -> ($[$returnTys:term],*)) =>
pure {
ident := name
name := toString name.getId
params := ← params.mapM valueTypeFromSyntax
returnTys := ← returnTys.mapM valueTypeFromSyntax
}
| `(verityExternal| external $name:ident ($[$params:term],*)) =>
pure {
ident := name
name := toString name.getId
params := ← params.mapM valueTypeFromSyntax
returnTys := #[]
}
| _ => throwErrorAt stx "invalid external declaration"
private def parseProofStatusIdent (stx : Syntax) : CommandElabM Compiler.ProofStatus := do
match stx with
| .ident _ raw _ _ =>
match raw.toString with
| "proved" => pure .proved
| "assumed" => pure .assumed
| "unchecked" => pure .unchecked
| other =>
throwErrorAt stx s!"unsupported proof status '{other}'; expected proved, assumed, or unchecked"
| _ => throwErrorAt stx "expected proof status identifier"
private def parseLocalObligation (stx : Syntax) : CommandElabM LocalObligationDecl := do
match stx with
| `(verityLocalObligation| $name:ident := $status:ident $obligation:str) =>
pure {
ident := name
name := toString name.getId
obligation := obligation.getString
proofStatus := ← parseProofStatusIdent status
}
| _ => throwErrorAt stx "invalid local obligation declaration"
private def parseMutabilityModifiers
(mods : Array (TSyntax `verityMutability))
(stx : Syntax) : CommandElabM (Bool × Bool) := do
let mut isPayable := false
let mut isView := false
for mod in mods do
match mod with
| `(verityMutability| payable) =>
if isPayable then
throwErrorAt mod "duplicate 'payable' modifier"
isPayable := true
| `(verityMutability| view) =>
if isView then
throwErrorAt mod "duplicate 'view' modifier"
isView := true
| _ => throwErrorAt stx "invalid function mutability modifier"
pure (isPayable, isView)
private def parseInitGuard (stx : TSyntax `verityInitGuard) : CommandElabM InitGuardDecl := do
match stx with
| `(verityInitGuard| initializer($field:ident)) =>
pure (.initializer field (toString field.getId))
| `(verityInitGuard| reinitializer($field:ident, $version:num)) => do
let versionNat ← natFromSyntax version
if versionNat == 0 then
throwErrorAt version "reinitializer version must be greater than 0"
pure (.reinitializer field (toString field.getId) versionNat)
| _ => throwErrorAt stx "invalid initializer guard"
private def parseLocalObligations
(stx : TSyntax `verityLocalObligations) : CommandElabM (Array LocalObligationDecl) := do
match stx with
| `(verityLocalObligations| local_obligations [ $[$obligations:verityLocalObligation],* ]) =>
obligations.mapM parseLocalObligation
| _ => throwErrorAt stx "invalid local obligations declaration"
private def hiddenEntrypointIdent (name : String) : Ident :=
mkIdent (Name.mkSimple s!"__verity_{name}")
private def parseSpecialEntrypoint (stx : Syntax) : CommandElabM FunctionDecl := do
match stx with
| `(veritySpecialEntrypoint| receive $[$localObligations?:verityLocalObligations]? := $body:term) => do
let parsedLocalObligations ←
match localObligations? with
| some obligations => parseLocalObligations obligations
| none => pure #[]
pure {
ident := hiddenEntrypointIdent "receive"
name := "receive"
params := #[]
returnTy := .unit
isPayable := true
localObligations := parsedLocalObligations
body := body
}
| `(veritySpecialEntrypoint| fallback $[$localObligations?:verityLocalObligations]? := $body:term) => do
let parsedLocalObligations ←
match localObligations? with
| some obligations => parseLocalObligations obligations
| none => pure #[]
pure {
ident := hiddenEntrypointIdent "fallback"
name := "fallback"
params := #[]
returnTy := .unit
localObligations := parsedLocalObligations
body := body
}
| _ => throwErrorAt stx "invalid special entrypoint declaration"
private def parseFunction (stx : Syntax) : CommandElabM FunctionDecl := do
match stx with
| `(verityFunction| function $[$mods:verityMutability]* $name:ident ($[$params:verityParam],*) $[$guard?:verityInitGuard]? $[$localObligations?:verityLocalObligations]? : $retTy:term := $body:term) => do
let (isPayable, isView) ← parseMutabilityModifiers mods stx
let parsedParams ← params.mapM parseParam
let parsedReturnTy ← valueTypeFromSyntax retTy
let parsedGuard? ←
match guard? with
| some guard => pure (some (← parseInitGuard guard))
| none => pure none
let parsedLocalObligations ←
match localObligations? with
| some obligations => parseLocalObligations obligations
| none => pure #[]
pure {
ident := name
name := toString name.getId
params := parsedParams
returnTy := parsedReturnTy
isPayable := isPayable
isView := isView
initGuard? := parsedGuard?
localObligations := parsedLocalObligations
body := body
}
| _ => throwErrorAt stx "invalid function declaration"
private def parseConstructor (stx : Syntax) : CommandElabM ConstructorDecl := do
match stx with
| `(verityConstructor| constructor ($[$params:verityParam],*) payable local_obligations [ $[$obligations:verityLocalObligation],* ] := $body:term) =>
pure {
params := ← params.mapM parseParam
isPayable := true
localObligations := ← obligations.mapM parseLocalObligation
body := body
}
| `(verityConstructor| constructor ($[$params:verityParam],*) payable := $body:term) =>
pure {
params := ← params.mapM parseParam
isPayable := true
body := body
}
| `(verityConstructor| constructor ($[$params:verityParam],*) local_obligations [ $[$obligations:verityLocalObligation],* ] := $body:term) =>
pure {
params := ← params.mapM parseParam
localObligations := ← obligations.mapM parseLocalObligation
body := body
}
| `(verityConstructor| constructor ($[$params:verityParam],*) := $body:term) =>
pure {
params := ← params.mapM parseParam
body := body
}
| _ => throwErrorAt stx "invalid constructor declaration"
private def immutableHiddenName (imm : ImmutableDecl) : String :=
s!"__immutable_{imm.name}"
private def immutableSlotIndex (fields : Array StorageFieldDecl) (idx : Nat) : Nat :=
let nextUserSlot := fields.foldl (fun maxSlot field => max maxSlot (field.slotNum + 1)) 0
nextUserSlot + idx
private def immutableSlotIdent (imm : ImmutableDecl) : Ident :=
mkIdent (Name.mkSimple s!"__verity_immutable_slot_{imm.name}")
def immutableStorageFieldDecl
(fields : Array StorageFieldDecl)
(imm : ImmutableDecl)
(idx : Nat) : StorageFieldDecl :=
{
ident := immutableSlotIdent imm
name := immutableHiddenName imm
ty := match imm.ty with
| .uint256 | .int256 | .uint8 | .bytes32 | .bool => .scalar .uint256
| .address => .scalar .address
| _ => .scalar imm.ty
slotNum := immutableSlotIndex fields idx
}
private def validateImmutableType (imm : ImmutableDecl) : CommandElabM Unit :=
match imm.ty with
| .uint256 | .int256 | .uint8 | .address | .bytes32 | .bool => pure ()
| _ =>
throwErrorAt imm.ident
s!"contract immutables currently support only Uint256, Int256, Uint8, Address, Bytes32, and Bool; '{imm.name}' uses unsupported type"
private def validateImmutableBodyType
(imm : ImmutableDecl)
(ctorParams : Array ParamDecl) : CommandElabM Unit := do
let expectedTy ← contractValueTypeTerm imm.ty
let mut wrappedBody : Term := imm.body
wrappedBody ← `(term| (($wrappedBody : $expectedTy)))
for param in ctorParams.reverse do
wrappedBody ← `(term| fun ($(param.ident) : $(← contractValueTypeTerm param.ty)) => $wrappedBody)
liftTermElabM do
discard <| Lean.Elab.Term.elabTerm wrappedBody none
private def externalExecutableWordType? : ValueType → Bool
| .uint256 | .int256 | .uint8 | .address | .bytes32 | .bool => true
| _ => false
private def validateExternalExecutableType
(extIdent : Ident)
(extName : String)
(ty : ValueType)
(role : String) : CommandElabM Unit := do
if !externalExecutableWordType? ty then
throwErrorAt extIdent
s!"linked external '{extName}' uses unsupported {role} type; executable externalCall currently supports only Uint256, Int256, Uint8, Address, Bytes32, and Bool"
private partial def stripParens (stx : Term) : Term :=
match stx with
| `(term| ($inner)) => stripParens inner
| _ => stx
private def tupleElemsFromTerm? (stx : Term) : Option (Array Term) :=
tupleElemsFromSyntax? (stripParens stx).raw |>.map (·.map (fun syn => ⟨syn⟩))
private def throwNonCompileTimeConstantError (stx : Syntax) (what : String) : CommandElabM α :=
throwErrorAt stx s!"contract constants must be compile-time expressions; '{what}' is runtime-dependent"
private def lookupStructMemberDecl
(fields : Array StorageFieldDecl)
(fieldName memberName : String)
(expectNested : Bool) : CommandElabM StructMemberDecl := do
let field ←
match fields.find? (fun f => f.name == fieldName) with
| some f => pure f
| none => throwError s!"unknown storage field '{fieldName}'"
let members ←
match field.ty with
| .mappingStruct _ members =>
if expectNested then
throwError s!"field '{fieldName}' is not a nested struct mapping"
pure members
| .mappingStruct2 _ _ members =>
if expectNested then pure members
else throwError s!"field '{fieldName}' is a nested struct mapping; use structMember2/setStructMember2"
| _ =>
if expectNested then
throwError s!"field '{fieldName}' is not a nested struct mapping"
else
throwError s!"field '{fieldName}' is not a struct-valued mapping"
match members.find? (fun member => member.name == memberName) with
| some member => pure member
| none => throwError s!"unknown struct member '{memberName}' on field '{fieldName}'"
private def lookupStorageField (fields : Array StorageFieldDecl) (name : String) : CommandElabM StorageFieldDecl := do
match fields.find? (fun f => f.name == name) with
| some f => pure f
| none => throwError s!"unknown storage field '{name}'"
private def resolveInitGuardField
(fields : Array StorageFieldDecl)
(guard : InitGuardDecl)
(stx : Syntax) : CommandElabM StorageFieldDecl := do
let field ←
match guard with
| .initializer _ fieldName => lookupStorageField fields fieldName
| .reinitializer _ fieldName _ => lookupStorageField fields fieldName
match field.ty with
| .scalar .uint256 => pure field
| _ =>
throwErrorAt stx
s!"initializer guard field '{field.name}' must be a Uint256 storage slot"
private def initGuardRequireMessage : InitGuardDecl → String
| .initializer .. => "initializer already run"
| .reinitializer _ _ version => s!"reinitializer({version}) already run"
private def initGuardVersionTerm (version : Nat) : Term :=
natTerm version
private def initGuardPreludeStmtTerms
(fields : Array StorageFieldDecl)
(fn : FunctionDecl) : CommandElabM (Array Term) := do
match fn.initGuard? with
| none => pure #[]
| some guard =>
let field ← resolveInitGuardField fields guard fn.ident
let message := strTerm (initGuardRequireMessage guard)
match guard with
| .initializer _ _ =>
pure #[
← `(Compiler.CompilationModel.Stmt.require
(Compiler.CompilationModel.Expr.eq
(Compiler.CompilationModel.Expr.storage $(strTerm field.name))
(Compiler.CompilationModel.Expr.literal 0))
$message),
← `(Compiler.CompilationModel.Stmt.setStorage
$(strTerm field.name)
(Compiler.CompilationModel.Expr.literal 1))
]
| .reinitializer _ _ version =>
pure #[
← `(Compiler.CompilationModel.Stmt.require
(Compiler.CompilationModel.Expr.lt
(Compiler.CompilationModel.Expr.storage $(strTerm field.name))
(Compiler.CompilationModel.Expr.literal $(initGuardVersionTerm version)))
$message),
← `(Compiler.CompilationModel.Stmt.setStorage
$(strTerm field.name)
(Compiler.CompilationModel.Expr.literal $(initGuardVersionTerm version)))
]
private def mkInitGuardedBody
(fields : Array StorageFieldDecl)
(fn : FunctionDecl) : CommandElabM Term := do
match fn.initGuard? with
| none => pure fn.body
| some guard =>
let field ← resolveInitGuardField fields guard fn.ident
let currentVersion := mkIdent (Name.mkSimple s!"__verity_init_version_{field.name}")
let message := strTerm (initGuardRequireMessage guard)
match fn.body with
| `(term| do $[$elems:doElem]*) =>
match guard with
| .initializer _ _ =>
`(do
let $currentVersion ← getStorage $field.ident
require ($currentVersion == 0) $message
setStorage $field.ident 1
$[$elems:doElem]*)
| .reinitializer _ _ version =>
`(do
let $currentVersion ← getStorage $field.ident
require ($currentVersion < $(initGuardVersionTerm version)) $message
setStorage $field.ident $(initGuardVersionTerm version)
$[$elems:doElem]*)
| _ => throwErrorAt fn.body "function body must be a do block"
private def mkImmutableBoundBody
(fields : Array StorageFieldDecl)
(immutableDecls : Array ImmutableDecl)
(fn : FunctionDecl)
(body : Term) : CommandElabM Term := do
let visibleImmutables := immutableDecls.filter fun imm =>
!fn.params.any (fun p => p.name == imm.name)
match body with
| `(term| do $[$elems:doElem]*) =>
let preludeElemGroups ← visibleImmutables.zipIdx.mapM fun (imm, idx) => do
let slotField := immutableStorageFieldDecl fields imm idx
match imm.ty with
| .uint256 | .uint8 | .bytes32 =>
pure #[← `(doElem| let $(imm.ident) ← getStorage $(slotField.ident))]
| .int256 =>
pure #[← `(doElem| let $(imm.ident) := toInt256 (← getStorage $(slotField.ident)))]
| .bool =>
let rawName := mkIdent (Name.mkSimple s!"__verity_immutable_raw_{imm.name}")
pure #[
← `(doElem| let $rawName ← getStorage $(slotField.ident)),
← `(doElem| let $(imm.ident) := ($rawName != 0))
]
| .address =>
pure #[← `(doElem| let $(imm.ident) ← getStorageAddr $(slotField.ident))]
| _ => throwErrorAt imm.ident s!"immutable '{imm.name}' uses unsupported type"
let preludeElems := preludeElemGroups.foldl (· ++ ·) #[]
`(do $[$preludeElems:doElem]* $[$elems:doElem]*)
| _ => throwErrorAt body "function body must be a do block"
private def expectStringLiteral (stx : Term) : CommandElabM String :=
match (stripParens stx).raw.isStrLit? with
| some s => pure s
| none => throwErrorAt stx "expected string literal"
private def expectStringOrIdent (stx : Term) : CommandElabM String := do
match stripParens stx with
| `(term| $id:ident) => pure (toString id.getId)
| other => expectStringLiteral other
private def expectStringList (stx : Term) : CommandElabM (Array String) := do
match stripParens stx with
| `(term| [ $[$xs],* ]) =>
xs.mapM expectStringOrIdent
| _ => throwErrorAt stx "expected list literal [..]"
private def tupleBinderNames? (stx : Syntax) : Option (Array (Option String)) := do
let elems ← tupleElemsFromSyntax? stx
elems.mapM fun elem =>
match elem with
| .ident _ raw _ _ => some raw.toString
| .node _ `Lean.Parser.Term.hole _ => some none
| _ => none
private def ensureFreshLocalNames
(locals : Array String)
(names : Array (Option String))
(stx : Syntax) : CommandElabM Unit := do
let boundNames := names.filterMap id
let rec firstDuplicate (seen : Array String) (rest : Array String) (idx : Nat) : Option String :=
if h : idx < rest.size then
let name := rest[idx]
if seen.contains name then
some name
else
firstDuplicate (seen.push name) rest (idx + 1)
else
none
match firstDuplicate #[] boundNames 0 with
| some dup => throwErrorAt stx s!"duplicate local variable '{dup}'"
| none => pure ()
for name in boundNames do
if locals.contains name then
throwErrorAt stx s!"duplicate local variable '{name}'"
private def freshDiscardName (usedNames : List String) (idx : Nat) : String :=
let base := s!"__tuple_discard_{idx}"
if !usedNames.contains base then
base
else
let rec go (suffix : Nat) (remaining : Nat) : String :=
let candidate := s!"{base}_{suffix}"
if !usedNames.contains candidate then
candidate
else
match remaining with
| 0 => s!"{base}_fresh"
| n + 1 => go (suffix + 1) n
go 1 usedNames.length
private def tupleParamElemExprs?
(params : Array ParamDecl)
(name : String) : CommandElabM (Option (Array Term)) := do
match params.find? (fun p => p.name == name) with
| some p =>
match p.ty with
| .tuple elemTys => do
let exprs ← (elemTys.toArray.zipIdx).mapM fun (_ty, idx) =>
`(Compiler.CompilationModel.Expr.param $(strTerm s!"{name}_{idx}"))
pure (some exprs)
| _ => pure none
| none => pure none
private def isTupleComponentRef (params : Array ParamDecl) (name : String) : Bool :=
-- Check if `name` matches `<paramName>_<digit>` for a tuple-typed param
match name.splitOn "_" with
| [baseName, indexStr] =>
match indexStr.toNat? with
| some idx =>
params.any fun p =>
p.name == baseName &&
match p.ty with
| .tuple elemTys => idx < elemTys.length
| _ => false
| none => false
| _ => false
private def lookupVarExpr (params : Array ParamDecl) (locals : Array String) (name : String) : CommandElabM Term := do
if params.any (fun p => p.name == name) then
`(Compiler.CompilationModel.Expr.param $(strTerm name))
else if isTupleComponentRef params name then
`(Compiler.CompilationModel.Expr.param $(strTerm name))
else if locals.contains name then
`(Compiler.CompilationModel.Expr.localVar $(strTerm name))
else
throwError s!"unknown variable '{name}'"
private abbrev TypedLocal := String × ValueType
private def typedLocalNames (locals : Array TypedLocal) : Array String :=
locals.map Prod.fst
private def isSignedWordValueType : ValueType → Bool
| .int256 => true
| _ => false
private def isWordLikeValueType : ValueType → Bool
| .uint256 | .int256 | .uint8 | .address | .bytes32 => true
| _ => false
private def isSingleWordStaticValueType : ValueType → Bool
| .bool => true
| ty => isWordLikeValueType ty
private def classifyWordArithmeticResultType
(stx : Syntax)
(context : String)
(lhsTy rhsTy : ValueType) : CommandElabM ValueType := do
unless isWordLikeValueType lhsTy do
throwErrorAt stx s!"{context} requires a word-like value (Uint256, Int256, Uint8, Address, or Bytes32), got {reprStr lhsTy}"
unless isWordLikeValueType rhsTy do
throwErrorAt stx s!"{context} requires a word-like value (Uint256, Int256, Uint8, Address, or Bytes32), got {reprStr rhsTy}"
if isSignedWordValueType lhsTy || isSignedWordValueType rhsTy then
if lhsTy == .int256 && rhsTy == .int256 then
pure .int256
else
throwErrorAt stx
s!"{context} requires explicit casts when mixing Int256 with non-Int256 words; got {reprStr lhsTy} and {reprStr rhsTy}"
else
pure .uint256
private def classifyUnsignedWordArithmeticResultType
(stx : Syntax)
(context : String)
(lhsTy rhsTy : ValueType) : CommandElabM ValueType := do
unless isWordLikeValueType lhsTy do
throwErrorAt stx s!"{context} requires a word-like value (Uint256, Int256, Uint8, Address, or Bytes32), got {reprStr lhsTy}"
unless isWordLikeValueType rhsTy do
throwErrorAt stx s!"{context} requires a word-like value (Uint256, Int256, Uint8, Address, or Bytes32), got {reprStr rhsTy}"
pure .uint256
private def isNatLiteralTerm (stx : Term) : Bool :=
match stripParens stx with
| `(term| $_n:num) => true
| _ => false
private def preferSignedNumericLiteralPeer
(lhs rhs : Term)
(lhsTy rhsTy : ValueType) : ValueType × ValueType :=
let lhsTy :=
if lhsTy == .uint256 && rhsTy == .int256 && isNatLiteralTerm lhs then .int256 else lhsTy
let rhsTy :=
if rhsTy == .uint256 && lhsTy == .int256 && isNatLiteralTerm rhs then .int256 else rhsTy
(lhsTy, rhsTy)
private def lookupTypedLocalType? (locals : Array TypedLocal) (name : String) : Option ValueType :=
locals.findSome? fun localTy =>
if localTy.1 == name then some localTy.2 else none
private def tupleParamElemType? (params : Array ParamDecl) (name : String) : Option ValueType :=
match name.splitOn "_" with
| [baseName, indexStr] =>
match indexStr.toNat? with
| some idx =>
params.findSome? fun p =>
if p.name == baseName then
match p.ty with
| .tuple elemTys => elemTys.toArray[idx]?
| _ => none
else
none
| none => none
| _ => none
private def renderValueType (ty : ValueType) : String :=
reprStr ty
private def requireWordLikeType (stx : Syntax) (context : String) (ty : ValueType) : CommandElabM Unit := do
unless isWordLikeValueType ty do
throwErrorAt stx s!"{context} requires a word-like value (Uint256, Int256, Uint8, Address, or Bytes32), got {renderValueType ty}"
private def requireBoolType (stx : Syntax) (context : String) (ty : ValueType) : CommandElabM Unit := do
unless ty == .bool do
throwErrorAt stx s!"{context} requires Bool, got {renderValueType ty}"
private def requireSupportedReturnArrayType
(stx : Syntax)
(context : String)
(ty : ValueType) : CommandElabM Unit := do
match ty with
| .array elemTy =>
unless isSingleWordStaticValueType elemTy do