mal.html: Fix title typo (#86).
[jackhill/mal.git] / swift / step8_macros.swift
CommitLineData
2539e6af
KR
1//******************************************************************************
2// MAL - step 8 - macros
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//******************************************************************************
9
10import Foundation
11
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.
14//
15var EVAL_level = 0
16
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
19// for safety's sake.
20//
21let EVAL_leval_max = 500
22
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).
26//
27let TCO = true
28
29// Control whether or not we emit debugging statements in EVAL.
30//
31let DEBUG_EVAL = false
32
b3ec2290
KR
33// String used to prefix information logged in EVAL. Increasing lengths of the
34// string are used the more EVAL is recursed.
35//
2539e6af
KR
36let INDENT_TEMPLATE = "|----|----|----|----|----|----|----|----|" +
37 "----|----|----|----|----|----|----|----|----|----|----|" +
38 "----|----|----|----|----|----|----|----|----|----|----|" +
39 "----|----|----|----|----|----|----|----|----|----|----|" +
40 "----|----|----|----|----|----|----|----|----|----|----|" +
41 "----|----|----|----|----|----|----|----|----|----|----|" +
42 "----|----|----|----|----|----|----|----|----|----|----|" +
43 "----|----|----|----|----|----|----|----|----|----|----|" +
44 "----|----|----|----|----|----|----|----|----|----|----|" +
45 "----|----|----|----|----|----|----|----|----|----|----|" +
46 "----|----|----|----|----|----|----|----|----|----|----|"
b3ec2290
KR
47
48// Holds the prefix of INDENT_TEMPLATE used for actual logging.
49//
2c4b8bd1 50var indent = String()
2539e6af 51
b3ec2290
KR
52// Symbols used in this module.
53//
2539e6af
KR
54let kSymbolArgv = MalSymbol(symbol: "*ARGV*")
55let kSymbolConcat = MalSymbol(symbol: "concat")
56let kSymbolCons = MalSymbol(symbol: "cons")
57let kSymbolDef = MalSymbol(symbol: "def!")
58let kSymbolDefMacro = MalSymbol(symbol: "defmacro!")
59let kSymbolDo = MalSymbol(symbol: "do")
60let kSymbolEval = MalSymbol(symbol: "eval")
b3ec2290 61let kSymbolFn = MalSymbol(symbol: "fn*")
2539e6af
KR
62let kSymbolIf = MalSymbol(symbol: "if")
63let kSymbolLet = MalSymbol(symbol: "let*")
64let kSymbolMacroExpand = MalSymbol(symbol: "macroexpand")
b3ec2290 65let kSymbolQuasiQuote = MalSymbol(symbol: "quasiquote")
2539e6af
KR
66let kSymbolQuote = MalSymbol(symbol: "quote")
67let kSymbolSpliceUnquote = MalSymbol(symbol: "splice-unquote")
68let kSymbolUnquote = MalSymbol(symbol: "unquote")
69
70// Class to help control the incrementing and decrementing of EVAL_level. We
71// create one of these on entry to EVAL, incrementing the level. When the
72// variable goes out of scope, the object is destroyed, decrementing the level.
73//
74class EVAL_Counter {
75 init() {
76 ++EVAL_level
77 }
78 deinit {
79 --EVAL_level
80 }
81}
82
83// Parse the string into an AST.
84//
85func READ(str: String) -> MalVal {
86 return read_str(str)
87}
88
89// Return whether or not `val` is a non-empty list.
90//
91func is_pair(val:MalVal) -> Bool {
92 if !is_sequence(val) { return false }
1c76df7d 93 let list = val as! MalSequence
2539e6af
KR
94 return !list.isEmpty
95}
96
97// Expand macros for as long as the expression looks like a macro invocation.
98//
99func macroexpand(var ast:MalVal, env:Environment) -> MalVal {
100 while true {
101 if !is_list(ast) { break }
1c76df7d 102 let ast_as_list = ast as! MalList
2539e6af
KR
103 if ast_as_list.isEmpty { break }
104 let first = ast_as_list.first()
105 if !is_symbol(first) { break }
1c76df7d 106 let macro_name = first as! MalSymbol
2539e6af
KR
107 let obj = env.get(macro_name)
108 if obj == nil { break }
109 if !is_closure(obj!) { break }
1c76df7d 110 let macro = obj! as! MalClosure
2539e6af
KR
111 if !macro.is_macro { break }
112 var new_env = Environment(outer: macro.env)
113 let rest = ast_as_list.rest()
114 let res = new_env.set_bindings(macro.args, with_exprs:rest)
115 if is_error(res) { return res }
116 ast = EVAL(macro.body, new_env)
117 }
118 return ast
119}
120
121// Evaluate `quasiquote`, possibly recursing in the process.
122//
123// As with quote, unquote, and splice-unquote, quasiquote takes a single
124// parameter, typically a list. In the general case, this list is processed
125// recursively as:
126//
127// (quasiquote (first rest...)) -> (cons (quasiquote first) (quasiquote rest))
128//
129// In the processing of the parameter passed to it, quasiquote handles three
130// special cases:
131//
132// * If the parameter is an atom or an empty list, the following expression
133// is formed and returned for evaluation:
134//
135// (quasiquote atom-or-empty-list) -> (quote atom-or-empty-list)
136//
137// * If the first element of the non-empty list is the symbol "unquote"
138// followed by a second item, the second item is returned as-is:
139//
140// (quasiquote (unquote fred)) -> fred
141//
142// * If the first element of the non-empty list is another list containing
143// the symbol "splice-unquote" followed by a list, that list is catenated
144// with the quasiquoted result of the remaining items in the non-empty
145// parent list:
146//
147// (quasiquote (splice-unquote list) rest...) -> (items-from-list items-from-quasiquote(rest...))
148//
149// Note the inconsistent handling between "quote" and "splice-quote". The former
150// is handled when this function is handed a list that starts with "quote",
151// whereas the latter is handled when this function is handled a list whose
152// first element is a list that starts with "splice-quote". The handling of the
153// latter is forced by the need to incorporate the results of (splice-quote
154// list) with the remaining items of the list containing that splice-quote
155// expression. However, it's not clear to me why the handling of "unquote" is
156// not handled similarly, for consistency's sake.
157
158func quasiquote(qq_arg:MalVal) -> MalVal {
159
160 // If the argument is an atom or empty list:
161 //
162 // Return: (quote <argument>)
163
164 if !is_pair(qq_arg) {
165 return MalList(objects: kSymbolQuote, qq_arg)
166 }
167
168 // The argument is a non-empty list -- that is (item rest...)
169
170 // If the first item from the list is a symbol and it's "unquote" -- that
171 // is, (unquote item ignored...):
172 //
173 // Return: item
174
1c76df7d 175 let qq_list = qq_arg as! MalSequence
2539e6af 176 if is_symbol(qq_list.first()) {
1c76df7d 177 let sym = qq_list.first() as! MalSymbol
2539e6af
KR
178 if sym == kSymbolUnquote {
179 return qq_list.count >= 2 ? qq_list[1] : MalNil()
180 }
181 }
182
183 // If the first item from the list is itself a non-empty list starting with
184 // "splice-unquote"-- that is, ((splice-unquote item ignored...) rest...):
185 //
186 // Return: (concat item quasiquote(rest...))
187
188 if is_pair(qq_list.first()) {
1c76df7d 189 let qq_list_item0 = qq_list.first() as! MalSequence
2539e6af 190 if is_symbol(qq_list_item0.first()) {
1c76df7d 191 let sym = qq_list_item0.first() as! MalSymbol
2539e6af
KR
192 if sym == kSymbolSpliceUnquote {
193 let result = quasiquote(qq_list.rest())
194 if is_error(result) { return result }
195 return MalList(array: [kSymbolConcat, qq_list_item0[1], result])
196 }
197 }
198 }
199
200 // General case: (item rest...):
201 //
202 // Return: (cons (quasiquote item) (quasiquote (rest...))
203
204 let first = quasiquote(qq_list.first())
205 if is_error(first) { return first }
206
207 let rest = quasiquote(qq_list.rest())
208 if is_error(rest) { return rest }
209
210 return MalList(objects: kSymbolCons, first, rest)
211}
212
213// Perform a simple evaluation of the `ast` object. If it's a symbol,
214// dereference it and return its value. If it's a collection, call EVAL on all
215// elements (or just the values, in the case of the hashmap). Otherwise, return
216// the object unchanged.
217//
218func eval_ast(ast: MalVal, env: Environment) -> MalVal {
3829ee8c
KR
219 switch ast.type {
220 case .TypeSymbol:
1c76df7d 221 let symbol = ast as! MalSymbol
3829ee8c
KR
222 if let val = env.get(symbol) {
223 return val
224 }
225 return MalError(message: "'\(symbol)' not found") // Specific text needed to match MAL unit tests
226 case .TypeList:
1c76df7d 227 let list = ast as! MalList
3829ee8c
KR
228 var result = [MalVal]()
229 result.reserveCapacity(list.count)
230 for item in list {
231 let eval = EVAL(item, env)
232 if is_error(eval) { return eval }
233 result.append(eval)
234 }
235 return MalList(array: result)
236 case .TypeVector:
1c76df7d 237 let vec = ast as! MalVector
3829ee8c
KR
238 var result = [MalVal]()
239 result.reserveCapacity(vec.count)
240 for item in vec {
241 let eval = EVAL(item, env)
242 if is_error(eval) { return eval }
243 result.append(eval)
244 }
245 return MalVector(array: result)
246 case .TypeHashMap:
1c76df7d 247 let hash = ast as! MalHashMap
3829ee8c
KR
248 var result = [MalVal]()
249 result.reserveCapacity(hash.count * 2)
250 for (k, v) in hash {
251 let new_v = EVAL(v, env)
252 if is_error(new_v) { return new_v }
253 result.append(k)
254 result.append(new_v)
255 }
256 return MalHashMap(array: result)
257 default:
258 return ast
2539e6af 259 }
2539e6af
KR
260}
261
b3ec2290
KR
262enum TCOVal {
263 case NoResult
264 case Return(MalVal)
265 case Continue(MalVal, Environment)
266
267 init() { self = .NoResult }
268 init(_ result: MalVal) { self = .Return(result) }
269 init(_ ast: MalVal, _ env: Environment) { self = .Continue(ast, env) }
270 init(_ e: String) { self = .Return(MalError(message: e)) }
271}
272
273// EVALuate "def!" and "defmacro!".
274//
275func eval_def(list: MalSequence, env: Environment) -> TCOVal {
276 if list.count != 3 {
277 return TCOVal("expected 2 arguments to def!, got \(list.count - 1)")
278 }
1c76df7d 279 let arg0 = list[0] as! MalSymbol
b3ec2290
KR
280 let arg1 = list[1]
281 let arg2 = list[2]
282 if !is_symbol(arg1) {
283 return TCOVal("expected symbol for first argument to def!")
284 }
1c76df7d 285 let sym = arg1 as! MalSymbol
b3ec2290
KR
286 let value = EVAL(arg2, env)
287 if is_error(value) { return TCOVal(value) }
288 if arg0 == kSymbolDefMacro {
289 if is_closure(value) {
1c76df7d 290 let as_closure = value as! MalClosure
b3ec2290
KR
291 as_closure.is_macro = true
292 } else {
293 return TCOVal("expected closure, got \(value)")
294 }
295 }
296 return TCOVal(env.set(sym, value))
297}
298
299// EVALuate "let*".
300//
301func eval_let(list: MalSequence, env: Environment) -> TCOVal {
302 if list.count != 3 {
303 return TCOVal("expected 2 arguments to let*, got \(list.count - 1)")
304 }
305 let arg1 = list[1]
306 let arg2 = list[2]
307 if !is_sequence(arg1) {
308 return TCOVal("expected list for first argument to let*")
309 }
1c76df7d 310 let bindings = arg1 as! MalSequence
b3ec2290
KR
311 if bindings.count % 2 == 1 {
312 return TCOVal("expected even number of elements in bindings to let*, got \(bindings.count)")
313 }
314 var new_env = Environment(outer: env)
315 for var index = 0; index < bindings.count; index += 2 {
316 let binding_name = bindings[index]
317 let binding_value = bindings[index + 1]
318
319 if !is_symbol(binding_name) {
320 return TCOVal("expected symbol for first element in binding pair")
321 }
1c76df7d 322 let binding_symbol = binding_name as! MalSymbol
b3ec2290
KR
323 let evaluated_value = EVAL(binding_value, new_env)
324 if is_error(evaluated_value) { return TCOVal(evaluated_value) }
325 new_env.set(binding_symbol, evaluated_value)
326 }
327 if TCO {
328 return TCOVal(arg2, new_env)
329 }
330 return TCOVal(EVAL(arg2, new_env))
331}
332
333// EVALuate "do".
334//
335func eval_do(list: MalSequence, env: Environment) -> TCOVal {
336 if TCO {
337 let eval = eval_ast(MalList(slice: list[1..<list.count-1]), env)
338 if is_error(eval) { return TCOVal(eval) }
339 return TCOVal(list.last(), env)
340 }
341
342 let evaluated_ast = eval_ast(list.rest(), env)
343 if is_error(evaluated_ast) { return TCOVal(evaluated_ast) }
1c76df7d 344 let evaluated_seq = evaluated_ast as! MalSequence
b3ec2290
KR
345 return TCOVal(evaluated_seq.last())
346}
347
348// EVALuate "if".
349//
350func eval_if(list: MalSequence, env: Environment) -> TCOVal {
351 if list.count < 3 {
352 return TCOVal("expected at least 2 arguments to if, got \(list.count - 1)")
353 }
354 let cond_result = EVAL(list[1], env)
355 var new_ast = MalVal()
356 if is_truthy(cond_result) {
357 new_ast = list[2]
358 } else if list.count == 4 {
359 new_ast = list[3]
360 } else {
361 return TCOVal(MalNil())
362 }
363 if TCO {
364 return TCOVal(new_ast, env)
365 }
366 return TCOVal(EVAL(new_ast, env))
367}
368
369// EVALuate "fn*".
370//
371func eval_fn(list: MalSequence, env: Environment) -> TCOVal {
372 if list.count != 3 {
373 return TCOVal("expected 2 arguments to fn*, got \(list.count - 1)")
374 }
375 if !is_sequence(list[1]) {
376 return TCOVal("expected list or vector for first argument to fn*")
377 }
1c76df7d 378 return TCOVal(MalClosure(eval: EVAL, args:list[1] as! MalSequence, body:list[2], env:env))
b3ec2290
KR
379}
380
381// EVALuate "quote".
382//
383func eval_quote(list: MalSequence, env: Environment) -> TCOVal {
384 if list.count >= 2 {
385 return TCOVal(list[1])
386 }
387 return TCOVal(MalNil())
388}
389
390// EVALuate "quasiquote".
391//
392func eval_quasiquote(list: MalSequence, env: Environment) -> TCOVal {
393 if list.count >= 2 {
394 if TCO {
395 return TCOVal(quasiquote(list[1]), env)
396 }
397 return TCOVal(EVAL(quasiquote(list[1]), env))
398 }
399 return TCOVal("Expected non-nil parameter to 'quasiquote'")
400}
401
402// EVALuate "macroexpand".
403//
404func eval_macroexpand(list: MalSequence, env: Environment) -> TCOVal {
405 if list.count >= 2 {
406 return TCOVal(macroexpand(list[1], env))
407 }
408 return TCOVal("Expected parameter to 'macroexpand'")
409}
410
2539e6af
KR
411// Walk the AST and completely evaluate it, handling macro expansions, special
412// forms and function calls.
413//
414func EVAL(var ast: MalVal, var env: Environment) -> MalVal {
2c4b8bd1 415 let x = EVAL_Counter()
2539e6af
KR
416 if EVAL_level > EVAL_leval_max {
417 return MalError(message: "Recursing too many levels (> \(EVAL_leval_max))")
418 }
419
2c4b8bd1
KR
420 if DEBUG_EVAL {
421 indent = prefix(INDENT_TEMPLATE, EVAL_level)
422 }
2539e6af
KR
423
424 while true {
425 if is_error(ast) { return ast }
426 if DEBUG_EVAL { println("\(indent)> \(ast)") }
427
b3ec2290 428 if !is_list(ast) {
2539e6af 429
b3ec2290 430 // Not a list -- just evaluate and return.
2539e6af 431
b3ec2290
KR
432 let answer = eval_ast(ast, env)
433 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
434 return answer
435 }
2539e6af 436
b3ec2290 437 // Special handling if it's a list.
2539e6af 438
1c76df7d 439 var list = ast as! MalList
b3ec2290
KR
440 ast = macroexpand(ast, env)
441 if !is_list(ast) { return ast }
1c76df7d 442 list = ast as! MalList
2539e6af 443
b3ec2290 444 if DEBUG_EVAL { println("\(indent)>. \(list)") }
2539e6af 445
b3ec2290
KR
446 if list.isEmpty {
447 return list
448 }
2539e6af 449
b3ec2290
KR
450 // Check for special forms, where we want to check the operation
451 // before evaluating all of the parameters.
452
453 let arg0 = list.first()
454 if is_symbol(arg0) {
455 var res: TCOVal
1c76df7d 456 let fn_symbol = arg0 as! MalSymbol
b3ec2290
KR
457
458 switch fn_symbol {
459 case kSymbolDef: res = eval_def(list, env)
460 case kSymbolDefMacro: res = eval_def(list, env)
461 case kSymbolLet: res = eval_let(list, env)
462 case kSymbolDo: res = eval_do(list, env)
463 case kSymbolIf: res = eval_if(list, env)
464 case kSymbolFn: res = eval_fn(list, env)
465 case kSymbolQuote: res = eval_quote(list, env)
466 case kSymbolQuasiQuote: res = eval_quasiquote(list, env)
467 case kSymbolMacroExpand: res = eval_macroexpand(list, env)
468 default: res = TCOVal()
2539e6af 469 }
b3ec2290
KR
470 switch res {
471 case let .Return(result): return result
472 case let .Continue(new_ast, new_env): ast = new_ast; env = new_env; continue
473 case .NoResult: break
474 }
475 }
2539e6af 476
b3ec2290 477 // Standard list to be applied. Evaluate all the elements first.
2539e6af 478
b3ec2290
KR
479 let eval = eval_ast(ast, env)
480 if is_error(eval) { return eval }
2539e6af 481
b3ec2290 482 // The result had better be a list and better be non-empty.
2539e6af 483
1c76df7d 484 let eval_list = eval as! MalList
b3ec2290
KR
485 if eval_list.isEmpty {
486 return eval_list
487 }
2539e6af 488
b3ec2290
KR
489 if DEBUG_EVAL { println("\(indent)>> \(eval)") }
490
491 // Get the first element of the list and execute it.
492
493 let first = eval_list.first()
494 let rest = eval_list.rest()
495
496 if is_builtin(first) {
1c76df7d 497 let fn = first as! MalBuiltin
b3ec2290
KR
498 let answer = fn.apply(rest)
499 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
500 return answer
501 } else if is_closure(first) {
1c76df7d 502 let fn = first as! MalClosure
b3ec2290
KR
503 var new_env = Environment(outer: fn.env)
504 let result = new_env.set_bindings(fn.args, with_exprs:rest)
505 if is_error(result) { return result }
506 if TCO {
507 env = new_env
508 ast = fn.body
509 continue
510 }
511 let answer = EVAL(fn.body, new_env)
512 if DEBUG_EVAL { println("\(indent)>>> \(answer)") }
513 return answer
2539e6af
KR
514 }
515
b3ec2290
KR
516 // The first element wasn't a function to be executed. Return an
517 // error saying so.
2539e6af 518
b3ec2290 519 return MalError(message: "first list item does not evaluate to a function: \(first)")
2539e6af
KR
520 }
521}
522
523// Convert the value into a human-readable string for printing.
524//
525func PRINT(exp: MalVal) -> String? {
526 if is_error(exp) { return nil }
527 return pr_str(exp, true)
528}
529
530// Perform the READ and EVAL steps. Useful for when you don't care about the
531// printable result.
532//
533func RE(text: String, env: Environment) -> MalVal? {
534 if text.isEmpty { return nil }
535 let ast = READ(text)
536 if is_error(ast) {
537 println("Error parsing input: \(ast)")
538 return nil
539 }
540 let exp = EVAL(ast, env)
541 if is_error(exp) {
542 println("Error evaluating input: \(exp)")
543 return nil
544 }
545 return exp
546}
547
548// Perform the full READ/EVAL/PRINT, returning a printable string.
549//
550func REP(text: String, env: Environment) -> String? {
551 let exp = RE(text, env)
552 if exp == nil { return nil }
553 return PRINT(exp!)
554}
555
556// Perform the full REPL.
557//
558func REPL(env: Environment) {
559 while true {
560 if let text = _readline("user> ") {
561 if let output = REP(text, env) {
562 println("\(output)")
563 }
564 } else {
565 println()
566 break
567 }
568 }
569}
570
571// Process any command line arguments. Any trailing arguments are incorporated
572// into the environment. Any argument immediately after the process name is
573// taken as a script to execute. If one exists, it is executed in lieu of
574// running the REPL.
575//
576func process_command_line(args:[String], env:Environment) -> Bool {
577 var argv = MalList()
578 if args.count > 2 {
579 let args1 = args[2..<args.count]
580 let args2 = args1.map { MalString(unescaped: $0) as MalVal }
581 let args3 = [MalVal](args2)
582 argv = MalList(array: args3)
583 }
584 env.set(kSymbolArgv, argv)
585
586 if args.count > 1 {
587 RE("(load-file \"\(args[1])\")", env)
588 return false
589 }
590
591 return true
592}
593
594func main() {
595 var env = Environment(outer: nil)
596
597 load_history_file()
598 load_builtins(env)
599
600 RE("(def! not (fn* (a) (if a false true)))", env)
601 RE("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", env)
602 RE("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) " +
603 "(throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", env)
604 RE("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) " +
605 "`(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", env)
606
607 env.set(kSymbolEval, MalBuiltin(function: {
608 unwrap($0) {
609 (ast:MalVal) -> MalVal in
610 EVAL(ast, env)
611 }
612 }))
613
614 if process_command_line(Process.arguments, env) {
615 REPL(env)
616 }
617
618 save_history_file()
619}