All: swap step9,A. Fixes for bash, C, perl.
[jackhill/mal.git] / perl / step9_try.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);
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)) { return $ast; }
110
111 my ($a0, $a1, $a2, $a3) = @{$ast->{val}};
112 given ((ref $a0) =~ /^Symbol/ ? $$a0 : $a0) {
113 when (/^def!$/) {
114 my $res = EVAL($a2, $env);
115 return $env->set($$a1, $res);
116 }
117 when (/^let\*$/) {
118 my $let_env = Env->new($env);
119 for(my $i=0; $i < scalar(@{$a1->{val}}); $i+=2) {
120 $let_env->set(${$a1->nth($i)}, EVAL($a1->nth($i+1), $let_env));
121 }
122 $ast = $a2;
123 $env = $let_env;
124 # Continue loop (TCO)
125 }
126 when (/^quote$/) {
127 return $a1;
128 }
129 when (/^quasiquote$/) {
130 $ast = quasiquote($a1);
131 # Continue loop (TCO)
132 }
133 when (/^defmacro!$/) {
134 my $func = EVAL($a2, $env);
135 $func->{ismacro} = 1;
136 return $env->set($$a1, $func);
137 }
138 when (/^macroexpand$/) {
139 return macroexpand($a1, $env);
140 }
141 when (/^try\*$/) {
142 do {
143 local $@;
144 my $ret;
145 eval {
146 use autodie; # always "throw" errors
147 $ret = EVAL($a1, $env);
148 1;
149 } or do {
150 my $err = $@;
151 if ($a2 && ${$a2->nth(0)} eq "catch\*") {
152 my $exc;
153 if (ref $err) {
154 $exc = $err;
155 } else {
156 $exc = String->new(substr $err, 0, -1);
157 }
158 return EVAL($a2->nth(2), Env->new($env,
159 List->new([$a2->nth(1)]),
160 List->new([$exc])));
161 } else {
162 die $err;
163 }
164 };
165 return $ret;
166 };
167 }
168 when (/^do$/) {
169 eval_ast($ast->slice(1, $#{$ast->{val}}-1), $env);
170 $ast = $ast->nth($#{$ast->{val}});
171 # Continue loop (TCO)
172 }
173 when (/^if$/) {
174 my $cond = EVAL($a1, $env);
175 if ($cond eq $nil || $cond eq $false) {
176 $ast = $a3 ? $a3 : $nil;
177 } else {
178 $ast = $a2;
179 }
180 # Continue loop (TCO)
181 }
182 when (/^fn\*$/) {
183 return Function->new(\&EVAL, $a2, $env, $a1);
184 }
185 default {
186 my $el = eval_ast($ast, $env);
187 my $f = $el->nth(0);
188 if ((ref $f) =~ /^Function/) {
189 $ast = $f->{ast};
190 $env = $f->gen_env($el->rest());
191 # Continue loop (TCO)
192 } else {
193 return &{ $f }($el->rest());
194 }
195 }
196 }
197
198 } # TCO while loop
199 }
200
201 # print
202 sub PRINT {
203 my $exp = shift;
204 return printer::_pr_str($exp);
205 }
206
207 # repl
208 my $repl_env = Env->new();
209 sub REP {
210 my $str = shift;
211 return PRINT(EVAL(READ($str), $repl_env));
212 }
213
214 # core.pl: defined using perl
215 foreach my $n (%$core_ns) { $repl_env->set($n, $core_ns->{$n}); }
216 $repl_env->set('eval', sub { EVAL($_[0]->nth(0), $repl_env); });
217 my @_argv = map {String->new($_)} @ARGV[1..$#ARGV];
218 $repl_env->set('*ARGV*', List->new(\@_argv));
219
220 # core.mal: defined using the language itself
221 REP("(def! *host-language* \"javascript\")");
222 REP("(def! not (fn* (a) (if a false true)))");
223 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))");
224 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)))))))");
225 REP("(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))))))))");
226
227
228 if (scalar(@ARGV) > 0) {
229 REP("(load-file \"" . $ARGV[0] . "\")");
230 exit 0;
231 }
232 REP("(println (str \"Mal [\" *host-language* \"]\"))");
233 while (1) {
234 my $line = mal_readline("user> ");
235 if (! defined $line) { last; }
236 do {
237 local $@;
238 my $ret;
239 eval {
240 use autodie; # always "throw" errors
241 print(REP($line), "\n");
242 1;
243 } or do {
244 my $err = $@;
245 given (ref $err) {
246 when (/^BlankException/) {
247 # ignore and continue
248 }
249 default {
250 chomp $err;
251 print "Error: $err\n";
252 }
253 }
254 };
255 };
256 }