Merged master into ada branch + fix Makefile
[jackhill/mal.git] / swift / step1_read_print.swift
1 //******************************************************************************
2 // MAL - step 1 - read/print
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
10 import Foundation
11
12 // Parse the string into an AST.
13 //
14 private func READ(str: String) throws -> MalVal {
15 return try read_str(str)
16 }
17
18 // Walk the AST and completely evaluate it, handling macro expansions, special
19 // forms and function calls.
20 //
21 private func EVAL(ast: MalVal) -> MalVal {
22 return ast
23 }
24
25 // Convert the value into a human-readable string for printing.
26 //
27 private func PRINT(exp: MalVal) -> String {
28 return pr_str(exp, true)
29 }
30
31 // Perform the READ and EVAL steps. Useful for when you don't care about the
32 // printable result.
33 //
34 private func RE(text: String) -> MalVal? {
35 if !text.isEmpty {
36 do {
37 let ast = try READ(text)
38 return EVAL(ast)
39 } catch let error as MalException {
40 print("Error parsing input: \(error)")
41 } catch {
42 print("Error parsing input: \(error)")
43 }
44 }
45 return nil
46 }
47
48 // Perform the full READ/EVAL/PRINT, returning a printable string.
49 //
50 private func REP(text: String) -> String? {
51 let exp = RE(text)
52 if exp == nil { return nil }
53 return PRINT(exp!)
54 }
55
56 // Perform the full REPL.
57 //
58 private func REPL() {
59 while true {
60 if let text = _readline("user> ") {
61 if let output = REP(text) {
62 print("\(output)")
63 }
64 } else {
65 print("")
66 break
67 }
68 }
69 }
70
71 func main() {
72 load_history_file()
73 REPL()
74 save_history_file()
75 }