/
pslTree.py
2155 lines (1797 loc) · 86.8 KB
/
pslTree.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
"""
Maude-PSL, Version: [1.0] [May 15th 2015]
Copyright (c) 2015, University of Illinois
All rights reserved.
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 the University of Illinois 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 THE COPYRIGHT HOLDERS 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 THE COPYRIGHT OWNER 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.
-----------------------------------------------------------------------------------------------------------
Copyright (c) 2015. To the extent that a federal employee is an author of
a portion of the software or a derivative work thereof, no copyright is
claimed by the United States Government, as represented by the Secretary
of the Navy ("GOVERNMENT") under Title 17, U.S. Code. All Other Rights Reserved.
Permission to use, copy, and modify this software and its documentation is
hereby granted, provided that both the copyright notice and this permission
notice appear in all copies of the software, derivative works or modified
versions, and any portions thereof, and that both notices appear in
supporting documentation.
GOVERNMENT ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING
FROM THE USE OF THIS SOFTWARE.
GOVERNMENT requests users of this software to return modifications,
improvements or extensions that they make to:
maudenpa@chacs.nrl.navy.mil]
-or-
Naval Research Laboratory, Code 5543
4555 Overlook Avenue, SW
Washington, DC 20375
"""
"""
Important: To simplify implementation, the parser assumes that the set of user-defined tokens are disjoint from the set of top level
tokens.
"""
import re
import pslErrors
import itertools
import operator
import warnings
#from fuzzywuzzy import fuzz
TOP_LEVEL_TOKENS = ['sort', 'type', 'sorts', 'types', '.', 'subsort', 'subsorts', 'subtype', 'subtypes', 'op', 'ops', '->', ':', '[', ']', 'eq', '=', 'ceq', 'if', ':=', '==', 'In', '(', ')', 'Def', '(', ')',
'Out', '=>', '<=>', ',', 'Intruder', 'learns', 'With', 'with', 'constraints:', 'without:', 'Subst', '|->', '!=', '|-', '$;']
'''
Blarge, don't really know what's going on with the bestTokenRatioPair crap, and I don't really feel like figuring it out right now.
def best_match(token, stmtTypes):
"""
Takes a token, and a list of statement types (i.e. equational theory statements, intruder statements). Builds a list of tokens
consisting of those tokens that begin each statement in stmtTypes, and returns the token that most closely matches the "token"
argument.
"""
bestTokenRatioPair = ('', 0)
for stmtType in stmtTypes:
startToken = stmtTypes[stmtType][0][0]
ratio = fuzz.ratio(token, startToken)
bestTokenRatioPair = (startToken, ratio) if ratio > bestTokenRatioPair[1] else bestTokenRatioPair
tokens, args = (bestTokenRatioPair[0].tokens, iter(bestTokenRatioPair[0].argNodes))
return ' '.join(next(args).class_name() if token == '_' else token for token in tokens)
'''
class Statement(object):
"""
Contains a pair of lists. The first is a list of tokens, and the second is a list of line numbers, such that tokens[n] appears on
line lineNums[n]
We could use a map, mapping tokens to line numbers, except that the same token may appear more than once in a single statement.
"""
def __init__(self, tokens=None, lineNums=None):
self.tokens = tokens if tokens else []
self.lineNums = lineNums if lineNums else []
#Yes, this check fails on strings, however I'm not treating strings as iterables, so this check should fail on
#strings.
assert(hasattr(self.tokens, '__iter__'))
assert(hasattr(self.lineNums, '__iter__'))
assert not (bool(self.tokens) ^ bool(self.lineNums)), "If 'tokens' is None (or empty), then 'lineNums' must also be None (or empty). If tokens is not None, then lineNums must also not be None."
def __repr__(self):
return str(zip(self.tokens, self.lineNums))
"""
lines = []
lineNums = []
currentLine = []
currentLineNum = self.lineNums[0]
for token, lineNum in self:
if lineNum == currentLineNum:
currentLine.append(token)
else:
lines.append(currentLine)
lineNums.append(currentLineNum)
currentLine = [token]
currentLineNum = lineNum
lines.append(currentLine)
lineNums.append(currentLineNum)
lines = (' '.join(line) for line in lines)
return '\n' + '\n'.join(map(' '.join, zip(["Line:"] * len(lineNums), map(str, lineNums), lines)))
"""
def append(self, value, lineNum):
self.tokens.append(value)
self.lineNums.append(lineNum)
class Node(object):
"""
Represents a Node in the AST. Consists of:
1. The operator of the associated statement.
2. Children nodes consisting of arguments to the
high-level argument.
3. The line at which this node occurs in the
original file.
For example, a statement of the form
1 . A -> B : pk(A, B) |- M . on line 5 would have a
Node that looks like:
Node(_._->_:_|-_.,
Node(1, [], 5),
Node(A, [], 5),
Node(B, [], 5),
Node(pk(A, B), [], 5),
Node(M, [], 5), 5)
Note that we don't attempt to parse user-defined
operators. We leave that to Maude.
Also has a function associated with it that performs error checking
for this particular node.
"""
def __init__(self, parent=None, op=None, children=None, lineNum=None):
"""
op is a tuple of tokens representing the syntax of the statement describing this Node. children is an iterable of Nodes (or strings if we're at a leaf node, i.e. a Token) below this Node in the Tree, and line is the line number at which the Node's
statement begins.
"""
self.op = op
self.parent = parent
if children is None:
children = []
self.children = children
self.lineNum = lineNum
def error_check(self):
raise NotImplementedError(self.class_name())
def get_ops(self):
return self.parent.get_ops()
def get_root(self):
root = self
while root.parent:
root = root.parent
return root
def translate(self):
"""
Returns an iterable of lines of Maude code that translates the information contained in this Node into Maude-NPA code.
"""
code = []
assert self.children, "Node %s doesn't have any children. Perhaps you forgot to implement a custom translate() method for this node?" % str(self)
for child in self.children:
code.extend(child.translate())
return code
@staticmethod
def parse(stmt, parent):
"""
Given an object with the statement interface (an iterable of strings representing tokens, and an iterable of numbers representing line numbers on which those tokens appear), attempts to parse the statement
into a parse tree. If successful, returns a parse tree with
this node at the root. Otherwise, raises a SyntaxError.
This is the function that should be overriden by children classes. The _parse static method is an internal method meant to be invoked by the children Nodes, because most of them perform the same basic
algorithm. _parse implements that algorithm.
"""
pass
def _parse(self, stmt, syntax):
"""
Given an object with the statement interface (an iterable of strings representing tokens, and an iterable of numbers representing
line numbers on which those tokens appear), attempts to parse the statement
into a parse tree. If successful, returns a parse tree with
this node at the root. Otherwise, raises a SyntaxError.
This method is meant to be invoked by the child classes of Node
Observe that at this level, we don't know what type of node to return. So this parse function simply returns a triple of the
operator tuple associated with the calling node, the arguments of the calling node, and the starting Line number.
The calling node then uses that information to construct a node of the appropriate type.
"""
tokens = stmt.tokens
opIter, argNodes = (iter(syntax.tokens), iter(syntax.argNodes))
args = []
unparsedTokens = iter(tokens)
lineNumIter = iter(stmt.lineNums)
startingLineNum = None
terminatingToken = None
userLevelTokenList = []
userLevelLineNums = []
for token in opIter:
if token == '_':
userLevelTokenList = []
userLevelLineNums = []
#Some syntaxes (i.e. DefPair) have an _ as the last token in the syntax.
try:
terminatingToken = next(opIter)
except StopIteration:
terminatingToken = None
stmtToken = next(unparsedTokens)
while stmtToken != terminatingToken:
userLevelTokenList.append(stmtToken)
currentLine = next(lineNumIter)
if startingLineNum is None:
startingLineNum = currentLine
userLevelLineNums.append(currentLine)
try:
stmtToken = next(unparsedTokens)
except StopIteration:
if terminatingToken:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(currentLine), "Missing",
pslErrors.color_token(terminatingToken), "in line: ", ' '.join(color_stmt_tokens(stmt.tokens)),
"Expected a statement of the form: ", ' '.join(color_stmt_tokens(syntax.tokens))]))
else:
break
args.append(next(argNodes).parse(Statement(userLevelTokenList, userLevelLineNums), self))
else:
try:
unparsedToken = next(unparsedTokens)
except StopIteration:
#This check may (or may not, I'm not sure) vary depending on the statement.
if token == '.':
break
else:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(currentLine), "Missing a token matching: ",
pslErrors.color_token(token), "When parsing line: ", pslErrors.color_token(' '.join(stmt.tokens)),
"Expected a", "statement of the form: ", pslErrors.color_token(' '.join(syntax.tokens))]))
else:
currentLine = next(lineNumIter)
if startingLineNum is None:
startingLineNum = currentLine
if token != unparsedToken:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(currentLine), "Unexpected token:",
pslErrors.color_token(unparsedToken), "when parsing statement:", pslErrors.color_token(' '.join(stmt.tokens)),
"Expected statement of the form: ", pslErrors.color_token(' '.join(syntax.tokens))]))
return (syntax.tokens, args, startingLineNum)
def __repr__(self):
return '\n'.join(['$$$$$$$$', 'Op::', repr(self.op), 'Line Number::', repr(self.lineNum), 'Children::', '----------------\n'.join(map(repr, self.children)), '########'])
@staticmethod
def class_name():
return "Node"
class Root(Node):
def __init__(self, op=None, children=None, lineNum=None):
super(Root, self).__init__(None, op, children, lineNum)
@staticmethod
def class_name():
return "Root"
def get_theory(self):
try:
return next(child for child in self.children if child.class_name() == Theory.className)
except StopIteration:
raise pslErrors.SyntaxError(' '.join([pslErrors.errorNoLine, "Missing Section:", pslErrors.color_token("Theory")]))
def get_protocol(self):
try:
return next(child for child in self.children if child.class_name() == Protocol.className)
except StopIteration:
raise pslErrors.SyntaxError(' '.join([pslErrors.errorNoLine, "Missing Section:", pslErrors.color_token("Protocol")]))
def get_intruder(self):
try:
return next(child for child in self.children if child.class_name() == Intruder.className)
except StopIteration:
raise pslErrors.SyntaxError(' '.join([pslErrors.errorNoLine, "Missing Section:", pslErrors.color_token("Intruder")]))
def get_attacks(self):
try:
return next(child for child in self.children if child.class_name() == Attacks.className)
except StopIteration:
raise pslErrors.SyntaxError(' '.join([pslErrors.errorNoLine, "Missing Section:", pslErrors.color_token("Attacks")]))
def sort_names(self):
return self.get_theory().sort_names()
def get_ops(self):
ops = []
for child in self.children:
try:
ops.append(child.get_user_defined_operator())
except AttributeError:
pass
return ops
class Section(Node):
def declared_variables(self, upToNode=None):
"""
upToNode is a VarDeclNode. If upToNode is not None, then Theory will return all the variables declared before upToNode. This is
particularly useful when checking for duplicate variable declarations.
Note: This returns only the variable NAMES. It does not return the sorts of the variables.
"""
declaredVars = []
for child in self.children:
if child is upToNode:
break
try:
declaredVars.extend(child.get_vars())
except AttributeError:
pass
return declaredVars
def var_name_sort_mapping(self):
"""
Returns a map from variable name to the variable's sort for all variables declared in this section.
"""
declaredVars = {}
for child in self.children:
try:
childMapping = child.name_sort_mapping()
except AttributeError:
pass
else:
for varName in childMapping:
declaredVars[varName] = childMapping[varName]
return declaredVars
class PSLSection(Section):
def sort_names(self):
return self.parent.sort_names()
def translate(self):
self.error_check()
return [self.class_name(), '{'] + super(PSLSection, self).translate() + ['}']
class Theory(Section):
"""
Root of the theory syntax tree.
Note that the theory section behaves differently from the other sections in a variety of ways, so it is not made a subtype of PSLSection, but rather only of Section
"""
className = "Theory"
def __init__(self, parent, line=0):
super(Theory, self).__init__(parent, None, [], line)
def class_name(self):
return Theory.className
def sort_nodes(self):
"""
Returns the list of nodes that declare sort names.
"""
return [arg for arg in self.children if arg.op in typeSyntax]
def sort_names(self):
"""
Returns a list of sort names declared in this module.
"""
sortNames = []
for arg in self.children:
try:
sortNames.extend(arg.sort_names())
except AttributeError:
pass
return sortNames
def ops(self):
ops = []
for child in self.children:
try:
ops.append(child.get_user_defined_operator())
except AttributeError:
pass
return ops
@staticmethod
def parse(stmts, parent):
#stmts is a list of Statement objects, each of which consists of a list of tokens and an associated list of line numbers for
#each token.
root = Theory(parent)
keywordList = [['type', 'sort', 'types', 'sorts'], ['subtype', 'subtypes', 'subsort', 'subsorts'], ['op', 'ops'],
['var', 'vars'], ['eq', 'ceq']]
syntaxDeclPairs = [(typeSyntax, TypeDecl), (subTypeSyntax, SubTypeDecl), (opSyntax, OpDecl), (varSyntax, VarDecl),
(eqSyntax, EqStmt)]
stmtTypes = {}
#These are already in PROTOCOL-DEFINITION-RULES, so we don't need to add them explicitly. We do however, need to remove them
#if people already declared them.
#builtInSorts = ['sorts'] + TypeDecl.builtInTypes + ['.']
#stmts = [Statement(builtInSorts, [-1] * len(builtInSorts))] + stmts
for keywords, sdPair in zip(keywordList, syntaxDeclPairs):
for word in keywords:
stmtTypes[word] = sdPair
for stmt in stmts:
for stmtType in stmtTypes:
syntaxList, nodeType = stmtTypes[stmtType]
if any(stmt.tokens[0] == stmtSyntax.tokens[0] for stmtSyntax in syntaxList):
root.children.append(nodeType.parse(stmt, root))
break
else:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(stmt.lineNums[0]), "Token",
pslErrors.color_token(stmt.tokens[0]), "does not begin an equational theory statement."])) #Did you mean:",
#pslErrors.color_token(best_match(stmt.tokens[0], stmtTypes)) + '?']))
#Make all sorts subsorts of Msg.
subsortDecl = ['subsorts'] + [sortName for sortName in root.sort_names() if sortName != 'Msg'] + ['<', 'Msg', '.']
root.children.append(SubTypeDecl.parse(Statement(subsortDecl, [-1] * len(subsortDecl)), root))
assert all(root.children)
return root
def error_check(self):
"""
If performance becomes an issue (unlikely considering the very small
size of specifications compared to programs. I doubt a specification
is going to be millions of lines of code!) then we can check for
duplicates as we parse the sort names
"""
errors = []
warnings = []
for arg in self.children:
try:
arg.error_check()
except pslErrors.PSLError, e:
errors.append(e)
except pslErrors.PSLWarning, e:
warnings.append(e)
try:
self.check_repeated_sorts()
except pslErrors.SyntaxWarning, e:
warnings.append(e)
try:
self.check_axioms()
except pslErrors.InvalidOpError, e:
errors.append(e)
if errors or warnings:
raise pslErrors.ErrorsAndWarnings(errors + warnings, errors,
warnings)
def check_repeated_sorts(self):
"""
Checks if the theory section has any multiply declared sorts. If
there are any, then the program raises a SyntaxWarning.
"""
seenSorts = set()
errorMsgs = []
for node in self.sort_nodes():
for sort in node.sort_names():
if sort in seenSorts:
errorMsgs.append(' '.join([pslErrors.warning,
pslErrors.color_line_number(node.line), "Sort",
pslErrors.color_token(sort), "already declared, and will be",
"ignored."]))
node.remove_sort(sort)
else:
seenSorts.add(sort)
if errorMsgs:
raise pslErrors.SyntaxWarning('\n'.join(errorMsgs))
def check_axioms(self):
"""
Checks to make sure the theory has only allowed combinations of axioms:
assoc-comm, comm, assoc-comm-id.
assoc, assoc-id, any combination containing only left-id, any
combination containing right-id, or any combination containing idem are
not allowed.
"""
#TODO: Implement
ops = self.get_op_nodes()
def get_op_nodes(self):
return [arg for arg in self.children if arg.op in opSyntax]
class StmtNode(Node):
"""
A StmtNode (statement node) is a node that a single Maude-NPA statement (i.e. a sort declaration, an operator, an equation).
It is assumed that Statement nodes contain a tuple "op" that defines their syntax. For example ('op', '_', ':', '_', '->', '_', '.') represents an op statement without brackets, where
underscores represent the position at which the user provides input. Furthermore the ith _ should correspond to the ith child of this node.
"""
@staticmethod
def class_name():
return "StmtNode"
def translate(self):
self.error_check()
code = list(self.op)
underscoreIndices = [i for i, x in enumerate(self.op) if x == '_']
for i in range(len(self.children)):
code[underscoreIndices[i]] = ' '.join(''.join(child) for child in self.children[i].translate())
return [' '.join(code)]
class PSLStmtNode(StmtNode):
className = "PSL Statement Node"
def class_name(self):
return PSLStmtNode.className
def translate(self):
"""
If we're translating statements that are not in the theory section, then we need to append the line number onto the end.
"""
code = super(PSLStmtNode, self).translate()
#Since these are all single statements, they should only create a single line of Maude code.
assert len(code) == 1
return self.append_line_number(code)
def append_line_number(self, code):
code = code[0]
return [' '.join([code, '[', str(self.lineNum), ']'])]
class TypeDecl(StmtNode):
"""
Used to encode type declarations (i.e. statements prefixed by one of:
sort(s), type(s)
A TypeDecl's children is a single PSLListNode of Tokens containing the sort names.
"""
builtInTypes = ['Msg', 'Public', 'Fresh']
@staticmethod
def class_name():
return "Type Declaration"
@staticmethod
def parse(stmt, parent):
syntax = next(syntax for syntax in typeSyntax if stmt.tokens[0] == syntax.tokens[0])
node = TypeDecl(parent, None, None, None)
op, children, lineNum = node._parse(stmt, syntax)
node.op = op
node.children = children
node.lineNum = lineNum
assert all(node.children)
return node
def sort_names(self):
"""
Returns a list of sort names declared in this node.
"""
sortList = []
for child in self.children:
sortList.extend(child.get_elements())
return [elem.get_token() for elem in sortList]
def remove_sort(self, sort):
for child in self.children:
try:
self.children.remove(sort)
except ValueError:
pass
else:
break
def add_sort(self, sort):
self.children[0].children.append(sort)
def translate(self):
self.op[0] = 'sorts'
return super(TypeDecl, self).translate()
def error_check(self):
errorMsgs = []
for sortName in self.sort_names():
invalidTokenMsg = self.invalid_tokens(sortName)
if invalidTokenMsg:
errorMsgs.append(invalidTokenMsg)
if sortName in TypeDecl.builtInTypes:
errorMsgs.append(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum),
"Type", pslErrors.color_token(sortName),
"already has a special meaning in Maude-NPA, and should not be explicitly declared in a PSL specification."]))
if errorMsgs:
raise pslErrors.SyntaxError('\n'.join(errorMsgs))
def invalid_tokens(self, sortName):
invalidTokens = ['`', '}', '{', '(', ')', '[', ']', ',']
invalidTokens = ', '.join([token for token in invalidTokens if token in sortName])
if invalidTokens:
return ' '.join(["Invalid tokens:", pslErrors.color_token(invalidTokens),
"are not allowed in sort names.",
"Invalid sort name: ", pslErrors.color_token(sortName)])
else:
return ''
class Term(Node):
"""
Used for discrete units of syntax (i.e. individual terms that serve
as arguments to one of the statements listed at bottom of this
file). These include
variables, numbers and terms using user-defined syntax that Python can't
handle as well as Maude.
"""
@staticmethod
def class_name():
return "Term"
def __init__(self, parent=None, children=None, lineNum=None):
"""
Children is an iterable of Tokens. lineNum is the line number on which this term begins.
op is not specified by the creator. It is always '_' because terms should only appear in
places where '_' appears in the high level syntax.
"""
super(Term, self).__init__(parent, '_', children, lineNum)
def __repr__(self):
return '\n'.join(map(repr, self.children))
def __str__(self):
return ' '.join(map(str, self.children))
def tokens(self):
return self.children
@staticmethod
def parse(stmt, parent):
node = Term(parent, [], stmt.lineNums[0])
node.children = [Token(node, [token], lineNum) for token, lineNum in zip(stmt.tokens, stmt.lineNums)]
return node
def translate(self):
code = []
opDecls = self.parent.get_ops()
for child in self.children:
code.extend(child.translate())
return [' '.join(code)]
def get_tokens(self):
"""
Returns the tokens (as token objects) that make up this term.
"""
return self.children
class Token(Node):
"""
A single token. This is a leaf node of the parse tree.
"""
#start multi-line comment /* ... */|end multi-line comment
#| single line comment|start of specification| parens/brackets/curly braces | whitespace
#tokenizer = re.compile(r'(/\*)|(\*/)|(//.*$)|(spec \S+ is)|([[\](){}])|(,)|(_)|(\s)')
tokenizer = re.compile(r'(/\*)|(\*/)|(//.*$)|(spec \S+ is)|([[\](){}])|(,)|\s')
@staticmethod
def class_name():
return "Token"
def __init__(self, parent, tokenList, lineNum):
assert(isinstance(tokenList, list))
super(Token, self).__init__(parent, None, tokenList, lineNum)
@staticmethod
def parse(stmt, parent, lineNum=None):
assert len(stmt.tokens) == 1, "Statement has been passed to the Token node with more than one tokens: %s" % ', '.join(stmt.tokens)
assert len(stmt.lineNums) == 1, "Statement has been passed to the Token node with more than one line number: %s" % ', '.join(map(str, stmt.lineNums))
return Token(parent, stmt.tokens, stmt.lineNums)
def get_token(self):
return self.children[0]
def translate(self):
"""
We don't need to do anything fancy to tokens to turn them into Maude-NPA code, since they're just discrete bits of string that are provided by the user.
"""
token = self.get_token()
parent = self.parent
while True:
try:
declaredVars = parent.declared_variables()
except AttributeError:
parent = parent.parent
else:
break
if token in declaredVars:
parent = self.parent
while True:
try:
varsWithSorts = parent.var_name_sort_mapping()
except AttributeError:
parent = parent.parent
else:
break
token = ':'.join([token, varsWithSorts[token]])
return [token]
def __repr__(self):
return ''.join([str(self.lineNum), ': ', ''.join(self.children)])
def __str__(self):
return ''.join(self.children)
class SubTypeDecl(StmtNode):
"""
The child of a SubTypeDecl node is a PSLListNode of lists of tokens: [[Token_1, Token_2, ..., Token_n], ..., [Token_m1, Token_m2, ... Token_mp] s.t.
s.t. Token_1 Token_2 ... Token_n < ... < Token_m1 Token_m2 ... Token_mp
"""
@staticmethod
def class_name():
return "Subtype Declaration"
@staticmethod
def parse(stmt, parent):
syntax = next(syntax for syntax in subTypeSyntax if syntax.tokens[0] == stmt.tokens[0])
node = SubTypeDecl(parent, None, None, None)
node.op, node.children, node.lineNum = node._parse(stmt, syntax)
assert all(node.children)
return node
def translate(self):
self.op[0] = 'subsorts'
code = super(SubTypeDecl, self).translate()[0]
return [code]
def error_check(self):
"""
All we need to check for subtype declarations is that the sorts used in the sub type declaration have been declared.
"""
declaredSorts = self.parent.sort_names()
sortNames = []
for child in self.children:
assert not isinstance(child.get_elements(), Node), "Should be a list: %s" % str(child.get_elements)
for element in child.get_elements():
sortNames.extend(element.get_elements())
sortNames = [sort.get_token() for sort in sortNames]
undeclaredSorts = [sort for sort in sortNames if not sort in declaredSorts]
errorMsgs = ''
for sort in filter(lambda x : x not in TypeDecl.builtInTypes, undeclaredSorts):
'\n'.join([errorMsgs, ' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Type name: ", pslErrors.color_token(sort) + " has not been declared."])])
if errorMsgs:
raise pslErrors.SyntaxError(errorMsgs)
class OpDecl(StmtNode):
@staticmethod
def class_name():
return "Op Declaration"
@staticmethod
def parse(stmt, parent):
#First, we distinguish between op and ops, then we'll distinguish between [_] and no [_].
syntaxList = [syntax for syntax in opSyntax if stmt.tokens[0] == syntax.tokens[0]]
reversedTokens = stmt.tokens[::-1]
indexBeforeColon = reversedTokens.index(':')-1
if stmt.tokens[-2] == ']':
syntaxList = (syntax for syntax in syntaxList if syntax.tokens[-2] == ']')
else:
syntaxList = (syntax for syntax in syntaxList if syntax.tokens[-2] != ']')
#We're checking the token after the colon in the original, non-reversed list.
if reversedTokens[indexBeforeColon] == '->':
syntax = next(syntax for syntax in syntaxList if syntax.tokens[-syntax.tokens[::-1].index(':')] == '->')
else:
syntax = next(syntax for syntax in syntaxList if syntax.tokens[-syntax.tokens[::-1].index(':')] != '->')
node = OpDecl(parent, None, None, None)
node.op, node.children, node.lineNum = node._parse(stmt, syntax)
assert all(node.children)
return node
def translate(self):
#Need to check if one of the attributes is frozen.
if '[' in self.op:
attributes = self.get_attributes()
if not 'frozen' in attributes and not self.is_constant():
opAttributeList = self.children[-1]
opAttributeList.append(Token(self, ['frozen'], self.lineNum))
elif not self.is_constant():
frozenIndex = attributes.index('frozen')
#This handles converting frozen(1, 2, 3) (or whatever operator positions) into frozen, since Maude-NPA requires every
#argument to be frozen.
try:
startParenIndex = frozenIndex+1
except IndexError:
pass
else:
try:
endParenIndex = attributes[frozenIndex:].index(')')
except ValueError:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum),
"Unbalanced parenthesis when declaring frozen properties."]))
self.children[-1].remove_range(startParenIndex, endParenIndex)
warnings.warn(' '.join([pslErrors.warning, pslErrors.color_line_number(self.lineNum),
"Maude-NPA requires all arguments on all operators to be frozen. Your partially frozen operator",
"has been converted into a completely frozen operator."]))
else:
if not self.is_constant():
self.children.append(PSLListNode(self, '', [Token(self, ['frozen'], self.lineNum)], self.lineNum))
#Need to change the op to be the version with operator attributes. Note that since we don't add frozen to the constant
#operators, we don't care about
#changing those (because we don't need to).
if 'ops' in self.op:
self.op = opSyntax[-1].tokens
else:
self.op = opSyntax[1].tokens
return super(OpDecl, self).translate()
def is_constant(self):
userOp = self.op[self.op.index(':'):self.op.index('->')]
for token in userOp:
if '_' in token:
return False
else:
return True
def error_check(self):
attributes = self.get_attributes()
if 'assoc' in attributes and not 'comm' in attributes:
raise pslErrors.TranslationError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Operator attribute", pslErrors.color_token('assoc'), "not allowed without the",
pslErrors.color_token('comm'), "attribute"]))
if 'id:' in attributes and not ('assoc' in attributes and 'comm' in attributes):
raise pslErrors.TranslationError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Operator attribute", pslErrors.color_token('id:'), "not allowed without the",
pslErrors.color_token('comm'), "and", pslErrors.color_token('assoc'), "attributes."]))
if 'idem' in attributes:
raise pslErrors.TranslationError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Operator attribute", pslErrors.color_token('idem'), "is not allowed."]))
userDefinedOperator = self.get_user_defined_operator()
for token in userDefinedOperator:
if token in TOP_LEVEL_TOKENS and (token != '(' and token != ')' or token == 'op'):
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Token:", pslErrors.color_token(token),
"is a token in the Maude-PSL top level syntax",
"and therefore is not allowed in a user-defined operator. Consider doubling the token (i.e.", pslErrors.color_token(token + token), "or tweaking the token in some other manner",
"to make it distinct."]))
elif (token == '(' or token == ')') and token == 'ops':
warnings.warn(' '.join([pslErrors.warning, pslErrors.color_line_number(self.lineNum), "Token ",
pslErrors.color_token(token),
"is not allowed to be part of a user-defined operator. Therefore,", pslErrors.color_token(token),
"is assumed to be enclosing one of several operators declared on the same line."]))
def get_attributes(self):
if '[' in self.op:
opAttributes = self.children[-1]
return [attribute.get_token() for attribute in opAttributes.children]
else:
return []
def get_user_defined_operator(self):
return [elem.get_token() for elem in self.children[0].get_elements()]
class VarDecl(StmtNode):
className = "Variable Declaration"
@staticmethod
def class_name():
return "Variable Declaration"
@staticmethod
def parse(stmt, parent):
syntax = next(syntax for syntax in varSyntax if stmt.tokens[0] == syntax.tokens[0])
node = VarDecl(parent, None, None, None)
node.op, node.children, node.lineNum = node._parse(stmt, syntax)
assert all(node.children)
return node
def get_sort_name(self):
return self.children[1].get_token()
def get_vars(self):
"""
Returns the tokens that represent variable names declared as a part of this decl.
"""
return [elem.get_token() for elem in self.children[0].get_elements()]
def error_check(self):
varNames = self.get_vars()
allVarsUpToMe = self.parent.declared_variables(self)
redeclaredVars = [varName for varName in varNames if varName in allVarsUpToMe]
if redeclaredVars:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Variables: ",
pslErrors.color_token(' '.join(redeclaredVars)), "have already been declared."]))
if not self.get_sort_name() in self.parent.sort_names() + TypeDecl.builtInTypes:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum), "Sort: ",
pslErrors.color_token(self.get_sort_name()), "has not been declared."]))
def name_sort_mapping(self):
"""
Returns a mapping from var name to sort name for each var name in this var declaration.
"""
sortName = self.get_sort_name()
return {varName:sortName for varName in self.get_vars()}
def translate(self):
"""
We convert all the variables into inline declarations as part of the translation of the Tokens, so we don't carry over the explicit variable declarations into the Maude code.
"""
self.error_check()
return ['']
class EqStmt(StmtNode):
@staticmethod
def class_name():
return "Equation"
@staticmethod
def parse(stmt, parent):
if stmt.tokens[-2] == ']':
syntax = next(syntax for syntax in eqSyntax if syntax.tokens[-2] == ']')
else:
syntax = next(syntax for syntax in eqSyntax if syntax.tokens[-2] != ']')
node = EqStmt(parent, None, None, None)
node.op, node.children, node.lineNum = node._parse(stmt, syntax)
assert all(node.children), "%s" % str(node)
return node
def get_attributes(self):
if '[' in self.op:
attributes = [elem.get_token() for elem in self.children[-1].get_elements()]
return attributes
else:
return []
def translate(self):
self.error_check()
if '[' in self.op:
attributes = self.get_attributes()
if not 'variant' in attributes and not 'homomorphism' in attributes:
self.children[-1].append(Token(self, ['variant'], self.lineNum))
elif 'homomorphism' in attributes:
self.children[-1].remove('homomorphism')
newTokens = ['label', 'homomorphism', 'metadata', '"builtin-unify"']
self.children[-1].extend([Token(self, [token], self.lineNum) for token in newTokens])
if not 'nonexec' in attributes:
pass
#self.children[-1].append(Token(self, ['nonexec'], self.lineNum))
else:
self.op = eqSyntax[1].tokens
self.children.append(PSLListNode(self, '', [Token(self, ['variant'], self.lineNum)], self.lineNum))
#Token(self, ['nonexec'], self.lineNum)]
return super(EqStmt, self).translate()
def error_check(self):
attributes = self.get_attributes()
if '[' in self.op:
if 'variant' in attributes and 'homomorphism' in attributes:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(self.lineNum),
"Equation cannot have both the attribute:", pslErrors.color_token('variant'), 'and the attribute:',
pslErrors.color_token('homomorphism') + '.']))
class Int(Node):
"""
Encapsulates integers
"""
@staticmethod
def class_name():
return "Integer"
@staticmethod
def parse(stmt, parent):
if len(stmt.tokens) != 1:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(stmt.lineNums[0]), "Expected a single integer when parsing ", pslErrors.color_token(' '.join(stmt.tokens)) + ".", "Make sure there are no spaces between your digits, and there is a",
"period after the integer."]))
try:
int(stmt.tokens[0])
except ValueError:
raise pslErrors.SyntaxError(' '.join([pslErrors.error, pslErrors.color_line_number(stmt.lineNums[0]), "Expected: ", pslErrors.color_token(' '.join(stmt.tokens)), "to be an integer."]))
else:
return Int(parent=parent, children=stmt.tokens, lineNum=stmt.lineNums[0])
def translate(self):
return [self.children[0]]
def value(self):
return int(self.children[0])