-
Notifications
You must be signed in to change notification settings - Fork 50
/
util.py
400 lines (329 loc) · 13.6 KB
/
util.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env python
# Copyright (C) 2014 Open Data ("Open Data" refers to
# one or more of the following companies: Open Data Partners LLC,
# Open Data Research LLC, or Open Data Capital LLC.)
#
# This file is part of Hadrian.
#
# Licensed under the Hadrian Personal Use and Evaluation License (PUEL);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://raw.githubusercontent.com/opendatagroup/hadrian/master/LICENSE
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
import sys
TYPE_ERRORS_IN_PRETTYPFA = True
def ts(avroType):
"""Create a human-readable type string of a type.
Note: if titus.util.TYPE_ERRORS_IN_PRETTYPFA is ``True``, the type will be printed in PrettyPFA notation; otherwise, as a raw Avro schema.
:type avroType: titus.datatype.AvroType
:param avroType: type to print out
:rtype: string
:return: string representation of the type.
"""
if TYPE_ERRORS_IN_PRETTYPFA:
pretty = avscToPretty(avroType.jsonNode(set()))
if pretty.count("\n") > 0:
pretty = "\n " + pretty.replace("\n", "\n ") + "\n"
return pretty
else:
return repr(avroType)
uniqueEngineNameCounter = 0
def uniqueEngineName():
"""Provide an engine name, incrementing titus.util.uniqueEngineNameCounter to ensure uniqueness of values supplied by this function."""
sys.modules["titus.util"].uniqueEngineNameCounter += 1
return "Engine_{0}".format(sys.modules["titus.util"].uniqueEngineNameCounter)
uniqueRecordNameCounter = 0
def uniqueRecordName():
"""Provide a record type name, incrementing titus.util.uniqueRecordNameCounter to ensure uniqueness of values supplied by this function."""
sys.modules["titus.util"].uniqueRecordNameCounter += 1
return "Record_{0}".format(sys.modules["titus.util"].uniqueRecordNameCounter)
uniqueEnumNameCounter = 0
def uniqueEnumName():
"""Provide an enum type name, incrementing titus.util.uniqueEnumNameCounter to ensure uniqueness of values supplied by this function."""
sys.modules["titus.util"].uniqueEnumNameCounter += 1
return "Enum_{0}".format(sys.modules["titus.util"].uniqueEnumNameCounter)
uniqueFixedNameCounter = 0
def uniqueFixedName():
"""Provide a fixed type name, incrementing titus.util.uniqueFixedNameCounter to ensure uniqueness of values supplied by this function."""
sys.modules["titus.util"].uniqueFixedNameCounter += 1
return "Fixed_{0}".format(sys.modules["titus.util"].uniqueFixedNameCounter)
def pos(dot, at):
"""Create a human-readable position of a PFA element in a JSON file."""
if at is None or at == "":
return "at {0}".format("" if (dot == "") else "PFA field \"" + dot + "\"")
else:
return "at {0}{1}".format(at, "" if (dot == "") else " (PFA field \"" + dot + "\")")
def flatten(x):
"""General-purpose list-of-lists flattening.
:type x: list of lists of something
:param x: list of lists to flatten
:rtype: list of that something
:return: flattened list
"""
return [item for sublist in x for item in sublist]
def div(numer, denom):
"""PFA division behavior: inf and -inf for a finite number divided by zero and nan for 0/0.
Also ensures that return type of any two numbers (including integers) is floating point.
:type numer: number
:param numer: the numerator
:type denom: number
:param denom: the denominator
:rtype: float
:return: fraction, including non-numeric possibilities
"""
try:
return numer / float(denom)
except ZeroDivisionError:
if numer > 0.0:
return float("inf")
elif numer < 0.0:
return float("-inf")
else:
return float("nan")
class DynamicScope(object):
"""Keep track of a variable scope dynamically, for the sake of simulating lexical scope in a PFA document (ironically)."""
def __init__(self, parent):
""":type parent: titus.util.DynamicScope or ``None``
:param parent: scope to use for resolving variables not found in this scope
"""
self.parent = parent
self.symbols = dict()
def get(self, symbol):
"""Look up a variable, returning its value.
:type symbol: string
:param symbol: variable name to look up
:rtype: anything
:return: variable value
"""
if symbol in self.symbols:
return self.symbols[symbol]
elif self.parent is not None:
return self.parent.get(symbol)
else:
raise RuntimeError()
def let(self, nameExpr):
"""Create a new variable.
:type nameExpr: dict from new variable names to their initial values
:param nameExpr: variables and values to assign
"""
for symbol, init in nameExpr.items():
self.symbols[symbol] = init
def set(self, nameExpr):
"""Reassign variables.
:type nameExpr: dict from new variable names to their new values
:param nameExpr: variables and values to assign
"""
for symbol, value in nameExpr.items():
if symbol in self.symbols:
self.symbols[symbol] = value
elif self.parent is not None:
self.parent.set(nameExpr)
else:
raise RuntimeError()
def callfcn(state, scope, fcn, args):
"""Helper function for calling function callbacks.
Used in library functions that have been given functions as arguments.
:type state: titus.genpy.ExecutionState
:param state: execution state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type fcn: callable
:param fcn: function to call (must be a PFA user-defined function or library function)
:type args: list of values
:param args: arguments to pass to the function (other than the ``state`` and ``scope``)
:rtype: anything
:return: whatever ``fcn`` returns
"""
if hasattr(fcn, "paramNames"):
callScope = DynamicScope(scope)
if isinstance(args, (tuple, list)):
args = dict(zip(fcn.paramNames, args))
callScope.let(args)
return fcn(state, callScope)
else:
return fcn(state, scope, pos, None, *args)
def negativeIndex(length, index):
"""Helper function for interpreting negative array indexes as counting from the end of the array (just like Python).
:type length: non-negative integer
:param length: length of the array in question
:type index: integer
:param index: index to interpret
:rtype: non-negative integer
:return: if negative, count from the end of the array; otherwise, pass-through
"""
if index >= 0:
return index
else:
return length + index
def startEnd(length, start, end):
"""Helper function to normalize the start and end of an array by counting from the end of the array (just like Python).
:type length: non-negative integer
:param length: length of the array in question
:type start: integer
:param start: starting index to interpret
:type end: integer
:param end: ending index to interpret
:rtype: (non-negative integer, non-negative integer)
:return: (normalized starting index, normalized ending index)
"""
if start >= 0:
normStart = start
else:
normStart = length + start
if normStart < 0:
normStart = 0
if normStart > length:
normStart = length
if end >= 0:
normEnd = end
else:
normEnd = length + end
if normEnd < 0:
normEnd = 0
if normEnd > length:
normEnd = length
if normEnd < normStart:
normEnd = normStart
return normStart, normEnd
def case(clazz):
"""Decoration to make a "case class" in Python.
When applied to a class, read the parameters of the ``__init__`` and turn them into class fields and show them in the ``__repr__`` representation.
"""
fields = [x for x in inspect.getargspec(clazz.__init__).args[1:] if x != "pos"]
try:
code = clazz.__init__.__func__
except AttributeError:
code = clazz.__init__.func_code
context = dict(globals())
context[clazz.__name__] = clazz
if "pos" in inspect.getargspec(clazz.__init__).args:
argFields = fields + ["pos=None"]
assignFields = fields + ["pos"]
else:
argFields = assignFields = fields
newMethods = {}
exec("""
def __init__(self, {args}):
{assign}
self._init({args})
""".format(args=", ".join(argFields),
assign="\n".join([" self.{0} = {0}".format(x) for x in (assignFields)])),
context,
newMethods)
if len(fields) == 0:
exec("""
def __repr__(self):
return \"{0}()\"
""".format(clazz.__name__), context, newMethods)
exec("""
def __eq__(self, other):
return isinstance(other, {0})
""".format(clazz.__name__), context, newMethods)
else:
exec("""
def __repr__(self):
return \"{0}(\" + {1} + \")\"
""".format(clazz.__name__, "+ \", \" + ".join(["repr(self." + x + ")" for x in fields])),
context,
newMethods)
exec("""
def __eq__(self, other):
if isinstance(other, {0}):
return {1}
else:
return False
""".format(clazz.__name__, " and ".join(["self.{x} == other.{x}".format(x=x) for x in fields])),
context,
newMethods)
clazz._init = clazz.__init__
clazz.__init__ = newMethods["__init__"]
if hasattr(clazz, "toString"):
clazz.__repr__ = clazz.toString
else:
clazz.__repr__ = newMethods["__repr__"]
if hasattr(clazz, "equals"):
clazz.__eq__ = clazz.equals
else:
clazz.__eq__ = newMethods["__eq__"]
return clazz
def untagUnion(expr, unionTypes):
"""Turn a tagged union datum into a bare Python object or pass-through if not a tagged union datum.
:type expr: anything
:param expr: tagged union, which may be of the form ``{"tag": value}`` or just ``value``
:type unionTypes: list of Pythonized JSON
:param unionTypes: types allowed by this union in Pythonized JSON schemas
:rtype: anything
:return: ``{"tag": value}`` collapsed to ``value`` if ``tag`` names one of the ``unionTypes``; otherwise, pass-through
"""
if isinstance(expr, dict) and len(expr) == 1:
tag, = expr.keys()
value, = expr.values()
for expectedTag in unionTypes:
if isinstance(expectedTag, dict):
if expectedTag["type"] in ("record", "enum", "fixed"):
if "namespace" in expectedTag and expectedTag["namespace"].strip() != "":
expectedTag = expectedTag["namespace"] + "." + expectedTag["name"]
else:
expectedTag = expectedTag["name"]
else:
expectedTag = expectedTag["type"]
if tag == expectedTag:
return value
return expr
def avscToPretty(avsc, indent=0):
"""Turn an Avro type from Pythonized JSON into a more human-readable PrettyPFA string.
:type avsc: Pythonized JSON
:param avsc: Avro type schema
:type indent: non-negative integer
:param indent: number of spaces to indent (default 0)
:rtype: string
:return: PrettyPFA representation
"""
if isinstance(avsc, basestring):
return " " * indent + avsc
elif isinstance(avsc, dict) and "type" in avsc:
tpe = avsc["type"]
if tpe == "function":
return " " * indent + "fcn(" + ", ".join("arg{}: {}".format(i + 1, avscToPretty(x)) for i, x in enumerate(avsc["params"])) + " -> " + avscToPretty(avsc["ret"]) + ")"
elif tpe == "exception":
return "exception"
elif tpe in ("null", "boolean", "int", "long", "float", "double", "bytes", "string"):
return " " * indent + tpe
elif tpe == "array":
return " " * indent + "array(" + avscToPretty(avsc["items"], indent + 6).lstrip() + ")"
elif tpe == "map":
return " " * indent + "map(" + avscToPretty(avsc["values"], indent + 4).lstrip() + ")"
elif tpe == "record":
name = avsc["name"]
if "namespace" in avsc and len(avsc["namespace"]) > 0:
name = avsc["namespace"] + "." + name
fields = []
for f in avsc["fields"]:
fields.append(" " * (indent + 7) + f["name"] + ": " + avscToPretty(f["type"], indent + 7 + len(f["name"]) + 2).lstrip())
return " " * indent + "record(" + name + ",\n" + ",\n".join(fields) + ")"
elif tpe == "fixed":
name = avsc["name"]
if "namespace" in avsc and len(avsc["namespace"]) > 0:
name = avsc["namespace"] + "." + name
return " " * indent + "fixed(" + str(avsc["size"]) + ", " + name + ")"
elif tpe == "enum":
name = avsc["name"]
if "namespace" in avsc and len(avsc["namespace"]) > 0:
name = avsc["namespace"] + "." + name
return " " * indent + "enum([" + ", ".join(x for x in avsc["symbols"]) + "], " + name + ")"
else:
raise TypeError("malformed Avro schema")
elif isinstance(avsc, (list, tuple)):
variants = []
for x in avsc:
variants.append(avscToPretty(x, indent + 6))
return " " * indent + "union(" + ",\n".join(variants).lstrip() + ")"
else:
raise TypeError("malformed Avro schema")