-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypes.lean
More file actions
1513 lines (1364 loc) · 54.8 KB
/
Copy pathTypes.lean
File metadata and controls
1513 lines (1364 loc) · 54.8 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 Init.Data.ByteArray.Extra
import LeanExe.Extract.Env
import LeanExe.IR.Core
open Lean
namespace LeanExe.Extract.Core
abbrev Ty := LeanExe.IR.Ty
abbrev IRExpr := LeanExe.IR.Expr
abbrev IRCond := LeanExe.IR.Cond
abbrev IRStmt := LeanExe.IR.Stmt
abbrev IRFunc := LeanExe.IR.Func
abbrev IRModule := LeanExe.IR.Module
structure Signature where
params : List Ty
result : Ty
deriving BEq, Repr
structure SyntheticFunction where
name : Name
sig : Signature
value : Expr
typeName : Name
typeParams : List Ty
dynamicPostArgTypes : List Ty
captureIndices : List Nat
captureTypes : List Ty
motive : Expr
step : Expr
postArgs : List Expr
inductive ExtractedValue where
| scalar (expr : IRExpr)
| array (owner ptr : IRExpr)
| byteArray (owner ptr len : IRExpr)
| product (left right : ExtractedValue)
| sum (tag : IRExpr) (left right : ExtractedValue)
| struct (name : Name) (fields : List ExtractedValue)
| variant (name : Name) (tag : IRExpr) (ctors : List (List ExtractedValue))
| recursiveVariant (name : Name) (tag : IRExpr) (ctors : List (List (Ty × ExtractedValue)))
| heapVariant (name : Name) (ptr : IRExpr)
| ite (cond : IRCond) (thenValue elseValue : ExtractedValue)
| letE (slot : Nat) (value : IRExpr) (body : ExtractedValue)
| letCall (slots : List Nat) (index : Nat) (args : List IRExpr) (body : ExtractedValue)
| letLocal (lets : List LeanExe.IR.LocalLet) (body : ExtractedValue)
deriving BEq, Repr
instance : Inhabited ExtractedValue :=
⟨.scalar .trap⟩
inductive StructuralBelow where
| unit
| call (functionName : Name) (arg : ExtractedValue) (capturedArgs : List ExtractedValue)
| pair (left right : StructuralBelow)
deriving BEq, Repr
inductive ValueLet where
| expr (slot : Nat) (value : IRExpr)
| call (slots : List Nat) (index : Nat) (args : List IRExpr)
| locals (lets : List LeanExe.IR.LocalLet)
deriving BEq, Repr
structure StrictSlots where
lets : List ValueLet
slots : List IRExpr
nextLocal : Nat
deriving BEq, Repr
structure StrictArgs where
lets : List ValueLet
args : List IRExpr
nextLocal : Nat
deriving BEq, Repr
inductive Binding where
| slot (index : Nat)
| value (value : ExtractedValue)
| thunk (locals : List Binding) (inlineStack : List Name) (expr : Expr)
| structuralRec (functionName : Name) (arg : ExtractedValue)
| structuralBelow (below : StructuralBelow)
| wfRecursor (functionName : Name)
| natRecursor (functionName : Name)
| recursor
deriving BEq, Repr
structure Context where
env : Environment
root : Name
names : Array Name
synthetics : Array SyntheticFunction
freshResultOwnerOffsets : Array (List Nat)
inlineStack : List Name
structure VariantCtorLayout where
name : Name
fields : List (Option Ty)
deriving BEq, Repr
structure VariantLayout where
name : Name
params : List Ty := []
ctors : List VariantCtorLayout
deriving BEq, Repr
partial def appFnArgsAux (expr : Expr) (args : List Expr) : Expr × List Expr :=
match expr.consumeMData with
| .app fn arg => appFnArgsAux fn (arg :: args)
| other => (other, args)
def appFnArgs (expr : Expr) : Expr × List Expr :=
appFnArgsAux expr []
def isConst (name : Name) (expr : Expr) : Bool :=
expr.consumeMData.isConstOf name
def isBVar (index : Nat) (expr : Expr) : Bool :=
match expr.consumeMData with
| .bvar candidate => candidate == index
| _ => false
partial def collectLambdas (expr : Expr) : Nat → Option Expr
| 0 => some expr
| count + 1 =>
match expr.consumeMData with
| .lam _ _ body _ => collectLambdas body count
| _ => none
def isIdType (expr : Expr) : Bool :=
isConst ``Id expr
def isOptionMonadType (expr : Expr) : Bool :=
isConst ``Option expr
def isStringType (expr : Expr) : Bool :=
isConst ``String expr
def isCharType (expr : Expr) : Bool :=
isConst ``Char expr
partial def containsBVar (index : Nat) (expr : Expr) : Bool :=
if isBVar index expr then
true
else
match expr.consumeMData with
| .app fn arg => containsBVar index fn || containsBVar index arg
| .lam _ type body _ => containsBVar (index + 1) type || containsBVar (index + 1) body
| .forallE _ type body _ => containsBVar index type || containsBVar (index + 1) body
| .letE _ type value body _ =>
containsBVar index type ||
containsBVar index value ||
containsBVar (index + 1) body
| .mdata _ body => containsBVar index body
| .proj _ _ body => containsBVar index body
| _ => false
def natLit? (expr : Expr) : Option Nat :=
match expr.consumeMData with
| .lit (.natVal value) => some value
| _ => none
def stringLit? (expr : Expr) : Option String :=
match expr.consumeMData with
| .lit (.strVal value) => some value
| _ => none
def asciiStringBytes? (value : String) : Option (List UInt8) :=
let bytes := value.toUTF8.data.toList
if bytes.all (fun byte => byte.toNat < 128) then some bytes else none
def byteArrayLiteralArrayExprAux (index : Nat) (array : IRExpr) : List UInt8 → IRExpr
| [] => array
| byte :: rest =>
byteArrayLiteralArrayExprAux
(index + 1)
(.arraySetSlots 1 0 0 array (.u64 index) [.u64 byte.toNat])
rest
def byteArrayLiteralArrayExpr (bytes : List UInt8) : IRExpr :=
byteArrayLiteralArrayExprAux 0 (.arrayAllocSlots 1 0 (.u64 bytes.length)) bytes
def byteArrayLiteralValue (slot : Nat) (bytes : List UInt8) : ExtractedValue × Nat :=
match bytes with
| [] => (.byteArray (.u64 0) (.u64 0) (.u64 0), slot)
| _ =>
let ptrSlot := slot + 1
(.letE slot (byteArrayLiteralArrayExpr bytes)
(.letE ptrSlot (.byteArrayFromArrayPtr (.local slot))
(.byteArray (.local ptrSlot) (.local ptrSlot) (.arraySize (.local slot)))),
ptrSlot + 1)
def ofNat? (typeName : Name) (expr : Expr) : Option Nat :=
match appFnArgs expr with
| (.const ``OfNat.ofNat _, [ty, value, _]) =>
if isConst typeName ty then natLit? value else none
| _ => none
def constNatValue? (env : Environment) (name : Name) : Option Nat :=
match env.find? name with
| none => none
| some info =>
match info.value? with
| none => none
| some value => ofNat? ``Nat value
def runtimeNatLimit : Nat :=
2 ^ 64
def boundedNatExpr (value : Nat) : Except String IRExpr :=
if value < runtimeNatLimit then
.ok (.u64 value)
else
.error s!"Nat literal exceeds bounded runtime representation: {value}"
def scalarLiteralExpr? (expr : Expr) : Option (Except String IRExpr) :=
match natLit? expr with
| some value => some (boundedNatExpr value)
| none =>
match ofNat? ``UInt64 expr with
| some value => some (.ok (.u64 value))
| none =>
match ofNat? ``UInt8 expr with
| some value => some (.ok (.u64 (value % 256)))
| none =>
match ofNat? ``UInt32 expr with
| some value => some (.ok (.u64 (value % (2 ^ 32))))
| none =>
match ofNat? ``Nat expr with
| some value => some (boundedNatExpr value)
| none => none
partial def peelForall (expr : Expr) : List Expr × Expr :=
match expr.consumeMData with
| .forallE _ domain body _ =>
let rest := peelForall body
(domain :: rest.fst, rest.snd)
| other => ([], other)
def nonRuntimeEvidenceTypeNames : List Name :=
[``Inhabited, ``Decidable, ``BEq, ``LT, ``LE, ``OfNat, ``HAdd, ``HSub, ``HMul, ``HDiv,
``HMod, ``GetElem, ``GetElem?]
def importedClassName (env : Environment) (name : Name) : Bool :=
env.allImportedModuleNames.any fun moduleName =>
match env.getModuleIdx? moduleName with
| some idx =>
let entries :=
PersistentEnvExtension.getModuleEntries classExtension env idx (level := .private)
entries.any fun entry => entry.name == name
| none => false
def className (env : Environment) (name : Name) : Bool :=
isClass env name || importedClassName env name
def isRuntimeStructure (env : Environment) (name : Name) : Bool :=
isStructure env name && !className env name && !nonRuntimeEvidenceTypeNames.contains name
def structureInductiveInfo? (env : Environment) (structName : Name) : Option InductiveVal :=
if !isRuntimeStructure env structName then
none
else
match env.find? structName with
| some (.inductInfo info) =>
if info.numIndices == 0 && info.ctors.length == 1 && !info.isRec then
some info
else
none
| _ => none
def structureCtorInfo? (env : Environment) (structName : Name) : Option ConstructorVal :=
match structureInductiveInfo? env structName with
| some info =>
match info.ctors with
| ctorName :: [] =>
match env.find? ctorName with
| some (.ctorInfo ctorInfo) => some ctorInfo
| _ => none
| _ => none
| none => none
def builtinInductiveNames : List Name :=
[``Bool, ``Nat, ``Unit, ``Option, ``Except, ``Prod, ``PSum, ``String]
def userInductiveInfo? (env : Environment) (typeName : Name) : Option InductiveVal :=
if builtinInductiveNames.contains typeName || isRuntimeStructure env typeName ||
className env typeName || nonRuntimeEvidenceTypeNames.contains typeName then
none
else
match env.find? typeName with
| some (.inductInfo info) =>
if info.numIndices == 0 && !info.isRec && !info.ctors.isEmpty then
some info
else
none
| _ => none
def userRecursiveInductiveInfo? (env : Environment) (typeName : Name) : Option InductiveVal :=
if builtinInductiveNames.contains typeName || isRuntimeStructure env typeName ||
className env typeName || nonRuntimeEvidenceTypeNames.contains typeName then
none
else
match env.find? typeName with
| some (.inductInfo info) =>
if info.numIndices == 0 && info.isRec && !info.ctors.isEmpty then
some info
else
none
| _ => none
def recursiveFamilyNames? (env : Environment) (typeName : Name) (params : List Ty) :
Option (List Name) := do
let info ← userRecursiveInductiveInfo? env typeName
if params.length != info.numParams then
none
else if info.all.all (fun member =>
match userRecursiveInductiveInfo? env member with
| some memberInfo =>
memberInfo.all == info.all &&
memberInfo.numParams == info.numParams &&
memberInfo.numIndices == 0
| none => false) then
some info.all
else
none
def runtimeTypesFromKinds (kinds : List (Option Ty)) : List Ty :=
kinds.filterMap id
def ctorIndex? (ctorName : Name) (ctors : List VariantCtorLayout) : Option Nat :=
let rec loop : Nat → List VariantCtorLayout → Option Nat
| _, [] => none
| index, ctor :: rest =>
if ctor.name == ctorName then
some index
else
loop (index + 1) rest
loop 0 ctors
partial def isProofType? (env : Environment) (expr : Expr) : Bool :=
match expr.consumeMData with
| .sort .zero => true
| .forallE _ _ body _ => isProofType? env body
| .mdata _ body => isProofType? env body
| _ =>
match appFnArgs expr with
| (fn, args) =>
match fn.consumeMData with
| .const name _ =>
match env.find? name with
| some info =>
let parts := peelForall info.type
if args.length >= parts.fst.length then
parts.snd.consumeMData.isProp
else
false
| none => false
| _ => false
def runtimeFieldIndexFromKinds (sourceIndex : Nat) (kinds : List (Option Ty)) :
Option (Option Nat) :=
let rec loop : Nat → Nat → List (Option Ty) → Option (Option Nat)
| _, _, [] => none
| currentSource, currentRuntime, kind :: rest =>
if currentSource == sourceIndex then
match kind with
| some _ => some (some currentRuntime)
| none => some none
else
let nextRuntime :=
match kind with
| some _ => currentRuntime + 1
| none => currentRuntime
loop (currentSource + 1) nextRuntime rest
loop 0 0 kinds
partial def tyExpr? : Ty → Option Expr
| .unit => some (.const ``Unit [])
| .bool => some (.const ``Bool [])
| .u8 => some (.const ``UInt8 [])
| .u32 => some (.const ``UInt32 [])
| .u64 => some (.const ``UInt64 [])
| .nat => some (.const ``Nat [])
| .byteArray => some (.const ``ByteArray [])
| .array item => tyExpr? item |>.map (fun itemExpr => .app (.const ``Array []) itemExpr)
| .product left right => do
let leftExpr ← tyExpr? left
let rightExpr ← tyExpr? right
some (.app (.app (.const ``Prod []) leftExpr) rightExpr)
| .struct name params _ => do
let paramExprs ← params.mapM tyExpr?
some (paramExprs.foldl (fun acc param => .app acc param) (.const name []))
| .variant name params [[], [payload]] =>
if name == ``Option then
tyExpr? payload |>.map (fun payloadExpr => .app (.const ``Option []) payloadExpr)
else do
let paramExprs ← params.mapM tyExpr?
some (paramExprs.foldl (fun acc param => .app acc param) (.const name []))
| .variant name params [[error], [ok]] =>
if name == ``Except then do
let errorExpr ← tyExpr? error
let okExpr ← tyExpr? ok
some (.app (.app (.const ``Except []) errorExpr) okExpr)
else do
let paramExprs ← params.mapM tyExpr?
some (paramExprs.foldl (fun acc param => .app acc param) (.const name []))
| .variant name params _ => do
let paramExprs ← params.mapM tyExpr?
some (paramExprs.foldl (fun acc param => .app acc param) (.const name []))
| .recVariant name params => do
let paramExprs ← params.mapM tyExpr?
some (paramExprs.foldl (fun acc param => .app acc param) (.const name []))
| .sum left right => do
let leftExpr ← tyExpr? left
let rightExpr ← tyExpr? right
some (.app (.app (.const ``PSum []) leftExpr) rightExpr)
def ctorFieldDomainsWithParams? (ctorInfo : ConstructorVal) (params : List Ty) :
Option (List Expr) := do
if params.length != ctorInfo.numParams then
none
else
let paramExprs ← params.mapM tyExpr?
let fields := (peelForall ctorInfo.type).fst.drop ctorInfo.numParams
if fields.length == ctorInfo.numFields then
let paramArray := paramExprs.toArray
fields.zipIdx.mapM fun item =>
let previousFields :=
(List.range item.snd).toArray.map fun i =>
.bvar (item.snd - i - 1)
some (item.fst.instantiateRev (paramArray ++ previousFields))
else
none
mutual
partial def typeAtom? (env : Environment) (expr : Expr) : Option Ty :=
if isConst ``UInt64 expr then
some .u64
else if isConst ``Nat expr then
some .nat
else if isConst ``Bool expr then
some .bool
else if isConst ``Unit expr then
some .unit
else if isConst ``PUnit expr then
some .unit
else if isConst ``UInt8 expr then
some .u8
else if isConst ``UInt32 expr then
some .u32
else if isConst ``ByteArray expr then
some .byteArray
else if isStringType expr || isCharType expr then
none
else
match appFnArgs expr with
| (.const ``Array _, [item]) => typeAtom? env item |>.map .array
| (.const ``Prod _, [left, right]) =>
match typeAtom? env left, typeAtom? env right with
| some leftTy, some rightTy => some (.product leftTy rightTy)
| _, _ => none
| (.const ``PSum _, [left, right]) =>
match typeAtom? env left, typeAtom? env right with
| some leftTy, some rightTy => some (.sum leftTy rightTy)
| _, _ => none
| (.const ``PSum.casesOn _, [_left, _right, _motive, _scrutinee, leftArm, rightArm]) =>
match collectLambdas leftArm 1, collectLambdas rightArm 1 with
| some leftBody, some rightBody =>
match typeAtom? env leftBody, typeAtom? env rightBody with
| some leftTy, some rightTy =>
if leftTy == rightTy then some leftTy else none
| _, _ => none
| _, _ => none
| (.const ``Option _, [item]) =>
typeAtom? env item |>.map (fun itemTy => .variant ``Option [itemTy] [[], [itemTy]])
| (.const ``Except _, [error, ok]) =>
match typeAtom? env error, typeAtom? env ok with
| some errorTy, some okTy =>
some (.variant ``Except [errorTy, okTy] [[errorTy], [okTy]])
| _, _ => none
| (.const name _, args) =>
if nonRuntimeEvidenceTypeNames.contains name then
none
else
match args.mapM (typeAtom? env) with
| some params =>
if isRuntimeStructure env name then
structureFieldKindsWithParams? env name params |>.map fun fields =>
.struct name params (runtimeTypesFromKinds fields)
else
match variantLayoutWithParams? env name params with
| some layout =>
some (.variant name params (layout.ctors.map fun ctor =>
runtimeTypesFromKinds ctor.fields))
| none =>
recursiveVariantLayout? env name params |>.map fun _layout =>
.recVariant name params
| none => none
| _ => none
partial def structureFieldKindsWithParams? (env : Environment) (structName : Name)
(params : List Ty) :
Option (List (Option Ty)) :=
if !isRuntimeStructure env structName then
none
else
match structureCtorInfo? env structName with
| some ctorInfo =>
if params.length != ctorInfo.numParams then
none
else
let fields? := ctorFieldDomainsWithParams? ctorInfo params
let flatFieldNames :=
(getStructureFieldsFlattened env structName (includeSubobjectFields := false)).toList
match fields? with
| some fields =>
if fields.length == ctorInfo.numFields && fields.length == flatFieldNames.length then
fields.mapM fun field =>
if isProofType? env field then
some none
else
typeAtom? env field |>.map some
else
none
| none => none
| none => none
partial def structureFieldKinds? (env : Environment) (structName : Name) :
Option (List (Option Ty)) :=
structureFieldKindsWithParams? env structName []
partial def structureFieldTypes? (env : Environment) (structName : Name) : Option (List Ty) :=
structureFieldKinds? env structName |>.map (fun fields => fields.filterMap id)
partial def structureTypeLayout? (env : Environment) (expr : Expr) :
Option (Name × List (Option Ty)) :=
match appFnArgs expr with
| (.const name _, args) =>
if isRuntimeStructure env name then
match args.mapM (typeAtom? env) with
| some params =>
structureFieldKindsWithParams? env name params |>.map fun fields => (name, fields)
| none => none
else
none
| _ => none
partial def variantLayoutWithParams? (env : Environment) (typeName : Name)
(params : List Ty) : Option VariantLayout :=
match userInductiveInfo? env typeName with
| some info =>
if params.length != info.numParams then
none
else
let ctorLayouts? := info.ctors.mapM fun ctorName =>
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
if ctorInfo.numParams == info.numParams && ctorInfo.induct == typeName then
match ctorFieldDomainsWithParams? ctorInfo params with
| some fields =>
fields.mapM (fun field =>
if isProofType? env field then
some none
else
typeAtom? env field |>.map some) |>.map fun fieldKinds =>
({ name := ctorName, fields := fieldKinds } : VariantCtorLayout)
| none => none
else
none
| _ => none
ctorLayouts? |>.map fun ctors =>
({ name := typeName, params := params, ctors := ctors } : VariantLayout)
| none => none
partial def variantLayout? (env : Environment) (typeName : Name) : Option VariantLayout :=
variantLayoutWithParams? env typeName []
partial def variantTypeLayout? (env : Environment) (expr : Expr) :
Option VariantLayout :=
match appFnArgs expr with
| (.const name _, args) =>
match args.mapM (typeAtom? env) with
| some params => variantLayoutWithParams? env name params
| none => none
| _ => none
partial def typeAtomRecursiveField?
(env : Environment)
(familyNames : List Name)
(familyParams : List Ty)
(expr : Expr) :
Option Ty :=
match appFnArgs expr with
| (.const ``Array _, [item]) =>
typeAtomRecursiveField? env familyNames familyParams item |>.map .array
| (.const ``Prod _, [left, right]) =>
match typeAtomRecursiveField? env familyNames familyParams left,
typeAtomRecursiveField? env familyNames familyParams right with
| some leftTy, some rightTy => some (.product leftTy rightTy)
| _, _ => none
| (.const ``PSum _, [left, right]) =>
match typeAtomRecursiveField? env familyNames familyParams left,
typeAtomRecursiveField? env familyNames familyParams right with
| some leftTy, some rightTy => some (.sum leftTy rightTy)
| _, _ => none
| (.const ``Option _, [item]) =>
typeAtomRecursiveField? env familyNames familyParams item |>.map
(fun itemTy => .variant ``Option [itemTy] [[], [itemTy]])
| (.const ``Except _, [error, ok]) =>
match typeAtomRecursiveField? env familyNames familyParams error,
typeAtomRecursiveField? env familyNames familyParams ok with
| some errorTy, some okTy =>
some (.variant ``Except [errorTy, okTy] [[errorTy], [okTy]])
| _, _ => none
| (.const name _, args) =>
if familyNames.contains name then
match args.mapM (typeAtom? env) with
| some params =>
if params == familyParams then some (.recVariant name familyParams) else none
| none => none
else
match typeAtom? env expr with
| some (.recVariant _ _) => none
| other => other
| _ =>
match typeAtom? env expr with
| some (.recVariant _ _) => none
| other => other
partial def recursiveVariantLayout? (env : Environment) (typeName : Name) (params : List Ty := []) :
Option VariantLayout :=
match userRecursiveInductiveInfo? env typeName with
| some info =>
match recursiveFamilyNames? env typeName params with
| none => none
| some familyNames =>
let ctorLayouts? := info.ctors.mapM fun ctorName =>
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
if ctorInfo.numParams == info.numParams && ctorInfo.induct == typeName then
match ctorFieldDomainsWithParams? ctorInfo params with
| some fields =>
fields.mapM (fun field =>
if isProofType? env field then
some none
else
typeAtomRecursiveField? env familyNames params field |>.map some)
|>.map fun fieldKinds =>
({ name := ctorName, fields := fieldKinds } : VariantCtorLayout)
| none => none
else
none
| _ => none
ctorLayouts? |>.map fun ctors =>
({ name := typeName, params := params, ctors := ctors } : VariantLayout)
| none => none
end
def anyVariantLayout? (env : Environment) (typeName : Name) : Option VariantLayout :=
match variantLayout? env typeName with
| some layout => some layout
| none => recursiveVariantLayout? env typeName
def structureConstructorForArgs? (env : Environment) (ctorName : Name) (args : List Expr) :
Option (Name × List (Option Ty) × List Expr) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
if ctorInfo.cidx == 0 && isRuntimeStructure env ctorInfo.induct then
let paramArgs := args.take ctorInfo.numParams
let runtimeArgs := args.drop ctorInfo.numParams
match paramArgs.mapM (typeAtom? env) with
| some params =>
structureFieldKindsWithParams? env ctorInfo.induct params |>.map fun fields =>
(ctorInfo.induct, fields, runtimeArgs)
| none => none
else
none
| _ => none
def structureConstructor? (env : Environment) (ctorName : Name) :
Option (Name × List (Option Ty)) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
if ctorInfo.numParams == 0 && ctorInfo.cidx == 0 &&
isRuntimeStructure env ctorInfo.induct then
structureFieldKinds? env ctorInfo.induct |>.map (fun fields => (ctorInfo.induct, fields))
else
none
| _ => none
def variantConstructor? (env : Environment) (ctorName : Name) :
Option (VariantLayout × Nat × VariantCtorLayout) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
match variantLayout? env ctorInfo.induct with
| some layout =>
match ctorIndex? ctorName layout.ctors with
| some index =>
match layout.ctors[index]? with
| some ctor => some (layout, index, ctor)
| none => none
| none => none
| none => none
| _ => none
def variantConstructorForArgs? (env : Environment) (ctorName : Name) (args : List Expr) :
Option (VariantLayout × Nat × VariantCtorLayout × List Expr) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
let paramArgs := args.take ctorInfo.numParams
let runtimeArgs := args.drop ctorInfo.numParams
match paramArgs.mapM (typeAtom? env) with
| some params =>
match variantLayoutWithParams? env ctorInfo.induct params with
| some layout =>
match ctorIndex? ctorName layout.ctors with
| some index =>
match layout.ctors[index]? with
| some ctor => some (layout, index, ctor, runtimeArgs)
| none => none
| none => none
| none => none
| none => none
| _ => none
def recursiveVariantConstructor? (env : Environment) (ctorName : Name) :
Option (VariantLayout × Nat × VariantCtorLayout) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
match recursiveVariantLayout? env ctorInfo.induct [] with
| some layout =>
match ctorIndex? ctorName layout.ctors with
| some index =>
match layout.ctors[index]? with
| some ctor => some (layout, index, ctor)
| none => none
| none => none
| none => none
| _ => none
def recursiveVariantConstructorForArgs? (env : Environment) (ctorName : Name) (args : List Expr) :
Option (VariantLayout × Nat × VariantCtorLayout × List Expr) :=
match env.find? ctorName with
| some (.ctorInfo ctorInfo) =>
let paramArgs := args.take ctorInfo.numParams
let runtimeArgs := args.drop ctorInfo.numParams
match paramArgs.mapM (typeAtom? env) with
| some params =>
match recursiveVariantLayout? env ctorInfo.induct params with
| some layout =>
match ctorIndex? ctorName layout.ctors with
| some index =>
match layout.ctors[index]? with
| some ctor => some (layout, index, ctor, runtimeArgs)
| none => none
| none => none
| none => none
| none => none
| _ => none
def anyVariantConstructor? (env : Environment) (ctorName : Name) :
Option (VariantLayout × Nat × VariantCtorLayout) :=
match variantConstructor? env ctorName with
| some result => some result
| none => recursiveVariantConstructor? env ctorName
def structureProjection? (env : Environment) (projName : Name) :
Option (Name × Option Nat) :=
match env.getProjectionFnInfo? projName with
| some projInfo =>
if projInfo.numParams == 0 then
match env.find? projInfo.ctorName with
| some (.ctorInfo ctorInfo) =>
if ctorInfo.numParams == 0 && isRuntimeStructure env ctorInfo.induct then
match structureFieldKinds? env ctorInfo.induct with
| some kinds =>
runtimeFieldIndexFromKinds projInfo.i kinds |>.map (fun index? =>
(ctorInfo.induct, index?))
| none => none
else
none
| _ => none
else
none
| none => none
def structureProjectionForArgs? (env : Environment) (projName : Name) (args : List Expr) :
Option (Name × Option Nat × Expr) :=
match env.getProjectionFnInfo? projName with
| some projInfo =>
match env.find? projInfo.ctorName with
| some (.ctorInfo ctorInfo) =>
if isRuntimeStructure env ctorInfo.induct then
let paramArgs := args.take projInfo.numParams
let restArgs := args.drop projInfo.numParams
match paramArgs.mapM (typeAtom? env), restArgs with
| some params, target :: [] =>
match structureFieldKindsWithParams? env ctorInfo.induct params with
| some kinds =>
runtimeFieldIndexFromKinds projInfo.i kinds |>.map fun index? =>
(ctorInfo.induct, index?, target)
| none => none
| _, _ => none
else
none
| _ => none
| none => none
def supportedArrayCellType : Ty → Bool
| .bool => true
| .u8 => true
| .u32 => true
| .u64 => true
| .nat => true
| _ => false
inductive ValueLayout where
| scalar
| pointer
| fixed (slots : Nat)
deriving BEq, Repr
def ValueLayout.slotCount : ValueLayout → Nat
| .scalar => 1
| .pointer => 1
| .fixed slots => slots
mutual
partial def valueLayout? : Ty → Option ValueLayout
| .unit => some .scalar
| .bool => some .scalar
| .u8 => some .scalar
| .u32 => some .scalar
| .u64 => some .scalar
| .nat => some .scalar
| .byteArray => some (.fixed 3)
| .array item => do
let _ ← arrayElementLayout? item
some (.fixed 2)
| .product left right => do
let leftSlots ← valueLayoutSlots? left
let rightSlots ← valueLayoutSlots? right
some (.fixed (leftSlots + rightSlots))
| .sum left right => do
let leftSlots ← valueLayoutSlots? left
let rightSlots ← valueLayoutSlots? right
some (.fixed (leftSlots + rightSlots + 1))
| .struct _ _ fields => do
let slots ← valueFieldSlots? fields
some (.fixed slots)
| .variant _ _ ctors => do
let payloadSlots ← valueCtorSlots? ctors
some (.fixed (payloadSlots + 1))
| .recVariant _ _ => some .pointer
partial def valueLayoutSlots? (ty : Ty) : Option Nat := do
let layout ← valueLayout? ty
some layout.slotCount
partial def valueFieldSlots? : List Ty → Option Nat
| [] => some 0
| field :: rest => do
let head ← valueLayoutSlots? field
let tail ← valueFieldSlots? rest
some (head + tail)
partial def valueCtorSlots? : List (List Ty) → Option Nat
| [] => some 0
| fields :: rest => do
let head ← valueFieldSlots? fields
let tail ← valueCtorSlots? rest
some (head + tail)
partial def arrayElementLayout? : Ty → Option ValueLayout
| .unit => some .scalar
| .bool => some .scalar
| .u8 => some .scalar
| .u32 => some .scalar
| .u64 => some .scalar
| .nat => some .scalar
| .array item => do
let _ ← arrayElementLayout? item
some (.fixed 2)
| .product left right => do
let leftSlots ← arrayElementSlots? left
let rightSlots ← arrayElementSlots? right
some (.fixed (leftSlots + rightSlots))
| .sum left right => do
let leftSlots ← arrayElementSlots? left
let rightSlots ← arrayElementSlots? right
some (.fixed (leftSlots + rightSlots + 1))
| .struct _ _ fields => do
let slots ← arrayFieldSlots? fields
some (.fixed slots)
| .variant _ _ ctors => do
let payloadSlots ← arrayCtorSlots? ctors
some (.fixed (payloadSlots + 1))
| .recVariant _ _ => some .pointer
| .byteArray => some (.fixed 3)
partial def arrayElementSlots? (ty : Ty) : Option Nat := do
let layout ← arrayElementLayout? ty
some layout.slotCount
partial def arrayFieldSlots? : List Ty → Option Nat
| [] => some 0
| field :: rest => do
let head ← arrayElementSlots? field
let tail ← arrayFieldSlots? rest
some (head + tail)
partial def arrayCtorSlots? : List (List Ty) → Option Nat
| [] => some 0
| fields :: rest => do
let head ← arrayFieldSlots? fields
let tail ← arrayCtorSlots? rest
some (head + tail)
end
def supportedArrayElementType (ty : Ty) : Bool :=
arrayElementSlots? ty |>.isSome
partial def supportedPublicArrayElementType : Ty → Bool
| .bool => true
| .u8 => true
| .u32 => true
| .u64 => true
| .nat => true
| .byteArray => true
| .array item => supportedPublicArrayElementType item
| .struct _ _ fields => fields.all supportedPublicArrayElementType
| .variant _ _ ctors => ctors.all (fun fields => fields.all supportedPublicArrayElementType)
| _ => false
def supportedAbiType : Ty → Bool
| .bool => true
| .u8 => true
| .u32 => true
| .u64 => true
| .nat => true
| .array item => supportedPublicArrayElementType item
| _ => false
partial def supportedParamAbiType : Ty → Bool
| .byteArray => true
| .struct _ _ fields => fields.all supportedParamAbiType
| .variant _ _ ctors => ctors.all (fun fields => fields.all supportedParamAbiType)
| ty => supportedAbiType ty
partial def supportedResultAbiType : Ty → Bool
| .byteArray => true
| .struct _ _ fields => fields.all supportedResultAbiType
| .variant _ _ ctors => ctors.all (fun fields => fields.all supportedResultAbiType)
| ty => supportedAbiType ty
def supportedInternalValueType (ty : Ty) : Bool :=
valueLayout? ty |>.isSome
def supportedInternalParamType : Ty → Bool
| .byteArray => true
| ty => supportedInternalValueType ty
def supportedInternalResultType : Ty → Bool :=
supportedInternalValueType
partial def abiSlots : Ty → Nat
| .byteArray => 2
| .sum left right => 1 + abiSlots left + abiSlots right
| .struct _ _ fields => fields.foldl (fun total field => total + abiSlots field) 0
| .variant _ _ ctors =>
1 + ctors.foldl
(fun total fields => total + fields.foldl (fun acc field => acc + abiSlots field) 0)
0
| .recVariant _ _ => 1
| _ => 1
partial def internalSlots : Ty → Nat
| .byteArray => 3
| .array _ => 2
| .product left right => internalSlots left + internalSlots right
| .sum left right => 1 + internalSlots left + internalSlots right
| .struct _ _ fields => fields.foldl (fun total field => total + internalSlots field) 0
| .variant _ _ ctors =>
1 + ctors.foldl
(fun total fields => total + fields.foldl (fun acc field => acc + internalSlots field) 0)
0
| .recVariant _ _ => 1
| _ => 1
def abiParamCount (params : List Ty) : Nat :=
params.foldl (fun total ty => total + abiSlots ty) 0
def functionParamSlots (useAbi : Bool) (ty : Ty) : Nat :=
if useAbi then abiSlots ty else internalSlots ty
def functionParamCount (useAbi : Bool) (params : List Ty) : Nat :=
params.foldl (fun total ty => total + functionParamSlots useAbi ty) 0
def functionTypeWith?