Debian Codegraph @

lib/3rdParty/composer/mtdowling/jmespath.php/src/Parser.php

raw symbols SCIP
1 <?php
2 namespace JmesPath;
3
4 use JmesPath\Lexer as T;
5
6 /**
7 * JMESPath Pratt parser
8 * @link http://hall.org.ua/halls/wizzard/pdf/Vaughan.Pratt.TDOP.pdf
9 */
10 class Parser
11 {
12 /** @var Lexer */
13 private $lexer;
14 private $tokens;
15 private $token;
16 private $tpos;
17 private $expression;
18 private static $nullToken = ['type' => T::T_EOF];
19 private static $currentNode = ['type' => T::T_CURRENT];
20
21 private static $bp = [
22 T::T_EOF => 0,
23 T::T_QUOTED_IDENTIFIER => 0,
24 T::T_IDENTIFIER => 0,
25 T::T_UNKNOWN => 0,
26 T::T_LITERAL => 0,
27 T::T_RBRACKET => 0,
28 T::T_RPAREN => 0,
29 T::T_COMMA => 0,
30 T::T_RBRACE => 0,
31 T::T_NUMBER => 0,
32 T::T_CURRENT => 0,
33 T::T_EXPREF => 0,
34 T::T_COLON => 0,
35 T::T_PIPE => 1,
36 T::T_OR => 2,
37 T::T_AND => 3,
38 T::T_COMPARATOR => 5,
39 T::T_FLATTEN => 9,
40 T::T_STAR => 20,
41 T::T_FILTER => 21,
42 T::T_DOT => 40,
43 T::T_NOT => 45,
44 T::T_LBRACE => 50,
45 T::T_LBRACKET => 55,
46 T::T_LPAREN => 60,
47 ];
48
49 /** @var array Acceptable tokens after a dot token */
50 private static $afterDot = [
51 T::T_IDENTIFIER => true, // foo.bar
52 T::T_QUOTED_IDENTIFIER => true, // foo."bar"
53 T::T_STAR => true, // foo.*
54 T::T_LBRACE => true, // foo[1]
55 T::T_LBRACKET => true, // foo{a: 0}
56 T::T_FILTER => true, // foo.[?bar==10]
57 ];
58
59 /**
60 * @param Lexer|null $lexer Lexer used to tokenize expressions
61 */
62 public function __construct(?Lexer $lexer = null)
63 {
64 $this->lexer = $lexer ?: new Lexer();
65 }
66
67 /**
68 * Parses a JMESPath expression into an AST
69 *
70 * @param string $expression JMESPath expression to compile
71 *
72 * @return array Returns an array based AST
73 * @throws SyntaxErrorException
74 */
75 public function parse($expression)
76 {
77 $this->expression = $expression;
78 $this->tokens = $this->lexer->tokenize($expression);
79 $this->tpos = -1;
80 $this->next();
81 $result = $this->expr();
82
83 if ($this->token['type'] === T::T_EOF) {
84 return $result;
85 }
86
87 throw $this->syntax('Did not reach the end of the token stream');
88 }
89
90 /**
91 * Parses an expression while rbp < lbp.
92 *
93 * @param int $rbp Right bound precedence
94 *
95 * @return array
96 */
97 private function expr($rbp = 0)
98 {
99 $left = $this->{"nud_{$this->token['type']}"}();
100 while ($rbp < self::$bp[$this->token['type']]) {
101 $left = $this->{"led_{$this->token['type']}"}($left);
102 }
103
104 return $left;
105 }
106
107 private function nud_identifier()
108 {
109 $token = $this->token;
110 $this->next();
111 return ['type' => 'field', 'value' => $token['value']];
112 }
113
114 private function nud_quoted_identifier()
115 {
116 $token = $this->token;
117 $this->next();
118 $this->assertNotToken(T::T_LPAREN);
119 return ['type' => 'field', 'value' => $token['value']];
120 }
121
122 private function nud_current()
123 {
124 $this->next();
125 return self::$currentNode;
126 }
127
128 private function nud_literal()
129 {
130 $token = $this->token;
131 $this->next();
132 return ['type' => 'literal', 'value' => $token['value']];
133 }
134
135 private function nud_expref()
136 {
137 $this->next();
138 return ['type' => T::T_EXPREF, 'children' => [$this->expr(self::$bp[T::T_EXPREF])]];
139 }
140
141 private function nud_not()
142 {
143 $this->next();
144 return ['type' => T::T_NOT, 'children' => [$this->expr(self::$bp[T::T_NOT])]];
145 }
146
147 private function nud_lparen()
148 {
149 $this->next();
150 $result = $this->expr(0);
151 if ($this->token['type'] !== T::T_RPAREN) {
152 throw $this->syntax('Unclosed `(`');
153 }
154 $this->next();
155 return $result;
156 }
157
158 private function nud_lbrace()
159 {
160 static $validKeys = [T::T_QUOTED_IDENTIFIER => true, T::T_IDENTIFIER => true];
161 $this->next($validKeys);
162 $pairs = [];
163
164 do {
165 $pairs[] = $this->parseKeyValuePair();
166 if ($this->token['type'] == T::T_COMMA) {
167 $this->next($validKeys);
168 }
169 } while ($this->token['type'] !== T::T_RBRACE);
170
171 $this->next();
172
173 return['type' => 'multi_select_hash', 'children' => $pairs];
174 }
175
176 private function nud_flatten()
177 {
178 return $this->led_flatten(self::$currentNode);
179 }
180
181 private function nud_filter()
182 {
183 return $this->led_filter(self::$currentNode);
184 }
185
186 private function nud_star()
187 {
188 return $this->parseWildcardObject(self::$currentNode);
189 }
190
191 private function nud_lbracket()
192 {
193 $this->next();
194 $type = $this->token['type'];
195 if ($type == T::T_NUMBER || $type == T::T_COLON) {
196 return $this->parseArrayIndexExpression();
197 } elseif ($type == T::T_STAR && $this->lookahead() == T::T_RBRACKET) {
198 return $this->parseWildcardArray();
199 } else {
200 return $this->parseMultiSelectList();
201 }
202 }
203
204 private function led_lbracket(array $left)
205 {
206 static $nextTypes = [T::T_NUMBER => true, T::T_COLON => true, T::T_STAR => true];
207 $this->next($nextTypes);
208 switch ($this->token['type']) {
209 case T::T_NUMBER:
210 case T::T_COLON:
211 return [
212 'type' => 'subexpression',
213 'children' => [$left, $this->parseArrayIndexExpression()]
214 ];
215 default:
216 return $this->parseWildcardArray($left);
217 }
218 }
219
220 private function led_flatten(array $left)
221 {
222 $this->next();
223
224 return [
225 'type' => 'projection',
226 'from' => 'array',
227 'children' => [
228 ['type' => T::T_FLATTEN, 'children' => [$left]],
229 $this->parseProjection(self::$bp[T::T_FLATTEN])
230 ]
231 ];
232 }
233
234 private function led_dot(array $left)
235 {
236 $this->next(self::$afterDot);
237
238 if ($this->token['type'] == T::T_STAR) {
239 return $this->parseWildcardObject($left);
240 }
241
242 return [
243 'type' => 'subexpression',
244 'children' => [$left, $this->parseDot(self::$bp[T::T_DOT])]
245 ];
246 }
247
248 private function led_or(array $left)
249 {
250 $this->next();
251 return [
252 'type' => T::T_OR,
253 'children' => [$left, $this->expr(self::$bp[T::T_OR])]
254 ];
255 }
256
257 private function led_and(array $left)
258 {
259 $this->next();
260 return [
261 'type' => T::T_AND,
262 'children' => [$left, $this->expr(self::$bp[T::T_AND])]
263 ];
264 }
265
266 private function led_pipe(array $left)
267 {
268 $this->next();
269 return [
270 'type' => T::T_PIPE,
271 'children' => [$left, $this->expr(self::$bp[T::T_PIPE])]
272 ];
273 }
274
275 private function led_lparen(array $left)
276 {
277 if (!isset($left['value'])) {
278 throw $this->syntax('Invalid function name');
279 }
280
281 $args = [];
282 $this->next();
283
284 while ($this->token['type'] != T::T_RPAREN) {
285 $args[] = $this->expr(0);
286 if ($this->token['type'] == T::T_COMMA) {
287 $this->next();
288 }
289 }
290
291 $this->next();
292
293 return [
294 'type' => 'function',
295 'value' => $left['value'],
296 'children' => $args
297 ];
298 }
299
300 private function led_filter(array $left)
301 {
302 $this->next();
303 $expression = $this->expr();
304 if ($this->token['type'] != T::T_RBRACKET) {
305 throw $this->syntax('Expected a closing rbracket for the filter');
306 }
307
308 $this->next();
309 $rhs = $this->parseProjection(self::$bp[T::T_FILTER]);
310
311 return [
312 'type' => 'projection',
313 'from' => 'array',
314 'children' => [
315 $left ?: self::$currentNode,
316 [
317 'type' => 'condition',
318 'children' => [$expression, $rhs]
319 ]
320 ]
321 ];
322 }
323
324 private function led_comparator(array $left)
325 {
326 $token = $this->token;
327 $this->next();
328
329 return [
330 'type' => T::T_COMPARATOR,
331 'value' => $token['value'],
332 'children' => [$left, $this->expr(self::$bp[T::T_COMPARATOR])]
333 ];
334 }
335
336 private function parseProjection($bp)
337 {
338 $type = $this->token['type'];
339 if (self::$bp[$type] < 10) {
340 return self::$currentNode;
341 } elseif ($type == T::T_DOT) {
342 $this->next(self::$afterDot);
343 return $this->parseDot($bp);
344 } elseif ($type == T::T_LBRACKET || $type == T::T_FILTER) {
345 return $this->expr($bp);
346 }
347
348 throw $this->syntax('Syntax error after projection');
349 }
350
351 private function parseDot($bp)
352 {
353 if ($this->token['type'] == T::T_LBRACKET) {
354 $this->next();
355 return $this->parseMultiSelectList();
356 } elseif ($this->token['type'] == T::T_LBRACE) {
357 // Like the multi-select list above, a multi-select hash ends any
358 // projection: tokens that follow apply to the projected list.
359 return $this->nud_lbrace();
360 }
361
362 return $this->expr($bp);
363 }
364
365 private function parseKeyValuePair()
366 {
367 static $validColon = [T::T_COLON => true];
368 $key = $this->token['value'];
369 $this->next($validColon);
370 $this->next();
371
372 return [
373 'type' => 'key_val_pair',
374 'value' => $key,
375 'children' => [$this->expr()]
376 ];
377 }
378
379 private function parseWildcardObject(?array $left = null)
380 {
381 $this->next();
382
383 return [
384 'type' => 'projection',
385 'from' => 'object',
386 'children' => [
387 $left ?: self::$currentNode,
388 $this->parseProjection(self::$bp[T::T_STAR])
389 ]
390 ];
391 }
392
393 private function parseWildcardArray(?array $left = null)
394 {
395 static $getRbracket = [T::T_RBRACKET => true];
396 $this->next($getRbracket);
397 $this->next();
398
399 return [
400 'type' => 'projection',
401 'from' => 'array',
402 'children' => [
403 $left ?: self::$currentNode,
404 $this->parseProjection(self::$bp[T::T_STAR])
405 ]
406 ];
407 }
408
409 /**
410 * Parses an array index expression (e.g., [0], [1:2:3]
411 */
412 private function parseArrayIndexExpression()
413 {
414 static $matchNext = [
415 T::T_NUMBER => true,
416 T::T_COLON => true,
417 T::T_RBRACKET => true
418 ];
419
420 $pos = 0;
421 $parts = [null, null, null];
422 $expected = $matchNext;
423
424 do {
425 if ($this->token['type'] == T::T_COLON) {
426 $pos++;
427 $expected = $matchNext;
428 } elseif ($this->token['type'] == T::T_NUMBER) {
429 $parts[$pos] = $this->token['value'];
430 $expected = [T::T_COLON => true, T::T_RBRACKET => true];
431 }
432 $this->next($expected);
433 } while ($this->token['type'] != T::T_RBRACKET);
434
435 // Consume the closing bracket
436 $this->next();
437
438 if ($pos === 0) {
439 // No colons were found so this is a simple index extraction
440 return ['type' => 'index', 'value' => $parts[0]];
441 }
442
443 if ($pos > 2) {
444 throw $this->syntax('Invalid array slice syntax: too many colons');
445 }
446
447 // Sliced array from start (e.g., [2:])
448 return [
449 'type' => 'projection',
450 'from' => 'array',
451 'children' => [
452 ['type' => 'slice', 'value' => $parts],
453 $this->parseProjection(self::$bp[T::T_STAR])
454 ]
455 ];
456 }
457
458 private function parseMultiSelectList()
459 {
460 $nodes = [];
461
462 do {
463 $nodes[] = $this->expr();
464 if ($this->token['type'] == T::T_COMMA) {
465 $this->next();
466 $this->assertNotToken(T::T_RBRACKET);
467 }
468 } while ($this->token['type'] !== T::T_RBRACKET);
469 $this->next();
470
471 return ['type' => 'multi_select_list', 'children' => $nodes];
472 }
473
474 private function syntax($msg)
475 {
476 return new SyntaxErrorException($msg, $this->token, $this->expression);
477 }
478
479 private function lookahead()
480 {
481 return (!isset($this->tokens[$this->tpos + 1]))
482 ? T::T_EOF
483 : $this->tokens[$this->tpos + 1]['type'];
484 }
485
486 private function next(?array $match = null)
487 {
488 if (!isset($this->tokens[$this->tpos + 1])) {
489 $this->token = self::$nullToken;
490 } else {
491 $this->token = $this->tokens[++$this->tpos];
492 }
493
494 if ($match && !isset($match[$this->token['type']])) {
495 throw $this->syntax($match);
496 }
497 }
498
499 private function assertNotToken($type)
500 {
501 if ($this->token['type'] == $type) {
502 throw $this->syntax("Token {$this->tpos} not allowed to be $type");
503 }
504 }
505
506 /**
507 * @internal Handles undefined tokens without paying the cost of validation
508 */
509 public function __call($method, $args)
510 {
511 $prefix = substr($method, 0, 4);
512 if ($prefix == 'nud_' || $prefix == 'led_') {
513 $token = substr($method, 4);
514 $message = "Unexpected \"$token\" token ($method). Expected one of"
515 . " the following tokens: "
516 . implode(', ', array_map(function ($i) {
517 return '"' . substr($i, 4) . '"';
518 }, array_filter(
519 get_class_methods($this),
520 function ($i) use ($prefix) {
521 return strpos($i, $prefix) === 0;
522 }
523 )));
524 throw $this->syntax($message);
525 }
526
527 throw new \BadMethodCallException("Call to undefined method $method");
528 }
529 }