forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep8_macros.elm
723 lines (575 loc) · 20.4 KB
/
step8_macros.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
port module Main exposing (..)
import Array
import Dict exposing (Dict)
import IO exposing (..)
import Json.Decode exposing (decodeValue)
import Platform exposing (programWithFlags)
import Types exposing (..)
import Reader exposing (readString)
import Printer exposing (printString)
import Utils exposing (maybeToList, zip, last, justValues, makeCall)
import Env
import Core
import Eval
main : Program Flags Model Msg
main =
programWithFlags
{ init = init
, update = update
, subscriptions =
\model -> input (decodeValue decodeIO >> Input)
}
type alias Args =
List String
type alias Flags =
{ args : Args
}
type Model
= InitIO Args Env (IO -> Eval MalExpr)
| ScriptIO Env (IO -> Eval MalExpr)
| ReplActive Env
| ReplIO Env (IO -> Eval MalExpr)
| Stopped
init : Flags -> ( Model, Cmd Msg )
init { args } =
let
makeFn =
CoreFunc >> MalFunction
initEnv =
Core.ns
|> Env.set "eval" (makeFn malEval)
|> Env.set "*ARGV*" (MalList (args |> List.map MalString))
evalMalInit =
malInit
|> List.map rep
|> justValues
|> List.foldl
(\b a -> a |> Eval.andThen (\_ -> b))
(Eval.succeed MalNil)
in
runInit args initEnv evalMalInit
malInit : List String
malInit =
[ """(def! not
(fn* (a)
(if a false true)))"""
, """(def! load-file
(fn* (f)
(eval (read-string
(str "(do " (slurp f) ")")))))"""
, """(defmacro! cond
(fn* (& xs)
(if (> (count xs) 0)
(list 'if (first xs)
(if (> (count xs) 1)
(nth xs 1)
(throw "odd number of forms to cond"))
(cons 'cond (rest (rest xs)))))))"""
, """(defmacro! or
(fn* (& xs)
(if (empty? xs)
nil
(if (= 1 (count xs))
(first xs)
`(let* (or_FIXME ~(first xs))
(if or_FIXME or_FIXME (or ~@(rest xs))))))))"""
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model of
Stopped ->
( model, Cmd.none )
InitIO args env cont ->
case msg of
Input (Ok io) ->
runInit args env (cont io)
Input (Err msg) ->
Debug.crash msg
ScriptIO env cont ->
case msg of
Input (Ok io) ->
runScriptLoop env (cont io)
Input (Err msg) ->
Debug.crash msg
ReplActive env ->
case msg of
Input (Ok (LineRead (Just line))) ->
case rep line of
Just expr ->
run env expr
Nothing ->
( model, readLine prompt )
Input (Ok LineWritten) ->
( model, readLine prompt )
Input (Ok (LineRead Nothing)) ->
-- Ctrl+D = The End.
( model, Cmd.none )
Input (Ok io) ->
Debug.crash "unexpected IO received: " io
Input (Err msg) ->
Debug.crash msg
ReplIO env cont ->
case msg of
Input (Ok io) ->
run env (cont io)
Input (Err msg) ->
Debug.crash msg ( model, Cmd.none )
runInit : Args -> Env -> Eval MalExpr -> ( Model, Cmd Msg )
runInit args env expr =
case Eval.run env expr of
( env, EvalOk expr ) ->
-- Init went okay.
case args of
-- If we got no args: start REPL.
[] ->
( ReplActive env, readLine prompt )
-- Run the script in the first argument.
-- Put the rest of the arguments as *ARGV*.
filename :: argv ->
runScript filename argv env
( env, EvalErr msg ) ->
-- Init failed, don't start REPL.
( Stopped, writeLine (printError env msg) )
( env, EvalIO cmd cont ) ->
-- IO in init.
( InitIO args env cont, cmd )
runScript : String -> List String -> Env -> ( Model, Cmd Msg )
runScript filename argv env =
let
malArgv =
MalList (List.map MalString argv)
newEnv =
env |> Env.set "*ARGV*" malArgv
program =
MalList
[ MalSymbol "load-file"
, MalString filename
]
in
runScriptLoop newEnv (eval program)
runScriptLoop : Env -> Eval MalExpr -> ( Model, Cmd Msg )
runScriptLoop env expr =
case Eval.run env expr of
( env, EvalOk expr ) ->
( Stopped, Cmd.none )
( env, EvalErr msg ) ->
( Stopped, writeLine (printError env msg) )
( env, EvalIO cmd cont ) ->
( ScriptIO env cont, cmd )
run : Env -> Eval MalExpr -> ( Model, Cmd Msg )
run env expr =
case Eval.run env expr of
( env, EvalOk expr ) ->
( ReplActive env, writeLine (print env expr) )
( env, EvalErr msg ) ->
( ReplActive env, writeLine (printError env msg) )
( env, EvalIO cmd cont ) ->
( ReplIO env cont, cmd )
prompt : String
prompt =
"user> "
{-| read can return three things:
Ok (Just expr) -> parsed okay
Ok Nothing -> empty string (only whitespace and/or comments)
Err msg -> parse error
-}
read : String -> Result String (Maybe MalExpr)
read =
readString
debug : String -> (Env -> a) -> Eval b -> Eval b
debug msg f e =
Eval.withEnv
(\env ->
Env.debug env msg (f env)
|> always e
)
eval : MalExpr -> Eval MalExpr
eval ast =
let
apply expr env =
case expr of
MalApply app ->
Left
(debug "evalApply"
(\env -> printString env True expr)
(evalApply app)
)
_ ->
Right expr
in
evalNoApply ast
|> Eval.andThen (Eval.runLoop apply)
malEval : List MalExpr -> Eval MalExpr
malEval args =
case args of
[ expr ] ->
Eval.inGlobal (eval expr)
_ ->
Eval.fail "unsupported arguments"
evalApply : ApplyRec -> Eval MalExpr
evalApply { frameId, bound, body } =
Eval.withEnv
(\env ->
Eval.modifyEnv (Env.enter frameId bound)
|> Eval.andThen (\_ -> evalNoApply body)
|> Eval.finally Env.leave
|> Eval.gcPass
)
evalNoApply : MalExpr -> Eval MalExpr
evalNoApply ast =
debug "evalNoApply"
(\env -> printString env True ast)
(macroexpand ast
|> Eval.andThen
(\ast ->
case ast of
MalList [] ->
Eval.succeed ast
MalList ((MalSymbol "def!") :: args) ->
evalDef args
MalList ((MalSymbol "let*") :: args) ->
evalLet args
MalList ((MalSymbol "do") :: args) ->
evalDo args
MalList ((MalSymbol "if") :: args) ->
evalIf args
MalList ((MalSymbol "fn*") :: args) ->
evalFn args
MalList ((MalSymbol "quote") :: args) ->
evalQuote args
MalList ((MalSymbol "quasiquote") :: args) ->
case args of
[ expr ] ->
-- TCO.
evalNoApply (evalQuasiQuote expr)
_ ->
Eval.fail "unsupported arguments"
MalList ((MalSymbol "defmacro!") :: args) ->
evalDefMacro args
MalList ((MalSymbol "macroexpand") :: args) ->
case args of
[ expr ] ->
macroexpand expr
_ ->
Eval.fail "unsupported arguments"
MalList list ->
evalList list
|> Eval.andThen
(\newList ->
case newList of
[] ->
Eval.fail "can't happen"
(MalFunction (CoreFunc fn)) :: args ->
fn args
(MalFunction (UserFunc { lazyFn })) :: args ->
lazyFn args
fn :: _ ->
Eval.withEnv
(\env ->
Eval.fail ((printString env True fn) ++ " is not a function")
)
)
_ ->
evalAst ast
)
)
evalAst : MalExpr -> Eval MalExpr
evalAst ast =
case ast of
MalSymbol sym ->
-- Lookup symbol in env and return value or raise error if not found.
Eval.withEnv (Env.get sym >> Eval.fromResult)
MalList list ->
-- Return new list that is result of calling eval on each element of list.
evalList list
|> Eval.map MalList
MalVector vec ->
evalList (Array.toList vec)
|> Eval.map (Array.fromList >> MalVector)
MalMap map ->
evalList (Dict.values map)
|> Eval.map
(zip (Dict.keys map)
>> Dict.fromList
>> MalMap
)
_ ->
Eval.succeed ast
evalList : List MalExpr -> Eval (List MalExpr)
evalList list =
let
go list acc =
case list of
[] ->
Eval.succeed (List.reverse acc)
x :: rest ->
eval x
|> Eval.andThen
(\val ->
go rest (val :: acc)
)
in
go list []
evalDef : List MalExpr -> Eval MalExpr
evalDef args =
case args of
[ MalSymbol name, uneValue ] ->
eval uneValue
|> Eval.andThen
(\value ->
Eval.modifyEnv (Env.set name value)
|> Eval.andThen (\_ -> Eval.succeed value)
)
_ ->
Eval.fail "def! expected two args: name and value"
evalDefMacro : List MalExpr -> Eval MalExpr
evalDefMacro args =
case args of
[ MalSymbol name, uneValue ] ->
eval uneValue
|> Eval.andThen
(\value ->
case value of
MalFunction (UserFunc fn) ->
let
macroFn =
MalFunction (UserFunc { fn | isMacro = True })
in
Eval.modifyEnv (Env.set name macroFn)
|> Eval.andThen (\_ -> Eval.succeed macroFn)
_ ->
Eval.fail "defmacro! is only supported on a user function"
)
_ ->
Eval.fail "defmacro! expected two args: name and value"
evalLet : List MalExpr -> Eval MalExpr
evalLet args =
let
evalBinds binds =
case binds of
(MalSymbol name) :: expr :: rest ->
eval expr
|> Eval.andThen
(\value ->
Eval.modifyEnv (Env.set name value)
|> Eval.andThen
(\_ ->
if List.isEmpty rest then
Eval.succeed ()
else
evalBinds rest
)
)
_ ->
Eval.fail "let* expected an even number of binds (symbol expr ..)"
go binds body =
Eval.modifyEnv Env.push
|> Eval.andThen (\_ -> evalBinds binds)
|> Eval.andThen (\_ -> evalNoApply body)
|> Eval.finally Env.pop
in
case args of
[ MalList binds, body ] ->
go binds body
[ MalVector bindsVec, body ] ->
go (Array.toList bindsVec) body
_ ->
Eval.fail "let* expected two args: binds and a body"
evalDo : List MalExpr -> Eval MalExpr
evalDo args =
case List.reverse args of
last :: rest ->
evalList (List.reverse rest)
|> Eval.andThen (\_ -> evalNoApply last)
[] ->
Eval.fail "do expected at least one arg"
evalIf : List MalExpr -> Eval MalExpr
evalIf args =
let
isThruthy expr =
expr /= MalNil && expr /= (MalBool False)
go condition trueExpr falseExpr =
eval condition
|> Eval.map isThruthy
|> Eval.andThen
(\cond ->
evalNoApply
(if cond then
trueExpr
else
falseExpr
)
)
in
case args of
[ condition, trueExpr ] ->
go condition trueExpr MalNil
[ condition, trueExpr, falseExpr ] ->
go condition trueExpr falseExpr
_ ->
Eval.fail "if expected at least two args"
evalFn : List MalExpr -> Eval MalExpr
evalFn args =
let
{- Extract symbols from the binds list and verify their uniqueness -}
extractSymbols acc list =
case list of
[] ->
Ok (List.reverse acc)
(MalSymbol name) :: rest ->
if List.member name acc then
Err "all binds must have unique names"
else
extractSymbols (name :: acc) rest
_ ->
Err "all binds in fn* must be a symbol"
parseBinds list =
case List.reverse list of
var :: "&" :: rest ->
Ok <| bindVarArgs (List.reverse rest) var
_ ->
if List.member "&" list then
Err "varargs separator '&' is used incorrectly"
else
Ok <| bindArgs list
extractAndParse =
extractSymbols [] >> Result.andThen parseBinds
bindArgs binds args =
let
numBinds =
List.length binds
in
if List.length args /= numBinds then
Err <|
"function expected "
++ (toString numBinds)
++ " arguments"
else
Ok <| zip binds args
bindVarArgs binds var args =
let
minArgs =
List.length binds
varArgs =
MalList (List.drop minArgs args)
in
if List.length args < minArgs then
Err <|
"function expected at least "
++ (toString minArgs)
++ " arguments"
else
Ok <| zip binds args ++ [ ( var, varArgs ) ]
makeFn frameId binder body =
MalFunction <|
let
lazyFn =
binder
>> Eval.fromResult
>> Eval.map
(\bound ->
MalApply
{ frameId = frameId
, bound = bound
, body = body
}
)
in
UserFunc
{ frameId = frameId
, lazyFn = lazyFn
, eagerFn = lazyFn >> Eval.andThen eval
, isMacro = False
, meta = Nothing
}
go bindsList body =
extractAndParse bindsList
|> Eval.fromResult
-- reference the current frame.
|> Eval.ignore (Eval.modifyEnv Env.ref)
|> Eval.andThen
(\binder ->
Eval.withEnv
(\env ->
Eval.succeed
(makeFn env.currentFrameId binder body)
)
)
in
case args of
[ MalList bindsList, body ] ->
go bindsList body
[ MalVector bindsVec, body ] ->
go (Array.toList bindsVec) body
_ ->
Eval.fail "fn* expected two args: binds list and body"
evalQuote : List MalExpr -> Eval MalExpr
evalQuote args =
case args of
[ expr ] ->
Eval.succeed expr
_ ->
Eval.fail "unsupported arguments"
evalQuasiQuote : MalExpr -> MalExpr
evalQuasiQuote expr =
let
apply list empty =
case list of
[ MalSymbol "unquote", ast ] ->
ast
(MalList [ MalSymbol "splice-unquote", ast ]) :: rest ->
makeCall "concat"
[ ast
, evalQuasiQuote (MalList rest)
]
ast :: rest ->
makeCall "cons"
[ evalQuasiQuote ast
, evalQuasiQuote (MalList rest)
]
_ ->
makeCall "quote" [ empty ]
in
case expr of
MalList list ->
apply list (MalList [])
MalVector vec ->
apply (Array.toList vec) (MalVector Array.empty)
ast ->
makeCall "quote" [ ast ]
macroexpand : MalExpr -> Eval MalExpr
macroexpand expr =
let
expand expr env =
case expr of
MalList ((MalSymbol name) :: args) ->
case Env.get name env of
Ok (MalFunction (UserFunc fn)) ->
if fn.isMacro then
Left <| fn.eagerFn args
else
Right expr
_ ->
Right expr
_ ->
Right expr
in
Eval.runLoop expand expr
print : Env -> MalExpr -> String
print env =
printString env True
printError : Env -> MalExpr -> String
printError env expr =
"ERR:" ++ (printString env False expr)
{-| Read-Eval-Print.
Doesn't actually run the Eval but returns the monad.
-}
rep : String -> Maybe (Eval MalExpr)
rep input =
case readString input of
Ok Nothing ->
Nothing
Err msg ->
Just (Eval.fail msg)
Ok (Just ast) ->
eval ast |> Just