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 let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
34 "----|----|----|----|----|----|----|----|----|----|----|" +
35 "----|----|----|----|----|----|----|----|----|----|----|" +
36 "----|----|----|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|"
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*")
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.
66 // Parse the string into an AST.
68 func READ(str: String) -> MalVal {
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.
77 func eval_ast(ast: MalVal, env: Environment) -> MalVal {
79 let symbol = ast as MalSymbol
80 if let val = env.get(symbol) {
83 return MalError(message: "'\(symbol)' not found") // Specific text needed to match MAL unit tests
86 let list = ast as MalList
87 var result = [MalVal]()
88 result.reserveCapacity(list.count)
90 let eval = EVAL(item, env)
91 if is_error(eval) { return eval }
94 return MalList(array: result)
97 let vec = ast as MalVector
98 var result = [MalVal]()
99 result.reserveCapacity(vec.count)
101 let eval = EVAL(item, env)
102 if is_error(eval) { return eval }
105 return MalVector(array: result)
108 let hash = ast as MalHashMap
109 var result = [MalVal]()
110 result.reserveCapacity(hash.count * 2)
112 let new_v = EVAL(v, env)
113 if is_error(new_v) { return new_v }
117 return MalHashMap(array: result)
122 // Walk the AST and completely evaluate it, handling macro expansions, special
123 // forms and function calls.
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))")
131 let indent = INDENT_TEMPLATE.substringToIndex(
132 advance(INDENT_TEMPLATE.startIndex, EVAL_level, INDENT_TEMPLATE.endIndex))
135 if is_error(ast) { return ast }
136 if DEBUG_EVAL { println("\(indent)> \(ast)") }
138 // Special handling if it's a list.
141 var list = ast as MalList
142 if DEBUG_EVAL { println("\(indent)>. \(list)") }
148 let arg1 = list.first()
150 let fn_symbol = arg1 as MalSymbol
152 // Check for special forms, where we want to check the operation
153 // before evaluating all of the parameters.
155 if fn_symbol == kSymbolDef {
157 return MalError(message: "expected 2 arguments to def!, got \(list.count - 1)")
161 if !is_symbol(arg1) {
162 return MalError(message: "expected symbol for first argument to def!")
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 {
170 return MalError(message: "expected 2 arguments to let*, got \(list.count - 1)")
174 if !is_sequence(arg1) {
175 return MalError(message: "expected list for first argument to let*")
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)")
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]
186 if !is_symbol(binding_name) {
187 return MalError(message: "expected symbol for first element in binding pair")
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)
199 return EVAL(arg2, new_env)
200 } else if fn_symbol == kSymbolDo {
202 let eval = eval_ast(MalList(slice: list[1..<list.count-1]), env)
203 if is_error(eval) { return eval }
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 {
214 return MalError(message: "expected at least 2 arguments to if, got \(list.count - 1)")
216 let cond_result = EVAL(list[1], env)
217 var new_ast = MalVal()
218 if is_truthy(cond_result) {
220 } else if list.count == 4 {
229 return EVAL(new_ast, env)
230 } else if fn_symbol == kSymbolFunction {
232 return MalError(message: "expected 2 arguments to fn*, got \(list.count - 1)")
234 if !is_sequence(list[1]) {
235 return MalError(message: "expected list or vector for first argument to fn*")
237 return MalClosure(eval: EVAL, args:list[1] as MalSequence, body:list[2], env:env)
241 // Standard list to be applied. Evaluate all the elements first.
243 let eval = eval_ast(ast, env)
244 if is_error(eval) { return eval }
246 // The result had better be a list and better be non-empty.
248 let eval_list = eval as MalList
249 if eval_list.isEmpty {
253 if DEBUG_EVAL { println("\(indent)>> \(eval)") }
255 // Get the first element of the list and execute it.
257 let first = eval_list.first()
258 let rest = eval_list.rest()
260 if is_builtin(first) {
261 let fn = first as MalBuiltin
262 let answer = fn.apply(rest)
263 if DEBUG_EVAL { println("\(indent)>>> \(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 }
275 let answer = EVAL(fn.body, new_env)
276 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
280 // The first element wasn't a function to be executed. Return an
283 return MalError(message: "first list item does not evaluate to a function: \(first)")
286 // Not a list -- just evaluate and return.
288 let answer = eval_ast(ast, env)
289 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
294 // Convert the value into a human-readable string for printing.
296 func PRINT(exp: MalVal) -> String? {
297 if is_error(exp) { return nil }
298 return pr_str(exp, true)
301 // Perform the READ and EVAL steps. Useful for when you don't care about the
304 func RE(text: String, env: Environment) -> MalVal? {
305 if text.isEmpty { return nil }
308 println("Error parsing input: \(ast)")
311 let exp = EVAL(ast, env)
313 println("Error evaluating input: \(exp)")
319 // Perform the full READ/EVAL/PRINT, returning a printable string.
321 func REP(text: String, env: Environment) -> String? {
322 let exp = RE(text, env)
323 if exp == nil { return nil }
327 // Perform the full REPL.
329 func REPL(env: Environment) {
331 if let text = _readline("user> ") {
332 if let output = REP(text, env) {
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
347 func process_command_line(args:[String], env:Environment) -> Bool {
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)
355 env.set(kSymbolArgv, argv)
358 RE("(load-file \"\(args[1])\")", env)
366 var env = Environment(outer: nil)
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)
374 env.set(kSymbolEval, MalBuiltin(function: {
376 (ast:MalVal) -> MalVal in
381 if process_command_line(Process.arguments, env) {