Merge pull request #156 from omarrayward/explain-regexp-tokenizer
[jackhill/mal.git] / perl / step8_macros.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
16 # read
17 sub READ {
18 my $str = shift;
19 return reader::read_str($str);
20 }
21
22 # eval
23 sub is_pair {
24 my ($x) = @_;
25 return _sequential_Q($x) && scalar(@{$x->{val}}) > 0;
26 }
27
28 sub quasiquote {
29 my ($ast) = @_;
30 if (!is_pair($ast)) {
31 return List->new([Symbol->new("quote"), $ast]);
32 } elsif (_symbol_Q($ast->nth(0)) && ${$ast->nth(0)} eq 'unquote') {
33 return $ast->nth(1);
34 } elsif (is_pair($ast->nth(0)) && _symbol_Q($ast->nth(0)->nth(0)) &&
35 ${$ast->nth(0)->nth(0)} eq 'splice-unquote') {
36 return List->new([Symbol->new("concat"),
37 $ast->nth(0)->nth(1),
38 quasiquote($ast->rest())]);
39 } else {
40 return List->new([Symbol->new("cons"),
41 quasiquote($ast->nth(0)),
42 quasiquote($ast->rest())]);
43 }
44 }
45
46 sub is_macro_call {
47 my ($ast, $env) = @_;
48 if (_list_Q($ast) &&
49 _symbol_Q($ast->nth(0)) &&
50 $env->find($ast->nth(0))) {
51 my ($f) = $env->get($ast->nth(0));
52 if ((ref $f) =~ /^Function/) {
53 return $f->{ismacro};
54 }
55 }
56 return 0;
57 }
58
59 sub macroexpand {
60 my ($ast, $env) = @_;
61 while (is_macro_call($ast, $env)) {
62 my $mac = $env->get($ast->nth(0));
63 $ast = $mac->apply($ast->rest());
64 }
65 return $ast;
66 }
67
68
69 sub eval_ast {
70 my($ast, $env) = @_;
71 given (ref $ast) {
72 when (/^Symbol/) {
73 $env->get($ast);
74 }
75 when (/^List/) {
76 my @lst = map {EVAL($_, $env)} @{$ast->{val}};
77 return List->new(\@lst);
78 }
79 when (/^Vector/) {
80 my @lst = map {EVAL($_, $env)} @{$ast->{val}};
81 return Vector->new(\@lst);
82 }
83 when (/^HashMap/) {
84 my $new_hm = {};
85 foreach my $k (keys( %{ $ast->{val} })) {
86 $new_hm->{$k} = EVAL($ast->get($k), $env);
87 }
88 return HashMap->new($new_hm);
89 }
90 default {
91 return $ast;
92 }
93 }
94 }
95
96 sub EVAL {
97 my($ast, $env) = @_;
98
99 while (1) {
100
101 #print "EVAL: " . printer::_pr_str($ast) . "\n";
102 if (! _list_Q($ast)) {
103 return eval_ast($ast, $env);
104 }
105
106 # apply list
107 $ast = macroexpand($ast, $env);
108 if (! _list_Q($ast)) {
109 return eval_ast($ast, $env);
110 }
111
112 my ($a0, $a1, $a2, $a3) = @{$ast->{val}};
113 given ((ref $a0) =~ /^Symbol/ ? $$a0 : $a0) {
114 when (/^def!$/) {
115 my $res = EVAL($a2, $env);
116 return $env->set($a1, $res);
117 }
118 when (/^let\*$/) {
119 my $let_env = Env->new($env);
120 for(my $i=0; $i < scalar(@{$a1->{val}}); $i+=2) {
121 $let_env->set($a1->nth($i), EVAL($a1->nth($i+1), $let_env));
122 }
123 $ast = $a2;
124 $env = $let_env;
125 # Continue loop (TCO)
126 }
127 when (/^quote$/) {
128 return $a1;
129 }
130 when (/^quasiquote$/) {
131 $ast = quasiquote($a1);
132 # Continue loop (TCO)
133 }
134 when (/^defmacro!$/) {
135 my $func = EVAL($a2, $env);
136 $func->{ismacro} = 1;
137 return $env->set($a1, $func);
138 }
139 when (/^macroexpand$/) {
140 return macroexpand($a1, $env);
141 }
142 when (/^do$/) {
143 eval_ast($ast->slice(1, $#{$ast->{val}}-1), $env);
144 $ast = $ast->nth($#{$ast->{val}});
145 # Continue loop (TCO)
146 }
147 when (/^if$/) {
148 my $cond = EVAL($a1, $env);
149 if ($cond eq $nil || $cond eq $false) {
150 $ast = $a3 ? $a3 : $nil;
151 } else {
152 $ast = $a2;
153 }
154 # Continue loop (TCO)
155 }
156 when (/^fn\*$/) {
157 return Function->new(\&EVAL, $a2, $env, $a1);
158 }
159 default {
160 my $el = eval_ast($ast, $env);
161 my $f = $el->nth(0);
162 if ((ref $f) =~ /^Function/) {
163 $ast = $f->{ast};
164 $env = $f->gen_env($el->rest());
165 # Continue loop (TCO)
166 } else {
167 return &{ $f }($el->rest());
168 }
169 }
170 }
171
172 } # TCO while loop
173 }
174
175 # print
176 sub PRINT {
177 my $exp = shift;
178 return printer::_pr_str($exp);
179 }
180
181 # repl
182 my $repl_env = Env->new();
183 sub REP {
184 my $str = shift;
185 return PRINT(EVAL(READ($str), $repl_env));
186 }
187
188 # core.pl: defined using perl
189 foreach my $n (%$core_ns) {
190 $repl_env->set(Symbol->new($n), $core_ns->{$n});
191 }
192 $repl_env->set(Symbol->new('eval'), sub { EVAL($_[0]->nth(0), $repl_env); });
193 my @_argv = map {String->new($_)} @ARGV[1..$#ARGV];
194 $repl_env->set(Symbol->new('*ARGV*'), List->new(\@_argv));
195
196 # core.mal: defined using the language itself
197 REP("(def! not (fn* (a) (if a false true)))");
198 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))");
199 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)))))))");
200 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))))))))");
201
202
203 if (scalar(@ARGV) > 0 && $ARGV[0] eq "--raw") {
204 set_rl_mode("raw");
205 shift @ARGV;
206 }
207 if (scalar(@ARGV) > 0) {
208 REP("(load-file \"" . $ARGV[0] . "\")");
209 exit 0;
210 }
211 while (1) {
212 my $line = mal_readline("user> ");
213 if (! defined $line) { last; }
214 do {
215 local $@;
216 my $ret;
217 eval {
218 use autodie; # always "throw" errors
219 print(REP($line), "\n");
220 1;
221 } or do {
222 my $err = $@;
223 given (ref $err) {
224 when (/^BlankException/) {
225 # ignore and continue
226 }
227 default {
228 chomp $err;
229 print "Error: $err\n";
230 }
231 }
232 };
233 };
234 }