-
Notifications
You must be signed in to change notification settings - Fork 38
/
parser.py
295 lines (227 loc) · 6.9 KB
/
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
# -*- coding: utf-8 -*-
"""The Lucene Query DSL parser based on PLY
"""
# TODO : add reserved chars and escaping, regex
# see : https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
# https://lucene.apache.org/core/3_6_0/queryparsersyntax.html
import re
import ply.lex as lex
import ply.yacc as yacc
from .tree import *
class ParseError(ValueError):
"""Exception while parsing a lucene statement
"""
pass
reserved = {
'AND': 'AND_OP',
'OR': 'OR_OP',
'NOT': 'NOT',
'TO': 'TO'}
# tokens of our grammar
tokens = (
['TERM',
'PHRASE',
'REGEX',
'APPROX',
'BOOST',
'MINUS',
'PLUS',
'COLUMN',
'LPAREN',
'RPAREN',
'LBRACKET',
'RBRACKET'] +
# we sort to have a deterministic order, so that gammar signature does not changes
sorted(list(reserved.values())))
# text of some simple tokens
t_PLUS = r'\+'
t_MINUS = r'\-'
t_NOT = 'NOT'
t_AND_OP = r'AND'
t_OR_OP = r'OR'
t_COLUMN = r':'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACKET = r'(\[|\{)'
t_RBRACKET = r'(\]|\})'
# precedence rules
precedence = (
('left', 'OR_OP',),
('left', 'AND_OP'),
('nonassoc', 'MINUS',),
('nonassoc', 'PLUS',),
('nonassoc', 'APPROX'),
('nonassoc', 'BOOST'),
('nonassoc', 'LPAREN', 'RPAREN'),
('nonassoc', 'LBRACKET', 'TO', 'RBRACKET'),
('nonassoc', 'REGEX'),
('nonassoc', 'PHRASE'),
('nonassoc', 'TERM'),
)
# term
# the case of : which is used in date is problematic because it is also a delimiter
# lets catch those expressions appart
# Note : we must use positive look behind, because regexp engine is eager,
# and it's only arrived at ':' that it will try this rule
TIME_RE = r'''
(?<=T\d{2}): # look behind for T and two digits: hours
\d{2} # minutes
(:\d{2})? # seconds
'''
# this is a wide catching expression, to also include date math.
# Inspired by the original lucene parser:
# https://github.com/apache/lucene-solr/blob/master/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/parser/QueryParser.jj#L189
# We do allow the wildcards operators ('*' and '?') as our parser doesn't deal with them.
TERM_RE = r'''
(?P<term> # group term
(?:
[^\s:^~(){{}}[\]/,"'+\-\\] # first char is not a space neither some char which have meanings
# note: escape of "-" and "]"
# and doubling of "{{}}" (because we use format)
| # but
\\. # we can start with an escaped character
)
([^\s:^\\~(){{}}[\]] # following chars
| # OR
\\. # an escaped char
| # OR
{time_re} # a time expression
)*
)
'''.format(time_re=TIME_RE)
# phrase
PHRASE_RE = r'''
(?P<phrase> # phrase
" # opening quote
(?: # repeating
[^\\"] # - a char which is not escape or end of phrase
| # OR
\\. # - an escaped char
)*
" # closing quote
)'''
#r'(?P<phrase>"(?:[^\\"]|\\"|\\[^"])*")' # this is quite complicated to handle \"
# modifiers after term or phrase
APPROX_RE = r'~(?P<degree>[0-9.]+)?'
BOOST_RE = r'\^(?P<force>[0-9.]+)?'
# regex
REGEX_RE = r'''
(?P<regex> # regex
/ # open slash
(?: # repeating
[^\\/] # - a char which is not escape or end of regex
| # OR
\\. # an escaped char
)*
/ # closing slash
)'''
def t_SEPARATOR(t):
r'\s+'
pass # discard separators
@lex.TOKEN(TERM_RE)
def t_TERM(t):
# check if it is not a reserved term (an operation)
t.type = reserved.get(t.value, 'TERM')
# it's not, make it a Word
if t.type == 'TERM':
m = re.match(TERM_RE, t.value, re.VERBOSE)
value = m.group("term")
t.value = Word(value)
return t
@lex.TOKEN(PHRASE_RE)
def t_PHRASE(t):
m = re.match(PHRASE_RE, t.value, re.VERBOSE)
value = m.group("phrase")
t.value = Phrase(value)
return t
@lex.TOKEN(REGEX_RE)
def t_REGEX(t):
m = re.match(REGEX_RE, t.value, re.VERBOSE)
value = m.group("regex")
t.value = Regex(value)
return t
@lex.TOKEN(APPROX_RE)
def t_APPROX(t):
m = re.match(APPROX_RE, t.value)
t.value = m.group("degree")
return t
@lex.TOKEN(BOOST_RE)
def t_BOOST(t):
m = re.match(BOOST_RE, t.value)
t.value = m.group("force")
return t
# Error handling rule FIXME
def t_error(t): # pragma: no cover
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
lexer = lex.lex()
def p_expression_or(p):
'expression : expression OR_OP expression'
p[0] = create_operation(OrOperation, p[1], p[3])
def p_expression_and(p):
'''expression : expression AND_OP expression'''
p[0] = create_operation(AndOperation, p[1], p[len(p) - 1])
def p_expression_implicit(p):
'''expression : expression expression'''
p[0] = create_operation(UnknownOperation, p[1], p[2])
def p_expression_plus(p):
'''unary_expression : PLUS unary_expression'''
p[0] = Plus(p[2])
def p_expression_minus(p):
'''unary_expression : MINUS unary_expression'''
p[0] = Prohibit(p[2])
def p_expression_not(p):
'''unary_expression : NOT unary_expression'''
p[0] = Not(p[2])
def p_expression_unary(p):
'''expression : unary_expression'''
p[0] = p[1]
def p_grouping(p):
'unary_expression : LPAREN expression RPAREN'
p[0] = Group(p[2]) # Will p_field_search will transform as FieldGroup if necessary
def p_range(p):
'''unary_expression : LBRACKET phrase_or_term TO phrase_or_term RBRACKET'''
include_low = p[1] == "["
include_high = p[5] == "]"
p[0] = Range(p[2], p[4], include_low, include_high)
def p_field_search(p):
'''unary_expression : TERM COLUMN unary_expression'''
if isinstance(p[3], Group):
p[3] = group_to_fieldgroup(p[3])
# for field name we take p[1].value for it was captured as a word expression
p[0] = SearchField(p[1].value, p[3])
def p_quoting(p):
'unary_expression : PHRASE'
p[0] = p[1]
def p_proximity(p):
'''unary_expression : PHRASE APPROX'''
p[0] = Proximity(p[1], p[2])
def p_boosting(p):
'''expression : expression BOOST'''
p[0] = Boost(p[1], p[2])
def p_terms(p):
'''unary_expression : TERM'''
p[0] = p[1]
def p_fuzzy(p):
'''unary_expression : TERM APPROX'''
p[0] = Fuzzy(p[1], p[2])
def p_regex(p):
'''unary_expression : REGEX'''
p[0] = p[1]
# handling a special case, TO is reserved only in range
def p_to_as_term(p):
'''unary_expression : TO'''
p[0] = Word(p[1])
def p_phrase_or_term(p):
'''phrase_or_term : TERM
| PHRASE'''
p[0] = p[1]
# Error rule for syntax errors
# TODO : should report better
def p_error(p):
if p is None:
p = "(probably at end of input, may be unmatch parenthesis or so)"
raise ParseError("Syntax error in input at %r!" % p)
parser = yacc.yacc()
"""This is the parser generated by PLY
"""