-
Notifications
You must be signed in to change notification settings - Fork 0
/
condition_data_structure.py
334 lines (249 loc) · 10.4 KB
/
condition_data_structure.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
import operator
from typing import Dict, List
from z3 import *
class ForeachVariable:
logicType = None
def __init__(self, logicType: str):
self.logicType = logicType
def getType(self):
return self.logicType
def getText(self, pretty=False) -> str:
pass
def evaluate(self):
pass
def satisfiable(self, condition: Dict) -> List:
pass
def getAssertions(self):
pass
def satModel(self, s: Solver):
pass
class LogicalExpression:
logicType = None
def __init__(self, logicType: str):
self.logicType = logicType
def getType(self):
return self.logicType
def getText(self, pretty=False) -> str:
pass
def evaluate(self):
pass
def satisfiable(self, condition: Dict) -> List:
pass
def getAssertions(self):
pass
def satModel(self, s: Solver):
pass
class OrExpression(LogicalExpression):
leftExpression: LogicalExpression = None
rightExpression: LogicalExpression = None
def __init__(self, left: LogicalExpression, right: LogicalExpression):
super(OrExpression, self).__init__('or')
self.leftExpression = left
self.rightExpression = right
def getLeft(self):
return self.leftExpression
def getRight(self):
return self.rightExpression
def getText(self, pretty=False):
result = '{} OR {}'.format(self.getLeft().getText(pretty),
self.getRight().getText(pretty))
return result if pretty is False else "({})".format(result)
def evaluate(self):
return self.leftExpression.evaluate() or self.rightExpression.evaluate()
def satisfiable(self, condition: Dict) -> List:
# We convert OR to AND and use the same function we have for AND to avoid duplicates
andEquivalent = NotExpression(AndExpression(NotExpression(self.getLeft()), NotExpression(self.getRight())))
return andEquivalent.satisfiable(condition)
def getAssertions(self):
return simplify(Or(self.leftExpression.getAssertions(),
self.rightExpression.getAssertions()))
class AndExpression(LogicalExpression):
leftExpression: LogicalExpression = None
rightExpression: LogicalExpression = None
def __init__(self, left: LogicalExpression, right: LogicalExpression):
super(AndExpression, self).__init__('and')
self.leftExpression = left
self.rightExpression = right
def getLeft(self):
return self.leftExpression
def getRight(self):
return self.rightExpression
def getText(self, pretty=False):
result = '{} AND {}'.format(self.getLeft().getText(pretty),
self.getRight().getText(pretty))
return result if pretty is False else "({})".format(result)
def evaluate(self):
return self.leftExpression.evaluate() and self.rightExpression.evaluate()
def satisfiable(self, condition: Dict) -> List:
left_satisfiable = self.getLeft().satisfiable(condition)
right_satisfiable = self.getRight().satisfiable(condition)
result = []
for l_sat in left_satisfiable:
for r_sat in right_satisfiable:
# We cannot merge two list of conditions with different values, like foo:True and foo:False
contradiction = False
for common_key in set(l_sat[1]).intersection(set(r_sat[1])):
if l_sat[1].get(common_key) != r_sat[1].get(common_key):
contradiction = True
if contradiction:
continue
# If left and right evaluated to True
if l_sat[0] and r_sat[0]:
if (True, {**l_sat[1], **r_sat[1]}) not in result:
result.append((True, {**l_sat[1], **r_sat[1]}))
continue
# If left and right evaluated to False, we only add one which is a subset of another
if l_sat[0] is False and r_sat[0] is False:
if set(l_sat[1]).issubset(set(r_sat[1])):
if (False, l_sat[1]) not in result:
result.append((False, l_sat[1]))
continue
elif set(r_sat[1]).issubset(set(l_sat[1])):
if (False, r_sat[1]) not in result:
result.append((False, r_sat[1]))
continue
if l_sat[0] is False and (False, l_sat[1]) not in result:
result.append((False, l_sat[1]))
if r_sat[0] is False and (False, r_sat[1]) not in result:
result.append((False, r_sat[1]))
return result
def getAssertions(self):
return simplify(And(self.leftExpression.getAssertions(),
self.rightExpression.getAssertions()))
class NotExpression(LogicalExpression):
rightExpression: LogicalExpression = None
def __init__(self, right: LogicalExpression):
super(NotExpression, self).__init__('not')
self.rightExpression = right
def getRight(self):
return self.rightExpression
def getText(self, pretty=False):
result = 'NOT {}'.format(self.getRight().getText(pretty))
return result if pretty is False else "({})".format(result)
def evaluate(self):
return not self.rightExpression.evaluate()
def satisfiable(self, condition: Dict) -> List:
child_satisfiable = self.rightExpression.satisfiable(condition)
result = []
for item in child_satisfiable:
result.append((not item[0], item[1]))
return result
def getAssertions(self):
return simplify(Not(self.rightExpression.getAssertions()))
class LocalVariable(LogicalExpression):
variableName: str = None
variable: [Bool, Int, String] = None
def __init__(self, variableName, varType='bool'):
super(LocalVariable, self).__init__('var')
self.variableName = variableName
if varType == 'bool':
self.variable = Bool(variableName)
elif varType == 'int':
self.variable = Int(variableName)
elif varType == 'string':
self.variable = String(variableName)
def getText(self, pretty=False):
return "${{{}}}".format(self.variableName)
def toInt(self):
self.variable = Int(self.variableName)
def toString(self):
self.variable = String(self.variableName)
def evaluate(self):
# TODO: Given the fact, we should evaluate this last piece in the evaluate tree
pass
def satisfiable(self, condition: Dict) -> List:
# First check if we have a fact about the variable
if self.variableName in condition:
return [(condition[self.variableName], {})]
return [
(True, {self.variableName: True}),
(False, {self.variableName: False})
]
def getAssertions(self):
return self.variable
class DummyExpression(LogicalExpression):
def __init__(self, assertion: List):
super(DummyExpression, self).__init__('DUMMY')
self.assertion = And(*assertion)
def getAssertions(self):
return simplify(self.assertion)
def getText(self, pretty=False) -> str:
return str(self.getAssertions())
class ConstantExpression(LogicalExpression):
value: str = None
PYTHON_STR = 'pythonSTR'
Z3_STR = 'z3STR'
def __init__(self, value, strType=PYTHON_STR):
super(ConstantExpression, self).__init__('constant')
self.value = value
self.type = strType
def getText(self, pretty=False):
return self.value
def evaluate(self):
if self.value.lower() in ('false', 'no'):
return False
return True
def satisfiable(self, condition: Dict) -> List:
return [(self.evaluate(), {})]
def getAssertions(self):
if self.value.lower() in ('false', 'no', 0, '0'):
return BoolVal(False)
if self.value.lower() in ('true', 'yes'):
return BoolVal(True)
if self.type == self.PYTHON_STR:
return self.value
elif self.type == self.Z3_STR:
return StringVal(self.value)
class ComparisonExpression(LogicalExpression):
leftExpression: LogicalExpression = None
rightExpression: LogicalExpression = None
def __init__(self, left: LogicalExpression, right: LogicalExpression, operator):
super(ComparisonExpression, self).__init__(operator)
self.leftExpression = left
self.rightExpression = right
def getLeft(self):
return self.leftExpression
def getRight(self):
return self.rightExpression
def getText(self, pretty=False):
result = '{} {} {}'.format(self.getLeft().getText(pretty),
self.logicType,
self.getRight().getText(pretty))
return result if pretty is False else "({})".format(result)
def satisfiable(self, condition: Dict) -> List:
return [(False, {})]
def returnOperator(self):
if self.logicType in ('GREATER', 'STRGREATER','VERSION_GREATER'):
return operator.gt
elif self.logicType in ('LESS', 'STRLESS','VERSION_LESS'):
return operator.lt
elif self.logicType in ('EQUAL', 'STREQUAL', 'MATCHES','VERSION_EQUAL'):
return operator.eq
elif self.logicType in ('GREATER_EQUAL','VERSION_GREATER_EQUAL'):
return operator.ge
def getAssertions(self):
return simplify(self.returnOperator()(self.leftExpression.getAssertions(),
self.rightExpression.getAssertions()))
class Rule:
type: str = None
level: int = None
args: list = None
condition: LogicalExpression = None
flattenedResult: list = [set()]
def setCondition(self, condition: LogicalExpression):
self.condition = condition
self.args = self.getText().split()
def getCondition(self) -> LogicalExpression:
return self.condition
def setType(self, type: str):
self.type = type
def getType(self):
return self.type
def setLevel(self, level: int):
self.level = level
def setArgs(self, args: list):
self.args = args
def getArgs(self):
return self.args
def getText(self):
return self.condition.getText()