Debian Codegraph @

extensions/AbuseFilter/includes/Parser/AFPTreeParser.php

raw symbols SCIP
1 <?php
2
3 /**
4 * A version of the abuse filter parser that separates parsing the filter and
5 * evaluating it into different passes, allowing the parse tree to be cached.
6 *
7 * @file
8 * @phan-file-suppress PhanPossiblyInfiniteRecursionSameParams Recursion controlled by class props
9 */
10
11 namespace MediaWiki\Extension\AbuseFilter\Parser;
12
13 use MediaWiki\Extension\AbuseFilter\KeywordsManager;
14 use MediaWiki\Extension\AbuseFilter\Parser\Exception\UserVisibleException;
15 use Psr\Log\LoggerInterface;
16 use Wikimedia\Stats\IBufferingStatsdDataFactory;
17
18 /**
19 * A parser that transforms the text of the filter into a parse tree.
20 */
21 class AFPTreeParser {
22 /**
23 * @var array[] Contains the AFPTokens for the code being parsed
24 * @phan-var array<int,array{0:AFPToken,1:int}>
25 */
26 private $mTokens;
27 /**
28 * @var AFPToken The current token
29 */
30 private $mCur;
31 /** @var int The position of the current token */
32 private $mPos;
33
34 /**
35 * @var string|null The ID of the filter being parsed, if available. Can also be "global-$ID"
36 */
37 private $mFilter;
38
39 public const CACHE_VERSION = 2;
40
41 /**
42 * @var LoggerInterface Used for debugging
43 */
44 private $logger;
45
46 /**
47 * @var IBufferingStatsdDataFactory
48 */
49 private $statsd;
50
51 /** @var KeywordsManager */
52 private $keywordsManager;
53
54 /**
55 * @param LoggerInterface $logger Used for debugging
56 * @param IBufferingStatsdDataFactory $statsd
57 * @param KeywordsManager $keywordsManager
58 */
59 public function __construct(
60 LoggerInterface $logger,
61 IBufferingStatsdDataFactory $statsd,
62 KeywordsManager $keywordsManager
63 ) {
64 $this->logger = $logger;
65 $this->statsd = $statsd;
66 $this->keywordsManager = $keywordsManager;
67 $this->resetState();
68 }
69
70 /**
71 * @param string $filter
72 */
73 public function setFilter( $filter ) {
74 $this->mFilter = $filter;
75 }
76
77 /**
78 * Resets the state
79 */
80 private function resetState() {
81 $this->mTokens = [];
82 $this->mPos = 0;
83 $this->mFilter = null;
84 }
85
86 /**
87 * Advances the parser to the next token in the filter code.
88 */
89 private function move() {
90 [ $this->mCur, $this->mPos ] = $this->mTokens[$this->mPos];
91 }
92
93 /**
94 * Get the next token. This is similar to move() but doesn't change class members,
95 * allowing to look ahead without rolling back the state.
96 *
97 * @return AFPToken
98 */
99 private function getNextToken() {
100 return $this->mTokens[$this->mPos][0];
101 }
102
103 /**
104 * getState() function allows parser state to be rollbacked to several tokens
105 * back.
106 *
107 * @return AFPParserState
108 */
109 private function getState() {
110 return new AFPParserState( $this->mCur, $this->mPos );
111 }
112
113 /**
114 * setState() function allows parser state to be rollbacked to several tokens
115 * back.
116 *
117 * @param AFPParserState $state
118 */
119 private function setState( AFPParserState $state ) {
120 $this->mCur = $state->token;
121 $this->mPos = $state->pos;
122 }
123
124 /**
125 * Parse the supplied filter source code into a tree.
126 *
127 * @param array[] $tokens
128 * @phan-param array<int,array{0:AFPToken,1:int}> $tokens
129 * @return AFPSyntaxTree
130 * @throws UserVisibleException
131 */
132 public function parse( array $tokens ): AFPSyntaxTree {
133 $this->mTokens = $tokens;
134 $this->mPos = 0;
135
136 return $this->buildSyntaxTree();
137 }
138
139 /**
140 * @return AFPSyntaxTree
141 */
142 private function buildSyntaxTree(): AFPSyntaxTree {
143 $startTime = microtime( true );
144 $root = $this->doLevelEntry();
145 $this->statsd->timing( 'abusefilter_cachingParser_buildtree', microtime( true ) - $startTime );
146 return new AFPSyntaxTree( $root );
147 }
148
149 /* Levels */
150
151 /**
152 * Handles unexpected characters after the expression.
153 * @return AFPTreeNode|null Null only if no statements
154 * @throws UserVisibleException
155 */
156 private function doLevelEntry() {
157 $result = $this->doLevelSemicolon();
158
159 if ( $this->mCur->type !== AFPToken::TNONE ) {
160 throw new UserVisibleException(
161 'unexpectedatend',
162 $this->mPos, [ $this->mCur->type ]
163 );
164 }
165
166 return $result;
167 }
168
169 /**
170 * Handles the semicolon operator.
171 *
172 * @return AFPTreeNode|null
173 */
174 private function doLevelSemicolon() {
175 $statements = [];
176
177 do {
178 $this->move();
179 $position = $this->mPos;
180
181 if (
182 $this->mCur->type === AFPToken::TNONE ||
183 ( $this->mCur->type === AFPToken::TBRACE && $this->mCur->value == ')' )
184 ) {
185 // Handle special cases which the other parser handled in doLevelAtom
186 break;
187 }
188
189 // Allow empty statements.
190 if ( $this->mCur->type === AFPToken::TSTATEMENTSEPARATOR ) {
191 continue;
192 }
193
194 $statements[] = $this->doLevelSet();
195 $position = $this->mPos;
196 } while ( $this->mCur->type === AFPToken::TSTATEMENTSEPARATOR );
197
198 // Flatten the tree if possible.
199 if ( count( $statements ) === 0 ) {
200 return null;
201 } elseif ( count( $statements ) === 1 ) {
202 return $statements[0];
203 } else {
204 return new AFPTreeNode( AFPTreeNode::SEMICOLON, $statements, $position );
205 }
206 }
207
208 /**
209 * Handles variable assignment.
210 *
211 * @return AFPTreeNode
212 * @throws UserVisibleException
213 */
214 private function doLevelSet() {
215 if ( $this->mCur->type === AFPToken::TID ) {
216 $varname = (string)$this->mCur->value;
217
218 // Speculatively parse the assignment statement assuming it can
219 // potentially be an assignment, but roll back if it isn't.
220 // @todo Use $this->getNextToken for clearer code
221 $initialState = $this->getState();
222 $this->move();
223
224 if ( $this->mCur->type === AFPToken::TOP && $this->mCur->value === ':=' ) {
225 $position = $this->mPos;
226 $this->move();
227 $value = $this->doLevelSet();
228
229 return new AFPTreeNode( AFPTreeNode::ASSIGNMENT, [ $varname, $value ], $position );
230 }
231
232 if ( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === '[' ) {
233 $this->move();
234
235 if ( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === ']' ) {
236 $index = 'append';
237 } else {
238 // Parse index offset.
239 $this->setState( $initialState );
240 $this->move();
241 $index = $this->doLevelSemicolon();
242 if ( !( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === ']' ) ) {
243 throw new UserVisibleException( 'expectednotfound', $this->mPos,
244 [ ']', $this->mCur->type, $this->mCur->value ] );
245 }
246 }
247
248 $this->move();
249 if ( $this->mCur->type === AFPToken::TOP && $this->mCur->value === ':=' ) {
250 $position = $this->mPos;
251 $this->move();
252 $value = $this->doLevelSet();
253 if ( $index === 'append' ) {
254 return new AFPTreeNode(
255 AFPTreeNode::ARRAY_APPEND, [ $varname, $value ], $position );
256 } else {
257 return new AFPTreeNode(
258 AFPTreeNode::INDEX_ASSIGNMENT,
259 [ $varname, $index, $value ],
260 $position
261 );
262 }
263 }
264 }
265
266 // If we reached this point, we did not find an assignment. Roll back
267 // and assume this was just a literal.
268 $this->setState( $initialState );
269 }
270
271 return $this->doLevelConditions();
272 }
273
274 /**
275 * Handles ternary operator and if-then-else-end.
276 *
277 * @return AFPTreeNode
278 * @throws UserVisibleException
279 */
280 private function doLevelConditions() {
281 if ( $this->mCur->type === AFPToken::TKEYWORD && $this->mCur->value === 'if' ) {
282 $position = $this->mPos;
283 $this->move();
284 $condition = $this->doLevelBoolOps();
285
286 if ( !( $this->mCur->type === AFPToken::TKEYWORD && $this->mCur->value === 'then' ) ) {
287 throw new UserVisibleException( 'expectednotfound',
288 $this->mPos,
289 [
290 'then',
291 $this->mCur->type,
292 $this->mCur->value
293 ]
294 );
295 }
296 $this->move();
297
298 $valueIfTrue = $this->doLevelConditions();
299
300 if ( $this->mCur->type === AFPToken::TKEYWORD && $this->mCur->value === 'else' ) {
301 $this->move();
302 $valueIfFalse = $this->doLevelConditions();
303 } else {
304 $valueIfFalse = null;
305 }
306
307 if ( !( $this->mCur->type === AFPToken::TKEYWORD && $this->mCur->value === 'end' ) ) {
308 throw new UserVisibleException( 'expectednotfound',
309 $this->mPos,
310 [
311 'end',
312 $this->mCur->type,
313 $this->mCur->value
314 ]
315 );
316 }
317 $this->move();
318
319 return new AFPTreeNode(
320 AFPTreeNode::CONDITIONAL,
321 [ $condition, $valueIfTrue, $valueIfFalse ],
322 $position
323 );
324 }
325
326 $condition = $this->doLevelBoolOps();
327 if ( $this->mCur->type === AFPToken::TOP && $this->mCur->value === '?' ) {
328 $position = $this->mPos;
329 $this->move();
330
331 $valueIfTrue = $this->doLevelConditions();
332 if ( !( $this->mCur->type === AFPToken::TOP && $this->mCur->value === ':' ) ) {
333 throw new UserVisibleException( 'expectednotfound',
334 $this->mPos,
335 [
336 ':',
337 $this->mCur->type,
338 $this->mCur->value
339 ]
340 );
341 }
342 $this->move();
343
344 $valueIfFalse = $this->doLevelConditions();
345 return new AFPTreeNode(
346 AFPTreeNode::CONDITIONAL,
347 [ $condition, $valueIfTrue, $valueIfFalse ],
348 $position
349 );
350 }
351
352 return $condition;
353 }
354
355 /**
356 * Handles logic operators.
357 *
358 * @return AFPTreeNode
359 */
360 private function doLevelBoolOps() {
361 $leftOperand = $this->doLevelCompares();
362 $ops = [ '&', '|', '^' ];
363 while ( $this->mCur->type === AFPToken::TOP && in_array( $this->mCur->value, $ops ) ) {
364 $op = $this->mCur->value;
365 $position = $this->mPos;
366 $this->move();
367
368 $rightOperand = $this->doLevelCompares();
369
370 $leftOperand = new AFPTreeNode(
371 AFPTreeNode::LOGIC,
372 [ $op, $leftOperand, $rightOperand ],
373 $position
374 );
375 }
376 return $leftOperand;
377 }
378
379 /**
380 * Handles comparison operators.
381 *
382 * @return AFPTreeNode
383 */
384 private function doLevelCompares() {
385 $leftOperand = $this->doLevelSumRels();
386 $equalityOps = [ '==', '===', '!=', '!==', '=' ];
387 $orderOps = [ '<', '>', '<=', '>=' ];
388 // Only allow either a single operation, or a combination of a single equalityOps and a single
389 // orderOps. This resembles what PHP does, and allows `a < b == c` while rejecting `a < b < c`
390 $allowedOps = array_merge( $equalityOps, $orderOps );
391 while ( $this->mCur->type === AFPToken::TOP && in_array( $this->mCur->value, $allowedOps ) ) {
392 $op = $this->mCur->value;
393 $allowedOps = in_array( $op, $equalityOps ) ?
394 array_diff( $allowedOps, $equalityOps ) :
395 array_diff( $allowedOps, $orderOps );
396 $position = $this->mPos;
397 $this->move();
398 $rightOperand = $this->doLevelSumRels();
399 $leftOperand = new AFPTreeNode(
400 AFPTreeNode::COMPARE,
401 [ $op, $leftOperand, $rightOperand ],
402 $position
403 );
404 }
405 return $leftOperand;
406 }
407
408 /**
409 * Handle addition and subtraction.
410 *
411 * @return AFPTreeNode
412 */
413 private function doLevelSumRels() {
414 $leftOperand = $this->doLevelMulRels();
415 $ops = [ '+', '-' ];
416 while ( $this->mCur->type === AFPToken::TOP && in_array( $this->mCur->value, $ops ) ) {
417 $op = $this->mCur->value;
418 $position = $this->mPos;
419 $this->move();
420 $rightOperand = $this->doLevelMulRels();
421 $leftOperand = new AFPTreeNode(
422 AFPTreeNode::SUM_REL,
423 [ $op, $leftOperand, $rightOperand ],
424 $position
425 );
426 }
427 return $leftOperand;
428 }
429
430 /**
431 * Handles multiplication and division.
432 *
433 * @return AFPTreeNode
434 */
435 private function doLevelMulRels() {
436 $leftOperand = $this->doLevelPow();
437 $ops = [ '*', '/', '%' ];
438 while ( $this->mCur->type === AFPToken::TOP && in_array( $this->mCur->value, $ops ) ) {
439 $op = $this->mCur->value;
440 $position = $this->mPos;
441 $this->move();
442 $rightOperand = $this->doLevelPow();
443 $leftOperand = new AFPTreeNode(
444 AFPTreeNode::MUL_REL,
445 [ $op, $leftOperand, $rightOperand ],
446 $position
447 );
448 }
449 return $leftOperand;
450 }
451
452 /**
453 * Handles exponentiation.
454 *
455 * @return AFPTreeNode
456 */
457 private function doLevelPow() {
458 $base = $this->doLevelBoolInvert();
459 while ( $this->mCur->type === AFPToken::TOP && $this->mCur->value === '**' ) {
460 $position = $this->mPos;
461 $this->move();
462 $exponent = $this->doLevelBoolInvert();
463 $base = new AFPTreeNode( AFPTreeNode::POW, [ $base, $exponent ], $position );
464 }
465 return $base;
466 }
467
468 /**
469 * Handles boolean inversion.
470 *
471 * @return AFPTreeNode
472 */
473 private function doLevelBoolInvert() {
474 if ( $this->mCur->type === AFPToken::TOP && $this->mCur->value === '!' ) {
475 $position = $this->mPos;
476 $this->move();
477 $argument = $this->doLevelKeywordOperators();
478 return new AFPTreeNode( AFPTreeNode::BOOL_INVERT, [ $argument ], $position );
479 }
480
481 return $this->doLevelKeywordOperators();
482 }
483
484 /**
485 * Handles keyword operators.
486 *
487 * @return AFPTreeNode
488 */
489 private function doLevelKeywordOperators() {
490 $leftOperand = $this->doLevelUnarys();
491 $keyword = strtolower( $this->mCur->value );
492 if ( $this->mCur->type === AFPToken::TKEYWORD &&
493 isset( FilterEvaluator::KEYWORDS[$keyword] )
494 ) {
495 $position = $this->mPos;
496 $this->move();
497 $rightOperand = $this->doLevelUnarys();
498
499 return new AFPTreeNode(
500 AFPTreeNode::KEYWORD_OPERATOR,
501 [ $keyword, $leftOperand, $rightOperand ],
502 $position
503 );
504 }
505
506 return $leftOperand;
507 }
508
509 /**
510 * Handles unary operators.
511 *
512 * @return AFPTreeNode
513 */
514 private function doLevelUnarys() {
515 $op = $this->mCur->value;
516 if ( $this->mCur->type === AFPToken::TOP && ( $op === "+" || $op === "-" ) ) {
517 $position = $this->mPos;
518 $this->move();
519 $argument = $this->doLevelArrayElements();
520 return new AFPTreeNode( AFPTreeNode::UNARY, [ $op, $argument ], $position );
521 }
522 return $this->doLevelArrayElements();
523 }
524
525 /**
526 * Handles accessing an array element by an offset.
527 *
528 * @return AFPTreeNode
529 * @throws UserVisibleException
530 */
531 private function doLevelArrayElements() {
532 $array = $this->doLevelParenthesis();
533 while ( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === '[' ) {
534 $position = $this->mPos;
535 $index = $this->doLevelSemicolon();
536 $array = new AFPTreeNode( AFPTreeNode::ARRAY_INDEX, [ $array, $index ], $position );
537
538 if ( !( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === ']' ) ) {
539 throw new UserVisibleException( 'expectednotfound', $this->mPos,
540 [ ']', $this->mCur->type, $this->mCur->value ] );
541 }
542 $this->move();
543 }
544
545 return $array;
546 }
547
548 /**
549 * Handles parenthesis.
550 *
551 * @return AFPTreeNode
552 * @throws UserVisibleException
553 */
554 private function doLevelParenthesis() {
555 if ( $this->mCur->type === AFPToken::TBRACE && $this->mCur->value === '(' ) {
556 $next = $this->getNextToken();
557 if ( $next->type === AFPToken::TBRACE && $next->value === ')' ) {
558 // Empty parentheses are never allowed
559 throw new UserVisibleException(
560 'unexpectedtoken',
561 $this->mPos,
562 [
563 $this->mCur->type,
564 $this->mCur->value
565 ]
566 );
567 }
568 $result = $this->doLevelSemicolon();
569
570 if ( !( $this->mCur->type === AFPToken::TBRACE && $this->mCur->value === ')' ) ) {
571 throw new UserVisibleException(
572 'expectednotfound',
573 $this->mPos,
574 [ ')', $this->mCur->type, $this->mCur->value ]
575 );
576 }
577 $this->move();
578
579 return $result;
580 }
581
582 return $this->doLevelFunction();
583 }
584
585 /**
586 * Handles function calls.
587 *
588 * @return AFPTreeNode
589 * @throws UserVisibleException
590 */
591 private function doLevelFunction() {
592 $next = $this->getNextToken();
593 if ( $this->mCur->type === AFPToken::TID &&
594 $next->type === AFPToken::TBRACE &&
595 $next->value === '('
596 ) {
597 $func = $this->mCur->value;
598 $position = $this->mPos;
599 $this->move();
600
601 $args = [];
602 $next = $this->getNextToken();
603 if ( $next->type !== AFPToken::TBRACE || $next->value !== ')' ) {
604 do {
605 $thisArg = $this->doLevelSemicolon();
606 if ( $thisArg !== null ) {
607 $args[] = $thisArg;
608 } elseif (
609 array_key_exists( $func, FilterEvaluator::FUNC_ARG_COUNT ) &&
610 FilterEvaluator::FUNC_ARG_COUNT[$func][1] !== INF
611 ) {
612 // If this function exists and is not variadic, fail now. If it does not exist, we'll fail when
613 // checking the call validity in SyntaxChecker (T387649). Trailing commas are allowed when
614 // calling variadic functions.
615 throw new UserVisibleException(
616 'unexpectedtoken',
617 $this->mPos,
618 [
619 $this->mCur->type,
620 $this->mCur->value
621 ]
622 );
623 }
624 } while ( $this->mCur->type === AFPToken::TCOMMA );
625 } else {
626 $this->move();
627 }
628
629 if ( $this->mCur->type !== AFPToken::TBRACE || $this->mCur->value !== ')' ) {
630 throw new UserVisibleException( 'expectednotfound',
631 $this->mPos,
632 [
633 ')',
634 $this->mCur->type,
635 $this->mCur->value
636 ]
637 );
638 }
639 $this->move();
640
641 array_unshift( $args, $func );
642 return new AFPTreeNode( AFPTreeNode::FUNCTION_CALL, $args, $position );
643 }
644
645 return $this->doLevelAtom();
646 }
647
648 /**
649 * Handle literals.
650 * @return AFPTreeNode
651 * @throws UserVisibleException
652 */
653 private function doLevelAtom() {
654 $tok = $this->mCur->value;
655 switch ( $this->mCur->type ) {
656 case AFPToken::TID:
657 $this->checkLogDeprecatedVar( strtolower( $tok ) );
658 // Fallthrough intended
659 case AFPToken::TSTRING:
660 case AFPToken::TFLOAT:
661 case AFPToken::TINT:
662 $result = new AFPTreeNode( AFPTreeNode::ATOM, $this->mCur, $this->mPos );
663 break;
664 case AFPToken::TKEYWORD:
665 if ( in_array( $tok, [ "true", "false", "null" ] ) ) {
666 $result = new AFPTreeNode( AFPTreeNode::ATOM, $this->mCur, $this->mPos );
667 break;
668 }
669
670 throw new UserVisibleException(
671 'unrecognisedkeyword',
672 $this->mPos,
673 [ $tok ]
674 );
675 /** @noinspection PhpMissingBreakStatementInspection */
676 case AFPToken::TSQUAREBRACKET:
677 if ( $this->mCur->value === '[' ) {
678 $array = [];
679 while ( true ) {
680 $this->move();
681 if ( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === ']' ) {
682 break;
683 }
684
685 $array[] = $this->doLevelSet();
686
687 if ( $this->mCur->type === AFPToken::TSQUAREBRACKET && $this->mCur->value === ']' ) {
688 break;
689 }
690 if ( $this->mCur->type !== AFPToken::TCOMMA ) {
691 throw new UserVisibleException(
692 'expectednotfound',
693 $this->mPos,
694 [ ', or ]', $this->mCur->type, $this->mCur->value ]
695 );
696 }
697 }
698
699 $result = new AFPTreeNode( AFPTreeNode::ARRAY_DEFINITION, $array, $this->mPos );
700 break;
701 }
702
703 // Fallthrough expected
704 default:
705 throw new UserVisibleException(
706 'unexpectedtoken',
707 $this->mPos,
708 [
709 $this->mCur->type,
710 $this->mCur->value
711 ]
712 );
713 }
714
715 $this->move();
716 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
717 // @phan-suppress-next-line PhanTypeMismatchReturnNullable Until phan can understand the switch
718 return $result;
719 }
720
721 /**
722 * Given a variable name, check if the variable is deprecated. If it is, log the use.
723 * Do that here, and not every time the AST is eval'ed. This means less logging, but more
724 * performance.
725 * @param string $varname
726 */
727 private function checkLogDeprecatedVar( $varname ) {
728 if ( $this->keywordsManager->isVarDeprecated( $varname ) ) {
729 $this->logger->debug( "Deprecated variable $varname used in filter {$this->mFilter}." );
730 }
731 }
732 }