-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathparser.py
executable file
·2450 lines (2221 loc) · 95.6 KB
/
parser.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
# Copyright (c) 2010-2017 Bo Lin
# Copyright (c) 2010-2017 Yanhong Annie Liu
# Copyright (c) 2010-2017 Stony Brook University
# Copyright (c) 2010-2017 The Research Foundation of SUNY
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
import builtins
from ast import *
from collections import abc
from da import common
from . import dast
from .utils import Namespace
from .utils import CompilerMessagePrinter
from .utils import MalformedStatementError
from .utils import ResolverException
from .utils import printe
from pprint import pprint
# DistAlgo keywords
KW_ENTRY_POINT = "main"
KW_PROCESS_DEF = "process"
KW_PROCESS_ENTRY_POINT = "run"
KW_CONFIG = "config"
KW_SETUP = "setup"
KW_START = "start"
KW_RECV_QUERY = "received"
KW_SENT_QUERY = "sent"
KW_RECV_EVENT = "receive"
KW_SENT_EVENT = "sent"
KW_MSG_PATTERN = "msg"
KW_EVENT_SOURCE = "from_"
KW_EVENT_DESTINATION = "to"
KW_EVENT_TIMESTAMP = "clk"
KW_EVENT_LABEL = "at"
KW_DECORATOR_LABEL = "labels"
KW_EXISTENTIAL_QUANT = "some"
KW_UNIVERSAL_QUANT = "each"
KW_AGGREGATE_SIZE = "len"
KW_AGGREGATE_MIN = "min"
KW_AGGREGATE_MAX = "max"
KW_AGGREGATE_SUM = "sum"
KW_AGGREGATE_PROD = "prod"
KW_COMP_SET = "setof"
KW_COMP_TUPLE = "tupleof"
KW_COMP_LIST = "listof"
KW_COMP_DICT = "dictof"
KW_COMP_MIN = "minof"
KW_COMP_MAX = "maxof"
KW_COMP_SUM = "sumof"
KW_COMP_LEN = "lenof"
KW_COMP_COUNT = "countof"
KW_COMP_PROD = "prodof"
KW_AWAIT = "await"
KW_AWAIT_TIMEOUT = "timeout"
KW_SEND = "send"
KW_SEND_TO = KW_EVENT_DESTINATION
KW_PRINT = "output"
KW_LEVEL = "level"
KW_SEP= "sep"
KW_SELF = "self"
KW_TRUE = "True"
KW_FALSE = "False"
KW_NULL = "None"
KW_SUCH_THAT = "has"
KW_RESET = "reset"
KW_INC_VERB = "_INC_"
exprDict = {
KW_COMP_SET: dast.SetCompExpr,
KW_COMP_LIST: dast.ListCompExpr,
KW_COMP_DICT: dast.DictCompExpr,
KW_COMP_TUPLE: dast.TupleCompExpr,
KW_COMP_MIN: dast.MinCompExpr,
KW_COMP_MAX: dast.MaxCompExpr,
KW_COMP_SUM: dast.SumCompExpr,
KW_COMP_PROD: dast.PrdCompExpr,
KW_COMP_LEN: dast.LenCompExpr,
KW_COMP_COUNT: dast.LenCompExpr
}
##########################
# Helper functions:
##########################
def is_setup_func(node):
"""Returns True if this node defines a function named 'setup'."""
return (isinstance(node, FunctionDef) and
node.name == KW_SETUP)
def is_process_class(node):
"""True if `node` is a process class.
A process class is a class whose bases contain the name $KW_PROCESS_DEF.
"""
if isinstance(node, ClassDef):
for b in node.bases:
if isinstance(b, Name) and b.id == KW_PROCESS_DEF:
return True
return False
def expr_check(names, minargs, maxargs, node,
keywords={}, optional_keywords={}):
"""Check a Call node against the requirements.
"""
if not (isinstance(node, Call) and
isinstance(node.func, Name) and
(((isinstance(names, abc.Set) or
isinstance(names, abc.Mapping)) and
node.func.id in names) or
node.func.id == names)):
return False
try:
if minargs is not None and len(node.args) < minargs:
raise MalformedStatementError("too few arguments.")
if maxargs is not None and len(node.args) > maxargs:
raise MalformedStatementError("too many arguments.")
if keywords is not None:
for kw in node.keywords:
if kw.arg in keywords:
keywords -= {kw.arg}
elif optional_keywords is not None and \
kw.arg not in optional_keywords:
raise MalformedStatementError(
"unrecognized keyword: '%s'." % kw.arg)
if len(keywords) > 0:
raise MalformedStatementError(
"missing required keywords: " + str(keywords))
except MalformedStatementError as e:
# Pre-format an error message for the common case:
e.node = node
e.name = node.func.id
e.msg = "malformed {stname} statement: {msg}".format(
stname=e.name, msg=e.reason)
raise e
return True
def kw_check(names, node):
if not isinstance(node, Name) or node.id not in names:
return False
return True
def is_await(node):
"""True if `node` is an await statement.
"""
return (expr_check(KW_AWAIT, 1, 1, node) or
isinstance(node, Await))
def extract_label(node):
"""Returns the label name specified in 'node', or None if 'node' is not a
label.
"""
if (isinstance(node, UnaryOp) and
isinstance(node.op, USub) and
isinstance(node.operand, UnaryOp) and
isinstance(node.operand.op, USub) and
isinstance(node.operand.operand, Name)):
return node.operand.operand.id
else:
return None
def daast_from_file(filename, args):
"""Generates DistAlgo AST from source file.
'filename' is the filename of source file. Optional argument 'args' is a
Namespace object containing the command line parameters for the compiler.
Returns the generated DistAlgo AST.
"""
try:
with open(filename, 'r') as infd:
global InputSize
src = infd.read()
InputSize = len(src)
return daast_from_str(src, filename, args)
except Exception as e:
print(type(e).__name__, ':', str(e), file=sys.stderr)
raise e
return None
def daast_from_str(src, filename='<str>', args=None):
"""Generates DistAlgo AST from source string.
'src' is the DistAlgo source string to parse. Optional argument 'filename'
specifies the filename that appears in error messages, defaults to
'<str>'. Optional argument 'args' is a Namespace object containing the
command line parameters for the compiler. Returns the generated DistAlgo
AST.
"""
try:
dt = Parser(filename, args)
rawast = parse(src, filename)
dt.visit(rawast)
sys.stderr.write("%s compiled with %d errors and %d warnings.\n" %
(filename, dt.errcnt, dt.warncnt))
if dt.errcnt == 0:
return dt.program
except SyntaxError as e:
sys.stderr.write("%s:%d:%d: SyntaxError: %s" % (e.filename, e.lineno,
e.offset, e.text))
return None
##########
# Operator mappings:
##########
NegatedOperators = {
NotEq : dast.EqOp,
IsNot : dast.IsOp,
NotIn : dast.InOp
}
OperatorMap = {
Add : dast.AddOp,
Sub : dast.SubOp,
Mult : dast.MultOp,
Div : dast.DivOp,
Mod : dast.ModOp,
Pow : dast.PowOp,
LShift : dast.LShiftOp,
RShift : dast.RShiftOp,
BitOr : dast.BitOrOp,
BitXor : dast.BitXorOp,
BitAnd : dast.BitAndOp,
FloorDiv : dast.FloorDivOp,
Eq : dast.EqOp,
NotEq: dast.NotEqOp,
Lt : dast.LtOp,
LtE : dast.LtEOp,
Gt : dast.GtOp,
GtE : dast.GtEOp,
Is : dast.IsOp,
IsNot : dast.IsNotOp,
In : dast.InOp,
NotIn : dast.NotInOp,
USub : dast.USubOp,
UAdd : dast.UAddOp,
Invert : dast.InvertOp,
And : dast.AndOp,
Or : dast.OrOp
}
# New matrix multiplication operator since 3.5:
if sys.version_info > (3, 5):
OperatorMap[MatMult] = dast.MatMultOp
# FIXME: is there a better way than hardcoding these?
KnownUpdateMethods = {
"add", "append", "extend", "update",
"insert", "reverse", "sort",
"delete", "remove", "pop", "clear", "discard"
}
ValidResetTypes = {"received", "sent", "Received", "Sent", ""}
ApiMethods = frozenset(common.api_registry.keys())
BuiltinMethods = frozenset(common.builtin_registry.keys())
InternalMethods = frozenset(common.internal_registry.keys())
PythonBuiltins = dir(builtins)
NodeProcName = "Node_"
AggregateMap = {
KW_AGGREGATE_MAX : dast.MaxExpr,
KW_AGGREGATE_MIN : dast.MinExpr,
KW_AGGREGATE_SIZE : dast.SizeExpr,
KW_AGGREGATE_SUM : dast.SumExpr,
# KW_AGGREGATE_PROD : dast.ProdExpr,
}
ComprehensionTypes = {KW_COMP_SET, KW_COMP_TUPLE, KW_COMP_DICT, KW_COMP_LIST,
KW_COMP_MAX, KW_COMP_MIN, KW_COMP_SUM, KW_COMP_LEN, KW_COMP_COUNT, KW_COMP_PROD}
EventKeywords = {KW_EVENT_DESTINATION, KW_EVENT_SOURCE, KW_EVENT_LABEL,
KW_EVENT_TIMESTAMP}
Quantifiers = {KW_UNIVERSAL_QUANT, KW_EXISTENTIAL_QUANT}
##########
# Name context types:
class NameContext:
def __init__(self, node, type=None):
self.node = node # The node containing this context
self.type = type # Optional, for type analysis
class Assignment(NameContext): pass
class Update(NameContext): pass
class Read(NameContext): pass
class IterRead(Read): pass
class FunCall(NameContext): pass
class Delete(NameContext): pass
class AttributeLookup(NameContext): pass
class SubscriptLookup(NameContext): pass
class PatternContext(NameContext): pass
class Existential(NameContext): pass
class Universal(NameContext): pass
##########
class PatternParser(NodeVisitor):
"""Parses a pattern.
"""
def __init__(self, parser, literal=False, local_only=False):
self._parser = parser
self.namescope = parser.current_scope
self.parent_node = parser.current_parent
self.current_query = parser.current_query
self.use_object_style = parser.get_option('enable_object_pattern',
default=False)
self.use_top_semantic = parser.get_option('use_top_semantic',
default=False)
self.literal = literal
self.local_only = local_only
def visit(self, node):
if isinstance(node, Name):
return self.visit_Name(node)
elif isinstance(node, Tuple):
return self.visit_Tuple(node)
elif isinstance(node, List):
return self.visit_List(node)
# Parse general expressions:
expr = self._parser.visit(node)
if isinstance(expr, dast.ConstantExpr):
return dast.ConstantPattern(self.parent_node, node, value=expr)
else:
return dast.BoundPattern(self.parent_node, node, value=expr)
def is_bound(self, name):
n = self.namescope.find_name(name)
if n is not None and self.current_query is not None:
if self.use_top_semantic:
return n in self.current_query.top_level_query.boundvars
else:
return n in self.current_query.boundvars
else:
return False
def is_free(self, name):
n = self.namescope.find_name(name)
if n is not None and self.current_query is not None:
if self.use_top_semantic:
return n in self.current_query.top_level_query.freevars
else:
return n in self.current_query.freevars
else:
return False
def visit_Name(self, node):
if self._parser.current_process is not None and \
node.id == KW_SELF:
return dast.ConstantPattern(
self.parent_node, node,
value=dast.SelfExpr(self.parent_node, node))
elif node.id == KW_TRUE:
return dast.ConstantPattern(
self.parent_node, node,
value=dast.TrueExpr(self.parent_node, node))
elif node.id == KW_FALSE:
return dast.ConstantPattern(
self.parent_node, node,
value=dast.FalseExpr(self.parent_node, node))
elif node.id == KW_NULL:
return dast.ConstantPattern(
self.parent_node, node,
value=dast.NoneExpr(self.parent_node, node))
elif self.literal:
name = node.id
n = self.namescope.find_name(name)
if n is None:
n = self.namescope.add_name(name)
pat = dast.BoundPattern(self.parent_node, node, value=n)
n.add_read(pat)
return pat
name = node.id
if name == "_":
# Wild card
return dast.FreePattern(self.parent_node, node)
elif name.startswith("_"):
# Bound variable:
name = node.id[1:]
n = self.namescope.find_name(name)
if n is None:
self._parser.warn(
("new variable '%s' introduced by bound pattern." % name),
node)
n = self.namescope.add_name(name)
pat = dast.BoundPattern(self.parent_node, node, value=n)
n.add_read(pat)
return pat
else:
# Could be free or bound:
name = node.id
if self.is_bound(name):
self._parser.debug("[PatternParser] reusing bound name " +
name, node)
n = self.namescope.find_name(name)
pat = dast.BoundPattern(self.parent_node, node, value=n)
n.add_read(pat)
else:
self._parser.debug("[PatternParser] free name " + name, node)
n = self.namescope.find_name(name, local=self.local_only)
if n is None:
# New name:
n = self.namescope.add_name(name)
pat = dast.FreePattern(self.parent_node, node, value=n)
n.add_assignment(self.parent_node)
else:
pat = dast.FreePattern(self.parent_node, node, value=n)
if self.is_free(name):
# Existing free var:
n.add_read(pat)
else:
n.add_assignment(self.parent_node)
return pat
def visit_Str(self, node):
return dast.ConstantPattern(
self.parent_node, node,
value=dast.ConstantExpr(self.parent_node, node, node.s))
def visit_Bytes(self, node):
return dast.ConstantPattern(
self.parent_node, node,
value=dast.ConstantExpr(self.parent_node, node, node.s))
def visit_Num(self, node):
return dast.ConstantPattern(
self.parent_node, node,
value=dast.ConstantExpr(self.parent_node, node, node.n))
def visit_Tuple(self, node):
return dast.TuplePattern(
self.parent_node, node,
value=[self.visit(e) for e in node.elts])
def visit_List(self, node):
return dast.ListPattern(
self.parent_node, node,
value=[self.visit(e) for e in node.elts])
def visit_Call(self, node):
if not self.use_object_style:
return self.generic_visit(node)
if not isinstance(node.func, Name): return None
elts = [dast.ConstantPattern(
self.parent_node, node,
value=dast.ConstantExpr(self.parent_node,
node.func,
value=node.func.id))]
for e in node.args:
elts.append(self.visit(e))
return dast.TuplePattern(self.parent_node, node,
value=elts)
class Pattern2Constant(NodeVisitor):
def __init__(self, parent):
super().__init__()
self.stack = [parent]
@property
def current_parent(self):
return self.stack[-1]
def visit_ConstantPattern(self, node):
expr = node.value.clone()
expr._parent = self.current_parent
return expr
def visit_BoundPattern(self, node):
return dast.NameExpr(node.parent, value=node.value)
def visit_FreePattern(self, node):
# This really shouldn't happen
mesg = "Can not convert FreePattern to constant!"
printe(mesg, node.lineno, node.col_offset)
return None
def visit_TuplePattern(self, node):
expr = dast.TupleExpr(self.current_parent)
self.stack.append(expr)
expr.subexprs = [self.visit(e) for e in node.value]
self.stack.pop()
if None in expr.subexprs:
expr = None
return expr
def visit_ListPattern(self, node):
expr = dast.ListExpr(self.current_parent)
self.stack.append(expr)
expr.subexprs = [self.visit(e) for e in node.value]
self.stack.pop()
if None in expr.subexprs:
expr = None
return expr
class PatternFinder(NodeVisitor):
def __init__(self):
self.found = False
# It's a pattern if it has bound variables:
def visit_Name(self, node):
if node.id.startswith("_"):
self.found = True
# It's also a pattern if it contains constants:
def visit_Constant(self, node):
self.found = True
visit_Num = visit_Constant
visit_Str = visit_Constant
visit_Bytes = visit_Constant
visit_NameConstant = visit_Constant
class Parser(NodeVisitor, CompilerMessagePrinter):
"""The main parser class.
"""
def __init__(self, filename="", options=None, execution_context=None,
_package=None, _parent=None):
# used in error messages:
CompilerMessagePrinter.__init__(self, filename, _parent=_parent)
# used to construct statement tree, also used for symbol table:
self.state_stack = []
# new statements are appended to this list:
self.current_block = None
self.current_context = None
self.current_label = None
# Allows temporarily overriding `current_process`:
self._dummy_process = None
self.program = execution_context
self.cmdline_args = options
self.module_args = Namespace()
from .symtab import Resolver
self.resolver = Resolver(filename, options,
_package if _package else options.module_name,
_parent=self)
def get_option(self, option, default=None):
if hasattr(self.cmdline_args, option):
return getattr(self.cmdline_args, option)
elif hasattr(self.module_args, option):
return getattr(self.module_args, option)
else:
return default
def push_state(self, node):
self.state_stack.append((node,
self.current_context,
self.current_label,
self.current_block))
def pop_state(self):
(_,
self.current_context,
self.current_label,
self.current_block) = self.state_stack.pop()
def is_in_setup(self):
if self.current_process is None:
return False
elif isinstance(self.current_scope, dast.Function):
return self.current_scope.name == "setup"
def enter_query(self):
pass
def leave_query(self, audit=False):
self.debug("Leaving query: " + str(self.current_query),
self.current_query)
if audit and self.get_option('use_top_semantic', default=False):
if self.current_parent is self.current_query:
self.audit_query(self.current_parent)
@property
def current_parent(self):
return self.state_stack[-1][0]
@property
def current_process(self):
if self._dummy_process is not None:
return self._dummy_process
for node, _, _, _ in reversed(self.state_stack):
if isinstance(node, dast.Process):
return node
return None
@property
def current_scope(self):
for node, _, _, _ in reversed(self.state_stack):
if isinstance(node, dast.NameScope):
return node
return None
@property
def current_query(self):
for node, _, _, _ in reversed(self.state_stack):
if isinstance(node, dast.QueryExpr):
return node
elif isinstance(node, dast.NameScope):
# A query can not span a namescope (e.g. lambda expression):
return None
return None
@property
def current_query_scope(self):
return self.current_query.scope \
if self.current_query is not None else None
@property
def current_loop(self):
for node, _, _, _ in reversed(self.state_stack):
if isinstance(node, dast.ArgumentsContainer) or \
isinstance(node, dast.ClassStmt):
break
elif isinstance(node, dast.LoopStmt):
return node
return None
def visit_Module(self, node):
dast.DistNode.reset_index()
self.parse_module_header(node)
self.program = dast.Program(None, ast=node)
self.program._compiler_options = self.module_args
# Populate global scope with Python builtins:
for name in PythonBuiltins:
self.program.add_name(name)
self.push_state(self.program)
self.current_block = self.program.body
self.current_context = Read(self.program)
self.body(node.body)
self.pop_state()
def visit_Interactive(self, node):
dast.DistNode.reset_index()
self.program = dast.InteractiveProgram(None, node)
# Populate global scope with Python builtins:
for name in PythonBuiltins:
self.program.add_name(name)
self.push_state(self.program)
contxtproc = dast.Process()
self.push_state(contxtproc)
# Helpers:
def parse_module_header(self, node):
assert isinstance(node, Module)
if not (len(node.body) > 0 and
isinstance(node.body[0], Expr) and
isinstance(node.body[0].value, Str)):
return
self.debug("parsing module header...")
opts = node.body[0].value.s.split()
for o in opts:
if o.startswith('--'):
attr = o[2:].replace('-', '_')
self.debug("setting module arg: " + attr, node.body[0])
setattr(self.module_args, attr, True)
else:
self.debug("option not recognized: " + o, node.body[0])
del node.body[0]
def parse_bases(self, node, clsobj):
"""Processes a ClassDef's bases list."""
bases = []
for b in node.bases:
if not (isinstance(b, Name) and b.id == KW_PROCESS_DEF):
self.current_context = Read(clsobj)
bases.append(self.visit(b))
if isinstance(clsobj, dast.Process):
# try to resolve the base classes:
for b in bases:
try:
pd = self.resolver.find_process_definiton(b)
clsobj.merge_scope(pd)
except ResolverException as e:
self.warn('unable to resolve base class spec, '
'compilation may be incomplete: {}.'
.format(e.reason), e.node if e.node else b)
return bases
def parse_pattern_expr(self, node, literal=False, local_only=False):
expr = self.create_expr(dast.PatternExpr, node)
pp = PatternParser(self, literal, local_only)
pattern = pp.visit(node)
if pattern is None:
self.error("invalid pattern", node)
self.pop_state()
return None
expr.pattern = pattern
self.pop_state()
return expr
def parse_decorators(self, node):
assert hasattr(node, 'decorator_list')
labels = set()
notlabels = set()
decorators = []
is_static = False
for exp in node.decorator_list:
if isinstance(exp, Call) and isinstance(exp.func, Name) and \
exp.func.id == KW_DECORATOR_LABEL:
for arg in exp.args:
l, negated = self.parse_label_spec(arg)
if negated:
notlabels |= l
else:
labels |= l
else:
if isinstance(exp, Name) and exp.id == 'staticmethod':
is_static = True
decorators.append(self.visit(exp))
return decorators, labels, notlabels, is_static
def parse_label_spec(self, expr):
negated = False
if (type(expr) is UnaryOp and
type(expr.operand) in {Set, Tuple, List}):
names = expr.operand.elts
negated = True
elif type(expr) in {Set, Tuple, List}:
names = expr.elts
else:
self.error("invalid label spec.", expr)
names = []
result = set()
for elt in names:
if type(elt) is not Name:
self.error("invalid label spec.", elt)
else:
result.add(elt.id)
return result, negated
def parse_event_handler(self, node):
if node.name == KW_RECV_EVENT:
eventtype = dast.ReceivedEvent
elif node.name == KW_SENT_EVENT:
eventtype = dast.SentEvent
else:
# Impossible
return None
extras = []
args = node.args
if len(args.defaults) < len(args.args):
extras.extend(args.args[:(len(args.args) - len(args.defaults))])
args.args = args.args[(len(args.args) - len(args.defaults)):]
if args.vararg:
extras.append(args.vararg)
if args.kwonlyargs:
extras.extend(args.kwonlyargs)
if args.kwarg:
extras.append(args.kwarg)
for node in extras:
self.error("Malformed event spec: unknown argument {!r}.".
format(node.arg), node)
events = []
labels = set()
notlabels = set()
self.enter_query()
for key, patexpr in zip(args.args, args.defaults):
if key.arg == KW_EVENT_LABEL:
ls, neg = self.parse_label_spec(patexpr)
if neg:
notlabels |= ls
else:
labels |= ls
continue
pat = self.parse_pattern_expr(patexpr, local_only=True)
if key.arg == KW_MSG_PATTERN:
events.append(dast.Event(self.current_process, ast=node,
event_type=eventtype, pattern=pat))
continue
if len(events) == 0:
self.error("invalid event spec: missing 'msg' argument.", node)
# Add a phony event so we can recover as much as possible:
events.append(dast.Event(self.current_process))
if key.arg == KW_EVENT_SOURCE:
events[-1].sources.append(pat)
elif key.arg == KW_EVENT_DESTINATION:
events[-1].destinations.append(pat)
elif key.arg == KW_EVENT_TIMESTAMP:
events[-1].timestamps.append(pat)
else:
self.warn("unrecognized event parameter '%s'" % key.arg, node)
self.leave_query()
return events, labels, notlabels
def body(self, statements):
"""Process a block of statements.
"""
for stmt in statements:
self.current_context = None
self.visit(stmt)
if self.current_label is not None:
# Create a noop statement to hold the last label:
self.create_stmt(dast.NoopStmt, statements[-1], nopush=True)
def proc_body(self, statements):
"""Process the body of a process definition.
Process bodies differs from normal ClassDef bodies in that the names
defined in this scope are visible to the whole process.
"""
for stmt in statements:
if (isinstance(stmt, FunctionDef) and stmt.name not in
{KW_RECV_EVENT, KW_SENT_EVENT}):
self.debug("Adding function %s to process scope." % stmt.name,
stmt)
self.current_scope.add_name(stmt.name)
elif isinstance(stmt, ClassDef):
self.debug("Adding class %s to process scope." % stmt.name,
stmt)
self.current_scope.add_name(stmt.name)
elif isinstance(stmt, Assign):
for expr in stmt.targets:
if isinstance(expr, Name):
self.debug(
"Adding variable %s to process scope." % expr.id,
stmt)
self.current_scope.add_name(expr.id)
elif isinstance(stmt, AugAssign):
if isinstance(target, Name):
self.current_scope.add_name(target.id)
for stmt in statements:
self.visit(stmt)
if self.current_label is not None:
# Create a noop statement to hold the last label:
self.create_stmt(dast.NoopStmt, statements[-1], nopush=True)
def signature(self, node):
"""Process the argument lists."""
assert isinstance(self.current_parent, dast.ArgumentsContainer)
padding = len(node.args) - len(node.defaults)
container = self.current_parent.args
for arg in node.args[:padding]:
if arg.annotation is not None:
annotation = self.visit(arg.annotation)
container.add_arg(arg.arg, annotation)
else:
container.add_arg(arg.arg)
for arg, val in zip(node.args[padding:], node.defaults):
if arg.annotation is not None:
annotation = self.visit(arg.annotation)
container.add_defaultarg(arg.arg, self.visit(val), annotation)
else:
container.add_defaultarg(arg.arg, self.visit(val))
if node.vararg is not None:
# Python 3.4 compatibility:
if type(node.vararg) is str:
container.add_vararg(node.vararg)
else:
if node.vararg.annotation is not None:
annotation = self.visit(node.vararg.annotation)
container.add_vararg(node.vararg.arg, annotation)
else:
container.add_vararg(node.vararg.arg)
if node.kwarg is not None:
# Python 3.4 compatibility:
if type(node.kwarg) is str:
container.add_kwarg(node.kwarg)
else:
if node.kwarg.annotation is not None:
annotation = self.visit(node.kwarg.annotation)
container.add_kwarg(node.kwarg.arg, annotation)
else:
container.add_kwarg(node.kwarg.arg)
for kwarg, val in zip(node.kwonlyargs, node.kw_defaults):
if val is not None:
val = self.visit(val)
if kwarg.annotation is not None:
annotation = self.visit(kwarg.annotation)
container.add_kwonlyarg(kwarg.arg, val, annotation)
else:
container.add_kwonlyarg(kwarg.arg, val)
# Top-level blocks:
def visit_ClassDef(self, node):
if is_process_class(node):
if type(self.current_parent) is not dast.Program:
self.error("Process definition must be at top level.", node)
initfun = None
bodyidx = None
for idx, s in enumerate(node.body):
if is_setup_func(s):
if initfun is None:
initfun = s
bodyidx = idx
else:
self.error("Duplicate setup() definition.", s)
if initfun is None:
self.warn("Process missing 'setup()' definition.", node)
n = self.current_scope.add_name(node.name)
proc = dast.Process(self.current_parent, node, name=node.name)
n.add_assignment(proc, proc)
proc.decorators, _, _, _ = self.parse_decorators(node)
self.push_state(proc)
self.program.processes.append(proc)
self.program.body.append(proc)
proc.bases = self.parse_bases(node, proc)
if initfun is not None:
self.signature(initfun.args)
if proc.args.kwarg is not None:
self.error("'setup()' can not have keyword argument.",
initfun)
self.current_block = proc.body
if bodyidx is not None:
# setup() has to be parsed first:
self.proc_body([node.body[bodyidx]] +
node.body[:bodyidx] + node.body[(bodyidx+1):])
else:
self.proc_body(node.body)
dbgstr = ["Process ", proc.name, " has names: "]
for n in proc._names.values():
dbgstr.append("%s: %s; " % (n, str(n.get_typectx())))
self.debug("".join(dbgstr))
self.pop_state()
if proc.entry_point is None:
self.warn("Process %s missing '%s()' method." %
(proc.name, KW_PROCESS_ENTRY_POINT), node)
else:
clsobj = dast.ClassStmt(self.current_parent, node, name=node.name)
if self.current_block is None or self.current_parent is None:
self.error("Statement not allowed in this context.", ast)
else:
self.current_block.append(clsobj)
n = self.current_scope.add_name(node.name)
n.add_assignment(clsobj, clsobj)
clsobj.decorators, _, _, _ = self.parse_decorators(node)
self.push_state(clsobj)
clsobj.bases = self.parse_bases(node, clsobj)
self.current_block = clsobj.body
self.body(node.body)
dbgstr = ["Class ", clsobj.name, " has names: "]
for n in clsobj._names.values():
dbgstr.append("%s: %s; " % (n, str(n.get_typectx())))
self.debug("".join(dbgstr))
self.pop_state()
def visit_AsyncFunctionDef(self, node):
self.error('Python async functions are not supported!', node)
def visit_FunctionDef(self, node):
if (self.current_process is None or
node.name not in {KW_SENT_EVENT, KW_RECV_EVENT}):
# This is a normal method
if self.current_parent is self.current_process:
# Check for name conflict with internal methods:
if node.name in InternalMethods:
self.error("Function name %r conflicts with DistAlgo "
"internals." % node.name, node)
n = self.current_scope.add_name(node.name)
s = self.create_stmt(dast.Function, node,
params={"name" : node.name})
n.add_assignment(s, s)
# Ignore the label decorators:
s.decorators, _, _, is_static = self.parse_decorators(node)
s.process = self.current_process