Commit | Line | Data |
---|---|---|
2539e6af KR |
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 | func READ(str: String) -> MalVal { | |
15 | return read_str(str) | |
16 | } | |
17 | ||
18 | // Walk the AST and completely evaluate it, handling macro expansions, special | |
19 | // forms and function calls. | |
20 | // | |
21 | func EVAL(ast: MalVal) -> MalVal { | |
22 | if is_error(ast) { return ast } | |
23 | return ast | |
24 | } | |
25 | ||
26 | // Convert the value into a human-readable string for printing. | |
27 | // | |
28 | func PRINT(exp: MalVal) -> String? { | |
29 | if is_error(exp) { return nil } | |
30 | return pr_str(exp, true) | |
31 | } | |
32 | ||
33 | // Perform the READ and EVAL steps. Useful for when you don't care about the | |
34 | // printable result. | |
35 | // | |
36 | func RE(text: String) -> MalVal? { | |
37 | if text.isEmpty { return nil } | |
38 | let ast = READ(text) | |
39 | if is_error(ast) { | |
40 | println("Error parsing input: \(ast)") | |
41 | return nil | |
42 | } | |
43 | let exp = EVAL(ast) | |
44 | if is_error(exp) { | |
45 | println("Error evaluating input: \(exp)") | |
46 | return nil | |
47 | } | |
48 | return exp | |
49 | } | |
50 | ||
51 | // Perform the full READ/EVAL/PRINT, returning a printable string. | |
52 | // | |
53 | func REP(text: String) -> String? { | |
54 | let exp = RE(text) | |
55 | if exp == nil { return nil } | |
56 | return PRINT(exp!) | |
57 | } | |
58 | ||
59 | // Perform the full REPL. | |
60 | // | |
61 | func REPL() { | |
62 | while true { | |
63 | if let text = _readline("user> ") { | |
64 | if let output = REP(text) { | |
65 | println("\(output)") | |
66 | } | |
67 | } else { | |
68 | println() | |
69 | break | |
70 | } | |
71 | } | |
72 | } | |
73 | ||
74 | func main() { | |
75 | load_history_file() | |
76 | REPL() | |
77 | save_history_file() | |
78 | } |