1 //******************************************************************************
2 // MAL - step 4 - if/fn/do
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 // Symbols used in this module.
14 private let kValDef = make_symbol("def!")
15 private let kValDo = make_symbol("do")
16 private let kValFn = make_symbol("fn*")
17 private let kValIf = make_symbol("if")
18 private let kValLet = make_symbol("let*")
19 private let kValTry = make_symbol("try*")
21 private let kSymbolDef = as_symbol(kValDef)
22 private let kSymbolDo = as_symbol(kValDo)
23 private let kSymbolFn = as_symbol(kValFn)
24 private let kSymbolIf = as_symbol(kValIf)
25 private let kSymbolLet = as_symbol(kValLet)
27 // Parse the string into an AST.
29 private func READ(str: String) throws -> MalVal {
30 return try read_str(str)
33 // Perform a simple evaluation of the `ast` object. If it's a symbol,
34 // dereference it and return its value. If it's a collection, call EVAL on all
35 // elements (or just the values, in the case of the hashmap). Otherwise, return
36 // the object unchanged.
38 private func eval_ast(ast: MalVal, _ env: Environment) throws -> MalVal {
39 if let symbol = as_symbolQ(ast) {
40 guard let val = env.get(symbol) else {
41 try throw_error("'\(symbol)' not found") // Specific text needed to match MAL unit tests
45 if let list = as_listQ(ast) {
46 var result = [MalVal]()
47 result.reserveCapacity(Int(list.count))
49 let eval = try EVAL(item, env)
52 return make_list(result)
54 if let vec = as_vectorQ(ast) {
55 var result = [MalVal]()
56 result.reserveCapacity(Int(vec.count))
58 let eval = try EVAL(item, env)
61 return make_vector(result)
63 if let hash = as_hashmapQ(ast) {
64 var result = [MalVal]()
65 result.reserveCapacity(Int(hash.count) * 2)
67 let new_v = try EVAL(v, env)
71 return make_hashmap(result)
78 private func eval_def(list: MalSequence, _ env: Environment) throws -> MalVal {
79 guard list.count == 3 else {
80 try throw_error("expected 2 arguments to def!, got \(list.count - 1)")
82 let arg1 = try! list.nth(1)
83 let arg2 = try! list.nth(2)
84 guard let sym = as_symbolQ(arg1) else {
85 try throw_error("expected symbol for first argument to def!")
87 let value = try EVAL(arg2, env)
88 return env.set(sym, value)
93 private func eval_let(list: MalSequence, _ env: Environment) throws -> MalVal {
94 guard list.count == 3 else {
95 try throw_error("expected 2 arguments to let*, got \(list.count - 1)")
97 let arg1 = try! list.nth(1)
98 let arg2 = try! list.nth(2)
99 guard let bindings = as_sequenceQ(arg1) else {
100 try throw_error("expected list for first argument to let*")
102 guard bindings.count % 2 == 0 else {
103 try throw_error("expected even number of elements in bindings to let*, got \(bindings.count)")
105 let new_env = Environment(outer: env)
106 for var index: MalIntType = 0; index < bindings.count; index += 2 {
107 let binding_name = try! bindings.nth(index)
108 let binding_value = try! bindings.nth(index + 1)
109 guard let binding_symbol = as_symbolQ(binding_name) else {
110 try throw_error("expected symbol for first element in binding pair")
112 let evaluated_value = try EVAL(binding_value, new_env)
113 new_env.set(binding_symbol, evaluated_value)
115 return try EVAL(arg2, new_env)
120 private func eval_do(list: MalSequence, _ env: Environment) throws -> MalVal {
121 let evaluated_ast = try eval_ast(list.rest(), env)
122 let evaluated_seq = as_sequence(evaluated_ast)
123 return evaluated_seq.last()
128 private func eval_if(list: MalSequence, _ env: Environment) throws -> MalVal {
129 guard list.count >= 3 else {
130 try throw_error("expected at least 2 arguments to if, got \(list.count - 1)")
132 let cond_result = try EVAL(try! list.nth(1), env)
134 if is_truthy(cond_result) {
135 new_ast = try! list.nth(2)
136 } else if list.count == 4 {
137 new_ast = try! list.nth(3)
141 return try EVAL(new_ast, env)
146 private func eval_fn(list: MalSequence, _ env: Environment) throws -> MalVal {
147 guard list.count == 3 else {
148 try throw_error("expected 2 arguments to fn*, got \(list.count - 1)")
150 guard let seq = as_sequenceQ(try! list.nth(1)) else {
151 try throw_error("expected list or vector for first argument to fn*")
153 return make_closure((eval: EVAL, args: seq, body: try! list.nth(2), env: env))
156 // Walk the AST and completely evaluate it, handling macro expansions, special
157 // forms and function calls.
159 private func EVAL(ast: MalVal, _ env: Environment) throws -> MalVal {
163 // Not a list -- just evaluate and return.
165 let answer = try eval_ast(ast, env)
169 // Special handling if it's a list.
171 let list = as_list(ast)
177 // Check for special forms, where we want to check the operation
178 // before evaluating all of the parameters.
180 let arg0 = list.first()
181 if let fn_symbol = as_symbolQ(arg0) {
184 case kSymbolDef: return try eval_def(list, env)
185 case kSymbolLet: return try eval_let(list, env)
186 case kSymbolDo: return try eval_do(list, env)
187 case kSymbolIf: return try eval_if(list, env)
188 case kSymbolFn: return try eval_fn(list, env)
193 // Standard list to be applied. Evaluate all the elements first.
195 let eval = try eval_ast(ast, env)
197 // The result had better be a list and better be non-empty.
199 let eval_list = as_list(eval)
200 if eval_list.isEmpty {
204 // Get the first element of the list and execute it.
206 let first = eval_list.first()
207 let rest = as_sequence(eval_list.rest())
209 if let fn = as_builtinQ(first) {
210 let answer = try fn.apply(rest)
212 } else if let fn = as_closureQ(first) {
213 let new_env = Environment(outer: fn.env)
214 let _ = try new_env.set_bindings(fn.args, with_exprs: rest)
215 let answer = try EVAL(fn.body, new_env)
219 // The first element wasn't a function to be executed. Return an
222 try throw_error("first list item does not evaluate to a function: \(first)")
225 // Convert the value into a human-readable string for printing.
227 private func PRINT(exp: MalVal) -> String {
228 return pr_str(exp, true)
231 // Perform the READ and EVAL steps. Useful for when you don't care about the
234 private func RE(text: String, _ env: Environment) -> MalVal? {
237 let ast = try READ(text)
239 return try EVAL(ast, env)
240 } catch let error as MalException {
241 print("Error evaluating input: \(error)")
243 print("Error evaluating input: \(error)")
245 } catch let error as MalException {
246 print("Error parsing input: \(error)")
248 print("Error parsing input: \(error)")
254 // Perform the full READ/EVAL/PRINT, returning a printable string.
256 private func REP(text: String, _ env: Environment) -> String? {
257 let exp = RE(text, env)
258 if exp == nil { return nil }
262 // Perform the full REPL.
264 private func REPL(env: Environment) {
266 if let text = _readline("user> ") {
267 if let output = REP(text, env) {
278 let env = Environment(outer: nil)
283 RE("(def! not (fn* (a) (if a false true)))", env)