Merge pull request #374 from sgtatham/vala-fixes
[jackhill/mal.git] / perl / stepA_mal.pl
1 use strict;
2 use warnings FATAL => qw(all);
3 no if $] >= 5.018, warnings => "experimental::smartmatch";
4 use File::Basename;
5 use lib dirname (__FILE__);
6 use readline qw(mal_readline set_rl_mode);
7 use feature qw(switch);
8 use Data::Dumper;
9
10 use types qw($nil $true $false _sequential_Q _symbol_Q _list_Q);
11 use reader;
12 use printer;
13 use env;
14 use core qw($core_ns);
15 use interop qw(pl_to_mal);
16
17 # read
18 sub READ {
19 my $str = shift;
20 return reader::read_str($str);
21 }
22
23 # eval
24 sub is_pair {
25 my ($x) = @_;
26 return _sequential_Q($x) && scalar(@{$x->{val}}) > 0;
27 }
28
29 sub quasiquote {
30 my ($ast) = @_;
31 if (!is_pair($ast)) {
32 return List->new([Symbol->new("quote"), $ast]);
33 } elsif (_symbol_Q($ast->nth(0)) && ${$ast->nth(0)} eq 'unquote') {
34 return $ast->nth(1);
35 } elsif (is_pair($ast->nth(0)) && _symbol_Q($ast->nth(0)->nth(0)) &&
36 ${$ast->nth(0)->nth(0)} eq 'splice-unquote') {
37 return List->new([Symbol->new("concat"),
38 $ast->nth(0)->nth(1),
39 quasiquote($ast->rest())]);
40 } else {
41 return List->new([Symbol->new("cons"),
42 quasiquote($ast->nth(0)),
43 quasiquote($ast->rest())]);
44 }
45 }
46
47 sub is_macro_call {
48 my ($ast, $env) = @_;
49 if (_list_Q($ast) &&
50 _symbol_Q($ast->nth(0)) &&
51 $env->find($ast->nth(0))) {
52 my ($f) = $env->get($ast->nth(0));
53 if ((ref $f) =~ /^Function/) {
54 return $f->{ismacro};
55 }
56 }
57 return 0;
58 }
59
60 sub macroexpand {
61 my ($ast, $env) = @_;
62 while (is_macro_call($ast, $env)) {
63 my $mac = $env->get($ast->nth(0));
64 $ast = $mac->apply($ast->rest());
65 }
66 return $ast;
67 }
68
69
70 sub eval_ast {
71 my($ast, $env) = @_;
72 given (ref $ast) {
73 when (/^Symbol/) {
74 $env->get($ast);
75 }
76 when (/^List/) {
77 my @lst = map {EVAL($_, $env)} @{$ast->{val}};
78 return List->new(\@lst);
79 }
80 when (/^Vector/) {
81 my @lst = map {EVAL($_, $env)} @{$ast->{val}};
82 return Vector->new(\@lst);
83 }
84 when (/^HashMap/) {
85 my $new_hm = {};
86 foreach my $k (keys( %{ $ast->{val} })) {
87 $new_hm->{$k} = EVAL($ast->get($k), $env);
88 }
89 return HashMap->new($new_hm);
90 }
91 default {
92 return $ast;
93 }
94 }
95 }
96
97 sub EVAL {
98 my($ast, $env) = @_;
99
100 while (1) {
101
102 #print "EVAL: " . printer::_pr_str($ast) . "\n";
103 if (! _list_Q($ast)) {
104 return eval_ast($ast, $env);
105 }
106
107 # apply list
108 $ast = macroexpand($ast, $env);
109 if (! _list_Q($ast)) {
110 return eval_ast($ast, $env);
111 }
112
113 my ($a0, $a1, $a2, $a3) = @{$ast->{val}};
114 if (!$a0) { return $ast; }
115 given ((ref $a0) =~ /^Symbol/ ? $$a0 : $a0) {
116 when (/^def!$/) {
117 my $res = EVAL($a2, $env);
118 return $env->set($a1, $res);
119 }
120 when (/^let\*$/) {
121 my $let_env = Env->new($env);
122 for(my $i=0; $i < scalar(@{$a1->{val}}); $i+=2) {
123 $let_env->set($a1->nth($i), EVAL($a1->nth($i+1), $let_env));
124 }
125 $ast = $a2;
126 $env = $let_env;
127 # Continue loop (TCO)
128 }
129 when (/^quote$/) {
130 return $a1;
131 }
132 when (/^quasiquote$/) {
133 $ast = quasiquote($a1);
134 # Continue loop (TCO)
135 }
136 when (/^defmacro!$/) {
137 my $func = EVAL($a2, $env);
138 $func->{ismacro} = 1;
139 return $env->set($a1, $func);
140 }
141 when (/^macroexpand$/) {
142 return macroexpand($a1, $env);
143 }
144 when (/^pl\*$/) {
145 return pl_to_mal(eval(${$a1}));
146 }
147 when (/^try\*$/) {
148 do {
149 local $@;
150 my $ret;
151 eval {
152 use autodie; # always "throw" errors
153 $ret = EVAL($a1, $env);
154 1;
155 } or do {
156 my $err = $@;
157 if ($a2 && ${$a2->nth(0)} eq "catch\*") {
158 my $exc;
159 if (ref $err) {
160 $exc = $err;
161 } else {
162 $exc = String->new(substr $err, 0, -1);
163 }
164 return EVAL($a2->nth(2), Env->new($env,
165 List->new([$a2->nth(1)]),
166 List->new([$exc])));
167 } else {
168 die $err;
169 }
170 };
171 return $ret;
172 };
173 }
174 when (/^do$/) {
175 eval_ast($ast->slice(1, $#{$ast->{val}}-1), $env);
176 $ast = $ast->nth($#{$ast->{val}});
177 # Continue loop (TCO)
178 }
179 when (/^if$/) {
180 my $cond = EVAL($a1, $env);
181 if ($cond eq $nil || $cond eq $false) {
182 $ast = $a3 ? $a3 : $nil;
183 } else {
184 $ast = $a2;
185 }
186 # Continue loop (TCO)
187 }
188 when (/^fn\*$/) {
189 return Function->new(\&EVAL, $a2, $env, $a1);
190 }
191 default {
192 my $el = eval_ast($ast, $env);
193 my $f = $el->nth(0);
194 if ((ref $f) =~ /^Function/) {
195 $ast = $f->{ast};
196 $env = $f->gen_env($el->rest());
197 # Continue loop (TCO)
198 } else {
199 return &{ $f }($el->rest());
200 }
201 }
202 }
203
204 } # TCO while loop
205 }
206
207 # print
208 sub PRINT {
209 my $exp = shift;
210 return printer::_pr_str($exp);
211 }
212
213 # repl
214 my $repl_env = Env->new();
215 sub REP {
216 my $str = shift;
217 return PRINT(EVAL(READ($str), $repl_env));
218 }
219
220 # core.pl: defined using perl
221 foreach my $n (%$core_ns) {
222 $repl_env->set(Symbol->new($n), $core_ns->{$n});
223 }
224 $repl_env->set(Symbol->new('eval'), sub { EVAL($_[0]->nth(0), $repl_env); });
225 my @_argv = map {String->new($_)} @ARGV[1..$#ARGV];
226 $repl_env->set(Symbol->new('*ARGV*'), List->new(\@_argv));
227
228 # core.mal: defined using the language itself
229 REP("(def! *host-language* \"perl\")");
230 REP("(def! not (fn* (a) (if a false true)))");
231 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))");
232 REP("(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)))))))");
233 REP("(def! inc (fn* [x] (+ x 1)))");
234 REP("(def! gensym (let* [counter (atom 0)] (fn* [] (symbol (str \"G__\" (swap! counter inc))))))");
235 REP("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) (let* (condvar (gensym)) `(let* (~condvar ~(first xs)) (if ~condvar ~condvar (or ~@(rest xs)))))))))");
236
237
238 if (scalar(@ARGV) > 0 && $ARGV[0] eq "--raw") {
239 set_rl_mode("raw");
240 shift @ARGV;
241 }
242 if (scalar(@ARGV) > 0) {
243 REP("(load-file \"" . $ARGV[0] . "\")");
244 exit 0;
245 }
246 REP("(println (str \"Mal [\" *host-language* \"]\"))");
247 while (1) {
248 my $line = mal_readline("user> ");
249 if (! defined $line) { last; }
250 do {
251 local $@;
252 my $ret;
253 eval {
254 use autodie; # always "throw" errors
255 print(REP($line), "\n");
256 1;
257 } or do {
258 my $err = $@;
259 given (ref $err) {
260 when (/^BlankException/) {
261 # ignore and continue
262 }
263 default {
264 if (ref $err) {
265 print "Error: ".printer::_pr_str($err)."\n";
266 } else {
267 chomp $err;
268 print "Error: $err\n";
269 }
270 }
271 }
272 };
273 };
274 }