forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.fnl
92 lines (85 loc) · 2.26 KB
/
printer.fnl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
(local t (require :types))
(fn escape
[a-str]
(pick-values 1
(-> a-str
(string.gsub "\\" "\\\\")
(string.gsub "\"" "\\\"")
(string.gsub "\n" "\\n"))))
(fn code*
[ast buf print_readably]
(let [value (t.get-value ast)]
(if (t.nil?* ast)
(table.insert buf value)
;;
(t.boolean?* ast)
(table.insert buf (if value "true" "false"))
;;
(t.number?* ast)
(table.insert buf (tostring value))
;;
(t.keyword?* ast)
(table.insert buf value)
;;
(t.symbol?* ast)
(table.insert buf value)
;;
(t.string?* ast)
(if print_readably
(do
(table.insert buf "\"")
(table.insert buf (escape value))
(table.insert buf "\""))
(table.insert buf value))
;;
(t.list?* ast)
(do
(table.insert buf "(")
(var remove false)
(each [idx elt (ipairs value)]
(code* elt buf print_readably)
(table.insert buf " ")
(set remove true))
(when remove
(table.remove buf))
(table.insert buf ")"))
;;
(t.vector?* ast)
(do
(table.insert buf "[")
(var remove false)
(each [idx elt (ipairs value)]
(code* elt buf print_readably)
(table.insert buf " ")
(set remove true))
(when remove
(table.remove buf))
(table.insert buf "]"))
;;
(t.hash-map?* ast)
(do
(table.insert buf "{")
(var remove false)
(each [idx elt (ipairs value)]
(code* elt buf print_readably)
(table.insert buf " ")
(set remove true))
(when remove
(table.remove buf))
(table.insert buf "}"))
;;
(t.atom?* ast)
(do
(table.insert buf "(atom ")
(code* (t.get-value ast) buf print_readably)
(table.insert buf ")")))
buf))
(fn pr_str
[ast print_readably]
(let [buf []]
(code* ast buf print_readably)
(table.concat buf)))
(comment
(pr_str (t.make-number 1) false)
)
{:pr_str pr_str}