Merge pull request #156 from omarrayward/explain-regexp-tokenizer
[jackhill/mal.git] / cs / step8_macros.cs
1 using System;
2 using System.IO;
3 using System.Collections;
4 using System.Collections.Generic;
5 using Mal;
6 using MalVal = Mal.types.MalVal;
7 using MalString = Mal.types.MalString;
8 using MalSymbol = Mal.types.MalSymbol;
9 using MalInt = Mal.types.MalInt;
10 using MalList = Mal.types.MalList;
11 using MalVector = Mal.types.MalVector;
12 using MalHashMap = Mal.types.MalHashMap;
13 using MalFunc = Mal.types.MalFunc;
14 using Env = Mal.env.Env;
15
16 namespace Mal {
17 class step8_macros {
18 // read
19 static MalVal READ(string str) {
20 return reader.read_str(str);
21 }
22
23 // eval
24 public static bool is_pair(MalVal x) {
25 return x is MalList && ((MalList)x).size() > 0;
26 }
27
28 public static MalVal quasiquote(MalVal ast) {
29 if (!is_pair(ast)) {
30 return new MalList(new MalSymbol("quote"), ast);
31 } else {
32 MalVal a0 = ((MalList)ast)[0];
33 if ((a0 is MalSymbol) &&
34 (((MalSymbol)a0).getName() == "unquote")) {
35 return ((MalList)ast)[1];
36 } else if (is_pair(a0)) {
37 MalVal a00 = ((MalList)a0)[0];
38 if ((a00 is MalSymbol) &&
39 (((MalSymbol)a00).getName() == "splice-unquote")) {
40 return new MalList(new MalSymbol("concat"),
41 ((MalList)a0)[1],
42 quasiquote(((MalList)ast).rest()));
43 }
44 }
45 return new MalList(new MalSymbol("cons"),
46 quasiquote(a0),
47 quasiquote(((MalList)ast).rest()));
48 }
49 }
50
51 public static bool is_macro_call(MalVal ast, Env env) {
52 if (ast is MalList) {
53 MalVal a0 = ((MalList)ast)[0];
54 if (a0 is MalSymbol &&
55 env.find((MalSymbol)a0) != null) {
56 MalVal mac = env.get((MalSymbol)a0);
57 if (mac is MalFunc &&
58 ((MalFunc)mac).isMacro()) {
59 return true;
60 }
61 }
62 }
63 return false;
64 }
65
66 public static MalVal macroexpand(MalVal ast, Env env) {
67 while (is_macro_call(ast, env)) {
68 MalSymbol a0 = (MalSymbol)((MalList)ast)[0];
69 MalFunc mac = (MalFunc) env.get(a0);
70 ast = mac.apply(((MalList)ast).rest());
71 }
72 return ast;
73 }
74
75 static MalVal eval_ast(MalVal ast, Env env) {
76 if (ast is MalSymbol) {
77 return env.get((MalSymbol)ast);
78 } else if (ast is MalList) {
79 MalList old_lst = (MalList)ast;
80 MalList new_lst = ast.list_Q() ? new MalList()
81 : (MalList)new MalVector();
82 foreach (MalVal mv in old_lst.getValue()) {
83 new_lst.conj_BANG(EVAL(mv, env));
84 }
85 return new_lst;
86 } else if (ast is MalHashMap) {
87 var new_dict = new Dictionary<string, MalVal>();
88 foreach (var entry in ((MalHashMap)ast).getValue()) {
89 new_dict.Add(entry.Key, EVAL((MalVal)entry.Value, env));
90 }
91 return new MalHashMap(new_dict);
92 } else {
93 return ast;
94 }
95 }
96
97
98 static MalVal EVAL(MalVal orig_ast, Env env) {
99 MalVal a0, a1, a2, res;
100 MalList el;
101
102 while (true) {
103
104 //Console.WriteLine("EVAL: " + printer._pr_str(orig_ast, true));
105 if (!orig_ast.list_Q()) {
106 return eval_ast(orig_ast, env);
107 }
108
109 // apply list
110 MalVal expanded = macroexpand(orig_ast, env);
111 if (!expanded.list_Q()) {
112 return eval_ast(expanded, env);
113 }
114 MalList ast = (MalList) expanded;
115
116 if (ast.size() == 0) { return ast; }
117 a0 = ast[0];
118
119 String a0sym = a0 is MalSymbol ? ((MalSymbol)a0).getName()
120 : "__<*fn*>__";
121
122 switch (a0sym) {
123 case "def!":
124 a1 = ast[1];
125 a2 = ast[2];
126 res = EVAL(a2, env);
127 env.set((MalSymbol)a1, res);
128 return res;
129 case "let*":
130 a1 = ast[1];
131 a2 = ast[2];
132 MalSymbol key;
133 MalVal val;
134 Env let_env = new Env(env);
135 for(int i=0; i<((MalList)a1).size(); i+=2) {
136 key = (MalSymbol)((MalList)a1)[i];
137 val = ((MalList)a1)[i+1];
138 let_env.set(key, EVAL(val, let_env));
139 }
140 orig_ast = a2;
141 env = let_env;
142 break;
143 case "quote":
144 return ast[1];
145 case "quasiquote":
146 orig_ast = quasiquote(ast[1]);
147 break;
148 case "defmacro!":
149 a1 = ast[1];
150 a2 = ast[2];
151 res = EVAL(a2, env);
152 ((MalFunc)res).setMacro();
153 env.set(((MalSymbol)a1), res);
154 return res;
155 case "macroexpand":
156 a1 = ast[1];
157 return macroexpand(a1, env);
158 case "do":
159 eval_ast(ast.slice(1, ast.size()-1), env);
160 orig_ast = ast[ast.size()-1];
161 break;
162 case "if":
163 a1 = ast[1];
164 MalVal cond = EVAL(a1, env);
165 if (cond == Mal.types.Nil || cond == Mal.types.False) {
166 // eval false slot form
167 if (ast.size() > 3) {
168 orig_ast = ast[3];
169 } else {
170 return Mal.types.Nil;
171 }
172 } else {
173 // eval true slot form
174 orig_ast = ast[2];
175 }
176 break;
177 case "fn*":
178 MalList a1f = (MalList)ast[1];
179 MalVal a2f = ast[2];
180 Env cur_env = env;
181 return new MalFunc(a2f, env, a1f,
182 args => EVAL(a2f, new Env(cur_env, a1f, args)) );
183 default:
184 el = (MalList)eval_ast(ast, env);
185 var f = (MalFunc)el[0];
186 MalVal fnast = f.getAst();
187 if (fnast != null) {
188 orig_ast = fnast;
189 env = f.genEnv(el.rest());
190 } else {
191 return f.apply(el.rest());
192 }
193 break;
194 }
195
196 }
197 }
198
199 // print
200 static string PRINT(MalVal exp) {
201 return printer._pr_str(exp, true);
202 }
203
204 // repl
205 static void Main(string[] args) {
206 var repl_env = new Mal.env.Env(null);
207 Func<string, MalVal> RE = (string str) => EVAL(READ(str), repl_env);
208
209 // core.cs: defined using C#
210 foreach (var entry in core.ns) {
211 repl_env.set(new MalSymbol(entry.Key), entry.Value);
212 }
213 repl_env.set(new MalSymbol("eval"), new MalFunc(
214 a => EVAL(a[0], repl_env)));
215 int fileIdx = 0;
216 if (args.Length > 0 && args[0] == "--raw") {
217 Mal.readline.mode = Mal.readline.Mode.Raw;
218 fileIdx = 1;
219 }
220 MalList _argv = new MalList();
221 for (int i=fileIdx+1; i < args.Length; i++) {
222 _argv.conj_BANG(new MalString(args[i]));
223 }
224 repl_env.set(new MalSymbol("*ARGV*"), _argv);
225
226 // core.mal: defined using the language itself
227 RE("(def! not (fn* (a) (if a false true)))");
228 RE("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))");
229 RE("(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)))))))");
230 RE("(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))))))))");
231
232 if (args.Length > fileIdx) {
233 RE("(load-file \"" + args[fileIdx] + "\")");
234 return;
235 }
236
237 // repl loop
238 while (true) {
239 string line;
240 try {
241 line = Mal.readline.Readline("user> ");
242 if (line == null) { break; }
243 if (line == "") { continue; }
244 } catch (IOException e) {
245 Console.WriteLine("IOException: " + e.Message);
246 break;
247 }
248 try {
249 Console.WriteLine(PRINT(RE(line)));
250 } catch (Mal.types.MalContinue) {
251 continue;
252 } catch (Exception e) {
253 Console.WriteLine("Error: " + e.Message);
254 Console.WriteLine(e.StackTrace);
255 continue;
256 }
257 }
258 }
259 }
260 }