You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

527 lines
19 KiB

4 years ago
  1. """Top down operator precedence parser.
  2. This is an implementation of Vaughan R. Pratt's
  3. "Top Down Operator Precedence" parser.
  4. (http://dl.acm.org/citation.cfm?doid=512927.512931).
  5. These are some additional resources that help explain the
  6. general idea behind a Pratt parser:
  7. * http://effbot.org/zone/simple-top-down-parsing.htm
  8. * http://javascript.crockford.com/tdop/tdop.html
  9. A few notes on the implementation.
  10. * All the nud/led tokens are on the Parser class itself, and are dispatched
  11. using getattr(). This keeps all the parsing logic contained to a single
  12. class.
  13. * We use two passes through the data. One to create a list of token,
  14. then one pass through the tokens to create the AST. While the lexer actually
  15. yields tokens, we convert it to a list so we can easily implement two tokens
  16. of lookahead. A previous implementation used a fixed circular buffer, but it
  17. was significantly slower. Also, the average jmespath expression typically
  18. does not have a large amount of token so this is not an issue. And
  19. interestingly enough, creating a token list first is actually faster than
  20. consuming from the token iterator one token at a time.
  21. """
  22. import random
  23. from jmespath import lexer
  24. from jmespath.compat import with_repr_method
  25. from jmespath import ast
  26. from jmespath import exceptions
  27. from jmespath import visitor
  28. class Parser(object):
  29. BINDING_POWER = {
  30. 'eof': 0,
  31. 'unquoted_identifier': 0,
  32. 'quoted_identifier': 0,
  33. 'literal': 0,
  34. 'rbracket': 0,
  35. 'rparen': 0,
  36. 'comma': 0,
  37. 'rbrace': 0,
  38. 'number': 0,
  39. 'current': 0,
  40. 'expref': 0,
  41. 'colon': 0,
  42. 'pipe': 1,
  43. 'or': 2,
  44. 'and': 3,
  45. 'eq': 5,
  46. 'gt': 5,
  47. 'lt': 5,
  48. 'gte': 5,
  49. 'lte': 5,
  50. 'ne': 5,
  51. 'flatten': 9,
  52. # Everything above stops a projection.
  53. 'star': 20,
  54. 'filter': 21,
  55. 'dot': 40,
  56. 'not': 45,
  57. 'lbrace': 50,
  58. 'lbracket': 55,
  59. 'lparen': 60,
  60. }
  61. # The maximum binding power for a token that can stop
  62. # a projection.
  63. _PROJECTION_STOP = 10
  64. # The _MAX_SIZE most recent expressions are cached in
  65. # _CACHE dict.
  66. _CACHE = {}
  67. _MAX_SIZE = 128
  68. def __init__(self, lookahead=2):
  69. self.tokenizer = None
  70. self._tokens = [None] * lookahead
  71. self._buffer_size = lookahead
  72. self._index = 0
  73. def parse(self, expression):
  74. cached = self._CACHE.get(expression)
  75. if cached is not None:
  76. return cached
  77. parsed_result = self._do_parse(expression)
  78. self._CACHE[expression] = parsed_result
  79. if len(self._CACHE) > self._MAX_SIZE:
  80. self._free_cache_entries()
  81. return parsed_result
  82. def _do_parse(self, expression):
  83. try:
  84. return self._parse(expression)
  85. except exceptions.LexerError as e:
  86. e.expression = expression
  87. raise
  88. except exceptions.IncompleteExpressionError as e:
  89. e.set_expression(expression)
  90. raise
  91. except exceptions.ParseError as e:
  92. e.expression = expression
  93. raise
  94. def _parse(self, expression):
  95. self.tokenizer = lexer.Lexer().tokenize(expression)
  96. self._tokens = list(self.tokenizer)
  97. self._index = 0
  98. parsed = self._expression(binding_power=0)
  99. if not self._current_token() == 'eof':
  100. t = self._lookahead_token(0)
  101. raise exceptions.ParseError(t['start'], t['value'], t['type'],
  102. "Unexpected token: %s" % t['value'])
  103. return ParsedResult(expression, parsed)
  104. def _expression(self, binding_power=0):
  105. left_token = self._lookahead_token(0)
  106. self._advance()
  107. nud_function = getattr(
  108. self, '_token_nud_%s' % left_token['type'],
  109. self._error_nud_token)
  110. left = nud_function(left_token)
  111. current_token = self._current_token()
  112. while binding_power < self.BINDING_POWER[current_token]:
  113. led = getattr(self, '_token_led_%s' % current_token, None)
  114. if led is None:
  115. error_token = self._lookahead_token(0)
  116. self._error_led_token(error_token)
  117. else:
  118. self._advance()
  119. left = led(left)
  120. current_token = self._current_token()
  121. return left
  122. def _token_nud_literal(self, token):
  123. return ast.literal(token['value'])
  124. def _token_nud_unquoted_identifier(self, token):
  125. return ast.field(token['value'])
  126. def _token_nud_quoted_identifier(self, token):
  127. field = ast.field(token['value'])
  128. # You can't have a quoted identifier as a function
  129. # name.
  130. if self._current_token() == 'lparen':
  131. t = self._lookahead_token(0)
  132. raise exceptions.ParseError(
  133. 0, t['value'], t['type'],
  134. 'Quoted identifier not allowed for function names.')
  135. return field
  136. def _token_nud_star(self, token):
  137. left = ast.identity()
  138. if self._current_token() == 'rbracket':
  139. right = ast.identity()
  140. else:
  141. right = self._parse_projection_rhs(self.BINDING_POWER['star'])
  142. return ast.value_projection(left, right)
  143. def _token_nud_filter(self, token):
  144. return self._token_led_filter(ast.identity())
  145. def _token_nud_lbrace(self, token):
  146. return self._parse_multi_select_hash()
  147. def _token_nud_lparen(self, token):
  148. expression = self._expression()
  149. self._match('rparen')
  150. return expression
  151. def _token_nud_flatten(self, token):
  152. left = ast.flatten(ast.identity())
  153. right = self._parse_projection_rhs(
  154. self.BINDING_POWER['flatten'])
  155. return ast.projection(left, right)
  156. def _token_nud_not(self, token):
  157. expr = self._expression(self.BINDING_POWER['not'])
  158. return ast.not_expression(expr)
  159. def _token_nud_lbracket(self, token):
  160. if self._current_token() in ['number', 'colon']:
  161. right = self._parse_index_expression()
  162. # We could optimize this and remove the identity() node.
  163. # We don't really need an index_expression node, we can
  164. # just use emit an index node here if we're not dealing
  165. # with a slice.
  166. return self._project_if_slice(ast.identity(), right)
  167. elif self._current_token() == 'star' and \
  168. self._lookahead(1) == 'rbracket':
  169. self._advance()
  170. self._advance()
  171. right = self._parse_projection_rhs(self.BINDING_POWER['star'])
  172. return ast.projection(ast.identity(), right)
  173. else:
  174. return self._parse_multi_select_list()
  175. def _parse_index_expression(self):
  176. # We're here:
  177. # [<current>
  178. # ^
  179. # | current token
  180. if (self._lookahead(0) == 'colon' or
  181. self._lookahead(1) == 'colon'):
  182. return self._parse_slice_expression()
  183. else:
  184. # Parse the syntax [number]
  185. node = ast.index(self._lookahead_token(0)['value'])
  186. self._advance()
  187. self._match('rbracket')
  188. return node
  189. def _parse_slice_expression(self):
  190. # [start:end:step]
  191. # Where start, end, and step are optional.
  192. # The last colon is optional as well.
  193. parts = [None, None, None]
  194. index = 0
  195. current_token = self._current_token()
  196. while not current_token == 'rbracket' and index < 3:
  197. if current_token == 'colon':
  198. index += 1
  199. if index == 3:
  200. self._raise_parse_error_for_token(
  201. self._lookahead_token(0), 'syntax error')
  202. self._advance()
  203. elif current_token == 'number':
  204. parts[index] = self._lookahead_token(0)['value']
  205. self._advance()
  206. else:
  207. self._raise_parse_error_for_token(
  208. self._lookahead_token(0), 'syntax error')
  209. current_token = self._current_token()
  210. self._match('rbracket')
  211. return ast.slice(*parts)
  212. def _token_nud_current(self, token):
  213. return ast.current_node()
  214. def _token_nud_expref(self, token):
  215. expression = self._expression(self.BINDING_POWER['expref'])
  216. return ast.expref(expression)
  217. def _token_led_dot(self, left):
  218. if not self._current_token() == 'star':
  219. right = self._parse_dot_rhs(self.BINDING_POWER['dot'])
  220. if left['type'] == 'subexpression':
  221. left['children'].append(right)
  222. return left
  223. else:
  224. return ast.subexpression([left, right])
  225. else:
  226. # We're creating a projection.
  227. self._advance()
  228. right = self._parse_projection_rhs(
  229. self.BINDING_POWER['dot'])
  230. return ast.value_projection(left, right)
  231. def _token_led_pipe(self, left):
  232. right = self._expression(self.BINDING_POWER['pipe'])
  233. return ast.pipe(left, right)
  234. def _token_led_or(self, left):
  235. right = self._expression(self.BINDING_POWER['or'])
  236. return ast.or_expression(left, right)
  237. def _token_led_and(self, left):
  238. right = self._expression(self.BINDING_POWER['and'])
  239. return ast.and_expression(left, right)
  240. def _token_led_lparen(self, left):
  241. if left['type'] != 'field':
  242. # 0 - first func arg or closing paren.
  243. # -1 - '(' token
  244. # -2 - invalid function "name".
  245. prev_t = self._lookahead_token(-2)
  246. raise exceptions.ParseError(
  247. prev_t['start'], prev_t['value'], prev_t['type'],
  248. "Invalid function name '%s'" % prev_t['value'])
  249. name = left['value']
  250. args = []
  251. while not self._current_token() == 'rparen':
  252. expression = self._expression()
  253. if self._current_token() == 'comma':
  254. self._match('comma')
  255. args.append(expression)
  256. self._match('rparen')
  257. function_node = ast.function_expression(name, args)
  258. return function_node
  259. def _token_led_filter(self, left):
  260. # Filters are projections.
  261. condition = self._expression(0)
  262. self._match('rbracket')
  263. if self._current_token() == 'flatten':
  264. right = ast.identity()
  265. else:
  266. right = self._parse_projection_rhs(self.BINDING_POWER['filter'])
  267. return ast.filter_projection(left, right, condition)
  268. def _token_led_eq(self, left):
  269. return self._parse_comparator(left, 'eq')
  270. def _token_led_ne(self, left):
  271. return self._parse_comparator(left, 'ne')
  272. def _token_led_gt(self, left):
  273. return self._parse_comparator(left, 'gt')
  274. def _token_led_gte(self, left):
  275. return self._parse_comparator(left, 'gte')
  276. def _token_led_lt(self, left):
  277. return self._parse_comparator(left, 'lt')
  278. def _token_led_lte(self, left):
  279. return self._parse_comparator(left, 'lte')
  280. def _token_led_flatten(self, left):
  281. left = ast.flatten(left)
  282. right = self._parse_projection_rhs(
  283. self.BINDING_POWER['flatten'])
  284. return ast.projection(left, right)
  285. def _token_led_lbracket(self, left):
  286. token = self._lookahead_token(0)
  287. if token['type'] in ['number', 'colon']:
  288. right = self._parse_index_expression()
  289. if left['type'] == 'index_expression':
  290. # Optimization: if the left node is an index expr,
  291. # we can avoid creating another node and instead just add
  292. # the right node as a child of the left.
  293. left['children'].append(right)
  294. return left
  295. else:
  296. return self._project_if_slice(left, right)
  297. else:
  298. # We have a projection
  299. self._match('star')
  300. self._match('rbracket')
  301. right = self._parse_projection_rhs(self.BINDING_POWER['star'])
  302. return ast.projection(left, right)
  303. def _project_if_slice(self, left, right):
  304. index_expr = ast.index_expression([left, right])
  305. if right['type'] == 'slice':
  306. return ast.projection(
  307. index_expr,
  308. self._parse_projection_rhs(self.BINDING_POWER['star']))
  309. else:
  310. return index_expr
  311. def _parse_comparator(self, left, comparator):
  312. right = self._expression(self.BINDING_POWER[comparator])
  313. return ast.comparator(comparator, left, right)
  314. def _parse_multi_select_list(self):
  315. expressions = []
  316. while True:
  317. expression = self._expression()
  318. expressions.append(expression)
  319. if self._current_token() == 'rbracket':
  320. break
  321. else:
  322. self._match('comma')
  323. self._match('rbracket')
  324. return ast.multi_select_list(expressions)
  325. def _parse_multi_select_hash(self):
  326. pairs = []
  327. while True:
  328. key_token = self._lookahead_token(0)
  329. # Before getting the token value, verify it's
  330. # an identifier.
  331. self._match_multiple_tokens(
  332. token_types=['quoted_identifier', 'unquoted_identifier'])
  333. key_name = key_token['value']
  334. self._match('colon')
  335. value = self._expression(0)
  336. node = ast.key_val_pair(key_name=key_name, node=value)
  337. pairs.append(node)
  338. if self._current_token() == 'comma':
  339. self._match('comma')
  340. elif self._current_token() == 'rbrace':
  341. self._match('rbrace')
  342. break
  343. return ast.multi_select_dict(nodes=pairs)
  344. def _parse_projection_rhs(self, binding_power):
  345. # Parse the right hand side of the projection.
  346. if self.BINDING_POWER[self._current_token()] < self._PROJECTION_STOP:
  347. # BP of 10 are all the tokens that stop a projection.
  348. right = ast.identity()
  349. elif self._current_token() == 'lbracket':
  350. right = self._expression(binding_power)
  351. elif self._current_token() == 'filter':
  352. right = self._expression(binding_power)
  353. elif self._current_token() == 'dot':
  354. self._match('dot')
  355. right = self._parse_dot_rhs(binding_power)
  356. else:
  357. self._raise_parse_error_for_token(self._lookahead_token(0),
  358. 'syntax error')
  359. return right
  360. def _parse_dot_rhs(self, binding_power):
  361. # From the grammar:
  362. # expression '.' ( identifier /
  363. # multi-select-list /
  364. # multi-select-hash /
  365. # function-expression /
  366. # *
  367. # In terms of tokens that means that after a '.',
  368. # you can have:
  369. lookahead = self._current_token()
  370. # Common case "foo.bar", so first check for an identifier.
  371. if lookahead in ['quoted_identifier', 'unquoted_identifier', 'star']:
  372. return self._expression(binding_power)
  373. elif lookahead == 'lbracket':
  374. self._match('lbracket')
  375. return self._parse_multi_select_list()
  376. elif lookahead == 'lbrace':
  377. self._match('lbrace')
  378. return self._parse_multi_select_hash()
  379. else:
  380. t = self._lookahead_token(0)
  381. allowed = ['quoted_identifier', 'unquoted_identifier',
  382. 'lbracket', 'lbrace']
  383. msg = (
  384. "Expecting: %s, got: %s" % (allowed, t['type'])
  385. )
  386. self._raise_parse_error_for_token(t, msg)
  387. def _error_nud_token(self, token):
  388. if token['type'] == 'eof':
  389. raise exceptions.IncompleteExpressionError(
  390. token['start'], token['value'], token['type'])
  391. self._raise_parse_error_for_token(token, 'invalid token')
  392. def _error_led_token(self, token):
  393. self._raise_parse_error_for_token(token, 'invalid token')
  394. def _match(self, token_type=None):
  395. # inline'd self._current_token()
  396. if self._current_token() == token_type:
  397. # inline'd self._advance()
  398. self._advance()
  399. else:
  400. self._raise_parse_error_maybe_eof(
  401. token_type, self._lookahead_token(0))
  402. def _match_multiple_tokens(self, token_types):
  403. if self._current_token() not in token_types:
  404. self._raise_parse_error_maybe_eof(
  405. token_types, self._lookahead_token(0))
  406. self._advance()
  407. def _advance(self):
  408. self._index += 1
  409. def _current_token(self):
  410. return self._tokens[self._index]['type']
  411. def _lookahead(self, number):
  412. return self._tokens[self._index + number]['type']
  413. def _lookahead_token(self, number):
  414. return self._tokens[self._index + number]
  415. def _raise_parse_error_for_token(self, token, reason):
  416. lex_position = token['start']
  417. actual_value = token['value']
  418. actual_type = token['type']
  419. raise exceptions.ParseError(lex_position, actual_value,
  420. actual_type, reason)
  421. def _raise_parse_error_maybe_eof(self, expected_type, token):
  422. lex_position = token['start']
  423. actual_value = token['value']
  424. actual_type = token['type']
  425. if actual_type == 'eof':
  426. raise exceptions.IncompleteExpressionError(
  427. lex_position, actual_value, actual_type)
  428. message = 'Expecting: %s, got: %s' % (expected_type,
  429. actual_type)
  430. raise exceptions.ParseError(
  431. lex_position, actual_value, actual_type, message)
  432. def _free_cache_entries(self):
  433. for key in random.sample(self._CACHE.keys(), int(self._MAX_SIZE / 2)):
  434. del self._CACHE[key]
  435. @classmethod
  436. def purge(cls):
  437. """Clear the expression compilation cache."""
  438. cls._CACHE.clear()
  439. @with_repr_method
  440. class ParsedResult(object):
  441. def __init__(self, expression, parsed):
  442. self.expression = expression
  443. self.parsed = parsed
  444. def search(self, value, options=None):
  445. interpreter = visitor.TreeInterpreter(options)
  446. result = interpreter.visit(self.parsed, value)
  447. return result
  448. def _render_dot_file(self):
  449. """Render the parsed AST as a dot file.
  450. Note that this is marked as an internal method because
  451. the AST is an implementation detail and is subject
  452. to change. This method can be used to help troubleshoot
  453. or for development purposes, but is not considered part
  454. of the public supported API. Use at your own risk.
  455. """
  456. renderer = visitor.GraphvizVisitor()
  457. contents = renderer.visit(self.parsed)
  458. return contents
  459. def __repr__(self):
  460. return repr(self.parsed)