Repository navigation
Expand file tree
/
Copy pathassertions_parser.py
More file actions
96 lines (75 loc) · 2.07 KB
/
Copy pathassertions_parser.py
File metadata and controls
96 lines (75 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from sly import Lexer, Parser
import modules.assertions.global_assertions
class AssertionLexer(Lexer):
tokens = {FUNC, NUMBER, STRING, AND, OR, XOR, NOT, LPAR, RPAR, ARG}
ignore = ' \t'
literals = {'&', '|', '^', '!', '(', ')'}
@_(r'\((\s*("[^"]*"|\'[^\']*\'|\d+)\s*,?)+\)')
def ARG(self, t):
arguments = t.value[1:-1].split(",")
args = []
for a in arguments:
a = a.strip()
if a.isnumeric:
args.append(float(a))
else:
args.append(a)
t.value = args
return t
AND = r'\&'
OR = r'\|'
XOR = r'\^'
NOT = r'\!'
LPAR = r'\('
RPAR = r'\)'
FUNC = r'@[a-zA-Z0-9_]+'
STRING = r'("[^"]*"|\'[^\']*\')'
NUMBER = r'\d+'
class AssertionParser(Parser):
tokens = AssertionLexer.tokens
precedence = (
('left', AND, OR, XOR),
('right', NOT)
)
def __init__(self, events):
self.names = {}
self.events = events
@_('FUNC ARG')
def expr(self, p):
f = getattr(modules.assertions.global_assertions, p.FUNC[1:])
return f(output=self.events, *p.ARG)
@_('FUNC LPAR RPAR')
def expr(self, p):
return "%s()" % p.FUNC
@_('expr AND expr')
def expr(self, p):
return p.expr0 and p.expr1
@_('expr OR expr')
def expr(self, p):
return p.expr0 or p.expr1
@_('expr XOR expr')
def expr(self, p):
return p.expr0 != p.expr1
@_('NOT expr')
def expr(self, p):
return not p.expr
@_('LPAR expr RPAR')
def expr(self, p):
return p.expr
@_('NUMBER')
def expr(self, p):
return int(p.NUMBER)
@_('STRING')
def expr(self, p):
return p.STRING
@_('ARG')
def expr(self, p):
return p.ARG
if __name__ == '__main__':
lexer = AssertionLexer()
parser = AssertionParser([1, 2, 3])
code = "@count_gt(0) & (@count_lt(5))"
for tok in lexer.tokenize(code):
print('type=%r, value=%r' % (tok.type, tok.value))
res = parser.parse(lexer.tokenize(code))
print(res)