Move implementations into impls/ dir
[jackhill/mal.git] / impls / factor / step2_eval / step2_eval.factor
1 ! Copyright (C) 2015 Jordan Lewis.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays assocs combinators combinators.short-circuit
4 continuations fry io kernel math lib.printer lib.reader lib.types
5 quotations readline sequences ;
6 IN: step2_eval
7
8 CONSTANT: repl-env H{
9 { "+" [ + ] }
10 { "-" [ - ] }
11 { "*" [ * ] }
12 { "/" [ / ] }
13 }
14
15 DEFER: EVAL
16
17 : eval-symbol ( sym env -- ast )
18 [ name>> ] dip ?at [ "no variable " prepend throw ] unless ;
19
20 : eval-list ( list env -- ast )
21 '[ _ EVAL ] map ;
22
23 : eval-assoc ( assoc env -- ast )
24 '[ [ _ EVAL ] bi@ ] assoc-map ;
25
26 : eval-ast ( ast env -- ast )
27 {
28 { [ over malsymbol? ] [ eval-symbol ] }
29 { [ over sequence? ] [ eval-list ] }
30 { [ over assoc? ] [ eval-assoc ] }
31 [ drop ]
32 } cond ;
33
34 : READ ( str -- maltype ) read-str ;
35
36 : EVAL ( maltype env -- maltype )
37 eval-ast dup { [ array? ] [ empty? not ] } 1&& [
38 unclip
39 dup quotation? [ "not a fn" throw ] unless
40 with-datastack first
41 ] when ;
42
43 : PRINT ( maltype -- str ) pr-str ;
44
45 : REP ( str -- str )
46 [
47 READ repl-env EVAL PRINT
48 ] [
49 nip pr-str "Error: " swap append
50 ] recover ;
51
52 : REPL ( -- )
53 [
54 "user> " readline [
55 [ REP print flush ] unless-empty
56 ] keep
57 ] loop ;
58
59 MAIN: REPL