-
Notifications
You must be signed in to change notification settings - Fork 1
/
QueryEvaluator.py
70 lines (64 loc) · 2.49 KB
/
QueryEvaluator.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
import TagHandler
import re
# Implementation of shuning yard algorithm
class QueryEvaluator :
def __init__(self, th: TagHandler.TagHandler) :
self.th = th
self.operators = []
self.values = []
self.fullresources = []
def tokenize(self, querystr):
tokens = re.findall("[()&|~]|[a-z0-9]+", querystr)
return tokens
def peek(self):
return self.operators[-1] if self.operators else None
def apply_operator(self) :
operator = self.operators.pop()
if operator == "&" :
v1 = self.values.pop()
v2 = self.values.pop()
self.values.append(v1.intersection(v2))
elif operator == "|" :
v1 = self.values.pop()
v2 = self.values.pop()
self.values.append(v1.union(v2))
elif operator == "~" :
v1 = self.values.pop()
if len(self.fullresources) == 0 :
self.fullresources = set(self.th.get_resource_ids())
self.values.append(self.fullresources.difference(v1))
else :
print("invalid operator")
exit(1)
def greater_precedence(self, op1, op2):
precedences = {"|": 0, "~": 0, "&": 1}
return precedences[op1] > precedences[op2]
def evaluate_query(self, expression):
tokens = self.tokenize(expression)
self.values = []
self.operators = []
for token in tokens:
if token == "(":
self.operators.append(token)
elif token == ")":
top = self.peek()
while top is not None and top != "(":
self.apply_operator()
top = self.peek()
self.operators.pop() # Discard the '('
elif token[0] not in ['|','&','~']:
tag_closure = self.th.get_tag_closure([token])
tag_closure_ids = list(map(self.th.get_tag_id, tag_closure))
r = set(self.th.get_resources_by_tag_id(tag_closure_ids))
self.values.append(r)
else:
# Operator
top = self.peek()
while top is not None and top != "(" and self.greater_precedence(top, token):
self.apply_operator()
top = self.peek()
self.operators.append(token)
while self.peek() is not None:
self.apply_operator()
res = list(map(self.th.get_resource_url, self.values[0]))
return res