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.
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 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).
29 // Control whether or not we emit debugging statements in EVAL.
31 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 let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|" +
44 "----|----|----|----|----|----|----|----|----|----|----|" +
45 "----|----|----|----|----|----|----|----|----|----|----|" +
46 "----|----|----|----|----|----|----|----|----|----|----|"
48 // Holds the prefix of INDENT_TEMPLATE used for actual logging.
52 // Symbols used in this module.
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*")
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.
75 // Parse the string into an AST.
77 func READ(str: String) -> MalVal {
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 func eval_ast(ast: MalVal, env: Environment) -> MalVal {
88 let symbol = ast as MalSymbol
89 if let val = env.get(symbol) {
92 return MalError(message: "'\(symbol)' not found") // Specific text needed to match MAL unit tests
95 let list = ast as MalList
96 var result = [MalVal]()
97 result.reserveCapacity(list.count)
99 let eval = EVAL(item, env)
100 if is_error(eval) { return eval }
103 return MalList(array: result)
106 let vec = ast as MalVector
107 var result = [MalVal]()
108 result.reserveCapacity(vec.count)
110 let eval = EVAL(item, env)
111 if is_error(eval) { return eval }
114 return MalVector(array: result)
117 let hash = ast as MalHashMap
118 var result = [MalVal]()
119 result.reserveCapacity(hash.count * 2)
121 let new_v = EVAL(v, env)
122 if is_error(new_v) { return new_v }
126 return MalHashMap(array: result)
134 case Continue(MalVal, Environment)
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)) }
144 func eval_def(list: MalSequence, env: Environment) -> TCOVal {
146 return TCOVal("expected 2 arguments to def!, got \(list.count - 1)")
150 if !is_symbol(arg1) {
151 return TCOVal("expected symbol for first argument to def!")
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))
161 func eval_let(list: MalSequence, env: Environment) -> TCOVal {
163 return TCOVal("expected 2 arguments to let*, got \(list.count - 1)")
167 if !is_sequence(arg1) {
168 return TCOVal("expected list for first argument to let*")
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)")
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]
179 if !is_symbol(binding_name) {
180 return TCOVal("expected symbol for first element in binding pair")
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)
188 return TCOVal(arg2, new_env)
190 return TCOVal(EVAL(arg2, new_env))
195 func eval_do(list: MalSequence, env: Environment) -> TCOVal {
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)
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())
210 func eval_if(list: MalSequence, env: Environment) -> TCOVal {
212 return TCOVal("expected at least 2 arguments to if, got \(list.count - 1)")
214 let cond_result = EVAL(list[1], env)
215 var new_ast = MalVal()
216 if is_truthy(cond_result) {
218 } else if list.count == 4 {
221 return TCOVal(MalNil())
224 return TCOVal(new_ast, env)
226 return TCOVal(EVAL(new_ast, env))
231 func eval_fn(list: MalSequence, env: Environment) -> TCOVal {
233 return TCOVal("expected 2 arguments to fn*, got \(list.count - 1)")
235 if !is_sequence(list[1]) {
236 return TCOVal("expected list or vector for first argument to fn*")
238 return TCOVal(MalClosure(eval: EVAL, args:list[1] as MalSequence, body:list[2], env:env))
241 // Walk the AST and completely evaluate it, handling macro expansions, special
242 // forms and function calls.
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))")
251 indent = prefix(INDENT_TEMPLATE, EVAL_level)
255 if is_error(ast) { return ast }
256 if DEBUG_EVAL { println("\(indent)> \(ast)") }
260 // Not a list -- just evaluate and return.
262 let answer = eval_ast(ast, env)
263 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
267 // Special handling if it's a list.
269 var list = ast as MalList
270 if DEBUG_EVAL { println("\(indent)>. \(list)") }
276 // Check for special forms, where we want to check the operation
277 // before evaluating all of the parameters.
279 let arg0 = list.first()
282 let fn_symbol = arg0 as MalSymbol
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()
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
299 // Standard list to be applied. Evaluate all the elements first.
301 let eval = eval_ast(ast, env)
302 if is_error(eval) { return eval }
304 // The result had better be a list and better be non-empty.
306 let eval_list = eval as MalList
307 if eval_list.isEmpty {
311 if DEBUG_EVAL { println("\(indent)>> \(eval)") }
313 // Get the first element of the list and execute it.
315 let first = eval_list.first()
316 let rest = eval_list.rest()
318 if is_builtin(first) {
319 let fn = first as MalBuiltin
320 let answer = fn.apply(rest)
321 if DEBUG_EVAL { println("\(indent)>>> \(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 }
333 let answer = EVAL(fn.body, new_env)
334 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
338 // The first element wasn't a function to be executed. Return an
341 return MalError(message: "first list item does not evaluate to a function: \(first)")
345 // Convert the value into a human-readable string for printing.
347 func PRINT(exp: MalVal) -> String? {
348 if is_error(exp) { return nil }
349 return pr_str(exp, true)
352 // Perform the READ and EVAL steps. Useful for when you don't care about the
355 func RE(text: String, env: Environment) -> MalVal? {
356 if text.isEmpty { return nil }
359 println("Error parsing input: \(ast)")
362 let exp = EVAL(ast, env)
364 println("Error evaluating input: \(exp)")
370 // Perform the full READ/EVAL/PRINT, returning a printable string.
372 func REP(text: String, env: Environment) -> String? {
373 let exp = RE(text, env)
374 if exp == nil { return nil }
378 // Perform the full REPL.
380 func REPL(env: Environment) {
382 if let text = _readline("user> ") {
383 if let output = REP(text, env) {
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
398 func process_command_line(args:[String], env:Environment) -> Bool {
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)
406 env.set(kSymbolArgv, argv)
409 RE("(load-file \"\(args[1])\")", env)
417 var env = Environment(outer: nil)
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)
425 env.set(kSymbolEval, MalBuiltin(function: {
427 (ast:MalVal) -> MalVal in
432 if process_command_line(Process.arguments, env) {