-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppl_clojure_forms.py
executable file
·293 lines (226 loc) · 8.72 KB
/
ppl_clojure_forms.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#
# This file is part of PyFOPPL, an implementation of a First Order Probabilistic Programming Language in Python.
#
# License: MIT (see LICENSE.txt)
#
# 20. Feb 2018, Tobias Kohn
# 28. Feb 2018, Tobias Kohn
#
from typing import Optional
import inspect
from ast import copy_location
class ClojureObject(object):
_attributes = {'col_offset', 'lineno'}
tag = None
def visit(self, visitor):
"""
The visitor-object given as argument must provide at least one `visit_XXX`-method to be called by this method.
If the visitor does not provide any specific `visit_XXX`-method to be called, the method will try and call
`visit_node` or `generic_visit`, respectively.
:param visitor: An object with a `visit_XXX`-method.
:return: The result returned by the `visit_XXX`-method of the visitor.
"""
name = self.__class__.__name__.lower()
method_names = ['visit_' + name + '_form', 'visit_node', 'generic_visit']
methods = [getattr(visitor, name, None) for name in method_names]
methods = [name for name in methods if name is not None]
if len(methods) == 0 and callable(visitor):
return visitor(self)
elif len(methods) > 0:
result = methods[0](self)
if hasattr(result, '_attributes'):
result = copy_location(result, self)
return result
else:
raise RuntimeError("visitor '{}' has no visit-methods to call".format(type(visitor)))
#######################################################################################################################
class Form(ClojureObject):
def __init__(self, items:list, lineno:Optional[int]=None):
self.items = items
if lineno is not None:
self.lineno = lineno
self._special_names = {
'->': 'arrow',
'->>': 'double_arrow',
'.': 'dot'
}
assert type(items) in [list, tuple]
assert all([isinstance(item, ClojureObject) for item in items])
assert lineno is None or type(lineno) is int
def __getitem__(self, item):
return self.items[item]
def __len__(self):
return len(self.items)
def __repr__(self):
return "({})".format(' '.join([repr(item) for item in self.items]))
def visit(self, visitor):
name = self.name
if name is not None:
if name in self._special_names:
name = '_sym_' + self._special_names[name]
if name.endswith('?'):
name = 'is_' + name[:-1]
name = name.replace('-', '_').replace('.', '_').replace('/', '_')
name = ''.join([n if n.islower() else "_" + n.lower() for n in name])
method = getattr(visitor, 'visit_' + name, None)
if method is not None:
arg_count = len(self.items) - 1
has_varargs = inspect.getfullargspec(method).varargs is not None
param_count = len(inspect.getfullargspec(method).args) - 1
has_correct_arg_count = arg_count >= param_count if has_varargs else arg_count == param_count
if not has_correct_arg_count:
s = "at least" if has_varargs else "exactly"
if param_count == 0:
t = "no arguments"
elif param_count == 1:
t = "one argument"
elif param_count == 2:
t = "two arguments"
elif param_count == 3:
t = "three arguments"
else:
t = "{} arguments".format(param_count)
pos = "(line {})".format(self.lineno) if self.lineno is not None else ''
raise TypeError("{}() takes {} {} ({} given) {}".format(self.name, s, t, arg_count, pos))
result = method(*self.items[1:])
if hasattr(result, '_attributes'):
result = copy_location(result, self)
return result
return super(Form, self).visit(visitor)
@property
def head(self):
return self.items[0]
@property
def tail(self):
return Form(self.items[1:])
@property
def last(self):
return self.items[-1]
@property
def name(self):
if len(self.items) > 0 and isinstance(self.items[0], Symbol):
return self.items[0].name
else:
return None
@property
def is_empty(self):
return len(self.items) == 0
@property
def non_empty(self):
return len(self.items) > 0
@property
def length(self):
return len(self.items)
class Map(ClojureObject):
def __init__(self, items:list, lineno:Optional[int]=None):
self.items = items
assert type(items) is list
assert all([isinstance(item, ClojureObject) for item in items])
assert len(self.items) % 2 == 0
assert lineno is None or type(lineno) is int
def __repr__(self):
return "{" + ' '.join([repr(item) for item in self.items]) + "}"
class Symbol(ClojureObject):
def __init__(self, name:str, lineno:Optional[int]=None):
self.name = name
if lineno is not None:
self.lineno = lineno
assert type(name) is str
assert lineno is None or type(lineno) is int
def __repr__(self):
return self.name
class Value(ClojureObject):
def __init__(self, value, lineno:Optional[int]=None):
self.value = value
if lineno is not None:
self.lineno = lineno
assert value is None or type(value) in [bool, complex, float, int, str]
assert lineno is None or type(lineno) is int
def __repr__(self):
return repr(self.value)
class Vector(ClojureObject):
def __init__(self, items:list, lineno:Optional[int]=None):
self.items = items
if lineno is not None:
self.lineno = lineno
assert type(items) in [list, tuple]
assert all([isinstance(item, ClojureObject) for item in items])
assert lineno is None or type(lineno) is int
def __getitem__(self, item):
return self.items[item]
def __len__(self):
return len(self.items)
def __repr__(self):
return "[{}]".format(' '.join([repr(item) for item in self.items]))
@property
def is_empty(self):
return len(self.items) == 0
@property
def non_empty(self):
return len(self.items) > 0
@property
def length(self):
return len(self.items)
#######################################################################################################################
class Visitor(object):
def visit(self, ast):
if isinstance(ast, ClojureObject):
return ast.visit(self)
elif hasattr(ast, '__iter__'):
return [self.visit(item) for item in ast]
else:
raise TypeError("cannot walk/visit an object of type '{}'".format(type(ast)))
def visit_node(self, node:ClojureObject):
return node
class LeafVisitor(Visitor):
def visit_symbol(self, node:Symbol):
self.visit_node(node)
def visit_value(self, node:Value):
self.visit_node(node)
def visit_form_form(self, node:Form):
for n in node.items:
n.visit(self)
def visit_map_form(self, node:Map):
for n in node.items:
n.visit(self)
def visit_symbol_form(self, node:Symbol):
self.visit_symbol(node)
def visit_value_form(self, node:Value):
self.visit_value(node)
def visit_vector_form(self, node:Vector):
for n in node.items:
n.visit(self)
#######################################################################################################################
def is_form(form):
return isinstance(form, Form)
def is_integer(form):
if isinstance(form, Value):
return type(form.value) is int
else:
return False
def is_map(form):
return isinstance(form, Map)
def is_numeric(form):
if isinstance(form, Value):
return type(form.value) in [complex, float, int]
else:
return False
def is_quoted(form):
return isinstance(form, Form) and len(form) == 2 and is_symbol(form.items[0], 'quote')
def is_string(form):
if isinstance(form, Value):
return type(form.value) is str
else:
return False
def is_symbol(form, symbol:str=None):
if isinstance(form, Symbol):
return form.name == symbol if symbol is not None else True
else:
return False
def is_symbol_vector(form):
if isinstance(form, Vector):
return all([isinstance(item, Symbol) for item in form.items])
else:
return False
def is_vector(form):
return isinstance(form, Vector)