Coverage for python/lsst/daf/butler/registry/queries/expressions/parser/parserYacc.py: 21%
162 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-01 11:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-01 11:00 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <https://www.gnu.org/licenses/>.
28# type: ignore
30"""Syntax definition for user expression parser.
31"""
33__all__ = ["ParserYacc", "ParserYaccError", "ParseError", "ParserEOFError"]
35# -------------------------------
36# Imports of standard modules --
37# -------------------------------
38import re
39import warnings
41# -----------------------------
42# Imports for other modules --
43# -----------------------------
44import astropy.time
46# As of astropy 4.2, the erfa interface is shipped independently and
47# ErfaWarning is no longer an AstropyWarning
48try:
49 import erfa
50except ImportError:
51 erfa = None
53from .exprTree import (
54 BinaryOp,
55 Identifier,
56 IsIn,
57 NumericLiteral,
58 Parens,
59 RangeLiteral,
60 StringLiteral,
61 TimeLiteral,
62 TupleNode,
63 UnaryOp,
64 function_call,
65)
66from .parserLex import ParserLex
67from .ply import yacc
69# ----------------------------------
70# Local non-exported definitions --
71# ----------------------------------
73# The purpose of this regex is to guess time format if it is not explicitly
74# provided in the string itself
75_re_time_str = re.compile(
76 r"""
77 ((?P<format>\w+)/)? # optionally prefixed by "format/"
78 (?P<value>
79 (?P<number>-?(\d+(\.\d*)|(\.\d+))) # floating point number
80 |
81 (?P<iso>\d+-\d+-\d+([ T]\d+:\d+(:\d+([.]\d*)?)?)?) # iso(t) [no timezone]
82 |
83 (?P<fits>[+]\d+-\d+-\d+(T\d+:\d+:\d+([.]\d*)?)?) # fits
84 |
85 (?P<yday>\d+:\d+(:\d+:\d+(:\d+([.]\d*)?)?)?) # yday
86 )
87 (/(?P<scale>\w+))? # optionally followed by "/scale"
88 $
89""",
90 re.VERBOSE | re.IGNORECASE,
91)
94def _parseTimeString(time_str):
95 """Try to convert time string into astropy.Time.
97 Parameters
98 ----------
99 time_str : `str`
100 Input string.
102 Returns
103 -------
104 time : `astropy.time.Time`
106 Raises
107 ------
108 ValueError
109 Raised if input string has unexpected format
110 """
111 # Check for time zone. Python datetime objects can be timezone-aware
112 # and if one has been stringified then there will be a +00:00 on the end.
113 # Special case UTC. Fail for other timezones.
114 time_str = time_str.replace("+00:00", "")
116 match = _re_time_str.match(time_str)
117 if not match:
118 raise ValueError(f'Time string "{time_str}" does not match known formats')
120 value, fmt, scale = match.group("value", "format", "scale")
121 if fmt is not None:
122 fmt = fmt.lower()
123 if fmt not in astropy.time.Time.FORMATS:
124 raise ValueError(f'Time string "{time_str}" specifies unknown time format "{fmt}"')
125 if scale is not None:
126 scale = scale.lower()
127 if scale not in astropy.time.Time.SCALES:
128 raise ValueError(f'Time string "{time_str}" specifies unknown time scale "{scale}"')
130 # convert number string to floating point
131 if match.group("number") is not None:
132 value = float(value)
134 # guess format if not given
135 if fmt is None:
136 if match.group("number") is not None:
137 fmt = "mjd"
138 elif match.group("iso") is not None:
139 if "T" in value or "t" in value:
140 fmt = "isot"
141 else:
142 fmt = "iso"
143 elif match.group("fits") is not None:
144 fmt = "fits"
145 elif match.group("yday") is not None:
146 fmt = "yday"
147 assert fmt is not None
149 # guess scale if not given
150 if scale is None:
151 if fmt in ("iso", "isot", "fits", "yday", "unix"):
152 scale = "utc"
153 elif fmt == "cxcsec":
154 scale = "tt"
155 else:
156 scale = "tai"
158 try:
159 # Hide warnings about future dates
160 with warnings.catch_warnings():
161 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning)
162 if erfa is not None:
163 warnings.simplefilter("ignore", category=erfa.ErfaWarning)
164 value = astropy.time.Time(value, format=fmt, scale=scale)
165 except ValueError:
166 # astropy makes very verbose exception that is not super-useful in
167 # many context, just say we don't like it.
168 raise ValueError(f'Time string "{time_str}" does not match format "{fmt}"') from None
170 return value
173# ------------------------
174# Exported definitions --
175# ------------------------
178class ParserYaccError(Exception):
179 """Base class for exceptions generated by parser."""
181 pass
184class ParseError(ParserYaccError):
185 """Exception raised for parsing errors.
187 Attributes
188 ----------
189 expression : str
190 Full initial expression being parsed
191 token : str
192 Current token at parsing position
193 pos : int
194 Current parsing position, offset from beginning of expression in
195 characters
196 lineno : int
197 Current line number in the expression
198 posInLine : int
199 Parsing position in current line, 0-based
200 """
202 def __init__(self, expression, token, pos, lineno):
203 self.expression = expression
204 self.token = token
205 self.pos = pos
206 self.lineno = lineno
207 self.posInLine = self._posInLine()
208 msg = "Syntax error at or near '{0}' (line: {1}, pos: {2})"
209 msg = msg.format(token, lineno, self.posInLine + 1)
210 ParserYaccError.__init__(self, msg)
212 def _posInLine(self):
213 """Return position in current line"""
214 lines = self.expression.split("\n")
215 pos = self.pos
216 for line in lines[: self.lineno - 1]:
217 # +1 for newline
218 pos -= len(line) + 1
219 return pos
222class ParserEOFError(ParserYaccError):
223 """Exception raised for EOF-during-parser."""
225 def __init__(self):
226 Exception.__init__(self, "End of input reached while expecting further input")
229class ParserYacc:
230 """Class which defines PLY grammar.
232 Based on MySQL grammar for expressions
233 (https://dev.mysql.com/doc/refman/5.7/en/expressions.html).
235 Parameters
236 ----------
237 idMap : `collections.abc.Mapping` [ `str`, `Node` ], optional
238 Mapping that provides substitutions for identifiers in the expression.
239 The key in the map is the identifier name, the value is the
240 `exprTree.Node` instance that will replace identifier in the full
241 expression. If identifier does not exist in the mapping then
242 `Identifier` is inserted into parse tree.
243 **kwargs
244 optional keyword arguments that are passed to `yacc.yacc` constructor.
245 """
247 def __init__(self, idMap=None, **kwargs):
248 kw = dict(write_tables=0, debug=False)
249 kw.update(kwargs)
251 self.parser = yacc.yacc(module=self, **kw)
252 self._idMap = idMap or {}
254 def parse(self, input, lexer=None, debug=False, tracking=False):
255 """Parse input expression ad return parsed tree object.
257 This is a trivial wrapper for yacc.LRParser.parse method which
258 provides lexer if not given in arguments.
260 Parameters
261 ----------
262 input : str
263 Expression to parse
264 lexer : object, optional
265 Lexer instance, if not given then ParserLex.make_lexer() is
266 called to create one.
267 debug : bool, optional
268 Set to True for debugging output.
269 tracking : bool, optional
270 Set to True for tracking line numbers in parser.
271 """
272 # make lexer
273 if lexer is None:
274 lexer = ParserLex.make_lexer()
275 tree = self.parser.parse(input=input, lexer=lexer, debug=debug, tracking=tracking)
276 return tree
278 tokens = ParserLex.tokens[:]
280 precedence = (
281 ("left", "OR"),
282 ("left", "AND"),
283 ("nonassoc", "OVERLAPS"), # Nonassociative operators
284 ("nonassoc", "EQ", "NE"), # Nonassociative operators
285 ("nonassoc", "LT", "LE", "GT", "GE"), # Nonassociative operators
286 ("left", "ADD", "SUB"),
287 ("left", "MUL", "DIV", "MOD"),
288 ("right", "UPLUS", "UMINUS", "NOT"), # unary plus and minus
289 )
291 # this is the starting rule
292 def p_input(self, p):
293 """input : expr
294 | empty
295 """
296 p[0] = p[1]
298 def p_empty(self, p):
299 """empty :"""
300 p[0] = None
302 def p_expr(self, p):
303 """expr : expr OR expr
304 | expr AND expr
305 | NOT expr
306 | bool_primary
307 """
308 if len(p) == 4:
309 p[0] = BinaryOp(lhs=p[1], op=p[2].upper(), rhs=p[3])
310 elif len(p) == 3:
311 p[0] = UnaryOp(op=p[1].upper(), operand=p[2])
312 else:
313 p[0] = p[1]
315 def p_bool_primary(self, p):
316 """bool_primary : bool_primary EQ predicate
317 | bool_primary NE predicate
318 | bool_primary LT predicate
319 | bool_primary LE predicate
320 | bool_primary GE predicate
321 | bool_primary GT predicate
322 | bool_primary OVERLAPS predicate
323 | predicate
324 """
325 if len(p) == 2:
326 p[0] = p[1]
327 else:
328 p[0] = BinaryOp(lhs=p[1], op=p[2], rhs=p[3])
330 def p_predicate(self, p):
331 """predicate : bit_expr IN LPAREN literal_or_id_list RPAREN
332 | bit_expr NOT IN LPAREN literal_or_id_list RPAREN
333 | bit_expr
334 """
335 if len(p) == 6:
336 p[0] = IsIn(lhs=p[1], values=p[4])
337 elif len(p) == 7:
338 p[0] = IsIn(lhs=p[1], values=p[5], not_in=True)
339 else:
340 p[0] = p[1]
342 def p_identifier(self, p):
343 """identifier : SIMPLE_IDENTIFIER
344 | QUALIFIED_IDENTIFIER
345 """
346 node = self._idMap.get(p[1])
347 if node is None:
348 node = Identifier(p[1])
349 p[0] = node
351 def p_literal_or_id_list(self, p):
352 """literal_or_id_list : literal_or_id_list COMMA literal
353 | literal_or_id_list COMMA identifier
354 | literal
355 | identifier
356 """
357 if len(p) == 2:
358 p[0] = [p[1]]
359 else:
360 p[0] = p[1] + [p[3]]
362 def p_bit_expr(self, p):
363 """bit_expr : bit_expr ADD bit_expr
364 | bit_expr SUB bit_expr
365 | bit_expr MUL bit_expr
366 | bit_expr DIV bit_expr
367 | bit_expr MOD bit_expr
368 | simple_expr
369 """
370 if len(p) == 2:
371 p[0] = p[1]
372 else:
373 p[0] = BinaryOp(lhs=p[1], op=p[2], rhs=p[3])
375 def p_simple_expr_lit(self, p):
376 """simple_expr : literal"""
377 p[0] = p[1]
379 def p_simple_expr_id(self, p):
380 """simple_expr : identifier"""
381 p[0] = p[1]
383 def p_simple_expr_function_call(self, p):
384 """simple_expr : function_call"""
385 p[0] = p[1]
387 def p_simple_expr_unary(self, p):
388 """simple_expr : ADD simple_expr %prec UPLUS
389 | SUB simple_expr %prec UMINUS
390 """
391 p[0] = UnaryOp(op=p[1], operand=p[2])
393 def p_simple_expr_paren(self, p):
394 """simple_expr : LPAREN expr RPAREN"""
395 p[0] = Parens(p[2])
397 def p_simple_expr_tuple(self, p):
398 """simple_expr : LPAREN expr COMMA expr RPAREN"""
399 # For now we only support tuples with two items,
400 # these are used for time ranges.
401 p[0] = TupleNode((p[2], p[4]))
403 def p_literal_num(self, p):
404 """literal : NUMERIC_LITERAL"""
405 p[0] = NumericLiteral(p[1])
407 def p_literal_num_signed(self, p):
408 """literal : ADD NUMERIC_LITERAL %prec UPLUS
409 | SUB NUMERIC_LITERAL %prec UMINUS
410 """
411 p[0] = NumericLiteral(p[1] + p[2])
413 def p_literal_str(self, p):
414 """literal : STRING_LITERAL"""
415 p[0] = StringLiteral(p[1])
417 def p_literal_time(self, p):
418 """literal : TIME_LITERAL"""
419 try:
420 value = _parseTimeString(p[1])
421 except ValueError as e:
422 raise ParseError(p.lexer.lexdata, p[1], p.lexpos(1), p.lineno(1)) from e
423 p[0] = TimeLiteral(value)
425 def p_literal_range(self, p):
426 """literal : RANGE_LITERAL"""
427 # RANGE_LITERAL value is tuple of three numbers
428 start, stop, stride = p[1]
429 p[0] = RangeLiteral(start, stop, stride)
431 def p_function_call(self, p):
432 """function_call : SIMPLE_IDENTIFIER LPAREN expr_list RPAREN"""
433 p[0] = function_call(p[1], p[3])
435 def p_expr_list(self, p):
436 """expr_list : expr_list COMMA expr
437 | expr
438 | empty
439 """
440 if len(p) == 2:
441 if p[1] is None:
442 p[0] = []
443 else:
444 p[0] = [p[1]]
445 else:
446 p[0] = p[1] + [p[3]]
448 # ---------- end of all grammar rules ----------
450 # Error rule for syntax errors
451 def p_error(self, p):
452 if p is None:
453 raise ParserEOFError()
454 else:
455 raise ParseError(p.lexer.lexdata, p.value, p.lexpos, p.lineno)