forked from lanl/coNCePTuaL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ncptl_parser.py
executable file
·1850 lines (1642 loc) · 74 KB
/
ncptl_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
########################################################################
#
# Parser module for the coNCePTuaL language
#
# By Scott Pakin <[email protected]>
#
# ----------------------------------------------------------------------
#
#
# Copyright (C) 2015, Los Alamos National Security, LLC
# All rights reserved.
#
# Copyright (2015). Los Alamos National Security, LLC. This software
# was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by
# Los Alamos National Security, LLC (LANS) for the U.S. Department
# of Energy. The U.S. Government has rights to use, reproduce,
# and distribute this software. NEITHER THE GOVERNMENT NOR LANS
# MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
# FOR THE USE OF THIS SOFTWARE. If software is modified to produce
# derivative works, such modified software should be clearly marked,
# so as not to confuse it with the version available from LANL.
#
# Additionally, redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the
# following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of Los Alamos National Security, LLC, Los Alamos
# National Laboratory, the U.S. Government, nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY LANS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LANS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
########################################################################
import sys
import os
import string
import re
import types
import copy
import lex
import yacc
from ncptl_ast import AST
from ncptl_token import Token
from ncptl_error import NCPTL_Error
from ncptl_config import ncptl_config
from ncptl_lexer import NCPTL_Lexer
try:
from java.security import AccessControlException
except ImportError:
class AccessControlException(Exception):
pass
# Define the name of the parse table to generate.
_tabmodule = "ncptl_parse_table"
class NCPTL_Parser:
language_version = "1.5"
def __init__(self, lexer):
"Initialize the coNCePTuaL parser."
self.lexer = lexer
self.tokens = lexer.tokens
self._opname = {'/\\' : 'op_land',
'\\/' : 'op_lor',
'=' : 'op_eq',
'<' : 'op_lt',
'>' : 'op_gt',
'<=' : 'op_le',
'>=' : 'op_ge',
'<>' : 'op_ne',
'DIVIDES' : 'op_divides',
'+' : 'op_plus',
'-' : 'op_minus',
'|' : 'op_or',
'XOR' : 'op_xor',
'**' : 'op_power',
'*' : 'op_mult',
'/' : 'op_div',
'MOD' : 'op_mod',
'>>' : 'op_shr',
'<<' : 'op_shl',
'&' : 'op_and',
'u+' : 'op_pos',
'u-' : 'op_neg',
'uNOT' : 'op_not'}
self.precedence = (tuple(['nonassoc'] + self.tokens),)
self.parser_list = {}
def parsetokens(self, tokenlist, filesource='<stdin>', start="program", write_tables=0):
"Parse a list of tokens into an AST."
self.tokenlist = tokenlist
self.tokidx = 0
self.errmsg = NCPTL_Error(filesource)
if not write_tables:
# Suppress "yacc: Symbol '...' is unreachable" messages.
orig_stderr = sys.stderr
try:
sys.stderr = open(ncptl_config["NULL_DEVICE_NAME"][1:-1], "w")
except (IOError, AccessControlException):
# We were built under one operating system but are
# running under a different operating system. (We
# might be running as a Java program.) Alternatively,
# we might be running in a sandbox with limited file
# access.
pass
try:
parser = self.parser_list[start]
except KeyError:
parser = yacc.yacc(module=self, start=start,
debug=0, tabmodule=_tabmodule,
write_tables=write_tables,
outputdir=os.path.dirname(__import__(self.__module__).__file__))
self.parser_list[start] = parser
if not write_tables:
# Restore the stderr filehandle.
if sys.stderr != orig_stderr:
sys.stderr.close()
sys.stderr = orig_stderr
return parser.parse(lexer=self)
def p_error(self, lextoken):
try:
token = self._lextoken2token(lextoken)
except AttributeError:
# We might have failed trying to parse an empty token list.
token = Token(type="", attr="", lineno=1)
self.errmsg.error_parse(token.printable, token.lineno, token.lineno)
def token(self):
"Return the next token in the list."
try:
next_token = self.tokenlist[self.tokidx]
self.tokidx = self.tokidx + 1
return next_token
except IndexError:
return None
def _lextoken2token(self, lextoken):
"Convert a PLY LexToken object to a coNCePTuaL Token object."
try:
if type(lextoken.value) not in (types.ListType, types.TupleType):
raise TypeError
printable = lextoken.value[1]
attr = lextoken.value[0]
except (TypeError, IndexError):
printable = lextoken.value
attr = lextoken.value
return Token(lineno=lextoken.lineno,
type=lextoken.type,
attr=attr,
printable=printable)
def _token2ast(self, token, left=None, right=None, kids=None):
"Convert a token to an AST."
if not kids:
kids = []
return AST(type=token, left=left, right=right, kids=kids)
def _lextoken2ast(self, lextoken, left=None, right=None, kids=None):
"Convert a token to an AST."
token = self._lextoken2token(lextoken)
return self._token2ast(token, left=left, right=right, kids=kids)
def _str2ast(self, str, lineno=-1, lineno0=-1, lineno1=-1,
attr=None, left=None, right=None, kids=None, printable=""):
"Convert a string into an AST."
dummyToken = Token(type=str, attr=attr, lineno=lineno)
dummyToken.printable = printable
if lineno0 != -1:
dummyToken.lineno0 = lineno0
if lineno1 != -1:
dummyToken.lineno1 = lineno1
if not kids:
kids = []
return AST(type=dummyToken, left=left, right=right, kids=kids)
def _wrapAST(self, typestr, args, kidofs=None, attr=None, assign0state=1,
source_task=None, target_tasks=None):
"Wrap args[kidofs] in an AST of a given type."
# Determine the subset of args to use and the corresponding
# line numbers.
if kidofs == None:
kidofs = range(1, len(args.slice))
else:
kidofs.sort()
if kidofs == []:
lineno0, lineno1 = args.linespan(0)
else:
lineno0, lineno1 = self._linespan(args, first=kidofs[0], last=kidofs[-1])
# Create new ASTs for source and target tasks, if specified.
args_copy = args
if source_task != None:
args_copy[source_task] = self._make_source_task(args, source_task)
if target_tasks != None:
args_copy[target_tasks] = self._make_target_tasks(args, target_tasks)
# Create a new AST.
newAST = self._str2ast(typestr,
lineno0=lineno0, lineno1=lineno1,
kids=filter(lambda k: hasattr(k, "attr"),
map(lambda o, args_copy=args_copy: args_copy[o], kidofs)),
attr=attr)
# Assign extra state to the AST and return it.
if assign0state:
self._assign0state(args_copy, ast=newAST, kidofs=kidofs)
return newAST
def _wrapAST_twice(self, typestr1, typestr2, args, kidofs=None, attr=None,
assign0state=1, source_task=None, target_tasks=None):
"""
Wrap args[kidofs] in an AST of a given type and wrap that
in an AST of a second type.
"""
innerAST = self._wrapAST(typestr2, args, kidofs, attr, assign0state,
source_task, target_tasks)
outerAST = self._wrapAST(typestr1, args, kidofs, None, assign0state)
outerAST.kids = [innerAST]
return outerAST
def _hoist_buffer_offset(self, message_spec):
"Move a buffer_offset from a child of buffer_number to a child of message_spec."
buffer_offset = message_spec.kids[6].kids[0]
if buffer_offset.type != "buffer_offset":
self.errmsg.error_internal("Expected buffer_offset; found %s" % buffer_offset.type)
del message_spec.kids[6].kids[0]
message_spec.kids.insert(6, buffer_offset)
def _apply2attr(self, func, astlist):
"Apply a function to the (unique) leaf's attribute."
if len(astlist.kids) == 0:
# Leaf
astlist.attr = func(astlist.attr)
elif len(astlist.kids) == 1:
# Unique child
self._apply2attr(func, astlist.kids[0])
else:
raise TypeError, "leaf is not unique"
def _linespan(self, args, first=1, last=None):
"""
Return the first line number of the first argument and
the last line number of the last argument.
"""
if last == None:
last = len(args.slice) - 1
lineno0, not_used = args.linespan(first)
not_used, lineno1 = args.linespan(last)
return (lineno0, lineno1)
def _assign0state(self, args, ast=None, kidofs=None):
"Assign line numbers to args[0] and introduce an is_empty attribute."
# Determine the subset of args[] that we care about
if kidofs == None:
numargs = len(args.slice)
if numargs == 1:
kidofs = []
elif numargs == 2:
kidofs = [1]
else:
kidofs = range(1, numargs)
# Assign empty status and line numbers. We set lineno0 to the
# smallest nonzero line number encountered and lineno1 to the
# largest nonzero line number encountered.
if ast == None:
ast = args[0]
ast.is_empty = int(len(args.slice) == 1)
if ast.is_empty:
ast.lineno0, ast.lineno1 = 0, 0
minlineno0, maxlineno1 = sys.maxint, 0
for argnum in kidofs:
try:
# AST
lineno0, lineno1 = args[argnum].lineno0, args[argnum].lineno1
except AttributeError:
# LexToken
lineno0 = args.slice[argnum].lineno
lineno1 = lineno0
if lineno0 != 0 and minlineno0 > lineno0:
minlineno0 = lineno0
if lineno1 != 0 and maxlineno1 < lineno1:
maxlineno1 = lineno1
if minlineno0 == sys.maxint:
minlineno0 = 0
ast.lineno0, ast.lineno1 = minlineno0, maxlineno1
# Assign printable text to the AST.
printable = []
max_text_len = 2**30 # Truncate strings after this many characters.
for argnum in kidofs:
arg = args[argnum]
if isinstance(arg, AST):
# AST
if hasattr(arg, "printable"):
printable.append(arg.printable)
else:
printable_list = map(lambda k: k.printable, arg.kids)
kidprintable = string.join(printable_list, "")
arg.printable = kidprintable
printable.append(kidprintable)
elif isinstance(arg, str):
# Token (string)
if arg in [".", ","] and argnum > 0:
# As a special case, don't put a space before "." or ",".
printable[-1] = printable[-1] + arg
else:
printable.append(arg)
elif isinstance(arg, tuple):
# Token (integer)
printable.append(arg[-1])
else:
self.errmsg.error_internal('Unexpected argument type "%s"' % str(type(arg)))
complete_text = string.join(filter(lambda s: s != "", printable), " ")
complete_text = string.replace(string.replace(complete_text, "( ", "("),
" )", ")")
if len(complete_text) > max_text_len:
complete_text = complete_text[:max_text_len] + " ..."
ast.printable = complete_text
def _make_source_task(self, args, argnum):
"Validate a source-style task_expr and return a source_task AST."
ast = args[argnum]
if ast.type != "task_expr":
self.errmsg.error_internal('Expected an AST of type "task_expr" but found "%s"' % ast.type)
return self._wrapAST("source_task", args, kidofs=[argnum])
def _make_target_tasks(self, args, argnum):
"Validate a target-style task_expr and return a target_tasks AST."
ast = args[argnum]
if ast.type != "task_expr":
self.errmsg.error_internal('Expected an AST of type "task_expr" but found "%s"' % ast.type)
return self._wrapAST("target_tasks", args, kidofs=[argnum])
def _dump_grammar(self):
"Output the complete grammar in a format suitable for the coNCePTuaL GUI."
# Store all of the main grammar rules.
rulelist = []
allfuncs = self.__class__.__dict__
for funcname in allfuncs.keys():
if funcname[:2] != "p_" or funcname == "p_error":
continue
rule = string.strip(allfuncs[funcname].__doc__)
(lhs, all_rhs) = string.split(rule, None, 1)
for sep_rhs in string.split(all_rhs, "\n"):
try:
# Right-hand side is nonempty.
(sep, rhs) = string.split(sep_rhs, None, 1)
rulelist.append("%s ::= %s" % (lhs, rhs))
except:
# Right-hand side is empty.
rulelist.append("%s ::=" % lhs)
# Store all of the rules that map to literal symbol sequences.
alltoks = self.lexer.__class__.__dict__
for tokname in alltoks.keys():
if tokname[:2] != "t_":
continue
try:
# String
rhs = re.sub(r'\\(.)', r'\1', string.strip(alltoks[tokname]))
rulelist.append("%s ::= %s" % (tokname[2:], rhs))
except AttributeError:
# Function
pass
# Output the sorted list of rules.
rulelist.sort()
for rule in rulelist:
print rule
#---------------------------#
# Start rules (and helpers) #
#---------------------------#
def p_program_1(self, args):
'''
program :
| header_decl_list
'''
args[0] = self._wrapAST("program", args)
if args[0].lineno0 == 0:
# Prevent the semantic analyzer from complaining about
# empty programs.
args[0].lineno0 = 1
args[0].lineno1 = 1
def p_program_2(self, args):
'''
program : top_level_stmt_list
| header_decl_list top_level_stmt_list
'''
args[0] = self._wrapAST("program", args)
def p_top_level_stmt_list_1(self, args):
'''
top_level_stmt_list : top_level_stmt
| top_level_stmt period
'''
args[0] = self._wrapAST("top_level_stmt_list", args, attr=1L)
def p_top_level_stmt_list_2(self, args):
'''
top_level_stmt_list : top_level_stmt top_level_stmt_list
| top_level_stmt period top_level_stmt_list
'''
numentries = args[len(args)-1].attr + 1L
args[len(args)-1].attr = None
args[0] = self._str2ast("top_level_stmt_list", attr=numentries,
kids=[args[1]] + args[len(args)-1].kids)
self._assign0state(args)
#---------------------#
# Header declarations #
#---------------------#
def p_header_decl_list_1(self, args):
'''
header_decl_list : header_decl
| header_decl period
'''
args[0] = self._wrapAST("header_decl_list", args, attr=1L)
def p_header_decl_list_2(self, args):
'''
header_decl_list : header_decl header_decl_list
| header_decl period header_decl_list
'''
numentries = args[len(args)-1].attr + 1L
args[len(args)-1].attr = None
args[0] = self._str2ast("header_decl_list", attr=numentries,
kids=[args[1]] + args[len(args)-1].kids)
self._assign0state(args)
def p_header_decl(self, args):
'''
header_decl : param_decl
| version_decl
| backend_decl
'''
args[0] = self._wrapAST("header_decl", args)
def p_param_decl(self, args):
' param_decl : ident ARE string AND COMES FROM string OR string WITH DEFAULT expr '
args[0] = self._wrapAST("param_decl", args)
def p_version_decl(self, args):
' version_decl : REQUIRE LANGUAGE VERSION string '
requested_version = args[4].attr
if requested_version != self.language_version:
self.errmsg.warning('language version "%s" was requested but only version "%s" is supported' %
(requested_version, self.language_version),
args[4].lineno0, args[4].lineno1)
args[0] = self._wrapAST("version_decl", args,
attr=[requested_version, self.language_version])
def p_backend_decl(self, args):
' backend_decl : THE BACKEND DECLARES string '
args[0] = self._wrapAST("backend_decl", args)
#------------#
# Statements #
#------------#
def p_top_level_stmt(self, args):
' top_level_stmt : simple_stmt_list '
args[0] = self._wrapAST("top_level_stmt", args)
def p_simple_stmt_list_1(self, args):
' simple_stmt_list : simple_stmt '
args[0] = self._wrapAST("simple_stmt_list", args, attr=1L)
def p_simple_stmt_list_2(self, args):
' simple_stmt_list : simple_stmt THEN simple_stmt_list '
numentries = args[3].attr + 1L
args[3].attr = None
args[0] = self._str2ast("simple_stmt_list", attr=numentries,
kids=[args[1]] + args[3].kids)
self._assign0state(args)
def p_simple_stmt_1(self, args):
'''
simple_stmt : send_stmt
| mcast_stmt
| receive_stmt
| delay_stmt
| wait_stmt
| sync_stmt
| touch_stmt
| touch_buffer_stmt
| log_stmt
| log_flush_stmt
| reset_stmt
| store_stmt
| restore_stmt
| assert_stmt
| output_stmt
| backend_stmt
| processor_stmt
| reduce_stmt
'''
args[0] = self._wrapAST("simple_stmt", args)
def p_simple_stmt_2(self, args):
' simple_stmt : FOR EACH ident IN range_list simple_stmt '
args[0] = self._wrapAST_twice("simple_stmt", "for_each", args)
def p_simple_stmt_3(self, args):
'''
simple_stmt : FOR expr REPETITIONS simple_stmt
| FOR expr REPETITIONS PLUS expr WARMUP REPETITIONS simple_stmt
| FOR expr REPETITIONS PLUS expr WARMUP REPETITIONS AND AN SYNCHRONIZATION simple_stmt
'''
if len(args.slice) == 12:
attr = "synchronized"
else:
attr = ""
args[0] = self._wrapAST_twice("simple_stmt", "for_count", args, attr=attr)
def p_simple_stmt_4(self, args):
'''
simple_stmt : FOR expr time_unit simple_stmt
| FOR expr time_unit PLUS expr WARMUP time_unit simple_stmt
| FOR expr time_unit PLUS expr WARMUP time_unit AND AN SYNCHRONIZATION simple_stmt
'''
if len(args.slice) == 12:
attr = "synchronized"
else:
attr = ""
args[0] = self._wrapAST_twice("simple_stmt", "for_time", args, attr=attr)
def p_simple_stmt_5(self, args):
' simple_stmt : LET let_binding_list WHILE simple_stmt '
args[0] = self._wrapAST_twice("simple_stmt", "let_stmt", args)
def p_simple_stmt_6(self, args):
' simple_stmt : lbrace simple_stmt_list rbrace '
args[0] = self._wrapAST("simple_stmt", args)
def p_simple_stmt_7(self, args):
' simple_stmt : lbrace rbrace '
args[0] = self._wrapAST("empty_stmt", args)
def p_simple_stmt_8(self, args):
'''
simple_stmt : IF rel_expr THEN simple_stmt
| IF rel_expr THEN simple_stmt OTHERWISE simple_stmt
'''
args[0] = self._wrapAST_twice("simple_stmt", "if_stmt", args)
def p_send_stmt_1(self, args):
' send_stmt : task_expr opt_async SENDS message_spec TO opt_unsusp task_expr '
# To simplify argument processing, assign a name to each argument.
source_arg = self._make_source_task(args, 1)
async_arg = args[2]
msg_spec_arg = args[4]
unsusp_arg = args[6]
target_arg = self._make_target_tasks(args, 7)
# Construct a list of send attributes.
attributes = []
async_lineno = args.lineno(3)
if async_arg.attr:
attributes.append("asynchronously")
async_lineno = async_arg.lineno0
unsusp_lineno = target_arg.lineno0
if unsusp_arg.attr:
attributes.append("unsuspecting")
unsusp_lineno = unsusp_arg.lineno1
attrAST = self._str2ast("send_attrs", attr=attributes,
lineno0=async_lineno, lineno1=unsusp_lineno)
attrAST.printable = string.join(filter(lambda s: s != "",
[async_arg.printable, unsusp_arg.printable]),
" ... ")
# Convert a message_spec into a recv_message_spec.
recv_attrAST = copy.deepcopy(attrAST)
recv_attrAST.type = "receive_attrs"
recv_message_spec = copy.deepcopy(msg_spec_arg)
recv_message_spec.kids[7].type = "recv_buffer_number"
if recv_message_spec.kids[7].attr == "from":
recv_message_spec.kids[7].attr = "into"
# Create and return an AST with all the information needed to
# send and receive a set of messages.
args[0] = self._str2ast("send_stmt",
kids=[source_arg, msg_spec_arg, attrAST,
target_arg, recv_message_spec, recv_attrAST])
self._assign0state(args)
def p_send_stmt_2(self, args):
' send_stmt : task_expr opt_async SENDS message_spec TO opt_unsusp task_expr WHO RECEIVES THEM recv_message_spec '
# To simplify argument processing, assign a name to each argument.
source_arg = self._make_source_task(args, 1)
async_arg = args[2]
msg_spec_arg = args[4]
opt_unsusp_arg = args[6]
target_arg = self._make_target_tasks(args, 7)
recv_msg_spec_arg = args[11]
if not opt_unsusp_arg.is_empty:
# The only reason we included opt_unsusp above is to
# appease the SLR parser.
self.errmsg.error_parse("unsuspecting",
opt_unsusp_arg.lineno0, opt_unsusp_arg.lineno1)
# Construct a list of send attributes.
attributes = []
async_lineno = args.lineno(3)
if async_arg.attr:
attributes.append("asynchronously")
async_lineno = async_arg.lineno0
attrAST = self._str2ast("send_attrs", attr=attributes,
lineno0=async_lineno, lineno1=args.lineno(5))
attrAST.printable = async_arg.printable
# Complain if *all* optional arguments were omitted.
no_arguments = 1
for child in recv_msg_spec_arg.kids:
if not child.is_empty:
no_arguments = 0
break
if no_arguments:
self.errmsg.error_parse(args.slice[10].value, args.lineno(10), args.lineno(10))
# The receiver receives the message(s) with different
# attributes from what the sender uses to send them.
recv_info = recv_msg_spec_arg.kids
recv_message_spec = copy.deepcopy(recv_msg_spec_arg)
recv_message_spec.type = "message_spec"
del recv_message_spec.kids[0]
recv_message_spec.kids[0] = copy.deepcopy(msg_spec_arg.kids[0])
recv_message_spec.kids.insert(2, copy.deepcopy(msg_spec_arg.kids[2]))
# Overwrite all fabricated attributes with the sender's version.
for arg in range(0, len(recv_info)):
if recv_info[arg].is_fabricated:
recv_message_spec.kids[arg] = copy.deepcopy(msg_spec_arg.kids[arg])
recv_message_spec.kids[7].type = "recv_buffer_number"
if recv_info[0].is_fabricated:
# Copy the sender's attributes.
recv_attributes = attributes
elif recv_info[0].attr:
recv_attributes = ["asynchronously"]
else:
recv_attributes = []
if recv_message_spec.attr == -1:
# Copy the misalignment flag from the sender.
recv_message_spec.attr = msg_spec_arg.attr
recv_attrAST = self._str2ast("receive_attrs", attr=recv_attributes,
lineno0=recv_msg_spec_arg.lineno0,
lineno1=recv_msg_spec_arg.lineno1)
recv_attrAST.printable = args[11].printable
# Create and return an AST with all the information needed to
# send and receive a set of messages.
args[0] = self._str2ast("send_stmt",
kids=[source_arg, msg_spec_arg, attrAST,
target_arg, recv_message_spec, recv_attrAST])
self._assign0state(args)
def p_mcast_stmt(self, args):
' mcast_stmt : task_expr opt_async MULTICASTS message_spec TO task_expr '
sourceAST = self._make_source_task(args, 1)
if args[2].attr:
attrAST = self._wrapAST("send_attrs", args,
attr=["asynchronously"], kidofs=[2])
else:
attrAST = self._wrapAST("send_attrs", args, attr=[], kidofs=[])
targetAST = self._make_target_tasks(args, 6)
args[0] = self._str2ast("mcast_stmt",
kids=[sourceAST, args[4], targetAST, attrAST])
self._assign0state(args)
def p_receive_stmt(self, args):
' receive_stmt : task_expr opt_async RECEIVES message_spec_into FROM task_expr '
targetAST = self._make_target_tasks(args, 1)
attr = []
if args[2].attr:
attr = ["asynchronously"]
attrAST = self._wrapAST("receive_attrs", args, attr=attr, kidofs=[2])
attrAST.kids = []
sourceAST = self._make_source_task(args, 6)
args[0] = self._str2ast("receive_stmt", kids=[targetAST, args[4], sourceAST, attrAST])
self._assign0state(args)
def p_delay_stmt(self, args):
'''
delay_stmt : task_expr COMPUTES FOR expr time_unit
| task_expr SLEEPS FOR expr time_unit
'''
args[0] = self._wrapAST("%s_%s" % (args.slice[2].type, args.slice[3].type),
args, source_task=1)
def p_wait_stmt(self, args):
' wait_stmt : task_expr AWAITS COMPLETIONS '
args[0] = self._wrapAST("awaits_completion", args, source_task=1)
def p_sync_stmt(self, args):
' sync_stmt : task_expr SYNCHRONIZES '
args[0] = self._wrapAST("sync_stmt", args, source_task=1)
def p_touch_stmt(self, args):
'''
touch_stmt : task_expr TOUCHES expr data_type OF AN item_size MEMORY REGION touch_repeat_count stride
| task_expr TOUCHES AN item_size MEMORY REGION touch_repeat_count stride
'''
args[0] = self._wrapAST("touch_stmt", args, source_task=1)
def p_touch_buffer_stmt(self, args):
'''
touch_buffer_stmt : task_expr TOUCHES ALL MESSAGES BUFFERS
| task_expr TOUCHES THE CURRENT MESSAGES BUFFERS
| task_expr TOUCHES MESSAGES BUFFERS expr
'''
if args.slice[3].type == "ALL":
attr = "all"
elif args.slice[3].type == "THE":
attr = "current"
else:
attr = "expr"
args[0] = self._wrapAST("touch_buffer_stmt", args, attr=attr, source_task=1)
def p_log_stmt(self, args):
' log_stmt : task_expr LOGS log_expr_list '
args[0] = self._wrapAST("log_stmt", args, source_task=1)
def p_log_flush_stmt(self, args):
' log_flush_stmt : task_expr COMPUTES AGGREGATES '
args[0] = self._wrapAST("log_flush_stmt", args, source_task=1)
def p_reset_stmt(self, args):
' reset_stmt : task_expr RESETS THEIR COUNTERS '
args[0] = self._wrapAST("reset_stmt", args, source_task=1)
def p_store_stmt(self, args):
' store_stmt : task_expr STORES THEIR COUNTERS '
args[0] = self._wrapAST("store_stmt", args, source_task=1)
def p_restore_stmt(self, args):
' restore_stmt : task_expr RESTORES THEIR COUNTERS '
args[0] = self._wrapAST("restore_stmt", args, source_task=1)
def p_assert_stmt(self, args):
' assert_stmt : ASSERT THAT string WITH rel_expr '
args[0] = self._wrapAST("assert_stmt", args)
def p_output_stmt(self, args):
' output_stmt : task_expr OUTPUTS string_or_expr_list '
args[0] = self._wrapAST("output_stmt", args, source_task=1)
def p_backend_stmt(self, args):
' backend_stmt : task_expr BACKEND EXECUTES string_or_expr_list '
args[0] = self._wrapAST("backend_stmt", args, source_task=1)
def p_processor_stmt(self, args):
'''
processor_stmt : task_expr ARE ASSIGNED TO PROCESSORS expr
| task_expr ARE ASSIGNED TO AN RANDOM PROCESSORS
'''
args[0] = self._wrapAST("processor_stmt", args, source_task=1)
def p_reduce_stmt_1(self, args):
'''
reduce_stmt : task_expr REDUCES reduce_message_spec
| task_expr REDUCES reduce_message_spec TO reduce_message_spec
'''
sourceAST = self._make_source_task(args, 1)
if len(args.slice) == 4:
recv_reduce_msg_spec = copy.deepcopy(args[3])
self._assign0state(args, ast=recv_reduce_msg_spec, kidofs=[3])
else:
recv_reduce_msg_spec = args[5]
args[0] = self._str2ast("reduce_stmt", attr=["allreduce"],
kids=[sourceAST, args[3], recv_reduce_msg_spec])
self._assign0state(args)
def p_reduce_stmt_2(self, args):
'''
reduce_stmt : task_expr REDUCES reduce_message_spec TO task_expr
| task_expr REDUCES reduce_message_spec TO task_expr WHO RECEIVES THE RESULTS reduce_target_message_spec
'''
sourceAST = self._make_source_task(args, 1)
targetAST = self._make_source_task(args, 5) # Yes, this is correct.
if len(args) == 6:
recv_reduce_msg_spec = copy.deepcopy(args[3])
self._assign0state(args, ast=recv_reduce_msg_spec, kidofs=[3])
else:
# Convert the reduce_target_message_spec to a reduce_message_spec.
recv_reduce_msg_spec = args[10]
for k in range(0, len(recv_reduce_msg_spec.kids)):
if recv_reduce_msg_spec.kids[k].attr == "unspecified":
recv_reduce_msg_spec.kids[k] = copy.deepcopy(args[3].kids[k])
if recv_reduce_msg_spec.attr == -1:
recv_reduce_msg_spec.attr = args[3].attr
recv_reduce_msg_spec.type = "reduce_message_spec"
args[0] = self._str2ast("reduce_stmt", attr=[],
kids=[sourceAST, args[3], recv_reduce_msg_spec, targetAST])
self._assign0state(args)
#------------------------#
# Relational expressions #
#------------------------#
def p_rel_expr(self, args):
' rel_expr : rel_disj_expr '
args[0] = self._wrapAST("rel_expr", args)
def p_rel_disj_expr_1(self, args):
' rel_disj_expr : rel_conj_expr '
args[0] = self._wrapAST("rel_disj_expr", args)
def p_rel_disj_expr_2(self, args):
r' rel_disj_expr : rel_disj_expr logic_or rel_conj_expr '
args[0] = self._wrapAST("rel_disj_expr", args,
attr=self._opname[args.slice[2].value])
def p_rel_conj_expr_1(self, args):
' rel_conj_expr : rel_primary_expr '
args[0] = self._wrapAST("rel_conj_expr", args)
def p_rel_conj_expr_2(self, args):
r' rel_conj_expr : rel_conj_expr logic_and rel_primary_expr '
args[0] = self._wrapAST("rel_conj_expr", args,
attr=self._opname[args.slice[2].value])
def p_rel_primary_expr(self, args):
'''
rel_primary_expr : eq_expr
| lparen rel_expr rparen
'''
args[0] = self._wrapAST("rel_primary_expr", args)
def p_eq_expr_1(self, args):
'''
eq_expr : expr op_eq expr
| expr op_lt expr
| expr op_gt expr
| expr op_leq expr
| expr op_geq expr
| expr op_neq expr
| expr DIVIDES expr
'''
args[0] = self._wrapAST("eq_expr", args,
attr=self._opname[string.upper(args.slice[2].value)])
def p_eq_expr_2(self, args):
'''
eq_expr : expr ARE EVEN
| expr ARE ODD
'''
lineno0, lineno1 = self._linespan(args)
args[0] = self._str2ast("eq_expr",
attr="op_"+string.lower(args.slice[3].type),
left=args[1],
lineno0=lineno0, lineno1=lineno1)
self._assign0state(args)
def p_eq_expr_3(self, args):
' eq_expr : expr ARE IN lbracket expr comma expr rbracket '
self.errmsg.warning('"%s %s [%s,%s]" is deprecated; please use "%s %s {%s,...,%s} instead' %
(args[2], args[3], args[5].printable, args[7].printable,
args[2], args[3], args[5].printable, args[7].printable))
args[0] = self._wrapAST("eq_expr", args, attr="op_in_range")
def p_eq_expr_4(self, args):
' eq_expr : expr ARE NOT IN lbracket expr comma expr rbracket '
self.errmsg.warning('"%s %s %s [%s,%s]" is deprecated; please use "%s %s %s {%s,...,%s} instead' %
(args[2], args[3], args[4], args[6].printable, args[8].printable,
args[2], args[3], args[4], args[6].printable, args[8].printable))
args[0] = self._wrapAST("eq_expr", args, attr="op_not_in_range")
def p_eq_expr_5(self, args):
' eq_expr : expr ARE IN range_list '
args[0] = self._wrapAST("eq_expr", args, attr="op_in_range_list")
def p_eq_expr_6(self, args):
' eq_expr : expr ARE NOT IN range_list '
args[0] = self._wrapAST("eq_expr", args, attr="op_not_in_range_list")
#-----------------------#
# Aggregate expressions #
#-----------------------#
def p_aggregate_expr_1(self, args):
'''
aggregate_expr : expr
| EACH expr
'''
args[0] = self._wrapAST("aggregate_expr", args, attr="no_aggregate")
def p_aggregate_expr_2(self, args):
' aggregate_expr : THE expr '
aggr_func_ast = self._str2ast("aggregate_func", attr="ONLY")
self._assign0state(args, ast=aggr_func_ast, kidofs=[1])
args[0] = self._str2ast("aggregate_expr", kids=[aggr_func_ast, args[2]])
self._assign0state(args)
def p_aggregate_expr_3(self, args):
'''
aggregate_expr : THE aggregate_func_list expr
| THE aggregate_func_list OF expr
| THE aggregate_func_list OF THE expr
'''
args[0] = self._wrapAST("aggregate_expr", args)
def p_aggregate_expr_4(self, args):
'''
aggregate_expr : AN HISTOGRAM OF expr
| AN HISTOGRAM OF THE expr
'''
lineno0, lineno1 = self._linespan(args, last=len(args.slice)-2)
funcAST = self._str2ast("aggregate_func", attr="HISTOGRAM",
lineno0=lineno0, lineno1=lineno1)
args[0] = self._str2ast("aggregate_expr",
left=funcAST, right=args[len(args)-1])
self._assign0state(args)
#------------------------#
# Arithmetic expressions #
#------------------------#
def p_expr(self, args):
' expr : ifelse_expr '
args[0] = self._wrapAST("expr", args)
def p_ifelse_expr_1(self, args):
' ifelse_expr : add_expr '
args[0] = self._wrapAST("ifelse_expr", args)
def p_ifelse_expr_2(self, args):
' ifelse_expr : add_expr IF rel_expr OTHERWISE ifelse_expr '
args[0] = self._wrapAST("ifelse_expr", args)
def p_add_expr_1(self, args):
' add_expr : mult_expr '
args[0] = self._wrapAST("add_expr", args)
def p_add_expr_2(self, args):
'''
add_expr : add_expr op_plus mult_expr
| add_expr op_minus mult_expr
| add_expr op_or mult_expr
| add_expr XOR mult_expr
'''
args[0] = self._wrapAST("add_expr", args,
attr=self._opname[string.upper(args.slice[2].value)])
def p_mult_expr_1(self, args):
' mult_expr : unary_expr '
args[0] = self._wrapAST("mult_expr", args)
def p_mult_expr_2(self, args):
'''
mult_expr : mult_expr op_mult unary_expr
| mult_expr op_div unary_expr
| mult_expr MOD unary_expr
| mult_expr op_rshift unary_expr
| mult_expr op_lshift unary_expr
| mult_expr op_and unary_expr
'''
args[0] = self._wrapAST("mult_expr", args,
attr=self._opname[string.upper(args.slice[2].value)])
def p_unary_expr_1(self, args):
' unary_expr : power_expr '
args[0] = self._wrapAST("unary_expr", args)