-
Notifications
You must be signed in to change notification settings - Fork 50
/
genpy.py
1821 lines (1506 loc) · 73.1 KB
/
genpy.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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 base64
import json
import math
import threading
import time
import random
import struct
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
from titus.errors import *
import titus.pfaast
import titus.datatype
import titus.fcn
import titus.options
import titus.P as P
import titus.reader
import titus.signature
import titus.util
from titus.util import DynamicScope
import titus.version
from titus.pfaast import EngineConfig
from titus.pfaast import Cell as AstCell
from titus.pfaast import Pool as AstPool
from titus.pfaast import FcnDef
from titus.pfaast import FcnRef
from titus.pfaast import FcnRefFill
from titus.pfaast import CallUserFcn
from titus.pfaast import Call
from titus.pfaast import Ref
from titus.pfaast import LiteralNull
from titus.pfaast import LiteralBoolean
from titus.pfaast import LiteralInt
from titus.pfaast import LiteralLong
from titus.pfaast import LiteralFloat
from titus.pfaast import LiteralDouble
from titus.pfaast import LiteralString
from titus.pfaast import LiteralBase64
from titus.pfaast import Literal
from titus.pfaast import NewObject
from titus.pfaast import NewArray
from titus.pfaast import Do
from titus.pfaast import Let
from titus.pfaast import SetVar
from titus.pfaast import AttrGet
from titus.pfaast import AttrTo
from titus.pfaast import CellGet
from titus.pfaast import CellTo
from titus.pfaast import PoolGet
from titus.pfaast import PoolTo
from titus.pfaast import PoolDel
from titus.pfaast import If
from titus.pfaast import Cond
from titus.pfaast import While
from titus.pfaast import DoUntil
from titus.pfaast import For
from titus.pfaast import Foreach
from titus.pfaast import Forkeyval
from titus.pfaast import CastCase
from titus.pfaast import CastBlock
from titus.pfaast import Upcast
from titus.pfaast import IfNotNull
from titus.pfaast import BinaryFormatter
from titus.pfaast import Pack
from titus.pfaast import Unpack
from titus.pfaast import Doc
from titus.pfaast import Error
from titus.pfaast import Try
from titus.pfaast import Log
from titus.pfaast import Method
from titus.pfaast import ArrayIndex
from titus.pfaast import MapIndex
from titus.pfaast import RecordIndex
from titus.pmml.reader import pmmlToAst
class GeneratePython(titus.pfaast.Task):
"""A ``titus.pfaast.Task`` for turning PFA into executable Python."""
@staticmethod
def makeTask(style):
"""Make a ``titus.genpy.GeneratePython`` Task with a particular style.
Currently, the only style is "pure" (``titus.genpy.GeneratePythonPure``).
"""
if style == "pure":
return GeneratePythonPure()
else:
raise NotImplementedError("unrecognized style " + style)
def commandsMap(self, codes, indent):
"""Concatenate commands for a map-type engine."""
suffix = indent + "self.actionsFinished += 1\n" + \
indent + "return last\n"
return "".join(indent + x + "\n" for x in codes[:-1]) + indent + "last = " + codes[-1] + "\n" + suffix
def commandsEmit(self, codes, indent):
"""Concatenate commands for an emit-type engine."""
suffix = indent + "self.actionsFinished += 1\n"
return "".join(indent + x + "\n" for x in codes) + suffix
def commandsFold(self, codes, indent):
"""Concatenate commands for a fold-type engine."""
prefix = indent + "scope.let({'tally': self.tally})\n"
suffix = indent + "self.tally = last\n" + \
indent + "self.actionsFinished += 1\n" + \
indent + "return self.tally\n"
return prefix + "".join(indent + x + "\n" for x in codes[:-1]) + indent + "last = " + codes[-1] + "\n" + suffix
def commandsFoldMerge(self, codes, indent):
"""Concatenate commands for the merge section of a fold-type engine."""
suffix = indent + "self.tally = last\n" + \
indent + "return self.tally\n"
return "".join(indent + x + "\n" for x in codes[:-1]) + indent + "last = " + codes[-1] + "\n" + suffix
def commandsBeginEnd(self, codes, indent):
"""Concatenate commands for the begin or end method."""
return "".join(indent + x + "\n" for x in codes)
def reprPath(self, path):
"""Build a path for "attr", "cell", or "pool" special forms."""
out = []
for p in path:
if isinstance(p, ArrayIndex):
out.append(p.i)
elif isinstance(p, MapIndex):
out.append(p.k)
elif isinstance(p, RecordIndex):
out.append(repr(p.f))
else:
raise Exception
return ", ".join(out)
def __call__(self, context, engineOptions):
"""Turn a PFA Context into Python."""
if isinstance(context, EngineConfig.Context):
if context.name is None:
name = titus.util.uniqueEngineName()
else:
name = context.name
begin, beginSymbols, beginCalls = context.begin
action, actionSymbols, actionCalls = context.action
end, endSymbols, endCalls = context.end
callGraph = {"(begin)": beginCalls, "(action)": actionCalls, "(end)": endCalls}
if context.merge is not None:
mergeTasks, mergeSymbols, mergeCalls = context.merge
callGraph["(merge)"] = mergeCalls
for fname, fctx in context.fcns:
callGraph[fname] = fctx.calls
out = ["class PFA_" + name + """(PFAEngine):
def __init__(self, cells, pools, config, options, log, emit, zero, instance, rand):
self.actionsStarted = 0
self.actionsFinished = 0
self.cells = cells
self.pools = pools
self.config = config
self.inputType = config.input
self.outputType = config.output
self.options = options
self.log = log
self.emit = emit
self.instance = instance
self.rand = rand
self.callGraph = """ + repr(callGraph) + "\n"]
if context.method == Method.FOLD:
out.append(" self.tally = zero\n")
out.append(""" def initialize(self):
self
""")
for ufname, fcnContext in context.fcns:
out.append(" self.f[" + repr(ufname) + "] = " + self(fcnContext, engineOptions) + "\n")
if len(begin) > 0:
out.append("""
def begin(self):
state = ExecutionState(self.options, self.rand, 'action', self.parser)
scope = DynamicScope(None)
scope.let({'name': self.config.name, 'instance': self.instance, 'metadata': self.config.metadata})
if self.config.version is not None:
scope.let({'version': self.config.version})
""" + self.commandsBeginEnd(begin, " "))
else:
out.append("""
def begin(self):
pass
""")
if context.method == Method.MAP:
commands = self.commandsMap(action, " ")
elif context.method == Method.EMIT:
commands = self.commandsEmit(action, " ")
elif context.method == Method.FOLD:
commands = self.commandsFold(action, " ")
out.append("""
def action(self, input, check=True):
if check:
input = checkData(input, self.inputType)
state = ExecutionState(self.options, self.rand, 'action', self.parser)
scope = DynamicScope(None)
for cell in self.cells.values():
cell.maybeSaveBackup()
for pool in self.pools.values():
pool.maybeSaveBackup()
self.actionsStarted += 1
try:
scope.let({'input': input, 'name': self.config.name, 'instance': self.instance, 'metadata': self.config.metadata, 'actionsStarted': self.actionsStarted, 'actionsFinished': self.actionsFinished})
if self.config.version is not None:
scope.let({'version': self.config.version})
""" + commands)
out.append(""" except Exception:
for cell in self.cells.values():
cell.maybeRestoreBackup()
for pool in self.pools.values():
pool.maybeRestoreBackup()
raise
""")
if context.merge is not None:
out.append("""
def merge(self, tallyOne, tallyTwo):
state = ExecutionState(self.options, self.rand, 'merge', self.parser)
scope = DynamicScope(None)
for cell in self.cells.values():
cell.maybeSaveBackup()
for pool in self.pools.values():
pool.maybeSaveBackup()
try:
scope.let({'tallyOne': tallyOne, 'tallyTwo': tallyTwo, 'name': self.config.name, 'instance': self.instance, 'metadata': self.config.metadata})
if self.config.version is not None:
scope.let({'version': self.config.version})
""" + self.commandsFoldMerge(mergeTasks, " "))
out.append(""" except Exception:
for cell in self.cells.values():
cell.maybeRestoreBackup()
for pool in self.pools.values():
pool.maybeRestoreBackup()
raise
""")
if len(end) > 0:
tallyLine = ""
if context.method == Method.FOLD:
tallyLine = """ scope.let({'tally': self.tally})\n"""
out.append("""
def end(self):
state = ExecutionState(self.options, self.rand, 'action', self.parser)
scope = DynamicScope(None)
scope.let({'name': self.config.name, 'instance': self.instance, 'metadata': self.config.metadata, 'actionsStarted': self.actionsStarted, 'actionsFinished': self.actionsFinished})
if self.config.version is not None:
scope.let({'version': self.config.version})
""" + tallyLine + self.commandsBeginEnd(end, " "))
else:
out.append("""
def end(self):
pass
""")
out.append("""
def pooldel(self, name, item):
p = self.pools[name]
try:
del p.value[item]
except KeyError:
pass
return None
""")
return "".join(out)
elif isinstance(context, FcnDef.Context):
return "labeledFcn(lambda state, scope: do(" + ", ".join(context.exprs) + "), [" + ", ".join(map(repr, context.paramNames)) + "])"
elif isinstance(context, FcnRef.Context):
return "self.f[" + repr(context.fcn.name) + "]"
elif isinstance(context, FcnRefFill.Context):
reducedArgs = ["\"$" + str(x) + "\"" for x in xrange(len(context.fcnType.params))]
j = 0
args = []
for name in context.originalParamNames:
if name in context.argTypeResult:
args.append(context.argTypeResult[name][1])
else:
args.append("scope.get(\"$" + str(j) + "\")")
j += 1
return "labeledFcn(lambda state, scope: call(state, DynamicScope(scope), self.f[" + repr(context.fcn.name) + "], [" + ", ".join(args) + "]), [" + ", ".join(reducedArgs) + "])"
elif isinstance(context, CallUserFcn.Context):
return "call(state, DynamicScope(None), self.f['u.' + " + context.name + "], [" + ", ".join(context.args) + "])"
elif isinstance(context, Call.Context):
return context.fcn.genpy(context.paramTypes + [context.retType], context.args, context.pos)
elif isinstance(context, Ref.Context):
return "scope.get({0})".format(repr(context.name))
elif isinstance(context, LiteralNull.Context):
return "None"
elif isinstance(context, LiteralBoolean.Context):
return str(context.value)
elif isinstance(context, LiteralInt.Context):
return str(context.value)
elif isinstance(context, LiteralLong.Context):
return str(context.value)
elif isinstance(context, LiteralFloat.Context):
return str(float(context.value))
elif isinstance(context, LiteralDouble.Context):
return str(float(context.value))
elif isinstance(context, LiteralString.Context):
return repr(context.value)
elif isinstance(context, LiteralBase64.Context):
return repr(context.value)
elif isinstance(context, Literal.Context):
return repr(titus.datatype.jsonDecoder(context.retType, json.loads(context.value)))
elif isinstance(context, NewObject.Context):
return "{" + ", ".join(repr(k) + ": " + v for k, v in context.fields.items()) + "}"
elif isinstance(context, NewArray.Context):
return "[" + ", ".join(context.items) + "]"
elif isinstance(context, Do.Context):
return "do(" + ", ".join(context.exprs) + ")"
elif isinstance(context, Let.Context):
return "scope.let({" + ", ".join(repr(n) + ": " + e for n, t, e in context.nameTypeExpr) + "})"
elif isinstance(context, SetVar.Context):
return "scope.set({" + ", ".join(repr(n) + ": " + e for n, t, e in context.nameTypeExpr) + "})"
elif isinstance(context, AttrGet.Context):
return "get(" + context.expr + ", [" + self.reprPath(context.path) + "], 2000, 2001, \"attr\", " + repr(context.pos) + ")"
elif isinstance(context, AttrTo.Context):
return "update(state, scope, {0}, [{1}], {2}, 2002, 2003, \"attr-to\", {3})".format(context.expr, self.reprPath(context.path), context.to, repr(context.pos))
elif isinstance(context, CellGet.Context):
return "get(self.cells[{0}].value, [{1}], 2004, 2005, \"cell\", {2})".format(repr(context.cell), self.reprPath(context.path), repr(context.pos))
elif isinstance(context, CellTo.Context):
return "self.cells[{0}].update(state, scope, [{1}], {2}, 2006, 2007, \"cell-to\", {3})".format(repr(context.cell), self.reprPath(context.path), context.to, repr(context.pos))
elif isinstance(context, PoolGet.Context):
return "get(self.pools[{0}].value, [{1}], 2008, 2009, \"pool\", {2})".format(repr(context.pool), self.reprPath(context.path), repr(context.pos))
elif isinstance(context, PoolTo.Context):
return "self.pools[{0}].update(state, scope, [{1}], {2}, {3}, 2010, 2011, \"pool-to\", {4})".format(repr(context.pool), self.reprPath(context.path), context.to, context.init, repr(context.pos))
elif isinstance(context, PoolDel.Context):
return "self.pooldel({0}, {1})".format(repr(context.pool), context.dell)
elif isinstance(context, If.Context):
if context.elseClause is None:
return "ifThen(state, scope, lambda state, scope: {0}, lambda state, scope: do({1}))".format(context.predicate, ", ".join(context.thenClause))
else:
return "ifThenElse(state, scope, lambda state, scope: {0}, lambda state, scope: do({1}), lambda state, scope: do({2}))".format(context.predicate, ", ".join(context.thenClause), ", ".join(context.elseClause))
elif isinstance(context, Cond.Context):
if not context.complete:
return "cond(state, scope, [{0}])".format(", ".join("(lambda state, scope: {0}, lambda state, scope: do({1}))".format(walkBlock.pred, ", ".join(walkBlock.exprs)) for walkBlock in context.walkBlocks))
else:
return "condElse(state, scope, [{0}], lambda state, scope: do({1}))".format(", ".join("(lambda state, scope: {0}, lambda state, scope: do({1}))".format(walkBlock.pred, ", ".join(walkBlock.exprs)) for walkBlock in context.walkBlocks[:-1]), ", ".join(context.walkBlocks[-1].exprs))
elif isinstance(context, While.Context):
return "doWhile(state, scope, lambda state, scope: {0}, lambda state, scope: do({1}))".format(context.predicate, ", ".join(context.loopBody))
elif isinstance(context, DoUntil.Context):
return "doUntil(state, scope, lambda state, scope: {0}, lambda state, scope: do({1}))".format(context.predicate, ", ".join(context.loopBody))
elif isinstance(context, For.Context):
return "doFor(state, scope, lambda state, scope: scope.let({" + ", ".join(repr(n) + ": " + e for n, t, e in context.initNameTypeExpr) + "}), lambda state, scope: " + context.predicate + ", lambda state, scope: scope.set({" + ", ".join(repr(n) + ": " + e for n, t, e in context.stepNameTypeExpr) + "}), lambda state, scope: do(" + ", ".join(context.loopBody) + "))"
elif isinstance(context, Foreach.Context):
return "doForeach(state, scope, {0}, {1}, lambda state, scope: do({2}))".format(repr(context.name), context.objExpr, ", ".join(context.loopBody))
elif isinstance(context, Forkeyval.Context):
return "doForkeyval(state, scope, {0}, {1}, {2}, lambda state, scope: do({3}))".format(repr(context.forkey), repr(context.forval), context.objExpr, ", ".join(context.loopBody))
elif isinstance(context, CastCase.Context):
return "(" + repr(context.name) + ", " + repr(context.toType) + ", lambda state, scope: do(" + ", ".join(context.clause) + "))"
elif isinstance(context, CastBlock.Context):
return "cast(state, scope, " + context.expr + ", " + repr(context.exprType) + ", [" + ", ".join(caseRes for castCtx, caseRes in context.cases) + "], " + repr(context.partial) + ", self.parser)"
elif isinstance(context, Upcast.Context):
if isinstance(context.retType, titus.datatype.AvroUnion) and not isinstance(context.originalType, titus.datatype.AvroUnion):
for t in context.retType.types:
if t.accepts(context.originalType):
return "wrapAsUnion({}, {})".format(context.expr, repr(t.name))
raise Exception # type-checking should have prevented this
else:
return context.expr
elif isinstance(context, IfNotNull.Context):
if context.elseClause is None:
return "ifNotNull(state, scope, {" + ", ".join(repr(n) + ": " + e for n, t, e in context.symbolTypeResult) + "}, {" + ", ".join(repr(n) + ": '" + repr(t) + "'" for n, t, e in context.symbolTypeResult) + "}, lambda state, scope: do(" + ", ".join(context.thenClause) + "))"
else:
return "ifNotNullElse(state, scope, {" + ", ".join(repr(n) + ": " + e for n, t, e in context.symbolTypeResult) + "}, {" + ", ".join(repr(n) + ": '" + repr(t) + "'" for n, t, e in context.symbolTypeResult) + "}, lambda state, scope: do(" + ", ".join(context.thenClause) + "), lambda state, scope: do(" + ", ".join(context.elseClause) + "))"
elif isinstance(context, Pack.Context):
return "pack(state, scope, [" + ", ".join("(" + str(d.value) + ", " + str(d) + ")" for d in context.exprsDeclareRes) + "], " + repr(context.pos) + ")"
elif isinstance(context, Unpack.Context):
if context.elseClause is None:
return "unpack(state, scope, " + context.bytes + ", [" + ", ".join(str(x) for x in context.formatter) + "], lambda state, scope: do(" + ", ".join(context.thenClause) + "))"
else:
return "unpackElse(state, scope, " + context.bytes + ", [" + ", ".join(str(x) for x in context.formatter) + "], lambda state, scope: do(" + ", ".join(context.thenClause) + "), lambda state, scope: do(" + ", ".join(context.elseClause) + "))"
elif isinstance(context, Doc.Context):
return "None"
elif isinstance(context, Error.Context):
return "error(" + repr(context.message) + ", " + repr(context.code) + ", " + repr(context.pos) + ")"
elif isinstance(context, Try.Context):
return "tryCatch(state, scope, lambda state, scope: do(" + ", ".join(context.exprs) + "), " + repr(context.filter) + ")"
elif isinstance(context, Log.Context):
return "self.log([{0}], {1})".format(", ".join(x[1] for x in context.exprTypes), repr(context.namespace))
else:
raise PFASemanticException("unrecognized context class: " + str(type(context)), "")
class GeneratePythonPure(GeneratePython):
"""A ``titus.pfaast.Task`` for generating a pure Python executable.
This is a dummy class; all of the work is done in ``titus.genpy.GeneratePython``. Non-pure styles would be siblings of this class.
"""
pass
###########################################################################
class ExecutionState(object):
"""Passed through a running PFA engine, carrying the state of that engine.
Every PFA function implementation gets this state as an argument.
It includes execution options, random number generators, whether we are in begin, action, or end, etc.
"""
def __init__(self, options, rand, routine, parser):
self.rand = rand
self.parser = parser
if routine == "begin":
self.timeout = options.timeout_begin
elif routine == "action":
self.timeout = options.timeout_action
elif routine == "end":
self.timeout = options.timeout_end
self.startTime = time.time()
def checkTime(self):
if self.timeout > 0 and (time.time() - self.startTime) * 1000 > self.timeout:
raise PFATimeoutException("exceeded timeout of {0} milliseconds".format(self.timeout))
class SharedState(object):
"""Represents the state of all shared cells and pools at runtime."""
def __init__(self):
self.cells = {}
self.pools = {}
def __repr__(self):
return "SharedState({0} cells, {1} pools)".format(len(self.cells), len(self.pools))
class PersistentStorageItem(object):
"""Represents the state of one cell or pool at runtime."""
def __init__(self, value, shared, rollback, source):
self.value = value
self.shared = shared
self.rollback = rollback
self.source = source
class Cell(PersistentStorageItem):
"""Represents the state of a cell at runtime."""
def __init__(self, value, shared, rollback, source):
if shared:
self.lock = threading.Lock()
super(Cell, self).__init__(value, shared, rollback, source)
def __repr__(self):
contents = repr(self.value)
if len(contents) > 30:
contents = contents[:27] + "..."
return "Cell(" + ("shared, " if self.shared else "") + ("rollback, " if self.rollback else "") + contents + ")"
def update(self, state, scope, path, to, arrayErrCode, mapErrCode, fcnName, pos):
result = None
if self.shared:
self.lock.acquire()
self.value = update(state, scope, self.value, path, to, arrayErrCode, mapErrCode, fcnName, pos)
result = self.value
self.lock.release()
else:
self.value = update(state, scope, self.value, path, to, arrayErrCode, mapErrCode, fcnName, pos)
result = self.value
return result
def maybeSaveBackup(self):
if self.rollback:
self.oldvalue = self.value
def maybeRestoreBackup(self):
if self.rollback:
self.value = self.oldvalue
class Pool(PersistentStorageItem):
"""Represents the state of a pool at runtime."""
def __init__(self, value, shared, rollback, source):
if shared:
self.locklock = threading.Lock()
self.locks = {}
super(Pool, self).__init__(value, shared, rollback, source)
def __repr__(self):
contents = repr(self.value)
if len(contents) > 30:
contents = contents[:27] + "..."
return "Pool(" + ("shared, " if self.shared else "") + ("rollback, " if self.rollback else "") + contents + ")"
def update(self, state, scope, path, to, init, arrayErrCode, mapErrCode, fcnName, pos):
result = None
head, tail = path[0], path[1:]
if self.shared:
self.locklock.acquire()
if head in self.locks:
self.locks[head].acquire()
else:
self.locks[head] = threading.Lock()
self.locks[head].acquire()
self.locklock.release()
if head not in self.value:
self.value[head] = init
self.value[head] = update(state, scope, self.value[head], tail, to, arrayErrCode, mapErrCode, fcnName, pos)
result = self.value[head]
self.locks[head].release()
else:
if head not in self.value:
self.value[head] = init
self.value[head] = update(state, scope, self.value[head], tail, to, arrayErrCode, mapErrCode, fcnName, pos)
result = self.value[head]
return result
def maybeSaveBackup(self):
if self.rollback:
self.oldvalue = dict(self.value)
def maybeRestoreBackup(self):
if self.rollback:
self.value = self.oldvalue
def labeledFcn(fcn, paramNames):
"""Wraps a function with its parameter names (in-place).
:type fcn: callable Python object
:param fcn: function to wrap
:type paramNames: list of strings
:param paramNames: parameters to attach to the function
:rtype: callable Python object
:return: the original function, modified in-place by adding ``paramNames`` as an attribute
"""
fcn.paramNames = paramNames
return fcn
def get(obj, path, arrayErrCode, mapErrCode, fcnName, pos):
"""Apply an "attr", "cell", or "pool" extraction path to an object.
:type obj: any object
:param obj: the object to extract an item from
:type path: list of integers and strings
:param path: attribute labels from outermost to innermost
:type arrayErrCode: integer
:param arrayErrCode: error code to raise if an array index is not found
:type mapErrCode: integer
:param mapErrCode: error code to raise if a map key is not found
:type fcnName: string
:param fcnName: function name for error reporting
:type pos: string or ``None``
:param pos: position from locator marks for error reporting
:rtype: an object
:return: the extracted object
"""
while len(path) > 0:
head, tail = path[0], path[1:]
try:
obj = obj[head]
except (KeyError, IndexError):
if isinstance(obj, (list, tuple)):
raise PFARuntimeException("array index not found", arrayErrCode, fcnName, pos)
else:
raise PFARuntimeException("map key not found", mapErrCode, fcnName, pos)
path = tail
return obj
def update(state, scope, obj, path, to, arrayErrCode, mapErrCode, fcnName, pos):
"""Return the updated state of a cell or pool at runtime (not in-place).
:type state: titus.genpy.ExecutionState
:param state: runtime state object
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type obj: an object
:param obj: cell or pool data that should be replaced
:type path: list of integers and strings
:param path: extraction path
:type to: an object, possibly callable
:param to: replacement object; if callable, the function is called to perform the update
:type arrayErrCode: integer
:param arrayErrCode: error code to raise if an array index is not found
:type mapErrCode: integer
:param mapErrCode: error code to raise if a map key is not found
:type fcnName: string
:param fcnName: function name for error reporting
:type pos: string or ``None``
:param pos: position from locator marks for error reporting
:rtype: an object
:return: an updated version of the object, for the sake of replacement
"""
if len(path) > 0:
head, tail = path[0], path[1:]
if isinstance(obj, dict):
if len(tail) > 0 and head not in obj:
raise PFARuntimeException("map key not found", mapErrCode, fcnName, pos)
out = {}
for k, v in obj.items():
if k == head:
out[k] = update(state, scope, v, tail, to, arrayErrCode, mapErrCode, fcnName, pos)
else:
out[k] = v
return out
elif isinstance(obj, (list, tuple)):
if (len(tail) > 0 and head >= len(obj)) or head < 0:
raise PFARuntimeException("array index not found", arrayErrCode, fcnName, pos)
out = []
for i, x in enumerate(obj):
if i == head:
out.append(update(state, scope, x, tail, to, arrayErrCode, mapErrCode, fcnName, pos))
else:
out.append(x)
return out
else:
raise Exception
elif callable(to):
callScope = DynamicScope(scope)
callScope.let({to.paramNames[0]: obj})
return to(state, callScope)
else:
return to
def do(*exprs):
"""Helper function for chaining expressions.
The expressions have already been evaluated when this function is called, so this function just returns the last one.
If the list of expressions is empty, it returns ``None``.
"""
# You've already done them; just return the right value.
if len(exprs) > 0:
return exprs[-1]
else:
return None
def ifThen(state, scope, predicate, thenClause):
"""Helper function for constructing an if-then branch as an expression.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type predicate: callable
:param predicate: function that returns ``True`` or ``False``
:type thenClause: callable
:param thenClause: function that is called if ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
if predicate(state, DynamicScope(scope)):
thenClause(state, DynamicScope(scope))
return None
def ifThenElse(state, scope, predicate, thenClause, elseClause):
"""Helper function for constructing an if-then-else branch as an expression.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type predicate: callable
:param predicate: function that returns ``True`` or ``False``
:type thenClause: callable
:param thenClause: function that is called if ``predicate`` returns ``True``
:type elseClause: callable
:param elseClause: function that is called if ``predicate`` returns ``False``
:rtype: return type of ``thenClause`` or ``elseClause``
:return: if ``predicate`` returns ``True``, the result of ``thenClause``, else the result of ``elseClause``
"""
if predicate(state, DynamicScope(scope)):
return thenClause(state, DynamicScope(scope))
else:
return elseClause(state, DynamicScope(scope))
def cond(state, scope, ifThens):
"""Helper function for constructing if-elif-elif-...-elif as an expression.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type ifThens: list of (callable, callable) pairs
:param ifThens: list of ``(predicate, thenClause)`` pairs
:rtype: ``None``
:return: nothing
"""
for predicate, thenClause in ifThens:
if predicate(state, DynamicScope(scope)):
thenClause(state, DynamicScope(scope))
break
return None
def condElse(state, scope, ifThens, elseClause):
"""Helper function for constructing if-elif-elif-...-elif as an expression.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type ifThens: list of (callable, callable) pairs
:param ifThens: list of ``(predicate, thenClause)`` pairs
:type elseClause: callable
:param elseClause: function that is called if ``predicate`` returns ``False``
:rtype: return type of any ``thenClause`` or the ``elseClause``
:return: if any ``predicate`` returns ``True``, the result of the corresponding ``thenClause``, else the result of ``elseClause``
"""
for predicate, thenClause in ifThens:
if predicate(state, DynamicScope(scope)):
return thenClause(state, DynamicScope(scope))
return elseClause(state, DynamicScope(scope))
def doWhile(state, scope, predicate, loopBody):
"""Helper function for constructing pretest loops as an expression.
Calls ``state.checkTime()`` on every iteration.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type predicate: callable
:param predicate: function that returns ``True`` or ``False``
:type loopBody: callable
:param loopBody: function that is called while ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
bodyScope = DynamicScope(scope)
predScope = DynamicScope(bodyScope)
while predicate(state, predScope):
state.checkTime()
loopBody(state, bodyScope)
return None
def doUntil(state, scope, predicate, loopBody):
"""Helper function for constructing posttest loops as an expression.
Calls ``state.checkTime()`` on every iteration.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type predicate: callable
:param predicate: function that returns ``True`` or ``False``
:type loopBody: callable
:param loopBody: function that is called until ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
bodyScope = DynamicScope(scope)
predScope = DynamicScope(bodyScope)
while True:
state.checkTime()
loopBody(state, bodyScope)
if predicate(state, predScope):
break
return None
def doFor(state, scope, initLet, predicate, stepSet, loopBody):
"""Helper function for constructing for loops as an expression.
Calls ``state.checkTime()`` on every iteration.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type initLet: callable
:param initLet: initialization of for loop variables
:type predicate: callable
:param predicate: function that returns ``True`` or ``False``
:type stepSet: callable
:param stepSet: updating of for loop variables
:type loopBody: callable
:param loopBody: function that is called while ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
loopScope = DynamicScope(scope)
predScope = DynamicScope(loopScope)
bodyScope = DynamicScope(loopScope)
initLet(state, loopScope)
while predicate(state, predScope):
state.checkTime()
loopBody(state, bodyScope)
stepSet(state, loopScope)
return None
def doForeach(state, scope, name, array, loopBody):
"""Helper function for constructing foreach loops as an expression.
Calls ``state.checkTime()`` on every iteration.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type name: string
:param name: new variable for each array item
:type name: Python iterable
:param name: array to loop over
:type loopBody: callable
:param loopBody: function that is called while ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
loopScope = DynamicScope(scope)
bodyScope = DynamicScope(loopScope)
for item in array:
state.checkTime()
loopScope.let({name: item})
loopBody(state, bodyScope)
return None
def doForkeyval(state, scope, forkey, forval, mapping, loopBody):
"""Helper function for constructing for key,value loops as an expression.
Calls ``state.checkTime()`` on every iteration.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type forkey: string
:param forkey: new variable for each item key
:type forval: string
:param forval: new variable for each item value
:type name: Python dict
:param name: map of key-value pairs to loop over
:type loopBody: callable
:param loopBody: function that is called while ``predicate`` returns ``True``
:rtype: ``None``
:return: nothing
"""
loopScope = DynamicScope(scope)
bodyScope = DynamicScope(loopScope)
for key, val in mapping.items():
state.checkTime()
loopScope.let({forkey: key, forval: val})
loopBody(state, bodyScope)
return None
def cast(state, scope, expr, fromType, cases, partial, parser):
"""Helper function for type-safe casting as an expression.
:type state: titus.genpy.ExecutionState
:param state: exeuction state
:type scope: titus.util.DynamicScope
:param scope: dynamic scope object
:type expr: evaluated expression
:param expr: object to cast
:type fromType: string
:param fromType: JSON-serialized Avro type
:type cases: list of (string, string, callable) triples
:param cases: list of (new variable for one case, JSON-serialized subtype, function to call if type matches) triples
:type partial: boolean
:param partial: if ``True``, allow the set of cases to incompletely cover the ``fromType``
:type parser: titus.datatype.ForwardDeclarationParser
:param parser: used to interpret ``fromType``
:rtype: ``None`` or result of one of the ``cases`` callable
:return: if ``partial``, returns ``None``, else returns the result of the matching case
"""
fromType = parser.getAvroType(fromType)
for name, toType, clause in cases:
toType = parser.getAvroType(toType)
if isinstance(fromType, titus.datatype.AvroUnion) and isinstance(expr, dict) and len(expr) == 1:
tag, = expr.keys()
value, = expr.values()
if not ((tag == toType.name) or \
(tag == "int" and toType.name in ("long", "float", "double")) or \
(tag == "long" and toType.name in ("float", "double")) or \
(tag == "float" and toType.name == "double")):
continue
else:
value = expr
try:
castValue = titus.datatype.jsonDecoder(toType, value)
except (AvroException, TypeError):
pass
else:
clauseScope = DynamicScope(scope)
clauseScope.let({name: castValue})
out = clause(state, clauseScope)
if partial:
return None