Merge pull request #378 from asarhaddon/test-macro-not-changing-function
[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 private 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 private 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 private let TCO = true
28
29 // Control whether or not we emit debugging statements in EVAL.
30 //
31 private 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 private 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 private var indent = String()
51
52 // Symbols used in this module.
53 //
54 private let kValArgv = make_symbol("*ARGV*")
55 private let kValDef = make_symbol("def!")
56 private let kValDo = make_symbol("do")
57 private let kValEval = make_symbol("eval")
58 private let kValFn = make_symbol("fn*")
59 private let kValIf = make_symbol("if")
60 private let kValLet = make_symbol("let*")
61 private let kValTry = make_symbol("try*")
62
63 private let kSymbolArgv = as_symbol(kValArgv)
64 private let kSymbolDef = as_symbol(kValDef)
65 private let kSymbolDo = as_symbol(kValDo)
66 private let kSymbolEval = as_symbol(kValEval)
67 private let kSymbolFn = as_symbol(kValFn)
68 private let kSymbolIf = as_symbol(kValIf)
69 private let kSymbolLet = as_symbol(kValLet)
70
71 func substring(s: String, _ begin: Int, _ end: Int) -> String {
72 return s[s.startIndex.advancedBy(begin) ..< s.startIndex.advancedBy(end)]
73 }
74
75 // Parse the string into an AST.
76 //
77 private func READ(str: String) throws -> MalVal {
78 return try 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 private func eval_ast(ast: MalVal, _ env: Environment) throws -> MalVal {
87 if let symbol = as_symbolQ(ast) {
88 guard let val = env.get(symbol) else {
89 try throw_error("'\(symbol)' not found") // Specific text needed to match MAL unit tests
90 }
91 return val
92 }
93 if let list = as_listQ(ast) {
94 var result = [MalVal]()
95 result.reserveCapacity(Int(list.count))
96 for item in list {
97 let eval = try EVAL(item, env)
98 result.append(eval)
99 }
100 return make_list(result)
101 }
102 if let vec = as_vectorQ(ast) {
103 var result = [MalVal]()
104 result.reserveCapacity(Int(vec.count))
105 for item in vec {
106 let eval = try EVAL(item, env)
107 result.append(eval)
108 }
109 return make_vector(result)
110 }
111 if let hash = as_hashmapQ(ast) {
112 var result = [MalVal]()
113 result.reserveCapacity(Int(hash.count) * 2)
114 for (k, v) in hash {
115 let new_v = try EVAL(v, env)
116 result.append(k)
117 result.append(new_v)
118 }
119 return make_hashmap(result)
120 }
121 return ast
122 }
123
124 private enum TCOVal {
125 case NoResult
126 case Return(MalVal)
127 case Continue(MalVal, Environment)
128
129 init() { self = .NoResult }
130 init(_ result: MalVal) { self = .Return(result) }
131 init(_ ast: MalVal, _ env: Environment) { self = .Continue(ast, env) }
132 }
133
134 // EVALuate "def!".
135 //
136 private func eval_def(list: MalSequence, _ env: Environment) throws -> TCOVal {
137 guard list.count == 3 else {
138 try throw_error("expected 2 arguments to def!, got \(list.count - 1)")
139 }
140 let arg1 = try! list.nth(1)
141 let arg2 = try! list.nth(2)
142 guard let sym = as_symbolQ(arg1) else {
143 try throw_error("expected symbol for first argument to def!")
144 }
145 let value = try EVAL(arg2, env)
146 return TCOVal(env.set(sym, value))
147 }
148
149 // EVALuate "let*".
150 //
151 private func eval_let(list: MalSequence, _ env: Environment) throws -> TCOVal {
152 guard list.count == 3 else {
153 try throw_error("expected 2 arguments to let*, got \(list.count - 1)")
154 }
155 let arg1 = try! list.nth(1)
156 let arg2 = try! list.nth(2)
157 guard let bindings = as_sequenceQ(arg1) else {
158 try throw_error("expected list for first argument to let*")
159 }
160 guard bindings.count % 2 == 0 else {
161 try throw_error("expected even number of elements in bindings to let*, got \(bindings.count)")
162 }
163 let new_env = Environment(outer: env)
164 for var index: MalIntType = 0; index < bindings.count; index += 2 {
165 let binding_name = try! bindings.nth(index)
166 let binding_value = try! bindings.nth(index + 1)
167 guard let binding_symbol = as_symbolQ(binding_name) else {
168 try throw_error("expected symbol for first element in binding pair")
169 }
170 let evaluated_value = try EVAL(binding_value, new_env)
171 new_env.set(binding_symbol, evaluated_value)
172 }
173 if TCO {
174 return TCOVal(arg2, new_env)
175 }
176 return TCOVal(try EVAL(arg2, new_env))
177 }
178
179 // EVALuate "do".
180 //
181 private func eval_do(list: MalSequence, _ env: Environment) throws -> TCOVal {
182 if TCO {
183 let _ = try eval_ast(list.range_from(1, to: list.count-1), env)
184 return TCOVal(list.last(), env)
185 }
186
187 let evaluated_ast = try eval_ast(list.rest(), env)
188 let evaluated_seq = as_sequence(evaluated_ast)
189 return TCOVal(evaluated_seq.last())
190 }
191
192 // EVALuate "if".
193 //
194 private func eval_if(list: MalSequence, _ env: Environment) throws -> TCOVal {
195 guard list.count >= 3 else {
196 try throw_error("expected at least 2 arguments to if, got \(list.count - 1)")
197 }
198 let cond_result = try EVAL(try! list.nth(1), env)
199 var new_ast: MalVal
200 if is_truthy(cond_result) {
201 new_ast = try! list.nth(2)
202 } else if list.count == 4 {
203 new_ast = try! list.nth(3)
204 } else {
205 return TCOVal(make_nil())
206 }
207 if TCO {
208 return TCOVal(new_ast, env)
209 }
210 return TCOVal(try EVAL(new_ast, env))
211 }
212
213 // EVALuate "fn*".
214 //
215 private func eval_fn(list: MalSequence, _ env: Environment) throws -> TCOVal {
216 guard list.count == 3 else {
217 try throw_error("expected 2 arguments to fn*, got \(list.count - 1)")
218 }
219 guard let seq = as_sequenceQ(try! list.nth(1)) else {
220 try throw_error("expected list or vector for first argument to fn*")
221 }
222 return TCOVal(make_closure((eval: EVAL, args: seq, body: try! list.nth(2), env: env)))
223 }
224
225 // Walk the AST and completely evaluate it, handling macro expansions, special
226 // forms and function calls.
227 //
228 private func EVAL(var ast: MalVal, var _ env: Environment) throws -> MalVal {
229 EVAL_level++
230 defer { EVAL_level-- }
231 guard EVAL_level <= EVAL_leval_max else {
232 try throw_error("Recursing too many levels (> \(EVAL_leval_max))")
233 }
234
235 if DEBUG_EVAL {
236 indent = substring(INDENT_TEMPLATE, 0, EVAL_level)
237 }
238
239 while true {
240 if DEBUG_EVAL { print("\(indent)> \(ast)") }
241
242 if !is_list(ast) {
243
244 // Not a list -- just evaluate and return.
245
246 let answer = try eval_ast(ast, env)
247 if DEBUG_EVAL { print("\(indent)>>> \(answer)") }
248 return answer
249 }
250
251 // Special handling if it's a list.
252
253 let list = as_list(ast)
254 if DEBUG_EVAL { print("\(indent)>. \(list)") }
255
256 if list.isEmpty {
257 return ast
258 }
259
260 // Check for special forms, where we want to check the operation
261 // before evaluating all of the parameters.
262
263 let arg0 = list.first()
264 if let fn_symbol = as_symbolQ(arg0) {
265 let res: TCOVal
266
267 switch fn_symbol {
268 case kSymbolDef: res = try eval_def(list, env)
269 case kSymbolLet: res = try eval_let(list, env)
270 case kSymbolDo: res = try eval_do(list, env)
271 case kSymbolIf: res = try eval_if(list, env)
272 case kSymbolFn: res = try eval_fn(list, env)
273 default: res = TCOVal()
274 }
275 switch res {
276 case let .Return(result): return result
277 case let .Continue(new_ast, new_env): ast = new_ast; env = new_env; continue
278 case .NoResult: break
279 }
280 }
281
282 // Standard list to be applied. Evaluate all the elements first.
283
284 let eval = try eval_ast(ast, env)
285
286 // The result had better be a list and better be non-empty.
287
288 let eval_list = as_list(eval)
289 if eval_list.isEmpty {
290 return eval
291 }
292
293 if DEBUG_EVAL { print("\(indent)>> \(eval)") }
294
295 // Get the first element of the list and execute it.
296
297 let first = eval_list.first()
298 let rest = as_sequence(eval_list.rest())
299
300 if let fn = as_builtinQ(first) {
301 let answer = try fn.apply(rest)
302 if DEBUG_EVAL { print("\(indent)>>> \(answer)") }
303 return answer
304 } else if let fn = as_closureQ(first) {
305 let new_env = Environment(outer: fn.env)
306 let _ = try new_env.set_bindings(fn.args, with_exprs: rest)
307 if TCO {
308 env = new_env
309 ast = fn.body
310 continue
311 }
312 let answer = try EVAL(fn.body, new_env)
313 if DEBUG_EVAL { print("\(indent)>>> \(answer)") }
314 return answer
315 }
316
317 // The first element wasn't a function to be executed. Return an
318 // error saying so.
319
320 try throw_error("first list item does not evaluate to a function: \(first)")
321 }
322 }
323
324 // Convert the value into a human-readable string for printing.
325 //
326 private func PRINT(exp: MalVal) -> String {
327 return pr_str(exp, true)
328 }
329
330 // Perform the READ and EVAL steps. Useful for when you don't care about the
331 // printable result.
332 //
333 private func RE(text: String, _ env: Environment) -> MalVal? {
334 if !text.isEmpty {
335 do {
336 let ast = try READ(text)
337 do {
338 return try EVAL(ast, env)
339 } catch let error as MalException {
340 print("Error evaluating input: \(error)")
341 } catch {
342 print("Error evaluating input: \(error)")
343 }
344 } catch let error as MalException {
345 print("Error parsing input: \(error)")
346 } catch {
347 print("Error parsing input: \(error)")
348 }
349 }
350 return nil
351 }
352
353 // Perform the full READ/EVAL/PRINT, returning a printable string.
354 //
355 private func REP(text: String, _ env: Environment) -> String? {
356 let exp = RE(text, env)
357 if exp == nil { return nil }
358 return PRINT(exp!)
359 }
360
361 // Perform the full REPL.
362 //
363 private func REPL(env: Environment) {
364 while true {
365 if let text = _readline("user> ") {
366 if let output = REP(text, env) {
367 print("\(output)")
368 }
369 } else {
370 print("")
371 break
372 }
373 }
374 }
375
376 // Process any command line arguments. Any trailing arguments are incorporated
377 // into the environment. Any argument immediately after the process name is
378 // taken as a script to execute. If one exists, it is executed in lieu of
379 // running the REPL.
380 //
381 private func process_command_line(args: [String], _ env: Environment) -> Bool {
382 var argv = make_list()
383 if args.count > 2 {
384 let args1 = args[2..<args.count]
385 let args2 = args1.map { make_string($0) }
386 let args3 = [MalVal](args2)
387 argv = make_list(args3)
388 }
389 env.set(kSymbolArgv, argv)
390
391 if args.count > 1 {
392 RE("(load-file \"\(args[1])\")", env)
393 return false
394 }
395
396 return true
397 }
398
399 func main() {
400 let env = Environment(outer: nil)
401
402 load_history_file()
403 load_builtins(env)
404
405 RE("(def! not (fn* (a) (if a false true)))", env)
406 RE("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", env)
407
408 env.set(kSymbolEval, make_builtin({
409 try! unwrap_args($0) {
410 (ast: MalVal) -> MalVal in
411 try EVAL(ast, env)
412 }
413 }))
414
415 if process_command_line(Process.arguments, env) {
416 REPL(env)
417 }
418
419 save_history_file()
420 }