refactor: move some code out of EVAL into their own functions for clarity (and, for...
[jackhill/mal.git] / swift / step6_file.swift
1 //******************************************************************************
2 // MAL - step 6 - file
3 //******************************************************************************
4 // This file is automatically generated from templates/step.swift. Rather than
5 // editing it directly, it's probably better to edit templates/step.swift and
6 // regenerate this file. Otherwise, your change might be lost if/when someone
7 // else performs that process.
8 //******************************************************************************
9
10 import Foundation
11
12 // The number of times EVAL has been entered recursively. We keep track of this
13 // so that we can protect against overrunning the stack.
14 //
15 var EVAL_level = 0
16
17 // The maximum number of times we let EVAL recurse before throwing an exception.
18 // Testing puts this at some place between 1800 and 1900. Let's keep it at 500
19 // for safety's sake.
20 //
21 let EVAL_leval_max = 500
22
23 // Control whether or not tail-call optimization (TCO) is enabled. We want it
24 // `true` most of the time, but may disable it for debugging purposes (it's
25 // easier to get a meaningful backtrace that way).
26 //
27 let TCO = true
28
29 // Control whether or not we emit debugging statements in EVAL.
30 //
31 let DEBUG_EVAL = false
32
33 // String used to prefix information logged in EVAL. Increasing lengths of the
34 // string are used the more EVAL is recursed.
35 //
36 let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|" +
44 "----|----|----|----|----|----|----|----|----|----|----|" +
45 "----|----|----|----|----|----|----|----|----|----|----|" +
46 "----|----|----|----|----|----|----|----|----|----|----|"
47
48 // Holds the prefix of INDENT_TEMPLATE used for actual logging.
49 //
50 var indent = String()
51
52 // Symbols used in this module.
53 //
54 let kSymbolArgv = MalSymbol(symbol: "*ARGV*")
55 let kSymbolDef = MalSymbol(symbol: "def!")
56 let kSymbolDo = MalSymbol(symbol: "do")
57 let kSymbolEval = MalSymbol(symbol: "eval")
58 let kSymbolFn = MalSymbol(symbol: "fn*")
59 let kSymbolIf = MalSymbol(symbol: "if")
60 let kSymbolLet = MalSymbol(symbol: "let*")
61
62 // Class to help control the incrementing and decrementing of EVAL_level. We
63 // create one of these on entry to EVAL, incrementing the level. When the
64 // variable goes out of scope, the object is destroyed, decrementing the level.
65 //
66 class EVAL_Counter {
67 init() {
68 ++EVAL_level
69 }
70 deinit {
71 --EVAL_level
72 }
73 }
74
75 // Parse the string into an AST.
76 //
77 func READ(str: String) -> MalVal {
78 return read_str(str)
79 }
80
81 // Perform a simple evaluation of the `ast` object. If it's a symbol,
82 // dereference it and return its value. If it's a collection, call EVAL on all
83 // elements (or just the values, in the case of the hashmap). Otherwise, return
84 // the object unchanged.
85 //
86 func eval_ast(ast: MalVal, env: Environment) -> MalVal {
87 if is_symbol(ast) {
88 let symbol = ast as MalSymbol
89 if let val = env.get(symbol) {
90 return val
91 }
92 return MalError(message: "'\(symbol)' not found") // Specific text needed to match MAL unit tests
93 }
94 if is_list(ast) {
95 let list = ast as MalList
96 var result = [MalVal]()
97 result.reserveCapacity(list.count)
98 for item in list {
99 let eval = EVAL(item, env)
100 if is_error(eval) { return eval }
101 result.append(eval)
102 }
103 return MalList(array: result)
104 }
105 if is_vector(ast) {
106 let vec = ast as MalVector
107 var result = [MalVal]()
108 result.reserveCapacity(vec.count)
109 for item in vec {
110 let eval = EVAL(item, env)
111 if is_error(eval) { return eval }
112 result.append(eval)
113 }
114 return MalVector(array: result)
115 }
116 if is_hashmap(ast) {
117 let hash = ast as MalHashMap
118 var result = [MalVal]()
119 result.reserveCapacity(hash.count * 2)
120 for (k, v) in hash {
121 let new_v = EVAL(v, env)
122 if is_error(new_v) { return new_v }
123 result.append(k)
124 result.append(new_v)
125 }
126 return MalHashMap(array: result)
127 }
128 return ast
129 }
130
131 enum TCOVal {
132 case NoResult
133 case Return(MalVal)
134 case Continue(MalVal, Environment)
135
136 init() { self = .NoResult }
137 init(_ result: MalVal) { self = .Return(result) }
138 init(_ ast: MalVal, _ env: Environment) { self = .Continue(ast, env) }
139 init(_ e: String) { self = .Return(MalError(message: e)) }
140 }
141
142 // EVALuate "def!".
143 //
144 func eval_def(list: MalSequence, env: Environment) -> TCOVal {
145 if list.count != 3 {
146 return TCOVal("expected 2 arguments to def!, got \(list.count - 1)")
147 }
148 let arg1 = list[1]
149 let arg2 = list[2]
150 if !is_symbol(arg1) {
151 return TCOVal("expected symbol for first argument to def!")
152 }
153 let sym = arg1 as MalSymbol
154 let value = EVAL(arg2, env)
155 if is_error(value) { return TCOVal(value) }
156 return TCOVal(env.set(sym, value))
157 }
158
159 // EVALuate "let*".
160 //
161 func eval_let(list: MalSequence, env: Environment) -> TCOVal {
162 if list.count != 3 {
163 return TCOVal("expected 2 arguments to let*, got \(list.count - 1)")
164 }
165 let arg1 = list[1]
166 let arg2 = list[2]
167 if !is_sequence(arg1) {
168 return TCOVal("expected list for first argument to let*")
169 }
170 let bindings = arg1 as MalSequence
171 if bindings.count % 2 == 1 {
172 return TCOVal("expected even number of elements in bindings to let*, got \(bindings.count)")
173 }
174 var new_env = Environment(outer: env)
175 for var index = 0; index < bindings.count; index += 2 {
176 let binding_name = bindings[index]
177 let binding_value = bindings[index + 1]
178
179 if !is_symbol(binding_name) {
180 return TCOVal("expected symbol for first element in binding pair")
181 }
182 let binding_symbol = binding_name as MalSymbol
183 let evaluated_value = EVAL(binding_value, new_env)
184 if is_error(evaluated_value) { return TCOVal(evaluated_value) }
185 new_env.set(binding_symbol, evaluated_value)
186 }
187 if TCO {
188 return TCOVal(arg2, new_env)
189 }
190 return TCOVal(EVAL(arg2, new_env))
191 }
192
193 // EVALuate "do".
194 //
195 func eval_do(list: MalSequence, env: Environment) -> TCOVal {
196 if TCO {
197 let eval = eval_ast(MalList(slice: list[1..<list.count-1]), env)
198 if is_error(eval) { return TCOVal(eval) }
199 return TCOVal(list.last(), env)
200 }
201
202 let evaluated_ast = eval_ast(list.rest(), env)
203 if is_error(evaluated_ast) { return TCOVal(evaluated_ast) }
204 let evaluated_seq = evaluated_ast as MalSequence
205 return TCOVal(evaluated_seq.last())
206 }
207
208 // EVALuate "if".
209 //
210 func eval_if(list: MalSequence, env: Environment) -> TCOVal {
211 if list.count < 3 {
212 return TCOVal("expected at least 2 arguments to if, got \(list.count - 1)")
213 }
214 let cond_result = EVAL(list[1], env)
215 var new_ast = MalVal()
216 if is_truthy(cond_result) {
217 new_ast = list[2]
218 } else if list.count == 4 {
219 new_ast = list[3]
220 } else {
221 return TCOVal(MalNil())
222 }
223 if TCO {
224 return TCOVal(new_ast, env)
225 }
226 return TCOVal(EVAL(new_ast, env))
227 }
228
229 // EVALuate "fn*".
230 //
231 func eval_fn(list: MalSequence, env: Environment) -> TCOVal {
232 if list.count != 3 {
233 return TCOVal("expected 2 arguments to fn*, got \(list.count - 1)")
234 }
235 if !is_sequence(list[1]) {
236 return TCOVal("expected list or vector for first argument to fn*")
237 }
238 return TCOVal(MalClosure(eval: EVAL, args:list[1] as MalSequence, body:list[2], env:env))
239 }
240
241 // Walk the AST and completely evaluate it, handling macro expansions, special
242 // forms and function calls.
243 //
244 func EVAL(var ast: MalVal, var env: Environment) -> MalVal {
245 let x = EVAL_Counter()
246 if EVAL_level > EVAL_leval_max {
247 return MalError(message: "Recursing too many levels (> \(EVAL_leval_max))")
248 }
249
250 if DEBUG_EVAL {
251 indent = prefix(INDENT_TEMPLATE, EVAL_level)
252 }
253
254 while true {
255 if is_error(ast) { return ast }
256 if DEBUG_EVAL { println("\(indent)> \(ast)") }
257
258 if !is_list(ast) {
259
260 // Not a list -- just evaluate and return.
261
262 let answer = eval_ast(ast, env)
263 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
264 return answer
265 }
266
267 // Special handling if it's a list.
268
269 var list = ast as MalList
270 if DEBUG_EVAL { println("\(indent)>. \(list)") }
271
272 if list.isEmpty {
273 return list
274 }
275
276 // Check for special forms, where we want to check the operation
277 // before evaluating all of the parameters.
278
279 let arg0 = list.first()
280 if is_symbol(arg0) {
281 var res: TCOVal
282 let fn_symbol = arg0 as MalSymbol
283
284 switch fn_symbol {
285 case kSymbolDef: res = eval_def(list, env)
286 case kSymbolLet: res = eval_let(list, env)
287 case kSymbolDo: res = eval_do(list, env)
288 case kSymbolIf: res = eval_if(list, env)
289 case kSymbolFn: res = eval_fn(list, env)
290 default: res = TCOVal()
291 }
292 switch res {
293 case let .Return(result): return result
294 case let .Continue(new_ast, new_env): ast = new_ast; env = new_env; continue
295 case .NoResult: break
296 }
297 }
298
299 // Standard list to be applied. Evaluate all the elements first.
300
301 let eval = eval_ast(ast, env)
302 if is_error(eval) { return eval }
303
304 // The result had better be a list and better be non-empty.
305
306 let eval_list = eval as MalList
307 if eval_list.isEmpty {
308 return eval_list
309 }
310
311 if DEBUG_EVAL { println("\(indent)>> \(eval)") }
312
313 // Get the first element of the list and execute it.
314
315 let first = eval_list.first()
316 let rest = eval_list.rest()
317
318 if is_builtin(first) {
319 let fn = first as MalBuiltin
320 let answer = fn.apply(rest)
321 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
322 return answer
323 } else if is_closure(first) {
324 let fn = first as MalClosure
325 var new_env = Environment(outer: fn.env)
326 let result = new_env.set_bindings(fn.args, with_exprs:rest)
327 if is_error(result) { return result }
328 if TCO {
329 env = new_env
330 ast = fn.body
331 continue
332 }
333 let answer = EVAL(fn.body, new_env)
334 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
335 return answer
336 }
337
338 // The first element wasn't a function to be executed. Return an
339 // error saying so.
340
341 return MalError(message: "first list item does not evaluate to a function: \(first)")
342 }
343 }
344
345 // Convert the value into a human-readable string for printing.
346 //
347 func PRINT(exp: MalVal) -> String? {
348 if is_error(exp) { return nil }
349 return pr_str(exp, true)
350 }
351
352 // Perform the READ and EVAL steps. Useful for when you don't care about the
353 // printable result.
354 //
355 func RE(text: String, env: Environment) -> MalVal? {
356 if text.isEmpty { return nil }
357 let ast = READ(text)
358 if is_error(ast) {
359 println("Error parsing input: \(ast)")
360 return nil
361 }
362 let exp = EVAL(ast, env)
363 if is_error(exp) {
364 println("Error evaluating input: \(exp)")
365 return nil
366 }
367 return exp
368 }
369
370 // Perform the full READ/EVAL/PRINT, returning a printable string.
371 //
372 func REP(text: String, env: Environment) -> String? {
373 let exp = RE(text, env)
374 if exp == nil { return nil }
375 return PRINT(exp!)
376 }
377
378 // Perform the full REPL.
379 //
380 func REPL(env: Environment) {
381 while true {
382 if let text = _readline("user> ") {
383 if let output = REP(text, env) {
384 println("\(output)")
385 }
386 } else {
387 println()
388 break
389 }
390 }
391 }
392
393 // Process any command line arguments. Any trailing arguments are incorporated
394 // into the environment. Any argument immediately after the process name is
395 // taken as a script to execute. If one exists, it is executed in lieu of
396 // running the REPL.
397 //
398 func process_command_line(args:[String], env:Environment) -> Bool {
399 var argv = MalList()
400 if args.count > 2 {
401 let args1 = args[2..<args.count]
402 let args2 = args1.map { MalString(unescaped: $0) as MalVal }
403 let args3 = [MalVal](args2)
404 argv = MalList(array: args3)
405 }
406 env.set(kSymbolArgv, argv)
407
408 if args.count > 1 {
409 RE("(load-file \"\(args[1])\")", env)
410 return false
411 }
412
413 return true
414 }
415
416 func main() {
417 var env = Environment(outer: nil)
418
419 load_history_file()
420 load_builtins(env)
421
422 RE("(def! not (fn* (a) (if a false true)))", env)
423 RE("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", env)
424
425 env.set(kSymbolEval, MalBuiltin(function: {
426 unwrap($0) {
427 (ast:MalVal) -> MalVal in
428 EVAL(ast, env)
429 }
430 }))
431
432 if process_command_line(Process.arguments, env) {
433 REPL(env)
434 }
435
436 save_history_file()
437 }