-
Notifications
You must be signed in to change notification settings - Fork 0
/
CPSInterpreter.elm
92 lines (65 loc) · 1.82 KB
/
CPSInterpreter.elm
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
module Ch1.L_Int.CPSInterpreter exposing
( Continuation
, Effect(..)
, Error(..)
, resume
, run
)
import Ch1.L_Int.AST as AST exposing (..)
import Ch1.L_Int.Parser as P
type Effect
= Value Int
| ReadInt Continuation
type Continuation
= EndCont
| NegateCont Continuation
| Add1Cont AST.Expr Continuation
| Add2Cont Int Continuation
| Sub1Cont AST.Expr Continuation
| Sub2Cont Int Continuation
type Error
= SyntaxError P.Error
run : String -> Result Error Effect
run source =
case P.parse source of
Ok program ->
Ok <| runProgram program
Err err ->
Err <| SyntaxError err
runProgram : AST.Program -> Effect
runProgram (Program expr) =
interpretExpr expr EndCont
interpretExpr : Expr -> Continuation -> Effect
interpretExpr expr cont =
case expr of
Int n ->
applyCont n cont
Prim Read ->
ReadInt cont
Prim (Negate aExpr) ->
interpretExpr aExpr (NegateCont cont)
Prim (Add aExpr bExpr) ->
interpretExpr aExpr (Add1Cont bExpr cont)
Prim (Sub aExpr bExpr) ->
interpretExpr aExpr (Sub1Cont bExpr cont)
applyCont : Int -> Continuation -> Effect
applyCont n cont =
case cont of
EndCont ->
Value n
NegateCont nextCont ->
applyCont -n nextCont
Add1Cont bExpr nextCont ->
interpretExpr bExpr (Add2Cont n nextCont)
Add2Cont a nextCont ->
applyCont (a + n) nextCont
Sub1Cont bExpr nextCont ->
interpretExpr bExpr (Sub2Cont n nextCont)
Sub2Cont a nextCont ->
applyCont (a - n) nextCont
resume : Int -> Continuation -> Effect
resume =
--
-- A better name for public consumers of this API.
--
applyCont