-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathppl_ast.py
More file actions
executable file
·1734 lines (1397 loc) · 56 KB
/
ppl_ast.py
File metadata and controls
executable file
·1734 lines (1397 loc) · 56 KB
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
#
# This file is part of PyFOPPL, an implementation of a First Order Probabilistic Programming Language in Python.
#
# License: MIT (see LICENSE.txt)
#
# 07. Feb 2018, Tobias Kohn
# 28. Mar 2018, Tobias Kohn
#
from typing import Optional
import enum
from ast import copy_location as _cl
import inspect as _inspect
class AstNode(object):
"""
The `AstNode` is the base-class for all AST-nodes. You will typically not instantiate an object of this class,
but derive a specific AST-node from it.
"""
_attributes = { 'col_offset', 'lineno' }
original_name = None
tag = None
def get_fields(self):
fields = set(self.__dict__).difference(set(AstNode.__dict__))
fields = [name for name in fields if len(name) > 0 and not name.startswith('_')]
return fields
def set_field_values(self, source):
if isinstance(source, self.__class__):
for field in self.get_fields():
setattr(self, field, getattr(source, field))
elif type(source) is dict:
for field in source:
if hasattr(self, field):
setattr(self, field, source[field])
else:
raise RuntimeError("cannot set fields from source '{}'".format(repr(source)))
def get_children(self):
"""
Returns a list of all fields, which are either `AstNode`-objects, or sequences (list/tuples) of such objects.
:return: A list of strings denoting fields, which are `AstNode`-objects or sequences thereof.
"""
def is_valid(name):
field = getattr(self, name, None)
if isinstance(field, AstNode):
return True
elif hasattr(field, '__iter__') and all([isinstance(item, AstNode) for item in field]):
return True
else:
return False
return [item for item in self.get_fields() if is_valid(item)]
def get_ast_children(self):
"""
Returns a flat list of all fields/children, which are `AstNode`-objects.
:return: A (possibly empty) list of `AstNode`-objects.
"""
result = []
for name in self.get_fields():
field = getattr(self, name, None)
if isinstance(field, AstNode):
result.append(field)
elif hasattr(field, '__iter__'):
for item in field:
if isinstance(item, AstNode):
result.append(item)
return result
def get_type(self):
"""
Returns the type of this node.
:return: Either an instance of `Type` (see `ppl_types`), or `None`.
"""
return getattr(self, '__type__', None)
def get_visitor_names(self):
"""
Returns an ordered list of possible names for the visit-methods to be called by `visit`.
We want to be flexible and provide a hierarchy of method names to try out. Take, for instance, an AST-node
for a FOR-loop. The visit-method to call might then be called `visit_ForLoop`, `visit_for_loop`, or we might
end up having a more generic `visit_loop` to call.
The default implementation given here provides various possibilities based on the name of the instance's class.
If, say, the node is of class `AstForLoop`, then we try the following names:
`visit_AstForLoop`, `visit_astforloop`, `visit_for_loop`, `visit_forloop`
Be overriding this method, you might change the names altogether, or insert a more general name such as
`visit_loop` or `visit_compound_statement`.
:return: A list of strings with possible method names.
"""
name = self.__class__.__name__
if name.startswith("Ast"):
name = name[3:]
elif name.endswith("Node"):
name = name[:-4]
if name.islower():
result = ['visit_' + name]
else:
name2 = ''.join([n if n.islower() else "_" + n.lower() for n in name])
while name2.startswith('_'): name2 = name2[1:]
result = ['visit_' + name, 'visit_' + name.lower(), 'visit_' + name2]
return result
def __get_envelop_method_names(self):
"""
Returns a list of two names `enter_XXX` and `leave_XXX`, where the `XXX` stands for the name of the class.
This is used inside the `visit`-method.
:return: A list with exactly two strings.
"""
name = self.__class__.__name__
if name.startswith("Ast"):
name = name[3:]
elif name.endswith("Node"):
name = name[:-4]
name = name.lower()
return ['enter_' + name, 'leave_' + name]
def visit(self, visitor):
"""
The visitor-object given as argument must provide at least one `visit_XXX`-method to be called by this method.
Possible names for the `visit_XXX`-method are given by `get_visitor_names()`. Override that method in order
to control which visitor-method is actually called.
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.
It is possible to provide, in addition to a `visit_XXX`-method, two methods `enter_XXX` and `leave_XXX`, which
are called right before, and right after, respectively, the `visit_XXX`-method itself is called. They do not
replace but supplement the `visit_XXX`-method.
:param visitor: An object with a `visit_XXX`-method.
:return: The result returned by the `visit_XXX`-method of the visitor.
"""
visit_children_first = getattr(visitor, '__visit_children_first__', False) is True
lm_method = getattr(visitor, 'set_current_line_number', None)
method_names = self.get_visitor_names() + ['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]
env_methods = [getattr(visitor, name, None) for name in self.__get_envelop_method_names()]
env_methods = [name for name in env_methods if name is not None]
if len(methods) == 0 and callable(visitor):
if visit_children_first:
self.visit_children(visitor)
return visitor(self)
elif len(methods) > 0:
if getattr(self, 'verbose', False) is True or getattr(visitor, 'verbose', False) is True:
print("calling {}".format(methods[0]))
if len(env_methods) == 2:
obj = self
if lm_method is not None and hasattr(self, 'lineno'):
lm_method(self.lineno)
env_methods[0](self)
try:
if visit_children_first:
self.visit_children(visitor)
if lm_method is not None and hasattr(self, 'lineno'):
lm_method(self.lineno)
result = methods[0](self)
if isinstance(result, self.__class__):
obj = result
finally:
env_methods[1](obj)
return result
else:
if visit_children_first:
self.visit_children(visitor)
if lm_method is not None and hasattr(self, 'lineno'):
lm_method(self.lineno)
return methods[0](self)
else:
raise RuntimeError("visitor '{}' has no visit-methods to call".format(type(visitor)))
def visit_children(self, visitor):
"""
Goes through all fields provided by the method `get_fields`, which are objects derived from `AstNode`.
For each such object, the `visit`-method (see above) is called.
:param visitor: An object with `visit_XXX`-methods to be called by the children of this node.
:return: A list with the values returned by the called `visit_XXX`-methods.
"""
result = []
for name in self.get_fields():
item = getattr(self, name, None)
if isinstance(item, AstNode) or type(item) in (list, tuple):
result.append(visitor.visit(item))
return result
def visit_attribute(self, visitor, attr_name:str, default=None):
"""
Sets an attribute on each node in the AST, based on the provided visitor (see `visit`-method above).
:param visitor: An object with `visit_XXX`-methods to be called.
:param attr_name: The name of the attribute to set, must be a string.
:return: The value of the attribute set.
"""
assert type(attr_name) is str
for name in self.get_fields():
item = getattr(self, name, default)
if isinstance(item, AstNode):
item.visit_attribute(visitor, attr_name)
elif hasattr(item, '__iter__'):
for node in item:
if isinstance(node, AstNode):
node.visit_attribute(visitor, attr_name)
result = self.visit(visitor)
result = result if result is not self else None
setattr(self, attr_name, result)
return result
def append(self, node):
"""
Append another node to this one. In most cases, this means that a new `AstBody` with two items is created,
i.e. `x.append(y)` -> `AstBody([x, y])`.
In case the current node is an `if`-node, the second node will be appended to both branches.
:param node: Another node to be appended to the current node.
:return: A node that contains both nodes.
"""
if node is not None:
return _cl(makeBody(self, node), self)
else:
return self
def equals(self, node):
try:
for attr in self.get_fields():
if attr in self._attributes: continue
attr_a = getattr(self, attr)
attr_b = getattr(node, attr)
if type(attr_a) in (list, tuple) and type(attr_b) in (list, tuple):
for a, b in zip(attr_a, attr_b):
if a != b:
return False
elif attr_a != attr_b:
return False
return True
except:
return False
def __eq__(self, other):
return self.equals(other) if isinstance(other, self.__class__) else False
def clone(self, **kwargs):
init_method = getattr(self, '__init__', None)
if init_method is not None:
args = { arg: getattr(self, arg, None) for arg in _inspect.getfullargspec(init_method).args if arg != 'self' }
for arg in args:
if arg in kwargs:
args[arg] = kwargs[arg]
result = self.__class__(**args)
else:
result = self.__class__()
fields = set(self.__dict__).difference(set(result.__dict__))
for field in fields:
setattr(result, field, getattr(self, field))
for key in kwargs:
setattr(result, key, kwargs[key])
return result
class Visitor(object):
"""
There is no strict need to derive a visitor or walker from this base class. It does, however, provide a
default implementation for `visit` as well as `visit_node`.
"""
def set_current_line_number(self, lineno:int):
if hasattr(self, 'current_lineno'):
self.current_lineno = lineno
def visit(self, ast):
if ast is None:
return None
elif type(ast) in (bool, complex, float, int, str):
return None
elif isinstance(ast, AstNode):
return ast.visit(self)
elif type(ast) is dict:
return { key: self.visit(ast[key]) for key in ast }
elif type(ast) is list:
return [self.visit(item) for item in ast]
elif type(ast) is tuple:
return tuple([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:AstNode):
node.visit_children(self)
return node
#######################################################################################################################
class Scope(object):
def __init__(self, prev, name:Optional[str]=None, lineno:Optional[int]=None):
self.prev = prev
self.name = name
self.lineno = lineno
self.bindings = {}
self.protected_names = set()
assert prev is None or isinstance(prev, Scope)
assert name is None or type(name) is str
assert lineno is None or type(lineno) is int
def define(self, name:str, value):
assert type(name) is str and str != '' and str != '_'
self.bindings[name] = value
def define_protected(self, name:str):
assert type(name) is str and str != '' and str != '_'
self.protected_names.add(name)
def resolve(self, name:str):
if name in self.protected_names:
return None
elif name in self.bindings:
return self.bindings[name]
elif self.prev is not None:
return self.prev.resolve(name)
else:
return None
def resolve_locally(self, name:str):
if name in self.protected_names:
return None
else:
return self.bindings.get(name, None)
def depth(self):
result = 1
p = self.prev
while p is not None:
result += 1
p = p.prev
return result
class ScopeContext(object):
"""
The `ScopeContext` is a thin layer used to support scoping in `with`-statements inside methods of
`ScopedVisitor`, i.e. `with create_scope(): do something`.
"""
def __init__(self, visitor):
self.visitor = visitor
def __enter__(self):
return self.visitor.scope
def __exit__(self, exc_type, exc_val, exc_tb):
self.visitor.leave_scope()
class ScopedVisitor(Visitor):
def __init__(self):
self.scope = Scope(None)
self.global_scope = self.scope
self.MAX_SCOPE_DEPTH = 100
def enter_scope(self, name:Optional[str]=None):
if self.scope.depth() >= self.MAX_SCOPE_DEPTH:
raise RuntimeError("exceeding max scope depth")
self.scope = Scope(self.scope, name)
def leave_scope(self):
self.scope = self.scope.prev
assert(self.scope is not None)
def create_scope(self, name:Optional[str]=None):
self.enter_scope(name)
return ScopeContext(self)
def define(self, name, value, *, globally:bool=False):
scope = self.global_scope if globally else self.scope
if type(name) is str:
scope.define(name, value)
elif type(name) is tuple:
if is_vector(value) and len(name) == len(value):
for n, v in zip(name, value):
scope.define(n, v)
else:
return False
return True
def protect(self, name):
if type(name) is str:
self.scope.define_protected(name)
elif type(name) is tuple:
for n in name:
self.protect(n)
def define_all(self, names:list, values:list, *, vararg:Optional[str]=None):
assert type(names) is list
assert type(values) is list
assert vararg is None or type(vararg) is str
for name, value in zip(names, values):
if isinstance(name, AstSymbol):
name = name.name
if type(name) is str:
self.define(name, value)
if vararg is not None:
self.define(str(vararg), makeVector(values[len(names):]) if len(values) > len(names) else [])
def resolve(self, name:str):
return self.scope.resolve(name)
def resolve_locally(self, name:str):
return self.scope.resolve_locally(name)
@property
def is_global_scope(self):
return self.scope.prev is None
#######################################################################################################################
class AstControl(AstNode):
pass
class AstLeaf(AstNode):
pass
class AstOperator(AstNode):
pass
#######################################################################################################################
class BodyContext(enum.Enum):
GLOBAL = 0
FUNCTION = 1
CONTROL = 2
#######################################################################################################################
class AstAttribute(AstNode):
def __init__(self, base:AstNode, attr:str):
self.base = base
self.attr = attr
assert isinstance(base, AstNode)
assert type(attr) is str
def __repr__(self):
return "{}.{}".format(repr(self.base), self.attr)
class AstBinary(AstOperator):
__binary_ops = {
'+': ('add', lambda x, y: x + y),
'-': ('sub', lambda x, y: x - y),
'*': ('mul', lambda x, y: x * y),
'/': ('div', lambda x, y: x / y),
'%': ('mod', lambda x, y: x % y),
'//': ('idiv', lambda x, y: x // y),
'**': ('pow', lambda x, y: x ** y),
'<<': ('shl', lambda x, y: x << y),
'>>': ('shr', lambda x, y: x >> y),
'&': ('bit_and', lambda x, y: x & y),
'|': ('bit_or', lambda x, y: x | y),
'^': ('bit-xor', lambda x, y: x ^ y),
'and': ('and', lambda x, y: x and y),
'or': ('or', lambda x, y: x or y),
}
def __init__(self, left:AstNode, op:str, right:AstNode):
self.left = left
self.op = op
self.right = right
assert isinstance(left, AstNode) and isinstance(right, AstNode)
assert op in self.__binary_ops
def __repr__(self):
return "({} {} {})".format(repr(self.left), self.op, repr(self.right))
def get_visitor_names(self):
name = 'visit_binary_' + self.op_name
return [name] + super(AstBinary, self).get_visitor_names()
@property
def op_function(self):
return self.__binary_ops[self.op][1]
@property
def op_name(self):
return self.__binary_ops[self.op][0]
def equals(self, node):
if self.op == node.op:
if self.left == node.left and self.right == node.right:
return True
elif self.op in ('+', '*', 'and', 'or') and self.left == node.right and self.right == node.left:
return True
return False
class AstBody(AstNode):
def __init__(self, items:Optional[list], context:BodyContext=None):
if items is None:
items = []
self.items = [item for item in items if item is not None]
self.context = context
assert type(self.items) is list
assert all([isinstance(item, AstNode) for item in self.items])
assert all([not isinstance(item, AstBody) for item in self.items]), self.items
def __getitem__(self, item):
return self.items[item]
def __len__(self):
return len(self.items)
def __repr__(self):
return "Body({})".format('; '.join([repr(item) for item in self.items]))
def append(self, node):
if len(self.items) > 0 and (isinstance(self.items[-1], AstBreak) or isinstance(self.items[-1], AstReturn)):
return self
elif node is not None:
return _cl(makeBody(self.items, node), self)
else:
return self
def equals(self, node):
if len(self.items) == len(node.items):
for i, j in zip(self.items, node.items):
if i != j:
return False
return True
else:
return False
@property
def is_empty(self):
return len(self.items) == 0
@property
def last_is_return(self):
if len(self.items) > 0:
return isinstance(self.items[-1], AstReturn)
else:
return False
@property
def non_empty(self):
return len(self.items) != 0
class AstBreak(AstNode):
def __repr__(self):
return "break"
def append(self, _):
return self
def equals(self, _):
return True
class AstCall(AstNode):
def __init__(self, function:AstNode, args:list, keywords:Optional[list]=None, is_builtin:bool=False):
if keywords is None:
keywords = []
self.function = function
self.args = args
self.keywords = keywords # type:list
self.is_builtin = is_builtin
assert isinstance(function, AstNode)
assert all([isinstance(arg, AstNode) for arg in args])
assert type(self.keywords) is list
assert all([type(keyword) is str for keyword in self.keywords])
assert type(self.is_builtin) is bool
def __repr__(self):
keywords = [''] * (len(self.args) - len(self.keywords)) + ['{}='.format(key) for key in self.keywords]
args = [repr(arg) for arg in self.args]
args = [a + b for a, b in zip(keywords, args)]
return "{}({})".format(repr(self.function), ', '.join(args))
def get_visitor_names(self):
name = self.function_name
if name is not None:
call_name = 'visit_call_' + name
for ch in ('+', '-', '.', '/', '*'):
call_name = call_name.replace(ch, '_')
result = [call_name]
if self.is_builtin:
builtin_name = 'visit_builtin_' + name.replace('.', '_')
result = [builtin_name] + result
mod_name = self.function_module
if mod_name is not None:
result.append('visit_call_{}_function'.format(mod_name))
return result + super().get_visitor_names()
else:
return super().get_visitor_names()
def get_position_of_arg(self, keyword:str, default:int=-1):
if keyword in self.keywords:
return self.pos_arg_count + self.keywords.index(keyword)
else:
return default
def get_keyword_arg_value(self, keyword:str, default=None):
if keyword in self.keywords:
i = self.keywords.index(keyword)
i += len(self.args) - len(self.keywords)
return self.args[i]
else:
return default
@property
def arg_count(self):
return len(self.args)
@property
def pos_arg_count(self):
return len(self.args) - len(self.keywords)
@property
def function_name(self):
if isinstance(self.function, AstSymbol):
return self.function.original_name
elif isinstance(self.function, AstAttribute):
if isinstance(self.function.base, AstSymbol):
return "{}.{}".format(self.function.base.original_name, self.function.attr)
else:
return None
else:
return None
@property
def function_module(self):
if isinstance(self.function, AstSymbol):
name = self.function.original_name
if '.' in name:
return name[:name.index('.')]
elif isinstance(self.function, AstAttribute):
if isinstance(self.function.base, AstSymbol):
return self.function.base.name
elif isinstance(self.function.base, AstNamespace):
return self.function.base.name
return None
@property
def has_keyword_args(self):
return len(self.keywords) > 0
def equals(self, node):
if self.function == node.function and len(self.args) == len(node.args) and \
len(self.keywords) == len(node.keywords):
for a, b in zip(self.args, node.args):
if a != b:
return False
for a, b in zip(self.keywords, node.keywords):
if a != b:
return False
return True
else:
return False
def add_keywords_to_args(self, args: list):
if len(self.keywords) > 0:
kw = [''] * (len(args) - len(self.keywords)) + [item+'=' for item in self.keywords]
return [a + b for a, b in zip(kw, args)]
return args
@property
def left(self):
if self.arg_count == 2:
return self.args[0]
else:
return None
@property
def right(self):
if self.arg_count == 2:
return self.args[1]
else:
return None
class AstCompare(AstOperator):
__cmp_ops = {
'==': ('eq', lambda x, y: x == y, '!='),
'!=': ('ne', lambda x, y: x != y, '=='),
'<': ('lt', lambda x, y: x < y, '>='),
'<=': ('le', lambda x, y: x <= y, '>'),
'>': ('gt', lambda x, y: x > y, '<='),
'>=': ('ge', lambda x, y: x >= y, '<'),
'is': ('is', lambda x, y: x is y, 'is not'),
'in': ('in', lambda x, y: x in y, 'not in'),
'is not': ('is_not', lambda x, y: x is not y, 'is'),
'not in': ('not_in', lambda x, y: x not in y, 'in'),
}
def __init__(self, left:AstNode, op:str, right:AstNode,
second_op:Optional[str]=None, second_right:Optional[AstNode]=None):
if op == '=': op = '=='
self.left = left
self.op = op
self.right = right
self.second_op = second_op
self.second_right = second_right
assert isinstance(left, AstNode)
assert isinstance(right, AstNode)
assert op in self.__cmp_ops
assert ((second_op is None and second_right is None) or
(second_op in self.__cmp_ops and isinstance(second_right, AstNode)))
def __repr__(self):
if self.second_op is not None:
return "({} {} {} {} {})".format(
repr(self.left), self.op, repr(self.right),
self.second_op, repr(self.second_right)
)
else:
return "({} {} {})".format(repr(self.left), self.op, repr(self.right))
def get_visitor_names(self):
if self.second_op is not None:
name = 'visit_ternary_' + self.op_name + '_' + self.op_name_2
else:
name = 'visit_binary_' + self.op_name
return [name] + super(AstCompare, self).get_visitor_names()
@property
def neg_op(self):
return self.__cmp_ops[self.op][2]
@property
def op_function(self):
return self.__cmp_ops[self.op][1]
@property
def op_name(self):
return self.__cmp_ops[self.op][0]
@property
def op_function_2(self):
return self.__cmp_ops[self.second_op][1] if self.second_op is not None else None
@property
def op_name_2(self):
return self.__cmp_ops[self.second_op][0] if self.second_op is not None else None
@property
def is_equality_const_test(self):
return self.op == '==' and self.second_op is None and (is_constant(self.left) or is_constant(self.right))
class AstDef(AstNode):
_attributes = {'col_offset', 'lineno', 'original_name'}
def __init__(self, name:str, value:AstNode, global_context:bool=True, original_name:Optional[str]=None):
self.name = name
self.value = value
self.global_context = global_context
self.original_name = name if original_name is None else original_name
assert type(name) is str
assert isinstance(value, AstNode)
assert type(global_context) is bool
def __repr__(self):
name = self.name
if self.global_context:
name = "def " + name
return "{} := {}".format(name, repr(self.value))
@property
def is_function_def(self):
return isinstance(self.value, AstFunction)
class AstDict(AstNode):
def __init__(self, items:dict):
self.items = items
assert type(items) is dict
assert all([type(key) in [bool, complex, float, int, str] and isinstance(self.items[key], AstNode)
for key in self.items])
def __repr__(self):
items = ["{}: {}".format(key, repr(self.items[key])) for key in self.items]
return "{" + (', '.join(items)) + "}"
def __len__(self):
return len(self.items)
def equals(self, node):
if len(self.items) == len(node.items):
for key in self.items:
if key not in node.items or self.items[key] != node.items[key]:
return False
return True
else:
return False
class AstFor(AstControl):
def __init__(self, target:str, source:AstNode, body:AstNode, original_target:Optional[str]=None):
self.target = target
self.source = source
self.body = body
self.original_target = target if original_target is None else original_target
assert type(target) is str
assert isinstance(source, AstNode)
assert isinstance(body, AstNode), body
def __repr__(self):
return "for {} in {}: ({})".format(self.target, repr(self.source), repr(self.body))
class AstFunction(AstNode):
def __init__(self, name:Optional[str], parameters:list, body:AstNode, *, vararg:Optional[str]=None,
defaults:Optional[list]=None, doc_string:Optional[str]=None, f_locals:Optional[set]=None):
if name is None:
name = '__lambda__'
if f_locals is None:
f_locals = set()
if defaults is None:
defaults = []
self.name = name
self.parameters = parameters
self.body = body
self.vararg = vararg
self.defaults = defaults
self.doc_string = doc_string
self.param_names = set(parameters + [vararg] if vararg is not None else parameters)
self.f_locals = f_locals
assert type(name) is str and name != ''
assert type(parameters) is list and all([type(p) is str for p in parameters])
assert isinstance(body, AstNode)
assert vararg is None or type(vararg) is str
assert type(defaults) is list and all([isinstance(item, AstNode) for item in defaults])
assert doc_string is None or type(doc_string) is str
assert type(f_locals) is set and all([type(n) is str for n in f_locals])
assert self.vararg is None or len(self.defaults) == 0
def __repr__(self):
params = self.parameters
if self.vararg is not None:
params.append('*' + self.vararg)
return "{}({}): ({})".format(self.name, ', '.join(params), repr(self.body))
def order_arguments(self, arguments: list, keywords: list):
parameters = self.parameters
arg_count = len(arguments)
param_count = len(parameters)
if len(keywords) == 0:
if arg_count == param_count or (arg_count > param_count and self.vararg is not None):
if self.vararg is not None:
result = arguments[:param_count]
if arg_count > param_count:
result.append(makeVector(arguments[param_count:]))
else:
result.append(makeVector([]))
return result
else:
return arguments
elif arg_count < param_count <= arg_count + len(self.defaults):
delta = param_count - arg_count
return arguments + self.defaults[-delta:]
else:
raise TypeError("{}() takes {} positional arguments but {} were given"
.format(self.name, param_count, arg_count))
else:
delta = arg_count - len(keywords)
result = [None] * param_count
for i in range(delta):
result[i] = arguments[i]
for i in range(len(keywords)):
key = keywords[i]
if key not in parameters:
raise TypeError("{}() got an unexpected keyword argument '{}'".format(self.name, key))
j = parameters.index(key)
if result[j] is None:
result[j] = arguments[delta + i]
else:
raise TypeError("{}() got multiple values for argument for '{}'".format(self.name, key))
if self.vararg is not None:
result.append(makeVector([]))
elif len(self.defaults) > 0:
delta = len(parameters) - len(self.defaults)
for i in range(len(self.defaults)):
if result[delta + i] is None:
result[delta + i] = self.defaults[i]
for key, item in zip(parameters, result):
if item is None:
raise TypeError("{}() missing a required positional argument: '{}'".format(self.name, key))
return result
class AstIf(AstControl):
def __init__(self, test:AstNode, if_node:AstNode, else_node:Optional[AstNode]=None, cond_name:Optional[str]=None):
if else_node is None:
else_node = AstValue(None)
self.test = test
self.if_node = if_node
self.else_node = else_node
self.cond_name = cond_name
assert isinstance(test, AstNode)
assert isinstance(if_node, AstNode)
assert isinstance(else_node, AstNode)
assert cond_name is None or type(cond_name) is str
def __repr__(self):
return "if {} then {} else {}".format(repr(self.test), repr(self.if_node), repr(self.else_node))
def append(self, node):
if node is not None:
if_node = self.if_node.append(node)
else_node = self.else_node.append(node) if self.else_node is not None else node
return _cl(AstIf(self.test, if_node, else_node), self)
else:
return self
@property
def has_elif(self):
return isinstance(self.else_node, AstIf)
@property
def has_else(self):
if isinstance(self.else_node, AstValue) and self.else_node.value is None:
return False
else:
return True
@property
def is_equality_test(self):
if isinstance(self.test, AstCompare):
return self.test.op == '==' and self.test.second_op is None
else:
return False
def cond_tuples(self):
result = []
current = self
while isinstance(current, AstIf):
result.append((current.test, current.if_node))
current = current.else_node
if current is not None:
result.append((AstValue(True), current))
return result
@classmethod
def from_cond_tuples(cls, cond):
if len(cond) == 0:
return makeBody([])
elif len(cond) == 1:
a, b = cond[0]
if is_boolean_true(a):
return b
else:
return AstIf(a, b)
else:
a, b = cond[0]
return AstIf(a, b, cls.from_cond_tuples(cond[1:]))
class AstImport(AstNode):
def __init__(self, module_name:str, imported_names:Optional[list]=None, alias:Optional[str]=None):
self.module_name = module_name
self.imported_names = imported_names
self.alias = alias
assert type(module_name) is str and module_name != ''
assert (imported_names is None or
(type(imported_names) is list and all([type(item) is str for item in imported_names])))
assert alias is None or (type(alias) is str and alias != '')
assert alias is None or (imported_names is None or len(imported_names) == 1)