-
Notifications
You must be signed in to change notification settings - Fork 125
/
defunctorize.fun
1113 lines (1090 loc) · 48.5 KB
/
defunctorize.fun
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
(* Copyright (C) 2015,2017,2019-2020 Matthew Fluet.
* Copyright (C) 1999-2008 Henry Cejtin, Matthew Fluet, Suresh
* Jagannathan, and Stephen Weeks.
* Copyright (C) 1997-2000 NEC Research Institute.
*
* MLton is released under a HPND-style license.
* See the file MLton-LICENSE for details.
*)
functor Defunctorize (S: DEFUNCTORIZE_STRUCTS): DEFUNCTORIZE =
struct
open S
local
open CoreML
in
structure Const = Const
structure Cdec = Dec
structure Cexp = Exp
structure Clambda = Lambda
structure Cpat = Pat
structure Prim = Prim
structure RealSize = RealSize
structure Record = Record
structure SortedRecord = SortedRecord
structure SourceInfo = SourceInfo
structure Ctype = Type
structure WordSize = WordSize
structure WordX = WordX
end
structure Field = Record.Field
local
open Xml
in
structure Xcases = Cases
structure Con = Con
structure Xdec = Dec
structure Xexp = DirectExp
structure Xlambda = Lambda
structure Xpat = Pat
structure XprimExp = PrimExp
structure Tycon = Tycon
structure Xtype = Type
structure Tyvar = Tyvar
structure Var = Var
structure XvarExp = VarExp
end
structure NestedPat = NestedPat (open Xml)
structure MatchCompile =
MatchCompile (open Xml
structure Type = Xtype
structure NestedPat = NestedPat
structure Exp =
struct
open Xexp
val lett = let1
val var = monoVar
fun detuple {tuple, body} =
Xexp.detuple
{tuple = tuple,
body = fn xts => body (Vector.map
(xts, fn (x, t) =>
(XvarExp.var x, t)))}
fun devector {vector, length, body} =
Xexp.devector
{vector = vector,
length = length,
body = fn xts => body (Vector.map
(xts, fn (x, t) =>
(XvarExp.var x, t)))}
end)
structure Xexp =
struct
open Xexp
local
fun exn (c: Con.t): Xexp.t =
conApp {arg = NONE,
con = c,
targs = Vector.new0 (),
ty = Xtype.exn}
in
val bind = exn Con.bind
val match = exn Con.match
end
end
fun enterLeave (e: Xexp.t, t, si): Xexp.t =
Xexp.fromExp (Xml.Exp.enterLeave (Xexp.toExp e, t, si), t)
local
val matchDiagnostics: (unit -> unit) list ref = ref []
in
fun addMatchDiagnostic (diag, mkArg) =
case diag of
Control.Elaborate.DiagEIW.Error =>
List.push (matchDiagnostics, Control.error o mkArg)
| Control.Elaborate.DiagEIW.Ignore => ()
| Control.Elaborate.DiagEIW.Warn =>
List.push (matchDiagnostics, Control.warning o mkArg)
fun showMatchDiagnostics () = List.foreach (!matchDiagnostics, fn th => th ())
end
fun casee {ctxt: unit -> Layout.t,
caseType: Xtype.t,
cases: {exp: Xexp.t,
layPat: (unit -> Layout.t) option,
pat: NestedPat.t,
regionPat: Region.t} vector,
conTycon,
kind: (string * string),
nest: string list,
matchDiags: {nonexhaustiveExn: Control.Elaborate.DiagDI.t,
nonexhaustive: Control.Elaborate.DiagEIW.t,
redundant: Control.Elaborate.DiagEIW.t},
noMatch,
region: Region.t,
test = (test: Xexp.t, testType: Xtype.t),
tyconCons}: Xexp.t =
let
val nonexhaustiveExnDiag = #nonexhaustiveExn matchDiags
val nonexhaustiveDiag = #nonexhaustive matchDiags
val redundantDiag = #redundant matchDiags
val cases = Vector.map (cases, fn {exp, layPat, pat, regionPat} =>
{exp = fn () => exp,
isDefault = false,
layPat = layPat,
numPats = ref 0,
numUses = ref 0,
pat = pat,
regionPat = regionPat})
fun raiseExn (f, mayWrap) =
let
val e = Var.newNoname ()
val exp = Xexp.raisee {exn = f e, extend = true, ty = caseType}
val exp =
fn () =>
if let
open Control
in
!profile <> ProfileNone
andalso !profileIL = ProfileSource
andalso !profileRaise
end
then case mayWrap of
NONE => exp
| SOME kind =>
enterLeave
(exp, caseType,
SourceInfo.function
{name = (concat ["<raise ", kind, ">"]) :: nest,
region = region})
else exp
in
Vector.concat
[cases,
Vector.new1 {exp = exp,
isDefault = true,
layPat = NONE,
numPats = ref 0,
numUses = ref 0,
pat = NestedPat.make (NestedPat.Var e, testType),
regionPat = Region.bogus}]
end
val cases =
let
datatype z = datatype Cexp.noMatch
in
case noMatch of
Impossible => cases
| RaiseAgain =>
raiseExn (fn e => Xexp.monoVar (e, Xtype.exn), NONE)
| RaiseBind => raiseExn (fn _ => Xexp.bind, SOME "Bind")
| RaiseMatch => raiseExn (fn _ => Xexp.match, SOME "Match")
end
fun matchCompile () =
let
val testVar = Var.newNoname ()
val decs = ref []
val cases =
Vector.map
(cases, fn {exp = e, numPats, numUses, pat = p, ...} =>
let
val args = Vector.fromList (NestedPat.varsAndTypes p)
val (vars, tys) = Vector.unzip args
val func = Var.newNoname ()
val arg = Var.newNoname ()
val argType = Xtype.tuple tys
val funcType = Xtype.arrow (argType, caseType)
fun dec () =
Xdec.MonoVal
{var = func,
ty = funcType,
exp =
XprimExp.Lambda
(Xlambda.make
{arg = arg,
argType = argType,
body = (Xexp.toExp
(Xexp.detupleBind
{tuple = Xexp.monoVar (arg, argType),
components = vars,
body = e ()})),
mayInline = true})}
fun finish np =
(numPats := np
; fn rename =>
(if 0 = !numUses then List.push (decs, dec ()) else ()
; Int.inc numUses
; (Xexp.app
{func = Xexp.monoVar (func, funcType),
arg =
Xexp.tuple {exps = (Vector.map
(args, fn (x, t) =>
Xexp.monoVar (rename x, t))),
ty = argType},
ty = caseType})))
in
(p, finish)
end)
val (body, nonexhaustiveExamples) =
MatchCompile.matchCompile {caseType = caseType,
cases = cases,
conTycon = conTycon,
test = testVar,
testType = testType,
tyconCons = tyconCons}
(* Must convert to a normal expression to force everything. *)
val body = Xexp.toExp body
val nonexhaustiveExamples =
if noMatch = Cexp.Impossible
then NONE
else let
val dropOnlyExns =
case nonexhaustiveExnDiag of
Control.Elaborate.DiagDI.Default =>
{dropOnlyExns = false}
| Control.Elaborate.DiagDI.Ignore =>
{dropOnlyExns = true}
in
nonexhaustiveExamples dropOnlyExns
end
in
(Xexp.let1 {var = testVar,
exp = test,
body = Xexp.lett {decs = !decs,
body = Xexp.fromExp (body, caseType)}},
nonexhaustiveExamples)
end
datatype z = datatype NestedPat.node
fun lett (x, e) = Xexp.let1 {var = x, exp = test, body = e}
fun wild e = lett (Var.newNoname (), e)
val (exp, nonexhaustiveExamples) =
if Vector.isEmpty cases
then Error.bug "Defunctorize.casee: case with no patterns"
else
let
val {exp = e, pat = p, numPats, numUses, ...} = Vector.first cases
fun use () = (numPats := 1; numUses := 1)
fun exhaustive exp = (exp, NONE)
fun loop p =
case NestedPat.node p of
Wild => (use (); exhaustive (wild (e ())))
| Var x => (use (); exhaustive (lett (x, e ())))
| Record rps =>
let
val ps = SortedRecord.range rps
fun doitRecord () =
(* It's a flat record pattern.
* Generate the selects.
*)
let
val _ = use ()
val t = Var.newNoname ()
val tuple = XvarExp.mono t
val tys = Xtype.deTuple testType
val (_, decs) =
Vector.fold2
(ps, tys, (0, []),
fn (p, ty, (i, decs)) =>
case NestedPat.node p of
Var x =>
(i + 1,
Xdec.MonoVal
{var = x,
ty = ty,
exp = (XprimExp.Select
{tuple = tuple,
offset = i})}
:: decs)
| Wild => (i + 1, decs)
| _ => Error.bug "Defunctorize.casee: flat record")
in
exhaustive (Xexp.let1
{var = t, exp = test,
body = Xexp.lett
{decs = decs,
body = e ()}})
end
in
if Vector.forall (ps, NestedPat.isVarOrWild)
then if Vector.length ps = 1
then loop (Vector.first ps)
else doitRecord ()
else matchCompile ()
end
| _ => matchCompile ()
in
loop p
end
(* diagnoseRedundant *)
val _ =
Vector.foreachr
(cases, fn {isDefault, layPat = layPat,
numPats, numUses, regionPat = regionPat, ...} =>
let
fun doit (msg1, msg2) =
let
open Layout
in
addMatchDiagnostic
(redundantDiag,
fn () =>
(regionPat,
str (concat [#1 kind, msg1]),
align [seq [str (concat [msg2, ": "]),
case layPat of
NONE => Error.bug "Defunctorize.casee: redundant match with no lay"
| SOME layPat => layPat ()],
ctxt ()]))
end
in
if not isDefault andalso !numUses = 0
then ((* Rule with no uses; fully redundant. *)
doit (" has redundant " ^ #2 kind,
"redundant pattern"))
else if not isDefault andalso !numUses > 0 andalso !numUses < !numPats
then ((* Rule with some uses but fewer uses than pats; partially redundant. *)
doit (" has " ^ #2 kind ^ " with redundancy",
"pattern with redundancy"))
else ()
end)
(* diagnoseNonexhaustive *)
val _ =
Option.app
(nonexhaustiveExamples, fn es =>
let
open Layout
in
addMatchDiagnostic
(nonexhaustiveDiag,
fn () =>
(region,
str (concat [#1 kind, " is not exhaustive"]),
align [seq [str "missing pattern: ", es],
ctxt ()]))
end)
in
exp
end
val casee =
Trace.trace ("Defunctorize.casee",
Region.layout o #region,
Xml.Exp.layout o Xexp.toExp)
casee
fun 'a sortByField (v: (Field.t * 'a) vector): 'a vector =
Vector.map (QuickSort.sortVector (v, fn ((f, _), (f', _)) =>
Field.<= (f, f')),
#2)
fun valDec (tyvars: Tyvar.t vector,
x: Var.t,
e: Xexp.t,
et: Xtype.t,
e': Xexp.t): Xexp.t =
Xexp.lett {body = e',
decs = [Xdec.PolyVal {exp = Xexp.toExp e,
ty = et,
tyvars = tyvars,
var = x}]}
structure Xexp =
struct
open Xexp
fun list (es: Xexp.t vector, ty: Xtype.t, {forceLeftToRight: bool})
: Xexp.t =
let
val targs = #2 (valOf (Xtype.deConOpt ty))
val eltTy = Vector.first targs
val nill: Xexp.t =
Xexp.conApp {arg = NONE,
con = Con.nill,
targs = targs,
ty = ty}
val consArgTy = Xtype.tuple (Vector.new2 (eltTy, ty))
val cons: Xexp.t * Xexp.t -> Xexp.t =
fn (e1, e2) =>
Xexp.conApp
{arg = SOME (Xexp.tuple {exps = Vector.new2 (e1, e2),
ty = consArgTy}),
con = Con.cons,
targs = targs,
ty = ty}
in
if not forceLeftToRight
then
(* Build the list right to left. *)
Vector.foldr (es, nill, fn (e, rest) =>
let
val var = Var.newNoname ()
in
Xexp.let1 {body = cons (e, monoVar (var, ty)),
exp = rest,
var = var}
end)
else if Vector.length es < 20
then Vector.foldr (es, nill, cons)
else
let
val revArgTy = Xtype.tuple (Vector.new2 (ty, ty))
val revTy = Xtype.arrow (revArgTy, ty)
val revVar = Var.newString "rev"
fun rev (e1, e2) =
Xexp.app
{func = Xexp.monoVar (revVar, revTy),
arg = Xexp.tuple {exps = Vector.new2 (e1, e2),
ty = revArgTy},
ty = ty}
fun detuple2 (tuple: Xexp.t,
f: XvarExp.t * XvarExp.t -> Xexp.t): Xexp.t =
Xexp.detuple {body = fn xs => let
fun x i = #1 (Vector.sub (xs, i))
in
f (x 0, x 1)
end,
tuple = tuple}
val revArg = Var.newNoname ()
val revLambda =
Xlambda.make
{arg = revArg,
argType = revArgTy,
mayInline = true,
body =
Xexp.toExp
(detuple2
(Xexp.monoVar (revArg, revArgTy), fn (l, ac) =>
let
val ac = Xexp.varExp (ac, ty)
val consArg = Var.newNoname ()
in
Xexp.casee
{cases =
Xcases.Con
(Vector.new2
((Xpat.T {arg = NONE,
con = Con.nill,
targs = targs},
ac),
(Xpat.T {arg = SOME (consArg, consArgTy),
con = Con.cons,
targs = targs},
detuple2
(Xexp.monoVar (consArg, consArgTy),
fn (x, l) =>
rev (Xexp.varExp (l, ty),
cons (Xexp.varExp (x, eltTy),
ac)))))),
default = NONE,
test = Xexp.varExp (l, ty),
ty = ty}
end))}
val revDec =
Xdec.Fun
{decs = Vector.new1 {lambda = revLambda,
ty = revTy,
var = revVar},
tyvars = Vector.new0 ()}
val l = Var.newNoname ()
val (l, body) =
Vector.foldr
(es, (l, Xexp.lett {decs = [revDec],
body = rev (Xexp.monoVar (l, ty),
nill)}),
fn (e, (l, body)) =>
let
val l' = Var.newNoname ()
in
(l',
Xexp.let1 {body = body,
exp = cons (e, Xexp.monoVar (l', ty)),
var = l})
end)
in
Xexp.let1 {body = body,
exp = nill,
var = l}
end
end
end
fun defunctorize (CoreML.Program.T {decs}) =
let
val {get = conExtraArgs: Con.t -> Xtype.t vector option,
set = setConExtraArgs, destroy = destroy1, ...} =
Property.destGetSetOnce (Con.plist, Property.initConst NONE)
val {get = tyconExtraArgs: Tycon.t -> Xtype.t vector option,
set = setTyconExtraArgs, destroy = destroy2, ...} =
Property.destGetSetOnce (Tycon.plist, Property.initConst NONE)
val {destroy = destroy3, hom = loopTy} =
let
fun con (c, ts) =
let
val ts =
case tyconExtraArgs c of
NONE => ts
| SOME ts' => Vector.concat [ts', ts]
in
Xtype.con (c, ts)
end
in
Ctype.makeHom {con = con, var = Xtype.var}
end
val loopTy =
Trace.trace
("Defunctorize.loopTy", Ctype.layout, Xtype.layout)
loopTy
fun conTargs (c: Con.t, ts: Ctype.t vector): Xtype.t vector =
let
val ts = Vector.map (ts, loopTy)
in
case conExtraArgs c of
NONE => ts
| SOME ts' => Vector.concat [ts', ts]
end
val {get = conTycon, set = setConTycon, ...} =
Property.getSetOnce (Con.plist,
Property.initRaise ("conTycon", Con.layout))
val {get = tyconCons: Tycon.t -> {con: Con.t,
hasArg: bool} vector,
set = setTyconCons, ...} =
Property.getSetOnce (Tycon.plist,
Property.initRaise ("tyconCons", Tycon.layout))
val setConTycon =
Trace.trace2
("Defunctorize.setConTycon",
Con.layout, Tycon.layout, Unit.layout)
setConTycon
val datatypes = ref []
(* Process all the datatypes. *)
fun loopDec (d: Cdec.t) =
let
datatype z = datatype Cdec.t
in
case d of
Datatype dbs =>
let
val frees: Tyvar.t list ref = ref []
val _ =
Vector.foreach
(dbs, fn {cons, tyvars, ...} =>
let
fun var (a: Tyvar.t): unit =
let
fun eq a' = Tyvar.equals (a, a')
in
if Vector.exists (tyvars, eq)
orelse List.exists (!frees, eq)
then ()
else List.push (frees, a)
end
val {destroy, hom} =
Ctype.makeHom {con = fn _ => (),
var = var}
val _ =
Vector.foreach (cons, fn {arg, ...} =>
Option.app (arg, hom))
val _ = destroy ()
in
()
end)
val frees = !frees
val dbs =
if List.isEmpty frees
then dbs
else
let
val frees = Vector.fromList frees
val extra = Vector.map (frees, Xtype.var)
in
Vector.map
(dbs, fn {cons, tycon, tyvars} =>
let
val _ = setTyconExtraArgs (tycon, SOME extra)
val _ =
Vector.foreach
(cons, fn {con, ...} =>
setConExtraArgs (con, SOME extra))
in
{cons = cons,
tycon = tycon,
tyvars = Vector.concat [frees, tyvars]}
end)
end
in
Vector.foreach
(dbs, fn {cons, tycon, tyvars} =>
let
val _ =
setTyconCons (tycon,
Vector.map (cons, fn {arg, con} =>
{con = con,
hasArg = isSome arg}))
val cons =
Vector.map
(cons, fn {arg, con} =>
(setConTycon (con, tycon)
; {arg = Option.map (arg, loopTy),
con = con}))
val _ =
if Tycon.equals (tycon, Tycon.reff)
then ()
else
List.push (datatypes, {cons = cons,
tycon = tycon,
tyvars = tyvars})
in
()
end)
end
| Exception {con, ...} => setConTycon (con, Tycon.exn)
| Fun {decs, ...} => Vector.foreach (decs, loopLambda o #lambda)
| Val {rvbs, vbs, ...} =>
(Vector.foreach (rvbs, loopLambda o #lambda)
; Vector.foreach (vbs, loopExp o #exp))
end
and loopExp (e: Cexp.t): unit =
let
datatype z = datatype Cexp.node
in
case Cexp.node e of
App (e, e') => (loopExp e; loopExp e')
| Case {rules, test, ...} =>
(loopExp test
; Vector.foreach (rules, loopExp o #exp))
| Con _ => ()
| Const _ => ()
| EnterLeave (e, _) => loopExp e
| Handle {handler, try, ...} => (loopExp handler; loopExp try)
| Lambda l => loopLambda l
| Let (ds, e) => (Vector.foreach (ds, loopDec); loopExp e)
| List es => Vector.foreach (es, loopExp)
| PrimApp {args, ...} => Vector.foreach (args, loopExp)
| Raise e => loopExp e
| Record r => Record.foreach (r, loopExp)
| Seq es => Vector.foreach (es, loopExp)
| Var _ => ()
| Vector es => Vector.foreach (es, loopExp)
end
and loopLambda (l: Clambda.t): unit =
loopExp (#body (Clambda.dest l))
fun loopPat (p: Cpat.t): NestedPat.t =
let
val (p, t) = Cpat.dest p
val t' = loopTy t
datatype z = datatype Cpat.node
val p =
case p of
Con {arg, con, targs} =>
NestedPat.Con {arg = Option.map (arg, loopPat),
con = con,
targs = conTargs (con, targs)}
| Const f =>
NestedPat.Const {const = f (),
isChar = Ctype.isCharX t,
isInt = Ctype.isInt t}
| Layered (x, p) => NestedPat.Layered (x, loopPat p)
| List ps =>
let
val targs = Vector.map (#2 (valOf (Ctype.deConOpt t)),
loopTy)
in
Vector.foldr
(ps,
NestedPat.Con {arg = NONE,
con = Con.nill,
targs = targs},
fn (p, np) =>
NestedPat.Con {arg = SOME (NestedPat.tuple
(Vector.new2
(loopPat p,
NestedPat.make (np, t')))),
con = Con.cons,
targs = targs})
end
| Record r =>
NestedPat.Record
(SortedRecord.fromVector
(Vector.map
(Ctype.deRecord t, fn (f, t: Ctype.t) =>
(f,
case Record.peek (r, f) of
NONE => NestedPat.make (NestedPat.Wild, loopTy t)
| SOME p => loopPat p))))
| Or ps => NestedPat.Or (Vector.map (ps, loopPat))
| Var x => NestedPat.Var x
| Vector ps => NestedPat.Vector (Vector.map (ps, loopPat))
| Wild => NestedPat.Wild
in
NestedPat.make (p, t')
end
val _ = Vector.foreach (decs, loopDec)
(* Now, do the actual defunctorization. *)
fun loopDec (d: Cdec.t, e: Xexp.t, et: Xtype.t): Xexp.t =
let
fun prefix (d: Xdec.t) =
Xexp.lett {decs = [d], body = e}
fun processLambdas v =
Vector.map
(Vector.rev v, fn {lambda, var} =>
let
val {arg, argType, body, bodyType, mayInline} =
loopLambda lambda
in
{lambda = Xlambda.make {arg = arg,
argType = argType,
body = Xexp.toExp body,
mayInline = mayInline},
ty = Xtype.arrow (argType, bodyType),
var = var}
end)
datatype z = datatype Cdec.t
in
case d of
Datatype _ => e
| Exception {arg, con} =>
prefix (Xdec.Exception {arg = Option.map (arg, loopTy),
con = con})
| Fun {decs, tyvars} =>
prefix (Xdec.Fun {decs = processLambdas decs,
tyvars = tyvars ()})
| Val {matchDiags, rvbs, tyvars, vbs} =>
let
val tyvars = tyvars ()
val bodyType = et
val e =
Vector.foldr
(vbs, e, fn ({ctxt, exp, layPat, nest, pat, regionPat}, e) =>
let
fun patDec (p: NestedPat.t,
e: Xexp.t,
body: Xexp.t,
bodyType: Xtype.t,
mayWarn: bool) =
casee {ctxt = ctxt,
caseType = bodyType,
cases = Vector.new1 {exp = body,
layPat = SOME layPat,
pat = p,
regionPat = regionPat},
conTycon = conTycon,
kind = ("declaration", "pattern"),
nest = nest,
matchDiags = if mayWarn
then matchDiags
else {nonexhaustiveExn = Control.Elaborate.DiagDI.Default,
nonexhaustive = Control.Elaborate.DiagEIW.Ignore,
redundant = Control.Elaborate.DiagEIW.Ignore},
noMatch = Cexp.RaiseBind,
region = regionPat,
test = (e, NestedPat.ty p),
tyconCons = tyconCons}
val isExpansive = Cexp.isExpansive exp
val (exp, expType) = loopExp exp
val pat = loopPat pat
fun vd (x: Var.t) = valDec (tyvars, x, exp, expType, e)
in
if Vector.isEmpty tyvars
then patDec (pat, exp, e, bodyType, true)
else if isExpansive
then
let
val x = Var.newNoname ()
val thunk =
let
open Xexp
in
toExp
(lambda
{arg = Var.newNoname (),
argType = Xtype.unit,
body = exp,
bodyType = expType,
mayInline = true})
end
val thunkTy =
Xtype.arrow (Xtype.unit, expType)
fun subst t =
Xtype.substitute
(t, Vector.map (tyvars, fn a =>
(a, Xtype.unit)))
val body =
Xexp.app
{arg = Xexp.unit (),
func =
Xexp.var
{targs = (Vector.map
(tyvars, fn _ =>
Xtype.unit)),
ty = subst thunkTy,
var = x},
ty = subst expType}
val decs =
[Xdec.PolyVal {exp = thunk,
ty = thunkTy,
tyvars = tyvars,
var = x}]
in
patDec (NestedPat.replaceTypes (pat, subst),
Xexp.lett {body = body, decs = decs},
e, bodyType, true)
end
else
case NestedPat.node pat of
NestedPat.Wild => vd (Var.newNoname ())
| NestedPat.Var x => vd x
| _ =>
(* Polymorphic pattern.
* val 'a Foo (y1, y2) = e
* Expands to
* val 'a x = e
* val Foo (_, _) = x (* for match warnings *)
* val 'a y1 = case x of Foo (y1', _) => y1'
* val 'a y2 = case x of Foo (_, y2') => y2'
*)
let
val x = Var.newNoname ()
val xt = expType
val targs = Vector.map (tyvars, Xtype.var)
val e =
List.fold
(NestedPat.varsAndTypes pat, e,
fn ((y, yt), e) =>
let
val y' = Var.new y
val pat =
NestedPat.removeOthersReplace
(pat, {old = y, new = y'})
in
valDec
(tyvars,
y,
patDec (pat,
Xexp.var {targs = targs,
ty = xt,
var = x},
Xexp.monoVar (y', yt),
yt,
false),
yt,
e)
end)
fun instantiatePat () =
let
val pat = NestedPat.removeVars pat
fun con (_, c, ts) = Xtype.con (c, ts)
fun var (t, a) =
if (Vector.exists
(tyvars, fn a' =>
Tyvar.equals (a, a')))
then Xtype.unit
else t
val {destroy, hom} =
Xtype.makeHom {con = con,
var = var}
val pat =
NestedPat.replaceTypes
(pat, hom)
val _ = destroy ()
in
pat
end
val e =
if NestedPat.isRefutable pat
then
let
val targs =
Vector.map (tyvars, fn _ =>
Xtype.unit)
val pat = instantiatePat ()
in
patDec
(pat,
Xexp.var
{targs = targs,
ty = NestedPat.ty pat,
var = x},
e,
bodyType,
true)
end
else e
in
valDec (tyvars, x, exp, expType, e)
end
end)
in
if Vector.isEmpty rvbs
then e
else
Xexp.lett {decs = [Xdec.Fun {decs = processLambdas rvbs,
tyvars = tyvars}],
body = e}
end
end
and loopDecs (ds: Cdec.t vector, (e: Xexp.t, t: Xtype.t)): Xexp.t =
loopDecsList (Vector.toList ds, (e, t))
(* Convert vector->list to allow processed Cdecs to be GC'ed. *)
and loopDecsList (ds: Cdec.t list, (e: Xexp.t, t: Xtype.t)): Xexp.t =
List.foldr (ds, e, fn (d, e) => loopDec (d, e, t))
and loopExp (e: Cexp.t): Xexp.t * Xtype.t =
let
val (n, ty) = Cexp.dest e
val ty = loopTy ty
fun conApp {arg, con, targs, ty} =
if Con.equals (con, Con.reff)
then Xexp.primApp {args = Vector.new1 arg,
prim = Prim.Ref_ref,
targs = targs,
ty = ty}
else Xexp.conApp {arg = SOME arg,
con = con,
targs = targs,
ty = ty}
datatype z = datatype Cexp.node
val exp =
case n of
App (e1, e2) =>
let
val (e2, _) = loopExp e2
in
case Cexp.node e1 of
Con (con, targs) =>
conApp {arg = e2,
con = con,
targs = conTargs (con, targs),
ty = ty}
| _ =>
Xexp.app {arg = e2,
func = #1 (loopExp e1),
ty = ty}
end
| Case {ctxt, kind, nest, matchDiags, noMatch, region, rules, test, ...} =>
casee {ctxt = ctxt,
caseType = ty,
cases = Vector.map (rules, fn {exp, layPat, pat, regionPat} =>
{exp = #1 (loopExp exp),
layPat = layPat,
pat = loopPat pat,
regionPat = regionPat}),
conTycon = conTycon,
kind = kind,
nest = nest,
matchDiags = matchDiags,
noMatch = noMatch,
region = region,
test = loopExp test,
tyconCons = tyconCons}
| Con (con, targs) =>
let
val targs = conTargs (con, targs)
in
case Xtype.deArrowOpt ty of
NONE =>
Xexp.conApp {arg = NONE,
con = con,
targs = targs,
ty = ty}
| SOME (argType, bodyType) =>
let
val arg = Var.newNoname ()
in
Xexp.lambda
{arg = arg,
argType = argType,
body = (conApp
{arg = Xexp.monoVar (arg, argType),
con = con,
targs = targs,