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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
|
module PeNatural (pevalExpr) where
import AnsiCodes (cyan, magenta)
import List ((\\), elemIndex, find, intersect, isPrefixOf, nub)
import Maybe (fromMaybe, isNothing)
import Pretty (pPrint)
import qualified Set (Set, elem, empty, insert, null)
import Utils (indentStr)
import FlatCurry.Types
import FlatCurryGoodies
import FlatCurryPretty (ppExp)
import Heap as H
import NDState
import Normalization (freshRule, simplifyExpr, normalizeFreeExpr)
import Output (assert, colorWith, debug, traceDetail)
import PevalOpts (Options (..), ProceedMode (..))
import Subst (mkSubst, subst)
import Utils (count)
pevalExpr :: Options -> Prog -> Expr -> Expr
pevalExpr opts p e = assert (all (< 0) fvs) "PeNatural.pevalExpr"
$ normalizeFreeExpr $ simplifyExpr $ flatND e'
where
fvs = freeVars e
e' = runState (nf e) (initState opts p fresh)
fresh = - (length fvs + 1)
flatND :: Result (Expr, PEState) -> Expr
flatND (Return (e, s)) = H.dereference (pesHeap s) e
flatND (Choice a b) = mkOr (flatND a) (flatND b)
data PEState = PEState
{ pesOptions :: Options
, pesTypes :: [TypeDecl]
, pesFuncs :: [FuncDecl]
, pesHeap :: H.Heap
, pesFresh :: VarIndex
, pesUnfolded :: Set.Set QName
, pesTrace :: Int
}
initState :: Options -> Prog -> Int -> PEState
initState opts (Prog _ _ ts fs _) fresh = PEState
{ pesOptions = opts
, pesTypes = ts
, pesFuncs = fs
, pesHeap = emptyHeap
, pesFresh = fresh
, pesUnfolded = Set.empty
, pesTrace = 1
}
type PEM a = State PEState a
getOpts :: PEM Options
getOpts = getsS pesOptions
isNotUserDefined :: QName -> PEM Bool
isNotUserDefined f = isNothing <$> lookupRule f
lookupRule :: QName -> PEM (Maybe ([VarIndex], Expr))
lookupRule f
= getsS (find (hasName f) . pesFuncs) >+= \mbFunc ->
returnS $ case mbFunc of
Just (Func _ _ _ _ (Rule vs rhs)) -> Just (vs, rhs)
_ -> Nothing
getAllCons :: QName -> PEM (Maybe [QName])
getAllCons c = getsS (gac . pesTypes)
where
gac [] = Nothing
gac (t : tds) | c `elem` cs = Just cs
| otherwise = gac tds
where cs = constructors t
traceM :: String -> PEM ()
traceM msg = getOpts >+= \opts ->
getTrace >+= \t ->
returnS (traceDetail opts (indentStr (2 * t) msg) ())
assertM :: PEM Bool -> String -> PEM ()
assertM check msg = getOpts >+= \opts -> case optAssert opts of
True -> check >+= \b -> returnS $ assert b msg ()
False -> returnS ()
freshVar :: PEM VarIndex
freshVar = getS >+= \s -> let fresh = pesFresh s in
putS s { pesFresh = fresh - 1 } >+ returnS fresh
getTrace :: PEM Int
getTrace = getsS pesTrace
nestTrace :: PEM a -> PEM a
nestTrace act = modifyS (\s -> s { pesTrace = pesTrace s + 1 }) >+
act >+= \res ->
modifyS (\s -> s { pesTrace = pesTrace s - 1 }) >+
returnS res
getUnfolded :: PEM (Set.Set QName)
getUnfolded = getsS pesUnfolded
addUnfolded :: QName -> PEM ()
addUnfolded f = modifyS (\s -> s { pesUnfolded = Set.insert f (pesUnfolded s) })
proceed :: QName -> PEM Bool
proceed f =
getUnfolded >+= \set ->
getOpts >+= \opts ->
case optProceedMode opts of
PMNone -> returnS False
PMOne | Set.null set -> addUnfolded f >+ returnS True
| otherwise -> returnS False
PMEach | Set.elem f set -> returnS False
| otherwise -> addUnfolded f >+ returnS True
PMAll -> returnS True
getHeap :: PEM Heap
getHeap = getsS pesHeap
modifyHeap :: (Heap -> Heap) -> PEM ()
modifyHeap f = modifyS $ \s -> s { pesHeap = f (pesHeap s) }
getBinding :: VarIndex -> PEM Binding
getBinding v = H.getHeap v <$> getHeap
bindHole :: VarIndex -> PEM ()
bindHole v = assert (v < 0) "PeNatural.bindHole: positive variable"
$ modifyHeap (H.bindHole v)
bindE :: VarIndex -> Expr -> PEM ()
bindE v e = assert (v < 0) "PeNatural.bindE: positive variable"
$ modifyHeap (H.bindExpr v e)
bindF :: VarIndex -> PEM ()
bindF v = assert (v < 0) "PeNatural.bindF: positive variable"
$ modifyHeap (H.bindFree v)
bindP :: VarIndex -> PEM ()
bindP v = assert (v < 0) "PeNatural.bindP: positive variable"
$ modifyHeap (H.bindParam v)
bindLE :: VarIndex -> Expr -> PEM ()
bindLE v e = assert (v < 0) "PeNatural.bindLE: positive variable"
$ modifyHeap (H.bindLazyExpr v e)
bindLF :: VarIndex -> PEM ()
bindLF v = assert (v < 0) "PeNatural.bindLF: positive variable"
$ modifyHeap (H.bindLazyFree v)
bindLP :: VarIndex -> PEM ()
bindLP v = assert (v < 0) "PeNatural.bindLP: positive variable"
$ modifyHeap (H.bindLazyParam v)
bindArg :: Expr -> PEM Expr
bindArg e = case e of
Var _ -> returnS e
Let ds e' -> addBindings ds e' >+= bindArg
Free vs e' -> addFrees vs e' >+= bindArg
_ -> freshVar >+= \v -> bindE v e >+ returnS (Var v)
bindFree :: PEM Expr
bindFree = freshVar >+= \v -> bindF v >+ returnS (Var v)
nf :: Expr -> PEM Expr
nf e = peval e >+= nf'
where
nf' e' = case e' of
Comb ct qn es | isConsCall ct -> Comb ct qn <$> mapS nf' es
| otherwise -> case getSQ e' of
Just de -> nf' de >+= defer
_ -> defer e'
Case ct ce bs -> Case ct ce <$> mapS (peBranch ce) bs
_ -> defer e'
peBranch e' b = freshBranch b >+= eval
where
eval (Branch p' be') = Branch p' <$> nested (case e' of
Var x -> bindE x (pat2exp p') >+ peval (delSQ be') >+= nf'
_ -> peval (delSQ be') >+= nf')
nested :: PEM Expr -> PEM Expr
nested act =
getS >+= \s ->
let s' = s { pesOptions = (pesOptions s) { optProceedMode = PMNone } }
in defer $ flatND $ runState nestedAct s'
where
nestedAct = modifyHeap restrictToValues >+
getHeap >+= \h ->
act >+= \e' ->
modifyHeap (\h' -> h' `H.without` h) >+
returnS e'
restrictToValues h = [ b | b@(_, BoundVar e) <- h, isValue e]
where
isValue e = case e of
Var _ -> True
Lit _ -> True
Comb ConsCall _ _ -> True
Comb (ConsPartCall _) _ _ -> True
Comb (FuncPartCall _) _ _ -> True
Comb FuncCall _ _ -> isSQ e || isFailed e
_ -> False
peval :: Expr -> PEM Expr
peval e =
getOpts >+= \opts ->
getHeap >+= \h1 -> traceM (showConfig opts h1 e) >!
nestTrace (hnf e) >+= \v ->
getHeap >+= \h2 -> traceM (showConfig opts h2 v) >!
assertM (returnS $ noShadowing v) ("Shadowing\n" ++ showExpr opts v) >!
assertM (isResidualValue v) ("No value\n" ++ showConfig opts h2 v) >!
returnS v
where
showHeap opts h = colorWith opts magenta (pPrint $ ppHeap h)
showExpr opts x = colorWith opts cyan (pPrint $ ppExp x)
showConfig opts h x = showHeap opts h ++ " : " ++ showExpr opts x
isResidualValue :: Expr -> PEM Bool
isResidualValue e = case e of
Var _ -> notEvaluable e
Lit _ -> returnS True
Comb FuncCall _ _
| isFailed e -> returnS True
| otherwise -> case getSQ e of
Just e' -> returnS $ not $ hasSQ e'
_ -> notEvaluable e
Comb _ _ es -> allS isNestedValue es
where isNestedValue x = (isVar x ||) <$> isResidualValue x
Case ct (Var x) bs -> getBinding x >+= \bdg -> case bdg of
BoundVar b -> notEvaluable b
LazyBound b -> notEvaluable b
FreeVar | ct == Rigid -> allS isResidualValue (branchExprs bs)
LazyFree | ct == Rigid -> allS isResidualValue (branchExprs bs)
Param -> allS isResidualValue (branchExprs bs)
LazyParam -> allS isResidualValue (branchExprs bs)
_ -> returnS False
Case _ e' bs -> (&&) <$> notEvaluable e'
<*> allS isResidualValue (branchExprs bs)
Or e1 e2 -> (&&) <$> isResidualValue e1 <*> isResidualValue e2
_ -> returnS False
where
notEvaluable e' = case e' of
Var x -> getBinding x >+= \bdg -> case bdg of
BlackHole -> returnS False
BoundVar b -> notEvaluable b
LazyBound b -> notEvaluable b
FreeVar -> returnS True
LazyFree -> returnS True
Param -> returnS True
LazyParam -> returnS True
Comb FuncCall f es
| isFailed e' || isSQ e' -> returnS True
| otherwise -> (&&) <$> isNotUserDefined f <*>
((not (isBuiltin f) ||) <$> anyS notEvaluable es)
Case _ s _ -> notEvaluable s
_ -> returnS False
defer :: Expr -> PEM Expr
defer e = case e of
Var x -> getBinding x >+= \bdg -> case bdg of
BlackHole -> failS
FreeVar -> returnS e
LazyFree -> returnS e
Param -> returnS e
LazyParam -> returnS e
_ -> returnS $ topSQ e
Lit _ -> returnS e
Comb FuncCall _ _
| isFailed e -> returnS e
| otherwise -> returnS $ topSQ e
Comb (FuncPartCall _) _ _ -> returnS $ topSQ e
Comb ct qn es -> Comb ct qn <$> mapS defer es
Case ct (Var x) bs -> getBinding x >+= \bdg -> case bdg of
BlackHole -> failS
FreeVar | ct == Rigid -> Case ct (Var x) <$> onBranchS defer bs
LazyFree | ct == Rigid -> Case ct (Var x) <$> onBranchS defer bs
Param -> Case ct (Var x) <$> onBranchS defer bs
LazyParam -> Case ct (Var x) <$> onBranchS defer bs
_ -> returnS $ topSQ e
_ -> returnS $ topSQ e
addBindings :: [(VarIndex, Expr)] -> Expr -> PEM Expr
addBindings ds e =
mapS (\_ -> freshVar) ds >+= \ys ->
let (xs, es) = unzip ds
sigma = mkSubst xs (map Var ys) in
mapS_ (uncurry bindE) (zip ys (map (subst sigma) es)) >+
returnS (subst sigma e)
addFrees :: [VarIndex] -> Expr -> PEM Expr
addFrees xs e =
mapS (\_ -> bindFree) xs >+= \ys ->
returnS (subst (mkSubst xs ys) e)
freshBranch :: BranchExpr -> PEM BranchExpr
freshBranch b@(Branch p be) = case p of
LPattern _ -> returnS b
Pattern c xs -> mapS (\_ -> freshVar) xs >+= \ys ->
returnS $ Branch (Pattern c ys)
(subst (mkSubst xs (map Var ys)) be)
hnf :: Expr -> PEM Expr
hnf (Var x) = peVar x
hnf (Lit l) = peLit l
hnf c@(Comb ct f es) = case getSQ c of
Just e -> defer e
_ -> peComb ct f es
hnf (Let ds e) = peLet ds e
hnf (Free vs e) = peFree vs e
hnf (Or e1 e2) = peOr e1 e2
hnf (Case ct e bs) = peCase ct bs e
hnf (Typed e _) = peval e
peVar :: VarIndex -> PEM Expr
peVar x = getBinding x >+= \bdg -> case bdg of
BlackHole -> failS
FreeVar -> returnS varx
LazyFree -> returnS varx
Param -> returnS varx
LazyParam -> returnS varx
BoundVar e -> bindHole x >+ peval e >+= bindAndCheck
LazyBound e -> bindHole x >+ peval e >+= bindAndCheckLazy
where
varx = Var x
bindAndCheck v = bindE x v >+ case v of
Var _ -> returnS v
Lit _ -> returnS v
Comb FuncCall _ _ | isFailed v -> returnS v
| isSQ v -> defer varx
| otherwise -> returnS varx
Comb _ _ _ -> returnS v
Case _ _ _ -> returnS varx
_ -> error $ "PeNatural.bindAndCheck: " ++ show v
bindAndCheckLazy v = case v of
Var w -> bindLE x v >+ getBinding w >+= \bdg -> case bdg of
BlackHole -> failS
BoundVar e -> bindLE w e >+ returnS v
FreeVar -> bindLF w >+ returnS v
Param -> bindLP w >+ returnS v
_ -> returnS v
Lit _ -> bindE x v >+ returnS v
Comb FuncCall _ _
| isFailed v -> bindE x v >+ returnS v
| isSQ v -> bindLE x v >+ defer varx
| otherwise -> bindLE x v >+ returnS varx
Comb ct qn xs -> mapS (const freshVar) xs >+= \ys ->
let val = Comb ct qn (map Var ys) in
mapS_ (uncurry bindLE) (zip ys xs) >+
bindE x val >+ returnS val
Case _ _ _ -> bindLE x v >+ returnS varx
_ -> error $ "PeNatural.bindAndCheckLazy: " ++ show v
peLit :: Literal -> PEM Expr
peLit l = returnS (Lit l)
peComb :: CombType -> QName -> [Expr] -> PEM Expr
peComb ct f es = case ct of
FuncCall -> lookupRule f >+= \mbRule -> case mbRule of
Nothing -> peBuiltin f es
Just (xs, e) -> peRule xs e f es
_ -> Comb ct f <$> mapS bindArg es
peRule :: [VarIndex] -> Expr -> QName -> [Expr] -> PEM Expr
peRule xs e f es = proceed f >+= \allowed -> if allowed
then unfold xs e es >+= peval
else defer (func f es)
unfold :: [VarIndex] -> Expr -> [Expr] -> PEM Expr
unfold xs e es =
mapS bindArg' (zip xs' es) >+= \es' ->
returnS (subst (mkSubst xs' es') e')
where
Rule xs' e' = freshRule (maximumVarIndex es + 1) (Rule xs e)
bindArg' (x, b)
| count x (freeVarsDup e') <= 1 || isConstrTerm b = returnS b
| otherwise = bindArg b
peLet :: [(VarIndex, Expr)] -> Expr -> PEM Expr
peLet ds e = addBindings ds e >+= peval
peFree :: [VarIndex] -> Expr -> PEM Expr
peFree xs e = addFrees xs e >+= peval
peOr :: Expr -> Expr -> PEM Expr
peOr e1 e2 = peval e1 <|> peval e2
peCase :: CaseType -> [BranchExpr] -> Expr -> PEM Expr
peCase ct bs subj = peval subj >+= \v -> case v of
Var x -> getBinding x >+= \bdg -> case bdg of
BlackHole -> failS
FreeVar | ct == Flex -> narrowCase
LazyFree | ct == Flex -> narrowCase
_ -> deferCase v
where
narrowCase = foldr choiceS failS $ map guess bs
guess (Branch (LPattern l) be) = bindE x (Lit l) >+ peval be
guess (Branch (Pattern c xs) be) = mapS (\_ -> bindFree) xs >+= \ys ->
bindE x (Comb ConsCall c ys) >+
peval (subst (mkSubst xs ys) be)
liftSubCase d e as = mapS freshBranch as >+= \as' ->
mkCase d e <$> onBranchS defer
[ Branch p (subcase v) | Branch p _ <- as']
Lit l -> case findBranch (LPattern l) bs of
Nothing -> failS
Just ( _, e) -> peval e
Comb ConsCall c es -> case findBranch (Pattern c []) bs of
Nothing -> failS
Just (xs, e) -> unfold xs e es >+= peval
Comb _ _ _
| v == failedExpr -> failS
| otherwise -> case getSQ v of
Just (Case d e as) -> mapS freshBranch as >+= \as' ->
defer (mkCase d e (subcase `onBranchExps` as'))
Just e -> defer (mkCase ct e bs)
_ -> deferCase v
Case d e as -> mapS freshBranch as >+= \as' ->
peval (mkCase d e (subcase `onBranchExps` as'))
_ -> error $ "PeNatural.peCase: " ++ show v
where subcase be = mkCase ct be bs
deferCase v = mkCase ct v <$> onBranchS defer bs
onBranchS :: (Expr -> PEM Expr) -> [BranchExpr] -> PEM [BranchExpr]
onBranchS f = mapS (\(Branch p e) -> Branch p <$> f e)
failS :: PEM Expr
failS = returnS failedExpr
succeedS :: PEM Expr
succeedS = returnS trueExpr
peBuiltin :: QName -> [Expr] -> PEM Expr
peBuiltin f es
| f == prelFailed = peBuiltinFailed f es
| f == prelSuccess = peBuiltinSuccess f es
| f == prelUnknown = peBuiltinUnknown f es
| f == prelChoice = binary peBuiltinChoice f es
| f == prelAmp = binary peBuiltinAmp f es
| f == prelCond = binary peBuiltInCond f es
| f == prelCond' = binary peBuiltInCond f es
| f == prelApply = binary peBuiltInApply f es
| f == prelPlus = binary peBuiltinPlus f es
| f == prelMinus = binary peBuiltinMinus f es
| f == prelTimes = binary peBuiltinTimes f es
| f == prelDiv = binary peBuiltinDiv f es
| f == prelMod = binary peBuiltinMod f es
| f == prelAnd = binary peBuiltinAnd f es
| f == prelOr = binary peBuiltinOr f es
| f == prelEq = binary peBuiltinEq f es
| f == prelNeq = binary peBuiltinNeq f es
| f `elem` orderOps = binary peBuiltinOrder f es
| f == prelUni = binary peBuiltinUni f es
| f == prelLazyUni = binary peBuiltinLazyUni f es
| otherwise = func f <$> mapS peval es
where orderOps = [prelLt, prelLeq, prelGt, prelGeq]
isBuiltin :: QName -> Bool
isBuiltin f = f `elem` builtin
where
builtin = [ prelFailed, prelSuccess, prelUnknown, prelChoice
, prelAmp, prelCond, prelCond', prelApply
, prelPlus, prelMinus, prelTimes, prelDiv, prelMod
, prelEq, prelNeq, prelLt, prelLeq, prelGt, prelLeq
, prelUni, prelLazyUni
]
binary :: (QName -> Expr -> Expr -> PEM a) -> QName -> [Expr] -> PEM a
binary act qn es = case es of
[e1, e2] -> act qn e1 e2
_ -> error $ "PeNatural.binary: " ++ show qn
peBuiltinFailed :: QName -> [Expr] -> PEM Expr
peBuiltinFailed _ es = case es of
[] -> failS
_ -> error "PeNatural.peBuiltinFailed"
peBuiltinSuccess :: QName -> [Expr] -> PEM Expr
peBuiltinSuccess _ es = case es of
[] -> succeedS
_ -> error "PeNatural.peBuiltinSuccess"
peBuiltinUnknown :: QName -> [Expr] -> PEM Expr
peBuiltinUnknown _ es = case es of
[] -> bindFree
_ -> error "PeNatural.peBuiltinUnknown"
peBuiltinChoice :: QName -> Expr -> Expr -> PEM Expr
peBuiltinChoice _ e1 e2 = peOr e1 e2
peBuiltinAmp :: QName -> Expr -> Expr -> PEM Expr
peBuiltinAmp f e1 e2 = peval e1 >+= \v1 -> case v1 of
Var x -> getBinding x >+= \bdg -> case bdg of
FreeVar -> bindE x trueExpr >+ peval e2
LazyFree -> bindE x trueExpr >+ peval e2
_ -> other v1
_ | v1 == trueExpr -> peval e2
| otherwise -> other v1
where
other v1 = parDefault cont v1 e2 $ peval e2 >+= \v2 -> case v2 of
_ | v2 == trueExpr -> peval v1
| otherwise -> parDefault (flip cont) v2 v1 (returnS $ cont v1 v2)
cont x y = func f [x, y]
peBuiltInCond :: QName -> Expr -> Expr -> PEM Expr
peBuiltInCond _ e1 e2 = peval e1 >+= \v1 -> case v1 of
Comb FuncCall g [a, b]
| g == prelCond -> peval $ func prelCond [a, func prelCond [b, e2]]
| g == prelCond' -> peval $ func prelCond [a, func prelCond [b, e2]]
_ | v1 == trueExpr -> peval e2
| otherwise -> seqDefault cont v1 e2 (returnS $ cont v1 e2)
where cont x y = func prelCond [x, y]
peBuiltInApply :: QName -> Expr -> Expr -> PEM Expr
peBuiltInApply f e1 e2 = peval e1 >+= \v1 -> case v1 of
Comb c g es | isPartCall c -> peval $ addPartCallArg c g es e2
_ -> seqDefault cont v1 e2 (returnS $ cont v1 e2)
where cont x y = func f [x, y]
peBuiltinPlus :: QName -> Expr -> Expr -> PEM Expr
peBuiltinPlus f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(Lit (Intc 0), _ ) -> returnS v2
(_ , Lit (Intc 0)) -> returnS v1
(Lit (Intc l1), Lit (Intc l2)) -> returnS (Lit (Intc (l1 + l2)))
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinMinus :: QName -> Expr -> Expr -> PEM Expr
peBuiltinMinus f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(_ , Lit (Intc 0)) -> returnS v1
(Lit (Intc l1), Lit (Intc l2)) -> returnS (Lit (Intc (l1 - l2)))
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinTimes :: QName -> Expr -> Expr -> PEM Expr
peBuiltinTimes f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(Lit (Intc 1), _ ) -> returnS v2
(_ , Lit (Intc 1)) -> returnS v1
(Lit (Intc l1), Lit (Intc l2)) -> returnS (Lit (Intc (l1 * l2)))
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinDiv :: QName -> Expr -> Expr -> PEM Expr
peBuiltinDiv f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(_ , Lit (Intc 0)) -> failS
(_ , Lit (Intc 1)) -> returnS v1
(Lit (Intc l1), Lit (Intc l2)) -> returnS (Lit (Intc (div l1 l2)))
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinMod :: QName -> Expr -> Expr -> PEM Expr
peBuiltinMod f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(_ , Lit (Intc 0)) -> failS
(_ , Lit (Intc 1)) -> returnS (Lit (Intc 0 ))
(Lit (Intc l1), Lit (Intc l2)) -> returnS (Lit (Intc (mod l1 l2)))
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinAnd :: QName -> Expr -> Expr -> PEM Expr
peBuiltinAnd f e1 e2 = peRule [1, 2] e f [e1, e2]
where e = Case Flex (Var 1)
[ Branch (Pattern prelFalse []) falseExpr
, Branch (Pattern prelTrue []) (Var 2)
]
peBuiltinOr :: QName -> Expr -> Expr -> PEM Expr
peBuiltinOr f e1 e2 = peRule [1, 2] e f [e1, e2]
where e = Case Flex (Var 1)
[ Branch (Pattern prelFalse []) (Var 2)
, Branch (Pattern prelTrue []) trueExpr
]
pevalOrDefer :: QName -> Expr -> PEM Expr
pevalOrDefer f e = proceed f >+= \p -> if p then peval e else defer e
peBuiltinEq :: QName -> Expr -> Expr -> PEM Expr
peBuiltinEq f e1 e2 = peval e1 >+= \v1 -> peval e2 >+= \v2 -> case (v1, v2) of
(Lit l1 , Lit l2 ) -> returnS $ mkBool (l1 == l2)
(Comb ConsCall c1 es1, Comb ConsCall c2 es2)
| c1 == c2 -> pevalOrDefer f
$ combine f prelAnd trueExpr es1 es2
| otherwise -> returnS falseExpr
_ | all (== trueExpr) [v1, v2] -> returnS trueExpr
| otherwise -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinNeq :: QName -> Expr -> Expr -> PEM Expr
peBuiltinNeq f e1 e2 = peval e1 >+= \v1 -> peval e2 >+= \v2 -> case (v1, v2) of
(Lit l1 , Lit l2 ) -> returnS $ mkBool (l1 /= l2)
(Comb ConsCall c1 es1, Comb ConsCall c2 es2)
| c1 == c2 -> pevalOrDefer f
$ combine f prelOr falseExpr es1 es2
| otherwise -> returnS trueExpr
_ | all (== trueExpr) [v1, v2] -> returnS falseExpr
| otherwise -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
peBuiltinOrder :: QName -> Expr -> Expr -> PEM Expr
peBuiltinOrder f e1 e2 = peval e1 >+= \v1 ->
peval e2 >+= \v2 -> case (v1, v2) of
(Lit l1 , Lit l2 ) -> returnS $ peLitOrder f l1 l2
(Comb ConsCall c1 es1, Comb ConsCall c2 es2) ->
getAllCons c1 >+= \mbCons -> case mbCons of
Nothing -> returnS $ cont v1 v2
Just cs -> pevalOrDefer f $ peConsOrder f cs c1 c2 es1 es2
_ -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1 (returnS $ cont v1 v2)
where
cont x y = func f [x, y]
peLitOrder :: QName -> Literal -> Literal -> Expr
peLitOrder f l1 l2
| f == prelLt = mkBool (l1 < l2)
| f == prelGt = mkBool (l1 > l2)
| f == prelLeq = mkBool (l1 <= l2)
| f == prelGeq = mkBool (l1 >= l2)
| otherwise = error $ "PeNatural.peLitOrder: " ++ show f
peConsOrder :: QName -> [QName] -> QName -> QName -> [Expr] -> [Expr] -> Expr
peConsOrder f cs c1 c2 es1 es2
| f == prelLt = case ordering of
LT -> mkBool True
EQ -> mkOrderCall prelLt prelLt (zip es1 es2)
GT -> mkBool False
| f == prelLeq = case ordering of
LT -> mkBool True
EQ -> mkOrderCall prelLt prelLeq (zip es1 es2)
GT -> mkBool False
| f == prelGt = case ordering of
LT -> mkBool False
EQ -> mkOrderCall prelGt prelGt (zip es1 es2)
GT -> mkBool True
| f == prelGeq = case ordering of
LT -> mkBool False
EQ -> mkOrderCall prelGt prelGeq (zip es1 es2)
GT -> mkBool True
| otherwise = error $ "PeNatural.peConsOrder: " ++ show f
where
ordering = compare (sureIndex c1 cs) (sureIndex c2 cs)
sureIndex x xs = fromMaybe (error "PeNatural.sureIndex") (elemIndex x xs)
mkOrderCall :: QName -> QName -> [(Expr, Expr)] -> Expr
mkOrderCall pre fin pairs = case pairs of
[] -> mkBool True
[(x, y)] -> func fin [x, y]
((x, y) : xys) -> func prelOr [ func pre [x, y]
, func prelAnd [ func prelEq [x, y]
, mkOrderCall pre fin xys
]
]
peBuiltinUni :: QName -> Expr -> Expr -> PEM Expr
peBuiltinUni f e1 e2 = peval e1 >+= \v1 -> peval e2 >+= \v2 -> case (v1, v2) of
(Var x, Var y)
| x == y -> getBinding x >+= \bdg -> case bdg of
FreeVar -> succeedS
LazyFree -> succeedS
_ -> returnS (cont v1 v2)
| otherwise -> getBinding x >+= \bdg -> case bdg of
FreeVar -> uniFree
LazyFree -> uniFree
_ -> returnS (cont v1 v2)
where uniFree = bindE x v2 >+ getBinding y >+= \bdgY -> case bdgY of
FreeVar -> succeedS
LazyFree -> succeedS
_ -> returnS (cont v1 v2)
(Var x, Lit l) -> getBinding x >+= \bdg -> case bdg of
FreeVar -> bindE x v2 >+ succeedS
LazyFree -> bindE x v2 >+ succeedS
_ -> returnS $ Case Flex v1 [Branch (LPattern l) trueExpr]
(Lit l, Var y) -> getBinding y >+= \bdg -> case bdg of
FreeVar -> bindE y v1 >+ succeedS
LazyFree -> bindE y v1 >+ succeedS
_ -> returnS $ Case Flex v2 [Branch (LPattern l) trueExpr]
(Lit l, Lit m)
| l == m -> succeedS
| otherwise -> failS
(Var x, Comb ConsCall c xs) -> occurCheck x v2
$ getBinding x >+= \bdg -> case bdg of
FreeVar -> uniFree
LazyFree -> uniFree
_ -> mapS (\_ -> freshVar) xs >+= \ys ->
pevalOrDefer f (Case Flex v1 [Branch (Pattern c ys)
(combine f prelAmp trueExpr (map Var ys) xs)])
where uniFree = mapS (\_ -> bindFree) xs >+= \ys ->
bindE x (Comb ConsCall c ys) >+
pevalOrDefer f (combine f prelAmp trueExpr ys xs)
(Comb ConsCall c xs, Var y) -> occurCheck y v1
$ getBinding y >+= \bdg -> case bdg of
FreeVar -> uniFree
LazyFree -> uniFree
_ -> mapS (\_ -> freshVar) xs >+= \ys ->
pevalOrDefer f (Case Flex v2 [Branch (Pattern c ys)
(combine f prelAmp trueExpr xs (map Var ys))])
where uniFree = mapS (\_ -> bindFree) xs >+= \ys ->
bindE y (Comb ConsCall c ys) >+
pevalOrDefer f (combine f prelAmp trueExpr xs ys)
(Comb ConsCall c1 es1, Comb ConsCall c2 es2)
| c1 == c2 -> pevalOrDefer f $ combine f prelAmp trueExpr es1 es2
| otherwise -> failS
_ | all (== trueExpr) [v1, v2] -> succeedS
| otherwise -> parDefault cont v1 v2
$ parDefault (flip cont) v2 v1
(returnS $ cont v1 v2)
where cont x y = func f [x, y]
occurCheck :: VarIndex -> Expr -> PEM Expr -> PEM Expr
occurCheck v e act = getHeap >+= \h ->
if v `elem` critVars h e then failS else act
critVars :: Heap -> Expr -> [VarIndex]
critVars h (Var x) = case H.lookupHeap x h of
Just (BoundVar e) -> critVars (H.unbind x h) e
Just (LazyBound e) -> critVars (H.unbind x h) e
_ -> [x]
critVars _ (Lit _) = []
critVars h c@(Comb ct _ es) = case getSQ c of
Just e -> critVars h e
_ -> case ct of
ConsCall -> nub $ concatMap (critVars h) es
_ -> []
critVars h (Let ds e) = critVars h e \\ map fst ds
critVars h (Free vs e) = critVars h e \\ vs
critVars h (Or e1 e2) = critVars h e1 `intersect` critVars h e2
critVars h (Case _ _ bs) = foldr1 intersect (map critBranch bs)
where critBranch (Branch p be) = critVars h be \\ patVars p
critVars h (Typed e _) = critVars h e
peBuiltinLazyUni :: QName -> Expr -> Expr -> PEM Expr
peBuiltinLazyUni f e1 e2 = peval e1 >+= \v1 -> case v1 of
Var x -> getBinding x >+= \bdg -> case bdg of
FreeVar -> bindLE x e2 >+ succeedS
LazyFree -> bindF x >+ peval (v1 .=:=. e2)
LazyParam -> bindP x >+ peval (v1 .=:=. e2)
_ -> returnS $ cont v1 e2
Lit l -> peval e2 >+= \v2 -> case v2 of
Lit m
| l == m -> succeedS
| otherwise -> failS
Var y -> getBinding y >+= \bdg -> case bdg of
Param -> returnS $ Case Flex v2 [Branch (LPattern l) trueExpr]
FreeVar -> bindE y v1 >+ succeedS
_ -> parDefault (flip cont) v2 v1 (returnS $ cont v1 v2)
_ -> parDefault (flip cont) v2 v1 (returnS $ cont v1 v2)
Comb ConsCall c xs -> peval e2 >+= \v2 -> case v2 of
Comb ConsCall d ys
| c == d -> pevalOrDefer f $ combine f prelAmp trueExpr xs ys
| otherwise -> failS
Var y -> getBinding y >+= \bdg -> case bdg of
Param -> mapS (\_ -> freshVar) xs >+= \ys ->
pevalOrDefer f (Case Flex v2 [Branch (Pattern c ys)
(combine f prelAmp trueExpr xs (map Var ys))])
LazyParam-> mapS (\_ -> freshVar) xs >+= \ys ->
pevalOrDefer f (Case Flex v2 [Branch (Pattern c ys)
(combine f prelAmp trueExpr xs (map Var ys))])
LazyFree -> mapS (\_ -> bindFree) xs >+= \ys ->
bindE y (Comb ConsCall c ys) >+
pevalOrDefer f (combine f prelAmp trueExpr xs ys)
FreeVar -> mapS (\_ -> bindFree) xs >+= \ys ->
bindE y (Comb ConsCall c ys) >+
pevalOrDefer f (combine f prelAmp trueExpr xs ys)
_ -> parDefault (flip cont) v2 v1 (returnS $ cont v1 v2)
_ -> parDefault cont v1 v2 $ returnS (cont v1 v2)
_ -> parDefault cont v1 e2 $ returnS (cont v1 e2)
where cont x y = func f [x, y]
parDefault :: (Expr -> Expr -> Expr) -> Expr -> Expr -> PEM Expr -> PEM Expr
parDefault cont e1 e2 alt = case getSQ e1 of
Just e' -> defer (cont e' e2)
_ -> case e1 of
Case ct e' bs -> mapS freshBranch bs >+= \bs' ->
peval (Case ct e' (flip cont e2 `onBranchExps` bs'))
_ | e1 == failedExpr -> failS
| otherwise -> alt
seqDefault :: (Expr -> Expr -> Expr) -> Expr -> Expr -> PEM Expr -> PEM Expr
seqDefault cont e1 e2 alt = case getSQ e1 of
Just e' -> defer (cont e' e2)
_ -> case e1 of
Var x -> getBinding x >+= \bdg -> case bdg of
Param -> cont e1 <$> defer e2
LazyParam -> cont e1 <$> defer e2
_ -> alt
Case ct e' bs -> mapS freshBranch bs >+= \bs' ->
peval (Case ct e' (flip cont e2 `onBranchExps` bs'))
Comb FuncCall _ _
| e1 == failedExpr -> failS
| otherwise -> cont e1 <$> peval e2
_ -> alt
|