1 //******************************************************************************
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 //******************************************************************************
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.
15 private var EVAL_level = 0
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
21 private let EVAL_leval_max = 500
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).
27 private let TCO = true
29 // Control whether or not we emit debugging statements in EVAL.
31 private let DEBUG_EVAL = false
33 // String used to prefix information logged in EVAL. Increasing lengths of the
34 // string are used the more EVAL is recursed.
36 private let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|" +
44 "----|----|----|----|----|----|----|----|----|----|----|" +
45 "----|----|----|----|----|----|----|----|----|----|----|" +
46 "----|----|----|----|----|----|----|----|----|----|----|"
48 // Holds the prefix of INDENT_TEMPLATE used for actual logging.
50 private var indent = String()
52 // Symbols used in this module.
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*")
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)
71 func substring(s: String, _ begin: Int, _ end: Int) -> String {
72 return s[s.startIndex.advancedBy(begin) ..< s.startIndex.advancedBy(end)]
75 // Parse the string into an AST.
77 private func READ(str: String) throws -> MalVal {
78 return try read_str(str)
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.
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
93 if let list = as_listQ(ast) {
94 var result = [MalVal]()
95 result.reserveCapacity(Int(list.count))
97 let eval = try EVAL(item, env)
100 return make_list(result)
102 if let vec = as_vectorQ(ast) {
103 var result = [MalVal]()
104 result.reserveCapacity(Int(vec.count))
106 let eval = try EVAL(item, env)
109 return make_vector(result)
111 if let hash = as_hashmapQ(ast) {
112 var result = [MalVal]()
113 result.reserveCapacity(Int(hash.count) * 2)
115 let new_v = try EVAL(v, env)
119 return make_hashmap(result)
124 private enum TCOVal {
127 case Continue(MalVal, Environment)
129 init() { self = .NoResult }
130 init(_ result: MalVal) { self = .Return(result) }
131 init(_ ast: MalVal, _ env: Environment) { self = .Continue(ast, env) }
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)")
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!")
145 let value = try EVAL(arg2, env)
146 return TCOVal(env.set(sym, value))
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)")
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*")
160 guard bindings.count % 2 == 0 else {
161 try throw_error("expected even number of elements in bindings to let*, got \(bindings.count)")
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")
170 let evaluated_value = try EVAL(binding_value, new_env)
171 new_env.set(binding_symbol, evaluated_value)
174 return TCOVal(arg2, new_env)
176 return TCOVal(try EVAL(arg2, new_env))
181 private func eval_do(list: MalSequence, _ env: Environment) throws -> TCOVal {
183 let _ = try eval_ast(list.range_from(1, to: list.count-1), env)
184 return TCOVal(list.last(), env)
187 let evaluated_ast = try eval_ast(list.rest(), env)
188 let evaluated_seq = as_sequence(evaluated_ast)
189 return TCOVal(evaluated_seq.last())
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)")
198 let cond_result = try EVAL(try! list.nth(1), env)
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)
205 return TCOVal(make_nil())
208 return TCOVal(new_ast, env)
210 return TCOVal(try EVAL(new_ast, env))
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)")
219 guard let seq = as_sequenceQ(try! list.nth(1)) else {
220 try throw_error("expected list or vector for first argument to fn*")
222 return TCOVal(make_closure((eval: EVAL, args: seq, body: try! list.nth(2), env: env)))
225 // Walk the AST and completely evaluate it, handling macro expansions, special
226 // forms and function calls.
228 private func EVAL(var ast: MalVal, var _ env: Environment) throws -> MalVal {
230 defer { EVAL_level-- }
231 guard EVAL_level <= EVAL_leval_max else {
232 try throw_error("Recursing too many levels (> \(EVAL_leval_max))")
236 indent = substring(INDENT_TEMPLATE, 0, EVAL_level)
240 if DEBUG_EVAL { print("\(indent)> \(ast)") }
244 // Not a list -- just evaluate and return.
246 let answer = try eval_ast(ast, env)
247 if DEBUG_EVAL { print("\(indent)>>> \(answer)") }
251 // Special handling if it's a list.
253 let list = as_list(ast)
254 if DEBUG_EVAL { print("\(indent)>. \(list)") }
260 // Check for special forms, where we want to check the operation
261 // before evaluating all of the parameters.
263 let arg0 = list.first()
264 if let fn_symbol = as_symbolQ(arg0) {
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()
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
282 // Standard list to be applied. Evaluate all the elements first.
284 let eval = try eval_ast(ast, env)
286 // The result had better be a list and better be non-empty.
288 let eval_list = as_list(eval)
289 if eval_list.isEmpty {
293 if DEBUG_EVAL { print("\(indent)>> \(eval)") }
295 // Get the first element of the list and execute it.
297 let first = eval_list.first()
298 let rest = as_sequence(eval_list.rest())
300 if let fn = as_builtinQ(first) {
301 let answer = try fn.apply(rest)
302 if DEBUG_EVAL { print("\(indent)>>> \(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)
312 let answer = try EVAL(fn.body, new_env)
313 if DEBUG_EVAL { print("\(indent)>>> \(answer)") }
317 // The first element wasn't a function to be executed. Return an
320 try throw_error("first list item does not evaluate to a function: \(first)")
324 // Convert the value into a human-readable string for printing.
326 private func PRINT(exp: MalVal) -> String {
327 return pr_str(exp, true)
330 // Perform the READ and EVAL steps. Useful for when you don't care about the
333 private func RE(text: String, _ env: Environment) -> MalVal? {
336 let ast = try READ(text)
338 return try EVAL(ast, env)
339 } catch let error as MalException {
340 print("Error evaluating input: \(error)")
342 print("Error evaluating input: \(error)")
344 } catch let error as MalException {
345 print("Error parsing input: \(error)")
347 print("Error parsing input: \(error)")
353 // Perform the full READ/EVAL/PRINT, returning a printable string.
355 private func REP(text: String, _ env: Environment) -> String? {
356 let exp = RE(text, env)
357 if exp == nil { return nil }
361 // Perform the full REPL.
363 private func REPL(env: Environment) {
365 if let text = _readline("user> ") {
366 if let output = REP(text, env) {
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
381 private func process_command_line(args: [String], _ env: Environment) -> Bool {
382 var argv = make_list()
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)
389 env.set(kSymbolArgv, argv)
392 RE("(load-file \"\(args[1])\")", env)
400 let env = Environment(outer: nil)
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)
408 env.set(kSymbolEval, make_builtin({
409 try! unwrap_args($0) {
410 (ast: MalVal) -> MalVal in
415 if process_command_line(Process.arguments, env) {