All: don't ignore */mal. Fixes #99
[jackhill/mal.git] / rpython / printer.py
1 import sys
2 IS_RPYTHON = sys.argv[0].endswith('rpython')
3
4 if IS_RPYTHON:
5 from rpython.rlib.rsre import rsre_re as re
6 else:
7 import re
8
9 import mal_types as types
10 from mal_types import (MalType, MalStr, MalSym, MalInt,
11 nil, true, false, MalAtom, MalFunc)
12
13 def _pr_a_str(s, print_readably=True):
14 if len(s) > 0 and s[0] == u'\u029e':
15 return u':' + s[1:]
16 elif print_readably:
17 return u'"' + types._replace(u'\\n', u'\\n',
18 types._replace(u'\"', u'\\"',
19 types._replace(u'\\', u'\\\\', s))) + u'"'
20 else:
21 return s
22
23 def _pr_str(obj, print_readably=True):
24 assert isinstance(obj, MalType)
25 _r = print_readably
26 if types._list_Q(obj):
27 res = []
28 for e in obj.values:
29 res.append(_pr_str(e,_r))
30 return u"(" + u" ".join(res) + u")"
31 elif types._vector_Q(obj):
32 res = []
33 for e in obj.values:
34 res.append(_pr_str(e,_r))
35 return u"[" + u" ".join(res) + u"]"
36 elif types._hash_map_Q(obj):
37 ret = []
38 for k in obj.dct.keys():
39 ret.append(_pr_a_str(k,_r))
40 ret.append(_pr_str(obj.dct[k],_r))
41 return u"{" + u" ".join(ret) + u"}"
42 elif isinstance(obj, MalStr):
43 return _pr_a_str(obj.value,_r)
44 elif obj is nil:
45 return u"nil"
46 elif obj is true:
47 return u"true"
48 elif obj is false:
49 return u"false"
50 elif types._atom_Q(obj):
51 return u"(atom " + _pr_str(obj.get_value(),_r) + u")"
52 elif isinstance(obj, MalSym):
53 return obj.value
54 elif isinstance(obj, MalInt):
55 return unicode(str(obj.value))
56 elif isinstance(obj, MalFunc):
57 return u"#<function>"
58 else:
59 return u"unknown"
60