-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.elm
796 lines (601 loc) · 15.7 KB
/
Interpreter.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
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
module Monkey.Interpreter exposing
( Answer(..), Value(..), Type(..), Error(..), RuntimeError(..)
, run
, answerToString
)
import Array exposing (Array)
import Monkey.Environment as Env
import Monkey.Eval as Eval
import Monkey.Hash as Hash exposing (Hash)
import Monkey.Output as Output exposing (Output)
import Monkey.Parser as P
type Answer
= Void
| Return Value
| Value Value
type Value
= VNull
| VNum Int
| VBool Bool
| VString String
| VArray (Array Value)
| VHash (Hash Value)
| VFunction Closure
| VBuiltInFunction BuiltInFunction
| VReturn Value
type alias Closure =
{ params : List P.Id
, body : P.Block
, savedEnv : Env
}
type alias BuiltInFunction = List Value -> Eval RuntimeError Value
type alias Env = Env.Environment P.Id Value
type Type
= TNull
| TInt
| TBool
| TString
| TArray
| THash
| TFunction
| TReturn Type
type Error
= SyntaxError P.Error
| RuntimeError RuntimeError
type RuntimeError
= ArgumentError Int Int
| IdentifierNotFound String
| TypeError (List Type) Type
| UnknownOperation String (List Type)
| ZeroDivisionError
type alias Eval err a = Eval.Eval Env err a
run : String -> (Result Error Answer, List String)
run input =
case P.parse input of
Ok program ->
evalProgram program
|> Eval.run builtInFunctions
|> Tuple.mapFirst (Result.map Tuple.second)
|> Tuple.mapFirst (Result.mapError RuntimeError)
|> Tuple.mapSecond Output.toList
Err err ->
( Err (SyntaxError err)
, []
)
evalProgram : P.Program -> Eval RuntimeError Answer
evalProgram (P.Program stmts) =
evalStmts stmts
|> Eval.map
(\answer ->
case answer of
Return value ->
Value value
_ ->
answer
)
evalStmts : List P.Stmt -> Eval RuntimeError Answer
evalStmts stmts =
case stmts of
[] ->
Eval.succeed Void
[stmt] ->
evalStmt stmt
stmt :: restStmts ->
evalStmt stmt
|> Eval.andThen
(\answer ->
case answer of
Return _ ->
Eval.succeed answer
_ ->
evalStmts restStmts
)
evalStmt : P.Stmt -> Eval RuntimeError Answer
evalStmt stmt =
case stmt of
P.Let identifier expr ->
case expr of
P.Function _ _ ->
Eval.getState
|> Eval.andThen
(Eval.replaceState << Env.extendRec identifier expr)
|> Eval.followedBy (Eval.succeed Void)
_ ->
evalExpr expr
|> Eval.andThen
(\value ->
Eval.getState
|> Eval.andThen
(Eval.replaceState << Env.extend identifier value)
|> Eval.followedBy (Eval.succeed Void)
)
P.Return expr ->
evalExpr expr
|> Eval.map
(\value ->
case value of
VReturn v ->
Return v
_ ->
Return value
)
P.ExprStmt expr ->
evalExpr expr
|> Eval.map
(\value ->
case value of
VReturn v ->
Return v
_ ->
Value value
)
evalExpr : P.Expr -> Eval RuntimeError Value
evalExpr expr =
case expr of
P.Var identifier ->
Eval.getState
|> Eval.andThen
(\env ->
case Env.lookup identifier env of
Env.FoundValue value ->
Eval.succeed value
Env.FoundExpr savedExpr ->
evalExpr savedExpr
Env.NotFound ->
Eval.fail (IdentifierNotFound identifier)
)
P.Num n ->
Eval.succeed <| VNum n
P.Bool b ->
Eval.succeed <| VBool b
P.String s ->
Eval.succeed <| VString s
P.Array exprs ->
evalExprs exprs
|> Eval.map (VArray << Array.fromList)
P.Hash kvExprs ->
evalKVExprs kvExprs
|> Eval.map (VHash << Hash.fromList)
P.Prefix op a ->
evalExpr a
|> Eval.andThen (evalPrefix op)
P.Infix op a b ->
Eval.andThen2 (evalInfix op) (evalExpr a) (evalExpr b)
P.Call f args ->
Eval.andThen2 evalCall (evalExpr f) (evalExprs args)
P.Index a i ->
Eval.andThen2 evalIndex (evalExpr a) (evalExpr i)
P.If condition thenBlock maybeElseBlock ->
evalExpr condition
|> Eval.andThen
(\conditionVal ->
if isTruthy conditionVal then
evalBlock thenBlock
else
case maybeElseBlock of
Just elseBlock ->
evalBlock elseBlock
Nothing ->
Eval.succeed VNull
)
P.Function params body ->
Eval.getState
|> Eval.map (VFunction << Closure params body)
evalExprs : List P.Expr -> Eval RuntimeError (List Value)
evalExprs exprs =
case exprs of
[] ->
Eval.succeed []
expr :: restExprs ->
evalExpr expr
|> Eval.andThen
(\value ->
evalExprs restExprs
|> Eval.map ((::) (toNonReturnValue value))
)
evalKVExprs : List (P.Expr, P.Expr) -> Eval RuntimeError (List (Hash.Key, Value))
evalKVExprs kvExprs =
case kvExprs of
[] ->
Eval.succeed []
(keyExpr, valueExpr) :: restKVExprs ->
evalExpr keyExpr
|> Eval.andThen
(\possibleKey ->
expectKey possibleKey
|> Eval.andThen
(\key ->
evalExpr valueExpr
|> Eval.andThen
(\value ->
evalKVExprs restKVExprs
|> Eval.map ((::) (key, toNonReturnValue value))
)
)
)
evalBlock : P.Block -> Eval RuntimeError Value
evalBlock block =
evalStmts block
|> Eval.andThen
(\answer ->
case answer of
Void ->
Eval.succeed VNull
Return value ->
Eval.succeed (VReturn value)
Value value ->
Eval.succeed value
)
evalPrefix : P.UnaryOp -> Value -> Eval RuntimeError Value
evalPrefix op v =
let
value =
toNonReturnValue v
in
case op of
P.Not ->
computeNot value
P.Negate ->
computeNegate value
computeNot : Value -> Eval RuntimeError Value
computeNot value =
case value of
VNull ->
Eval.succeed <| VBool True
VBool b ->
Eval.succeed <| VBool <| not b
_ ->
Eval.succeed <| VBool False
computeNegate : Value -> Eval RuntimeError Value
computeNegate value =
case value of
VNum n ->
Eval.succeed <| VNum <| negate n
_ ->
Eval.fail <| UnknownOperation "-" [typeOf value]
evalInfix : P.BinOp -> Value -> Value -> Eval RuntimeError Value
evalInfix op vA vB =
let
valueA =
toNonReturnValue vA
valueB =
toNonReturnValue vB
in
case op of
P.Equal ->
computeEqual valueA valueB
P.NotEqual ->
computeNotEqual valueA valueB
P.LessThan ->
computeLessThan valueA valueB
P.GreaterThan ->
computeGreaterThan valueA valueB
P.Add ->
computeAdd valueA valueB
P.Sub ->
computeSub valueA valueB
P.Mul ->
computeMul valueA valueB
P.Div ->
computeDiv valueA valueB
computeEqual : Value -> Value -> Eval RuntimeError Value
computeEqual valueA valueB =
Eval.succeed <| VBool <| valueEqual valueA valueB
computeNotEqual : Value -> Value -> Eval RuntimeError Value
computeNotEqual valueA valueB =
Eval.succeed <| VBool <| not <| valueEqual valueA valueB
valueEqual : Value -> Value -> Bool
valueEqual valueA valueB =
case (valueA, valueB) of
(VNull, VNull) ->
True
(VNum a, VNum b) ->
a == b
(VBool a, VBool b) ->
a == b
(VString a, VString b) ->
a == b
_ ->
False
computeLessThan : Value -> Value -> Eval RuntimeError Value
computeLessThan valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
Eval.succeed <| VBool <| a < b
_ ->
Eval.fail <| UnknownOperation "<" [typeOf valueA, typeOf valueB]
computeGreaterThan : Value -> Value -> Eval RuntimeError Value
computeGreaterThan valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
Eval.succeed <| VBool <| a > b
_ ->
Eval.fail <| UnknownOperation ">" [typeOf valueA, typeOf valueB]
computeAdd : Value -> Value -> Eval RuntimeError Value
computeAdd valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
Eval.succeed <| VNum <| a + b
(VString a, VString b) ->
Eval.succeed <| VString <| a ++ b
_ ->
Eval.fail <| UnknownOperation "+" [typeOf valueA, typeOf valueB]
computeSub : Value -> Value -> Eval RuntimeError Value
computeSub valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
Eval.succeed <| VNum <| a - b
_ ->
Eval.fail <| UnknownOperation "-" [typeOf valueA, typeOf valueB]
computeMul : Value -> Value -> Eval RuntimeError Value
computeMul valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
Eval.succeed <| VNum <| a * b
_ ->
Eval.fail <| UnknownOperation "*" [typeOf valueA, typeOf valueB]
computeDiv : Value -> Value -> Eval RuntimeError Value
computeDiv valueA valueB =
case (valueA, valueB) of
(VNum a, VNum b) ->
if b /= 0 then
Eval.succeed <| VNum <| a // b
else
Eval.fail ZeroDivisionError
_ ->
Eval.fail <| UnknownOperation "/" [typeOf valueA, typeOf valueB]
evalCall : Value -> List Value -> Eval RuntimeError Value
evalCall v args =
let
value =
toNonReturnValue v
in
case value of
VFunction closure ->
applyClosure closure args
VBuiltInFunction builtInFunction ->
builtInFunction args
_ ->
Eval.fail <| TypeError [TFunction] (typeOf value)
applyClosure : Closure -> List Value -> Eval RuntimeError Value
applyClosure { params, body, savedEnv } args =
let
numParams =
List.length params
numArgs =
List.length args
in
if numParams == numArgs then
evalBlock body
|> Eval.withState (Env.extendMany (zip params args []) savedEnv)
else
Eval.fail <| ArgumentError numParams numArgs
zip : List a -> List b -> List (a, b) -> List (a, b)
zip xs ys revList =
case (xs, ys) of
([], []) ->
List.reverse revList
(x :: restXs, y :: restYs) ->
zip restXs restYs ((x, y) :: revList)
_ ->
[]
evalIndex : Value -> Value -> Eval RuntimeError Value
evalIndex vA vB =
let
valueA =
toNonReturnValue vA
valueB =
toNonReturnValue vB
in
case valueA of
VArray array ->
expectInt valueB
|> Eval.andThen
(\index ->
Array.get index array
|> Maybe.withDefault VNull
|> Eval.succeed
)
VHash hash ->
expectKey valueB
|> Eval.andThen
(\key ->
Hash.lookup key hash
|> Maybe.withDefault VNull
|> Eval.succeed
)
_ ->
Eval.fail <| TypeError [TArray, THash] (typeOf valueA)
expectInt : Value -> Eval RuntimeError Int
expectInt v =
let
value =
toNonReturnValue v
in
case value of
VNum n ->
Eval.succeed n
_ ->
Eval.fail <| TypeError [TInt] (typeOf value)
expectKey : Value -> Eval RuntimeError Hash.Key
expectKey v =
let
value =
toNonReturnValue v
in
case value of
VNum n ->
Eval.succeed <| Hash.KNum n
VBool b ->
Eval.succeed <| Hash.KBool b
VString s ->
Eval.succeed <| Hash.KString s
_ ->
Eval.fail <| TypeError [TInt, TBool, TString] (typeOf value)
isTruthy : Value -> Bool
isTruthy v =
let
value =
toNonReturnValue v
in
case value of
VNull ->
False
VBool False ->
False
_ ->
True
toNonReturnValue : Value -> Value
toNonReturnValue value =
case value of
VReturn v ->
toNonReturnValue v
_ ->
value
typeOf : Value -> Type
typeOf value =
case value of
VNull ->
TNull
VNum _ ->
TInt
VBool _ ->
TBool
VString _ ->
TString
VArray _ ->
TArray
VHash _ ->
THash
VFunction _ ->
TFunction
VBuiltInFunction _ ->
TFunction
VReturn v ->
TReturn (typeOf v)
answerToString : Answer -> String
answerToString answer =
case answer of
Void ->
""
Return value ->
valueToString value
Value value ->
valueToString value
valueToString : Value -> String
valueToString value =
case value of
VNull ->
"null"
VNum n ->
String.fromInt n
VBool b ->
if b then "true" else "false"
VString s ->
"\"" ++ s ++ "\""
VArray array ->
let
inside =
array
|> Array.toList
|> List.map valueToString
|> String.join ", "
in
"[" ++ inside ++ "]"
VHash hash ->
let
inside =
hash
|> Hash.toList
|> List.map
(\(k, v) ->
Hash.keyToString k ++ ": " ++ valueToString v
)
|> String.join ", "
in
"{" ++ inside ++ "}"
VFunction _ ->
"<function>"
VBuiltInFunction _ ->
"<built-in function>"
VReturn v ->
"return " ++ valueToString v
builtInFunctions : Env
builtInFunctions =
[ ("len", builtInLen)
, ("first", builtInFirst)
, ("last", builtInLast)
, ("rest", builtInRest)
, ("push", builtInPush)
, ("puts", builtInPuts)
]
|> List.map (Tuple.mapSecond VBuiltInFunction)
|> Env.fromList
builtInLen : BuiltInFunction
builtInLen args =
case args of
[VString s] ->
Eval.succeed <| VNum <| String.length s
[VArray a] ->
Eval.succeed <| VNum <| Array.length a
[arg] ->
Eval.fail <| TypeError [TString, TArray] (typeOf arg)
_ ->
Eval.fail <| ArgumentError 1 (List.length args)
builtInFirst : BuiltInFunction
builtInFirst args =
case args of
[VArray a] ->
Array.get 0 a
|> Maybe.withDefault VNull
|> Eval.succeed
[arg] ->
Eval.fail <| TypeError [TArray] (typeOf arg)
_ ->
Eval.fail <| ArgumentError 1 (List.length args)
builtInLast : BuiltInFunction
builtInLast args =
case args of
[VArray a] ->
Array.get (Array.length a - 1) a
|> Maybe.withDefault VNull
|> Eval.succeed
[arg] ->
Eval.fail <| TypeError [TArray] (typeOf arg)
_ ->
Eval.fail <| ArgumentError 1 (List.length args)
builtInRest : BuiltInFunction
builtInRest args =
case args of
[VArray a] ->
let
rest =
Array.toList >> List.tail >> Maybe.map Array.fromList
in
rest a
|> Maybe.map VArray
|> Maybe.withDefault VNull
|> Eval.succeed
[arg] ->
Eval.fail <| TypeError [TArray] (typeOf arg)
_ ->
Eval.fail <| ArgumentError 1 (List.length args)
builtInPush : BuiltInFunction
builtInPush args =
case args of
[VArray a, value] ->
Eval.succeed <| VArray <| Array.push value a
[arg, _] ->
Eval.fail <| TypeError [TArray] (typeOf arg)
_ ->
Eval.fail <| ArgumentError 2 (List.length args)
builtInPuts : BuiltInFunction
builtInPuts args =
case args of
[] ->
Eval.succeed VNull
(arg :: restArgs) ->
printValue arg
|> Eval.followedBy (builtInPuts restArgs)
printValue : Value -> Eval RuntimeError ()
printValue = Eval.print valueToString