Merge pull request #49 from keith-rollin/swift
[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 let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
34 "----|----|----|----|----|----|----|----|----|----|----|" +
35 "----|----|----|----|----|----|----|----|----|----|----|" +
36 "----|----|----|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|"
44
45 let kSymbolArgv = MalSymbol(symbol: "*ARGV*")
46 let kSymbolDef = MalSymbol(symbol: "def!")
47 let kSymbolDo = MalSymbol(symbol: "do")
48 let kSymbolEval = MalSymbol(symbol: "eval")
49 let kSymbolFunction = MalSymbol(symbol: "fn*")
50 let kSymbolIf = MalSymbol(symbol: "if")
51 let kSymbolLet = MalSymbol(symbol: "let*")
52
53 // Class to help control the incrementing and decrementing of EVAL_level. We
54 // create one of these on entry to EVAL, incrementing the level. When the
55 // variable goes out of scope, the object is destroyed, decrementing the level.
56 //
57 class EVAL_Counter {
58 init() {
59 ++EVAL_level
60 }
61 deinit {
62 --EVAL_level
63 }
64 }
65
66 // Parse the string into an AST.
67 //
68 func READ(str: String) -> MalVal {
69 return read_str(str)
70 }
71
72 // Perform a simple evaluation of the `ast` object. If it's a symbol,
73 // dereference it and return its value. If it's a collection, call EVAL on all
74 // elements (or just the values, in the case of the hashmap). Otherwise, return
75 // the object unchanged.
76 //
77 func eval_ast(ast: MalVal, env: Environment) -> MalVal {
78 if is_symbol(ast) {
79 let symbol = ast as MalSymbol
80 if let val = env.get(symbol) {
81 return val
82 }
83 return MalError(message: "'\(symbol)' not found") // Specific text needed to match MAL unit tests
84 }
85 if is_list(ast) {
86 let list = ast as MalList
87 var result = [MalVal]()
88 result.reserveCapacity(list.count)
89 for item in list {
90 let eval = EVAL(item, env)
91 if is_error(eval) { return eval }
92 result.append(eval)
93 }
94 return MalList(array: result)
95 }
96 if is_vector(ast) {
97 let vec = ast as MalVector
98 var result = [MalVal]()
99 result.reserveCapacity(vec.count)
100 for item in vec {
101 let eval = EVAL(item, env)
102 if is_error(eval) { return eval }
103 result.append(eval)
104 }
105 return MalVector(array: result)
106 }
107 if is_hashmap(ast) {
108 let hash = ast as MalHashMap
109 var result = [MalVal]()
110 result.reserveCapacity(hash.count * 2)
111 for (k, v) in hash {
112 let new_v = EVAL(v, env)
113 if is_error(new_v) { return new_v }
114 result.append(k)
115 result.append(new_v)
116 }
117 return MalHashMap(array: result)
118 }
119 return ast
120 }
121
122 // Walk the AST and completely evaluate it, handling macro expansions, special
123 // forms and function calls.
124 //
125 func EVAL(var ast: MalVal, var env: Environment) -> MalVal {
126 var x = EVAL_Counter()
127 if EVAL_level > EVAL_leval_max {
128 return MalError(message: "Recursing too many levels (> \(EVAL_leval_max))")
129 }
130
131 let indent = INDENT_TEMPLATE.substringToIndex(
132 advance(INDENT_TEMPLATE.startIndex, EVAL_level, INDENT_TEMPLATE.endIndex))
133
134 while true {
135 if is_error(ast) { return ast }
136 if DEBUG_EVAL { println("\(indent)> \(ast)") }
137
138 // Special handling if it's a list.
139
140 if is_list(ast) {
141 var list = ast as MalList
142 if DEBUG_EVAL { println("\(indent)>. \(list)") }
143
144 if list.isEmpty {
145 return ast
146 }
147
148 let arg1 = list.first()
149 if is_symbol(arg1) {
150 let fn_symbol = arg1 as MalSymbol
151
152 // Check for special forms, where we want to check the operation
153 // before evaluating all of the parameters.
154
155 if fn_symbol == kSymbolDef {
156 if list.count != 3 {
157 return MalError(message: "expected 2 arguments to def!, got \(list.count - 1)")
158 }
159 let arg1 = list[1]
160 let arg2 = list[2]
161 if !is_symbol(arg1) {
162 return MalError(message: "expected symbol for first argument to def!")
163 }
164 let sym = arg1 as MalSymbol
165 let value = EVAL(arg2, env)
166 if is_error(value) { return value }
167 return env.set(sym, value)
168 } else if fn_symbol == kSymbolLet {
169 if list.count != 3 {
170 return MalError(message: "expected 2 arguments to let*, got \(list.count - 1)")
171 }
172 let arg1 = list[1]
173 let arg2 = list[2]
174 if !is_sequence(arg1) {
175 return MalError(message: "expected list for first argument to let*")
176 }
177 let bindings = arg1 as MalSequence
178 if bindings.count % 2 == 1 {
179 return MalError(message: "expected even number of elements in bindings to let*, got \(bindings.count)")
180 }
181 var new_env = Environment(outer: env)
182 for var index = 0; index < bindings.count; index += 2 {
183 let binding_name = bindings[index]
184 let binding_value = bindings[index + 1]
185
186 if !is_symbol(binding_name) {
187 return MalError(message: "expected symbol for first element in binding pair")
188 }
189 let binding_symbol = binding_name as MalSymbol
190 let evaluated_value = EVAL(binding_value, new_env)
191 if is_error(evaluated_value) { return evaluated_value }
192 new_env.set(binding_symbol, evaluated_value)
193 }
194 if TCO {
195 env = new_env
196 ast = arg2
197 continue
198 }
199 return EVAL(arg2, new_env)
200 } else if fn_symbol == kSymbolDo {
201 if TCO {
202 let eval = eval_ast(MalList(slice: list[1..<list.count-1]), env)
203 if is_error(eval) { return eval }
204 ast = list.last()
205 continue
206 }
207
208 let evaluated_ast = eval_ast(list.rest(), env)
209 if is_error(evaluated_ast) { return evaluated_ast }
210 let evaluated_seq = evaluated_ast as MalSequence
211 return evaluated_seq.last()
212 } else if fn_symbol == kSymbolIf {
213 if list.count < 3 {
214 return MalError(message: "expected at least 2 arguments to if, got \(list.count - 1)")
215 }
216 let cond_result = EVAL(list[1], env)
217 var new_ast = MalVal()
218 if is_truthy(cond_result) {
219 new_ast = list[2]
220 } else if list.count == 4 {
221 new_ast = list[3]
222 } else {
223 return MalNil()
224 }
225 if TCO {
226 ast = new_ast
227 continue
228 }
229 return EVAL(new_ast, env)
230 } else if fn_symbol == kSymbolFunction {
231 if list.count != 3 {
232 return MalError(message: "expected 2 arguments to fn*, got \(list.count - 1)")
233 }
234 if !is_sequence(list[1]) {
235 return MalError(message: "expected list or vector for first argument to fn*")
236 }
237 return MalClosure(eval: EVAL, args:list[1] as MalSequence, body:list[2], env:env)
238 }
239 }
240
241 // Standard list to be applied. Evaluate all the elements first.
242
243 let eval = eval_ast(ast, env)
244 if is_error(eval) { return eval }
245
246 // The result had better be a list and better be non-empty.
247
248 let eval_list = eval as MalList
249 if eval_list.isEmpty {
250 return eval_list
251 }
252
253 if DEBUG_EVAL { println("\(indent)>> \(eval)") }
254
255 // Get the first element of the list and execute it.
256
257 let first = eval_list.first()
258 let rest = eval_list.rest()
259
260 if is_builtin(first) {
261 let fn = first as MalBuiltin
262 let answer = fn.apply(rest)
263 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
264 return answer
265 } else if is_closure(first) {
266 let fn = first as MalClosure
267 var new_env = Environment(outer: fn.env)
268 let result = new_env.set_bindings(fn.args, with_exprs:rest)
269 if is_error(result) { return result }
270 if TCO {
271 env = new_env
272 ast = fn.body
273 continue
274 }
275 let answer = EVAL(fn.body, new_env)
276 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
277 return answer
278 }
279
280 // The first element wasn't a function to be executed. Return an
281 // error saying so.
282
283 return MalError(message: "first list item does not evaluate to a function: \(first)")
284 }
285
286 // Not a list -- just evaluate and return.
287
288 let answer = eval_ast(ast, env)
289 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
290 return answer
291 }
292 }
293
294 // Convert the value into a human-readable string for printing.
295 //
296 func PRINT(exp: MalVal) -> String? {
297 if is_error(exp) { return nil }
298 return pr_str(exp, true)
299 }
300
301 // Perform the READ and EVAL steps. Useful for when you don't care about the
302 // printable result.
303 //
304 func RE(text: String, env: Environment) -> MalVal? {
305 if text.isEmpty { return nil }
306 let ast = READ(text)
307 if is_error(ast) {
308 println("Error parsing input: \(ast)")
309 return nil
310 }
311 let exp = EVAL(ast, env)
312 if is_error(exp) {
313 println("Error evaluating input: \(exp)")
314 return nil
315 }
316 return exp
317 }
318
319 // Perform the full READ/EVAL/PRINT, returning a printable string.
320 //
321 func REP(text: String, env: Environment) -> String? {
322 let exp = RE(text, env)
323 if exp == nil { return nil }
324 return PRINT(exp!)
325 }
326
327 // Perform the full REPL.
328 //
329 func REPL(env: Environment) {
330 while true {
331 if let text = _readline("user> ") {
332 if let output = REP(text, env) {
333 println("\(output)")
334 }
335 } else {
336 println()
337 break
338 }
339 }
340 }
341
342 // Process any command line arguments. Any trailing arguments are incorporated
343 // into the environment. Any argument immediately after the process name is
344 // taken as a script to execute. If one exists, it is executed in lieu of
345 // running the REPL.
346 //
347 func process_command_line(args:[String], env:Environment) -> Bool {
348 var argv = MalList()
349 if args.count > 2 {
350 let args1 = args[2..<args.count]
351 let args2 = args1.map { MalString(unescaped: $0) as MalVal }
352 let args3 = [MalVal](args2)
353 argv = MalList(array: args3)
354 }
355 env.set(kSymbolArgv, argv)
356
357 if args.count > 1 {
358 RE("(load-file \"\(args[1])\")", env)
359 return false
360 }
361
362 return true
363 }
364
365 func main() {
366 var env = Environment(outer: nil)
367
368 load_history_file()
369 load_builtins(env)
370
371 RE("(def! not (fn* (a) (if a false true)))", env)
372 RE("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", env)
373
374 env.set(kSymbolEval, MalBuiltin(function: {
375 unwrap($0) {
376 (ast:MalVal) -> MalVal in
377 EVAL(ast, env)
378 }
379 }))
380
381 if process_command_line(Process.arguments, env) {
382 REPL(env)
383 }
384
385 save_history_file()
386 }