Merge pull request #377 from asarhaddon/fix-runtests-pre-eval
[jackhill/mal.git] / crystal / printer.cr
1 require "./types"
2
3 def pr_str(value, print_readably = true)
4 case value
5 when Nil then "nil"
6 when Bool then value.to_s
7 when Int64 then value.to_s
8 when Mal::List then "(#{value.map { |v| pr_str(v, print_readably).as(String) }.join(" ")})"
9 when Mal::Vector then "[#{value.map { |v| pr_str(v, print_readably).as(String) }.join(" ")}]"
10 when Mal::Symbol then value.str.to_s
11 when Mal::Func then "<function>"
12 when Mal::Closure then "<closure>"
13 when Mal::HashMap
14 # step1_read_print.cr requires specifying type
15 "{#{value.map { |k, v| "#{pr_str(k, print_readably)} #{pr_str(v, print_readably)}".as(String) }.join(" ")}}"
16 when String
17 case
18 when value.empty?
19 print_readably ? value.inspect : value
20 when value[0] == '\u029e'
21 ":#{value[1..-1]}"
22 else
23 print_readably ? value.inspect : value
24 end
25 when Mal::Atom
26 "(atom #{pr_str(value.val, print_readably)})"
27 else
28 raise "invalid MalType: #{value.to_s}"
29 end
30 end
31
32 def pr_str(t : Mal::Type, print_readably = true)
33 pr_str(t.unwrap, print_readably) + (t.macro? ? " (macro)" : "")
34 end