1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-21 02:27:10 +03:00
mal/nim/printer.nim

28 lines
1019 B
Nim
Raw Normal View History

2015-02-28 21:52:01 +03:00
import strutils, sequtils, tables, types
2015-02-28 16:14:18 +03:00
2015-03-01 19:39:15 +03:00
proc str_handle(x: string, pr = true): string =
if x.len > 0 and x[0] == '\xff':
result = ":" & x[1 .. x.high]
2015-10-31 06:05:49 +03:00
elif pr: result = "\"" & x.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") & "\""
2015-03-01 19:39:15 +03:00
else: result = x
2015-02-28 21:52:01 +03:00
proc pr_str*(m: MalType, pr = true): string =
2015-02-28 16:14:18 +03:00
case m.kind
of Nil: result = "nil"
2015-02-28 21:52:01 +03:00
of True: result = "true"
of False: result = "false"
of Fun: result = "#<function>"
2015-03-01 05:55:05 +03:00
of MalFun: result = "#<malfun>"
2015-03-04 16:12:19 +03:00
of Atom: result = "(atom " & m.val.pr_str & ")"
2015-03-01 06:38:43 +03:00
of Symbol: result = m.str
2015-03-01 19:39:15 +03:00
of String: result = m.str.str_handle(pr)
2015-02-28 16:14:18 +03:00
of Number: result = $m.number
2015-02-28 21:52:01 +03:00
of List: result = "(" & m.list.mapIt(string, it.pr_str(pr)).join(" ") & ")"
of Vector: result = "[" & m.list.mapIt(string, it.pr_str(pr)).join(" ") & "]"
2015-02-28 16:14:18 +03:00
of HashMap:
result = "{"
for key, val in m.hash_map.pairs:
if result.len > 1: result.add " "
2015-03-01 19:39:15 +03:00
result.add key.str_handle & " " & val.pr_str(pr)
2015-02-28 16:14:18 +03:00
result.add "}"