Fix unescaping in matlab, miniMAL and rpython.
[jackhill/mal.git] / yorick / printer.i
1 require, "types.i"
2
3 func format_seq(val, start_char, end_char, readable)
4 {
5 seq = *val
6 res = ""
7 for (i = 1; i <= numberof(seq); ++i) {
8 if (i > 1) res += " "
9 res += pr_str(*seq(i), readable)
10 }
11 return start_char + res + end_char
12 }
13
14 func format_hashmap(h, readable)
15 {
16 res = ""
17 for (i = 1; i <= numberof(*h.keys); ++i) {
18 if (i > 1) res += " "
19 key = hashmap_key_to_obj((*h.keys)(i))
20 res += pr_str(key, readable) + " " + pr_str(*((*h.vals)(i)), readable)
21 }
22 return "{" + res + "}"
23 }
24
25 func escape(s)
26 {
27 s1 = streplaceall(s, "\\", "\\\\")
28 s2 = streplaceall(s1, "\"", "\\\"")
29 s3 = streplaceall(s2, "\n", "\\n")
30 return "\"" + s3 + "\""
31 }
32
33 func pr_str(ast, readable)
34 {
35 type = structof(ast)
36 if (type == MalNil) return "nil"
37 else if (type == MalTrue) return "true"
38 else if (type == MalFalse) return "false"
39 else if (type == MalNumber) return totxt(ast.val)
40 else if (type == MalSymbol) return ast.val
41 else if (type == MalString) return readable ? escape(ast.val) : ast.val
42 else if (type == MalKeyword) return ":" + ast.val
43 else if (type == MalList) return format_seq(ast.val, "(", ")", readable)
44 else if (type == MalVector) return format_seq(ast.val, "[", "]", readable)
45 else if (type == MalHashmap) return format_hashmap(*ast.val, readable)
46 else if (type == MalAtom) return "(atom " + pr_str(*(ast.val->val), readable) + ")"
47 else if (type == MalNativeFunction) return "#<nativefunction:" + ast.val + ">"
48 else if (type == MalFunction) return "#<function:" + totxt(numberof(*ast.binds)) + " args>"
49 else MalError(message=("Unknown type " + totxt(type)))
50 }