-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep8_macros.ts
225 lines (202 loc) · 8.79 KB
/
step8_macros.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { read_str } from "./reader"
import { pr_str } from "./printer"
import { Mal, List, Symbol, Null, Function, Vector, Map, Nil, False, TCOFunction, String } from "./types"
import { Env } from "./env";
import { ns } from "./core"
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
function read(str: string): Mal {
return read_str(str)
}
function eval_ast(ast: Mal, repl_env: Env): Mal {
if (ast instanceof Symbol) {
let result = repl_env.get(ast.contents)
if (result)
return result
else
throw "'" + ast.contents + "' not found"
} else if (ast instanceof List) {
return new List(ast.contents.map(x => evaluate(x, repl_env)))
} else if (ast instanceof Vector) {
return new Vector(ast.contents.map(x => evaluate(x, repl_env)))
} else {
return ast
}
}
function is_macro_call(ast: Mal, env: Env) {
if (ast instanceof List)
if (ast.contents[0])
if (ast.contents[0] instanceof Symbol) {
let fn_name = ast.contents[0].contents
let fn = env.find(fn_name)
if (fn instanceof TCOFunction)
return fn.isMacro
}
return false
}
function macroexpand(ast: Mal, env: Env) {
while (is_macro_call(ast, env)) {
let fn = <TCOFunction> env.find(ast.contents.shift().contents)
let args = ast.contents
if (fn instanceof TCOFunction) {
repl_env = new Env(env, fn.params, args)
ast = evaluate(fn.ast, repl_env)
}
}
return ast
}
function evaluate(ast: Mal, repl_env: Env): Mal {
while (true) {
ast = macroexpand(ast, repl_env)
if (!(ast instanceof List))
return eval_ast(ast, repl_env)
if (ast instanceof List) {
if (ast.contents.length == 0) {
return ast
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "quote") {
if (ast.contents[1] instanceof Vector)
return new List(ast.contents[1].contents)
return ast.contents[1]
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "macroexpand") {
return macroexpand(ast.contents[1], repl_env)
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "quasiquote") {
ast = quasiquote(ast.contents[1])
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "defmacro!") {
if (!(ast.contents[1] instanceof Symbol))
throw "Second parameter of define needs to be a valid symbol"
if (!(ast.contents[2]))
throw "Third parameter is needed for the value"
let result = <TCOFunction> evaluate(ast.contents[2], repl_env)
result.isMacro = true
repl_env.set(ast.contents[1].contents, result)
return result
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "def!") {
if (!(ast.contents[1] instanceof Symbol))
throw "Second parameter of define needs to be a valid symbol"
if (!(ast.contents[2]))
throw "Third parameter is needed for the value"
let result = evaluate(ast.contents[2], repl_env)
repl_env.set(ast.contents[1].contents, result)
return result
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "let*") {
if (ast.contents.length != 3)
throw "Invalid number of arguments for let*"
if (!(ast.contents[1] instanceof List || ast.contents[1] instanceof Vector))
throw "Invalid first parameter to let*"
else if (ast.contents[1].contents.length % 2 == 1)
throw "Invalid number of args in first parameter"
let new_env = new Env(repl_env, [], [])
let dec_lst: Mal[] = ast.contents[1].contents
for (var i = 0; i < ast.contents[1].contents.length; i += 2) {
if (!(dec_lst[i] instanceof Symbol))
throw "Invalid symbol given in let* list"
let result = evaluate(dec_lst[i+1], new_env)
new_env.set(dec_lst[i].contents, result)
}
repl_env = new_env
ast = ast.contents[2]
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "do") {
if (ast.contents.length < 2)
throw "Invalid number of args to do"
for (var i = 1; i < ast.contents.length - 1; i++)
evaluate(ast.contents[i], repl_env)
ast = ast.contents[ast.contents.length - 1]
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "if") {
let result = evaluate(ast.contents[1], repl_env)
if (result instanceof Nil || result instanceof False) {
if (ast.contents[3])
ast = ast.contents[3]
else
return new Nil()
} else {
ast = ast.contents[2]
}
} else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "fn*") {
let binds: string[] = ast.contents[1].contents.map(x => x.contents)
let fn = new Function((...args: Mal[]) => {
let new_env = new Env(repl_env, binds, args)
return evaluate(ast.contents[2], new_env)
})
return new TCOFunction(fn, ast.contents[2], binds, repl_env)
} else {
let evaluated = eval_ast(ast, repl_env)
let fn = evaluated.contents.shift()
let args = evaluated.contents
if (fn instanceof TCOFunction) {
repl_env = new Env(repl_env, fn.params, args)
ast = fn.ast
} else {
return fn.contents.apply(null, args)
}
}
//} else if (ast instanceof Map) {
// let result = evaluate(ast.contents, repl_env)
// return new Map(ast.key, result)
} else {
return eval_ast(ast, repl_env)
}
}
}
function is_pair(str: Mal): boolean {
return (str instanceof List || str instanceof Vector) && str.contents.length > 0
}
function quasiquote(ast: Mal): Mal {
if (!is_pair(ast))
return new List([
new Symbol("quote"),
ast
])
else if (ast.contents[0] instanceof Symbol && ast.contents[0].contents == "unquote")
return ast.contents[1]
else if (is_pair(ast.contents[0]) && ast.contents[0].contents[0] instanceof Symbol &&
ast.contents[0].contents[0].contents == "splice-unquote")
return new List([
new Symbol("concat"),
ast.contents[0].contents[1],
quasiquote(new List(ast.contents.slice(1)))
])
else
return new List([
new Symbol("cons"),
quasiquote(ast.contents[0]),
quasiquote(new List(ast.contents.slice(1)))
])
}
function rep(str: string, repl_env: Env): void {
try {
let ast: Mal = read(str)
let processed: Mal = evaluate(ast, repl_env)
if (!(ast instanceof Null))
console.log(pr_str(processed, true))
} catch (error) {
console.log(error)
}
}
// Initialize environment
let repl_env = new Env(null, [], [])
for (var symbol in ns) {
repl_env.set(symbol, new Function(ns[symbol]))
}
repl_env.set("eval", new Function((ast: Mal) => evaluate(ast, repl_env)))
repl_env.set("*ARGV*", new List(
process.argv.slice(2).map(x => new String(x))
))
// Load predefined functions in mal
function load(str: string): void {
let ast = read(str)
evaluate(ast, repl_env)
}
load("(def! not (fn* (a) (if a false true)))")
load('(def! load-file (fn* (f) (eval (read-string (str "(do " (remove-comments (slurp f)) ")")))))')
load("(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)))))))")
load("(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))))))))")
// Main loop
process.stdout.write("user> ")
rl.on('line', (input: string) => {
if (input.trim() != "")
rep(input, repl_env)
process.stdout.write("user> ")
});