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 // Symbols used in this module.
14 private let kValDef = make_symbol("def!")
15 private let kValLet = make_symbol("let*")
16 private let kValTry = make_symbol("try*")
18 private let kSymbolDef = as_symbol(kValDef)
19 private let kSymbolLet = as_symbol(kValLet)
21 // Parse the string into an AST.
23 private func READ(str: String) throws -> MalVal {
24 return try read_str(str)
27 // Perform a simple evaluation of the `ast` object. If it's a symbol,
28 // dereference it and return its value. If it's a collection, call EVAL on all
29 // elements (or just the values, in the case of the hashmap). Otherwise, return
30 // the object unchanged.
32 private func eval_ast(ast: MalVal, _ env: Environment) throws -> MalVal {
33 if let symbol = as_symbolQ(ast) {
34 guard let val = env.get(symbol) else {
35 try throw_error("'\(symbol)' not found") // Specific text needed to match MAL unit tests
39 if let list = as_listQ(ast) {
40 var result = [MalVal]()
41 result.reserveCapacity(Int(list.count))
43 let eval = try EVAL(item, env)
46 return make_list(result)
48 if let vec = as_vectorQ(ast) {
49 var result = [MalVal]()
50 result.reserveCapacity(Int(vec.count))
52 let eval = try EVAL(item, env)
55 return make_vector(result)
57 if let hash = as_hashmapQ(ast) {
58 var result = [MalVal]()
59 result.reserveCapacity(Int(hash.count) * 2)
61 let new_v = try EVAL(v, env)
65 return make_hashmap(result)
72 private func eval_def(list: MalSequence, _ env: Environment) throws -> MalVal {
73 guard list.count == 3 else {
74 try throw_error("expected 2 arguments to def!, got \(list.count - 1)")
76 let arg1 = try! list.nth(1)
77 let arg2 = try! list.nth(2)
78 guard let sym = as_symbolQ(arg1) else {
79 try throw_error("expected symbol for first argument to def!")
81 let value = try EVAL(arg2, env)
82 return env.set(sym, value)
87 private func eval_let(list: MalSequence, _ env: Environment) throws -> MalVal {
88 guard list.count == 3 else {
89 try throw_error("expected 2 arguments to let*, got \(list.count - 1)")
91 let arg1 = try! list.nth(1)
92 let arg2 = try! list.nth(2)
93 guard let bindings = as_sequenceQ(arg1) else {
94 try throw_error("expected list for first argument to let*")
96 guard bindings.count % 2 == 0 else {
97 try throw_error("expected even number of elements in bindings to let*, got \(bindings.count)")
99 let new_env = Environment(outer: env)
100 for var index: MalIntType = 0; index < bindings.count; index += 2 {
101 let binding_name = try! bindings.nth(index)
102 let binding_value = try! bindings.nth(index + 1)
103 guard let binding_symbol = as_symbolQ(binding_name) else {
104 try throw_error("expected symbol for first element in binding pair")
106 let evaluated_value = try EVAL(binding_value, new_env)
107 new_env.set(binding_symbol, evaluated_value)
109 return try EVAL(arg2, new_env)
112 // Walk the AST and completely evaluate it, handling macro expansions, special
113 // forms and function calls.
115 private func EVAL(ast: MalVal, _ env: Environment) throws -> MalVal {
119 // Not a list -- just evaluate and return.
121 let answer = try eval_ast(ast, env)
125 // Special handling if it's a list.
127 let list = as_list(ast)
133 // Check for special forms, where we want to check the operation
134 // before evaluating all of the parameters.
136 let arg0 = list.first()
137 if let fn_symbol = as_symbolQ(arg0) {
140 case kSymbolDef: return try eval_def(list, env)
141 case kSymbolLet: return try eval_let(list, env)
146 // Standard list to be applied. Evaluate all the elements first.
148 let eval = try eval_ast(ast, env)
150 // The result had better be a list and better be non-empty.
152 let eval_list = as_list(eval)
153 if eval_list.isEmpty {
157 // Get the first element of the list and execute it.
159 let first = eval_list.first()
160 let rest = as_sequence(eval_list.rest())
162 if let fn = as_builtinQ(first) {
163 let answer = try fn.apply(rest)
167 // The first element wasn't a function to be executed. Return an
170 try throw_error("first list item does not evaluate to a function: \(first)")
173 // Convert the value into a human-readable string for printing.
175 private func PRINT(exp: MalVal) -> String {
176 return pr_str(exp, true)
179 // Perform the READ and EVAL steps. Useful for when you don't care about the
182 private func RE(text: String, _ env: Environment) -> MalVal? {
185 let ast = try READ(text)
187 return try EVAL(ast, env)
188 } catch let error as MalException {
189 print("Error evaluating input: \(error)")
191 print("Error evaluating input: \(error)")
193 } catch let error as MalException {
194 print("Error parsing input: \(error)")
196 print("Error parsing input: \(error)")
202 // Perform the full READ/EVAL/PRINT, returning a printable string.
204 private func REP(text: String, _ env: Environment) -> String? {
205 let exp = RE(text, env)
206 if exp == nil { return nil }
210 // Perform the full REPL.
212 private func REPL(env: Environment) {
214 if let text = _readline("user> ") {
215 if let output = REP(text, env) {
226 let env = Environment(outer: nil)