Completed
Push — master ( 31bf53...69db6d )
by Maurício
02:21 queued 02:17
created

Lexer::solveAmbiguityOnStarOperator()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7.0368

Importance

Changes 0
Metric Value
cc 7
eloc 11
c 0
b 0
f 0
nc 4
nop 0
dl 0
loc 22
ccs 10
cts 11
cp 0.9091
crap 7.0368
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin\SqlParser;
6
7
use Exception;
8
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
9
10
use function in_array;
11
use function mb_strlen;
12
use function sprintf;
13
use function str_ends_with;
14
use function strlen;
15
use function substr;
16
17
/**
18
 * Defines the lexer of the library.
19
 *
20
 * This is one of the most important components, along with the parser.
21
 *
22
 * Depends on context to extract lexemes.
23
 *
24
 * Performs lexical analysis over a SQL statement and splits it in multiple tokens.
25
 *
26
 * The output of the lexer is affected by the context of the SQL statement.
27
 *
28
 * @see Context
29
 */
30
class Lexer
31
{
32
    /**
33
     * Whether errors should throw exceptions or just be stored.
34
     */
35
    private bool $strict = false;
36
37
    /**
38
     * List of errors that occurred during lexing.
39
     *
40
     * Usually, the lexing does not stop once an error occurred because that
41
     * error might be false positive or a partial result (even a bad one)
42
     * might be needed.
43
     *
44
     * @var Exception[]
45
     */
46
    public array $errors = [];
47
48
    /**
49
     * A list of keywords that indicate that the function keyword
50
     * is not used as a function
51
     */
52
    private const KEYWORD_NAME_INDICATORS = [
53
        'FROM',
54
        'SET',
55
        'WHERE',
56
    ];
57
58
    /**
59
     * A list of operators that indicate that the function keyword
60
     * is not used as a function
61
     */
62
    private const OPERATOR_NAME_INDICATORS = [
63
        ',',
64
        '.',
65
    ];
66
67
    /**
68
     * The string to be parsed.
69
     */
70
    public string|UtfString $str = '';
71
72
    /**
73
     * The length of `$str`.
74
     *
75
     * By storing its length, a lot of time is saved, because parsing methods
76
     * would call `strlen` everytime.
77
     */
78
    public int $len = 0;
79
80
    /**
81
     * The index of the last parsed character.
82
     */
83
    public int $last = 0;
84
85
    /**
86
     * Tokens extracted from given strings.
87
     */
88
    public TokensList $list;
89
90
    /**
91
     * The default delimiter. This is used, by default, in all new instances.
92
     */
93
    public static string $defaultDelimiter = ';';
94
95
    /**
96
     * Statements delimiter.
97
     * This may change during lexing.
98
     */
99
    public string $delimiter;
100
101
    /**
102
     * The length of the delimiter.
103
     *
104
     * Because `parseDelimiter` can be called a lot, it would perform a lot of
105
     * calls to `strlen`, which might affect performance when the delimiter is
106
     * big.
107
     */
108
    public int $delimiterLen;
109
110
    /**
111
     * @param string|UtfString $str       the query to be lexed
112
     * @param bool             $strict    whether strict mode should be
113
     *                                    enabled or not
114
     * @param string           $delimiter the delimiter to be used
115
     */
116 1444
    public function __construct(string|UtfString $str, bool $strict = false, string|null $delimiter = null)
117
    {
118 1444
        if (Context::$keywords === []) {
119
            Context::load();
120
        }
121
122
        // `strlen` is used instead of `mb_strlen` because the lexer needs to
123
        // parse each byte of the input.
124 1444
        $len = $str instanceof UtfString ? $str->length() : strlen($str);
125
126
        // For multi-byte strings, a new instance of `UtfString` is initialized.
127 1444
        if (! $str instanceof UtfString && $len !== mb_strlen($str, 'UTF-8')) {
128 10
            $str = new UtfString($str);
129
        }
130
131 1444
        $this->str = $str;
132 1444
        $this->len = $str instanceof UtfString ? $str->length() : $len;
133
134 1444
        $this->strict = $strict;
135
136
        // Setting the delimiter.
137 1444
        $this->setDelimiter(! empty($delimiter) ? $delimiter : static::$defaultDelimiter);
138
139 1444
        $this->lex();
140
    }
141
142
    /**
143
     * Sets the delimiter.
144
     *
145
     * @param string $delimiter the new delimiter
146
     */
147 1444
    public function setDelimiter(string $delimiter): void
148
    {
149 1444
        $this->delimiter = $delimiter;
150 1444
        $this->delimiterLen = strlen($delimiter);
151
    }
152
153
    /**
154
     * Parses the string and extracts lexemes.
155
     */
156 1444
    public function lex(): void
157
    {
158
        // TODO: Sometimes, static::parse* functions make unnecessary calls to
159
        // is* functions. For a better performance, some rules can be deduced
160
        // from context.
161
        // For example, in `parseBool` there is no need to compare the token
162
        // every time with `true` and `false`. The first step would be to
163
        // compare with 'true' only and just after that add another letter from
164
        // context and compare again with `false`.
165
        // Another example is `parseComment`.
166
167 1444
        $list = new TokensList();
168
169
        /**
170
         * Last processed token.
171
         */
172 1444
        $lastToken = null;
173
174 1444
        for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
175 1434
            $token = $this->parse();
176
177 1434
            if ($token === null) {
178
                // @assert($this->last === $lastIdx);
179 6
                $token = new Token($this->str[$this->last]);
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $token of PhpMyAdmin\SqlParser\Token::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

179
                $token = new Token(/** @scrutinizer ignore-type */ $this->str[$this->last]);
Loading history...
180 6
                $this->error('Unexpected character.', $this->str[$this->last], $this->last);
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $str of PhpMyAdmin\SqlParser\Lexer::error() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

180
                $this->error('Unexpected character.', /** @scrutinizer ignore-type */ $this->str[$this->last], $this->last);
Loading history...
181
            } elseif (
182 1434
                $lastToken !== null
183 1434
                && $token->type === TokenType::Symbol
184 1434
                && $token->flags & Token::FLAG_SYMBOL_VARIABLE
185
                && (
186 1434
                    $lastToken->type === TokenType::String
187 1434
                    || (
188 1434
                        $lastToken->type === TokenType::Symbol
189 1434
                        && $lastToken->flags & Token::FLAG_SYMBOL_BACKTICK
190 1434
                    )
191
                )
192
            ) {
193
                // Handles ```... FROM 'user'@'%' ...```.
194 46
                $lastToken->token .= $token->token;
195 46
                $lastToken->type = TokenType::Symbol;
196 46
                $lastToken->flags = Token::FLAG_SYMBOL_USER;
197 46
                $lastToken->value .= '@' . $token->value;
198 46
                continue;
199
            } elseif (
200 1434
                $lastToken !== null
201 1434
                && $token->type === TokenType::Keyword
202 1434
                && $lastToken->type === TokenType::Operator
203 1434
                && $lastToken->value === '.'
204
            ) {
205
                // Handles ```... tbl.FROM ...```. In this case, FROM is not
206
                // a reserved word.
207 30
                $token->type = TokenType::None;
208 30
                $token->flags = 0;
209 30
                $token->value = $token->token;
210
            }
211
212 1434
            $token->position = $lastIdx;
213
214 1434
            $list->tokens[$list->count++] = $token;
215
216
            // Handling delimiters.
217 1434
            if ($token->type === TokenType::None && $token->value === 'DELIMITER') {
218 36
                if ($this->last + 1 >= $this->len) {
219 2
                    $this->error('Expected whitespace(s) before delimiter.', '', $this->last + 1);
220 2
                    continue;
221
                }
222
223
                // Skipping last R (from `delimiteR`) and whitespaces between
224
                // the keyword `DELIMITER` and the actual delimiter.
225 34
                $pos = ++$this->last;
226 34
                $token = $this->parseWhitespace();
227
228 34
                if ($token !== null) {
229 32
                    $token->position = $pos;
230 32
                    $list->tokens[$list->count++] = $token;
231
                }
232
233
                // Preparing the token that holds the new delimiter.
234 34
                if ($this->last + 1 >= $this->len) {
235 2
                    $this->error('Expected delimiter.', '', $this->last + 1);
236 2
                    continue;
237
                }
238
239 32
                $pos = $this->last + 1;
240
241
                // Parsing the delimiter.
242 32
                $this->delimiter = '';
243 32
                $delimiterLen = 0;
244
                while (
245 32
                    ++$this->last < $this->len
246 32
                    && ! Context::isWhitespace($this->str[$this->last])
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
                    && ! Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last])
Loading history...
247 32
                    && $delimiterLen < 15
248
                ) {
249 30
                    $this->delimiter .= $this->str[$this->last];
250 30
                    ++$delimiterLen;
251
                }
252
253 32
                if ($this->delimiter === '') {
254 2
                    $this->error('Expected delimiter.', '', $this->last);
255 2
                    $this->delimiter = ';';
256
                }
257
258 32
                --$this->last;
259
260
                // Saving the delimiter and its token.
261 32
                $this->delimiterLen = strlen($this->delimiter);
262 32
                $token = new Token($this->delimiter, TokenType::Delimiter);
263 32
                $token->position = $pos;
264 32
                $list->tokens[$list->count++] = $token;
265
            }
266
267 1430
            $lastToken = $token;
268
        }
269
270
        // Adding a final delimiter to mark the ending.
271 1444
        $list->tokens[$list->count++] = new Token('', TokenType::Delimiter);
272
273
        // Saving the tokens list.
274 1444
        $this->list = $list;
275
276 1444
        $this->solveAmbiguityOnStarOperator();
277 1444
        $this->solveAmbiguityOnFunctionKeywords();
278
    }
279
280
    /**
281
     * Resolves the ambiguity when dealing with the "*" operator.
282
     *
283
     * In SQL statements, the "*" operator can be an arithmetic operator (like in 2*3) or an SQL wildcard (like in
284
     * SELECT a.* FROM ...). To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
285
     * comments, right after the "*" position. The "*" is for sure an SQL wildcard if the next token found is any of:
286
     * - "FROM" (the FROM keyword like in "SELECT * FROM...");
287
     * - "USING" (the USING keyword like in "DELETE table_name.* USING...");
288
     * - "," (a comma separator like in "SELECT *, field FROM...");
289
     * - ")" (a closing parenthesis like in "COUNT(*)").
290
     * This methods will change the flag of the "*" tokens when any of those condition above is true. Otherwise, the
291
     * default flag (arithmetic) will be kept.
292
     */
293 1444
    private function solveAmbiguityOnStarOperator(): void
294
    {
295 1444
        $iBak = $this->list->idx;
296 1444
        while (($starToken = $this->list->getNextOfTypeAndValue(TokenType::Operator, '*')) !== null) {
297
            // getNext() already gets rid of whitespaces and comments.
298 198
            $next = $this->list->getNext();
299
300 198
            if ($next === null) {
301
                continue;
302
            }
303
304
            if (
305 198
                ($next->type !== TokenType::Keyword || ! in_array($next->value, ['FROM', 'USING'], true))
306 198
                && ($next->type !== TokenType::Operator || ! in_array($next->value, [',', ')'], true))
307
            ) {
308 16
                continue;
309
            }
310
311 184
            $starToken->flags = Token::FLAG_OPERATOR_SQL;
312
        }
313
314 1444
        $this->list->idx = $iBak;
315
    }
316
317
    /**
318
     * Resolves the ambiguity when dealing with the functions keywords.
319
     *
320
     * In SQL statements, the function keywords might be used as table names or columns names.
321
     * To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
322
     * comments, right after the function keyword position. The function keyword is for sure used
323
     * as column name or table name if the next token found is any of:
324
     *
325
     * - "FROM" (the FROM keyword like in "SELECT Country x, AverageSalary avg FROM...");
326
     * - "WHERE" (the WHERE keyword like in "DELETE FROM emp x WHERE x.salary = 20");
327
     * - "SET" (the SET keyword like in "UPDATE Country x, City y set x.Name=x.Name");
328
     * - "," (a comma separator like 'x,' in "UPDATE Country x, City y set x.Name=x.Name");
329
     * - "." (a dot separator like in "x.asset_id FROM (SELECT evt.asset_id FROM evt)".
330
     * - "NULL" (when used as a table alias like in "avg.col FROM (SELECT ev.col FROM ev) avg").
331
     *
332
     * This method will change the flag of the function keyword tokens when any of those
333
     * condition above is true. Otherwise, the
334
     * default flag (function keyword) will be kept.
335
     */
336 1444
    private function solveAmbiguityOnFunctionKeywords(): void
337
    {
338 1444
        $iBak = $this->list->idx;
339 1444
        $keywordFunction = TokenType::Keyword->value | Token::FLAG_KEYWORD_FUNCTION;
340 1444
        while (($keywordToken = $this->list->getNextOfTypeAndFlag(TokenType::Keyword, $keywordFunction)) !== null) {
341 214
            $next = $this->list->getNext();
342
            if (
343 214
                ($next->type !== TokenType::Keyword
344 214
                    || ! in_array($next->value, self::KEYWORD_NAME_INDICATORS, true)
345
                )
346 214
                && ($next->type !== TokenType::Operator
347 214
                    || ! in_array($next->value, self::OPERATOR_NAME_INDICATORS, true)
348
                )
349 214
                && ($next->value !== '')
350
            ) {
351 204
                continue;
352
            }
353
354 12
            $keywordToken->type = TokenType::None;
355 12
            $keywordToken->flags = Token::FLAG_NONE;
356 12
            $keywordToken->keyword = $keywordToken->value;
357
        }
358
359 1444
        $this->list->idx = $iBak;
360
    }
361
362
    /**
363
     * Creates a new error log.
364
     *
365
     * @param string $msg  the error message
366
     * @param string $str  the character that produced the error
367
     * @param int    $pos  the position of the character
368
     * @param int    $code the code of the error
369
     *
370
     * @throws LexerException throws the exception, if strict mode is enabled.
371
     */
372 34
    public function error(string $msg, string $str = '', int $pos = 0, int $code = 0): void
373
    {
374 34
        $error = new LexerException(
375 34
            Translator::gettext($msg),
376 34
            $str,
377 34
            $pos,
378 34
            $code,
379 34
        );
380
381 34
        if ($this->strict) {
382 2
            throw $error;
383
        }
384
385 32
        $this->errors[] = $error;
386
    }
387
388
    /**
389
     * Parses a keyword.
390
     */
391 1416
    public function parseKeyword(): Token|null
392
    {
393 1416
        $token = '';
394
395
        /**
396
         * Value to be returned.
397
         *
398
         * @var Token
399
         */
400 1416
        $ret = null;
401
402
        /**
403
         * The value of `$this->last` where `$token` ends in `$this->str`.
404
         */
405 1416
        $iEnd = $this->last;
406
407
        /**
408
         * Whether last parsed character is a whitespace.
409
         *
410
         * @var bool
411
         */
412 1416
        $lastSpace = false;
413
414 1416
        for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
415
            // Composed keywords shouldn't have more than one whitespace between
416
            // keywords.
417 1416
            if (Context::isWhitespace($this->str[$this->last])) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

417
            if (Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last])) {
Loading history...
418 1380
                if ($lastSpace) {
419 270
                    --$j; // The size of the keyword didn't increase.
420 270
                    continue;
421
                }
422
423 1380
                $lastSpace = true;
424
            } else {
425 1416
                $lastSpace = false;
426
            }
427
428 1416
            $token .= $this->str[$this->last];
429 1416
            $flags = Context::isKeyword($token);
430
431 1416
            if (($this->last + 1 !== $this->len && ! Context::isSeparator($this->str[$this->last + 1])) || ! $flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
Bug introduced by
It seems like $this->str[$this->last + 1] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

431
            if (($this->last + 1 !== $this->len && ! Context::isSeparator(/** @scrutinizer ignore-type */ $this->str[$this->last + 1])) || ! $flags) {
Loading history...
432 1416
                continue;
433
            }
434
435 1380
            $ret = new Token($token, TokenType::Keyword, $flags);
436 1380
            $iEnd = $this->last;
437
438
            // We don't break so we find longest keyword.
439
            // For example, `OR` and `ORDER` have a common prefix `OR`.
440
            // If we stopped at `OR`, the parsing would be invalid.
441
        }
442
443 1416
        $this->last = $iEnd;
444
445 1416
        return $ret;
446
    }
447
448
    /**
449
     * Parses a label.
450
     */
451 1064
    public function parseLabel(): Token|null
452
    {
453 1064
        $token = '';
454
455
        /**
456
         * Value to be returned.
457
         *
458
         * @var Token
459
         */
460 1064
        $ret = null;
461
462
        /**
463
         * The value of `$this->last` where `$token` ends in `$this->str`.
464
         */
465 1064
        $iEnd = $this->last;
466 1064
        for ($j = 1; $j < Context::LABEL_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
467 1064
            if ($this->str[$this->last] === ':' && $j > 1) {
468
                // End of label
469 4
                $token .= $this->str[$this->last];
470 4
                $ret = new Token($token, TokenType::Label);
471 4
                $iEnd = $this->last;
472 4
                break;
473
            }
474
475 1064
            if (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

475
            if (Context::isWhitespace(/** @scrutinizer ignore-type */ $this->str[$this->last]) && $j > 1) {
Loading history...
476
                // Whitespace between label and :
477
                // The size of the keyword didn't increase.
478 828
                --$j;
479 1064
            } elseif (Context::isSeparator($this->str[$this->last])) {
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

479
            } elseif (Context::isSeparator(/** @scrutinizer ignore-type */ $this->str[$this->last])) {
Loading history...
480
                // Any other separator
481 812
                break;
482
            }
483
484 1060
            $token .= $this->str[$this->last];
485
        }
486
487 1064
        $this->last = $iEnd;
488
489 1064
        return $ret;
490
    }
491
492
    /**
493
     * Parses an operator.
494
     */
495 1434
    public function parseOperator(): Token|null
496
    {
497 1434
        $token = '';
498
499
        /**
500
         * Value to be returned.
501
         *
502
         * @var Token
503
         */
504 1434
        $ret = null;
505
506
        /**
507
         * The value of `$this->last` where `$token` ends in `$this->str`.
508
         */
509 1434
        $iEnd = $this->last;
510
511 1434
        for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
512 1434
            $token .= $this->str[$this->last];
513 1434
            $flags = Context::isOperator($token);
514
515 1434
            if (! $flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
516 1430
                continue;
517
            }
518
519 1026
            $ret = new Token($token, TokenType::Operator, $flags);
520 1026
            $iEnd = $this->last;
521
        }
522
523 1434
        $this->last = $iEnd;
524
525 1434
        return $ret;
526
    }
527
528
    /**
529
     * Parses a whitespace.
530
     */
531 1434
    public function parseWhitespace(): Token|null
532
    {
533 1434
        $token = $this->str[$this->last];
534
535 1434
        if (! Context::isWhitespace($token)) {
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isWhitespace() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

535
        if (! Context::isWhitespace(/** @scrutinizer ignore-type */ $token)) {
Loading history...
536 1434
            return null;
537
        }
538
539 1396
        while (++$this->last < $this->len && Context::isWhitespace($this->str[$this->last])) {
540 274
            $token .= $this->str[$this->last];
541
        }
542
543 1396
        --$this->last;
544
545 1396
        return new Token($token, TokenType::Whitespace);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $token of PhpMyAdmin\SqlParser\Token::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

545
        return new Token(/** @scrutinizer ignore-type */ $token, TokenType::Whitespace);
Loading history...
546
    }
547
548
    /**
549
     * Parses a comment.
550
     */
551 1434
    public function parseComment(): Token|null
552
    {
553 1434
        $iBak = $this->last;
554 1434
        $token = $this->str[$this->last];
555
556
        // Bash style comments. (#comment\n)
557 1434
        if (Context::isComment($token)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Context::isComment($token) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isComment() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

557
        if (Context::isComment(/** @scrutinizer ignore-type */ $token)) {
Loading history...
558 6
            while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
559 6
                $token .= $this->str[$this->last];
560
            }
561
562
            // Include trailing \n as whitespace token
563 6
            if ($this->last < $this->len) {
564 6
                --$this->last;
565
            }
566
567 6
            return new Token($token, TokenType::Comment, Token::FLAG_COMMENT_BASH);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $token of PhpMyAdmin\SqlParser\Token::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

567
            return new Token(/** @scrutinizer ignore-type */ $token, TokenType::Comment, Token::FLAG_COMMENT_BASH);
Loading history...
568
        }
569
570
        // C style comments. (/*comment*\/)
571 1434
        if (++$this->last < $this->len) {
572 1430
            $token .= $this->str[$this->last];
573 1430
            if (Context::isComment($token)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Context::isComment($token) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
574
                // There might be a conflict with "*" operator here, when string is "*/*".
575
                // This can occurs in the following statements:
576
                // - "SELECT */* comment */ FROM ..."
577
                // - "SELECT 2*/* comment */3 AS `six`;"
578 100
                $next = $this->last + 1;
579 100
                if (($next < $this->len) && $this->str[$next] === '*') {
580
                    // Conflict in "*/*": first "*" was not for ending a comment.
581
                    // Stop here and let other parsing method define the true behavior of that first star.
582 2
                    $this->last = $iBak;
583
584 2
                    return null;
585
                }
586
587 100
                $flags = Token::FLAG_COMMENT_C;
588
589
                // This comment already ended. It may be a part of a
590
                // previous MySQL specific command.
591 100
                if ($token === '*/') {
592 36
                    return new Token($token, TokenType::Comment, $flags);
593
                }
594
595
                // Checking if this is a MySQL-specific command.
596 98
                if ($this->last + 1 < $this->len && $this->str[$this->last + 1] === '!') {
597 34
                    $flags |= Token::FLAG_COMMENT_MYSQL_CMD;
598 34
                    $token .= $this->str[++$this->last];
599
600
                    while (
601 34
                        ++$this->last < $this->len
602 34
                        && $this->str[$this->last] >= '0'
603 34
                        && $this->str[$this->last] <= '9'
604
                    ) {
605 32
                        $token .= $this->str[$this->last];
606
                    }
607
608 34
                    --$this->last;
609
610
                    // We split this comment and parse only its beginning
611
                    // here.
612 34
                    return new Token($token, TokenType::Comment, $flags);
613
                }
614
615
                // Parsing the comment.
616
                while (
617 68
                    ++$this->last < $this->len
618 68
                    && (
619 68
                        $this->str[$this->last - 1] !== '*'
620 68
                        || $this->str[$this->last] !== '/'
621 68
                    )
622
                ) {
623 68
                    $token .= $this->str[$this->last];
624
                }
625
626
                // Adding the ending.
627 68
                if ($this->last < $this->len) {
628 68
                    $token .= $this->str[$this->last];
629
                }
630
631 68
                return new Token($token, TokenType::Comment, $flags);
632
            }
633
        }
634
635
        // SQL style comments. (-- comment\n)
636 1434
        if (++$this->last < $this->len) {
637 1428
            $token .= $this->str[$this->last];
638 1428
            $end = false;
639
        } else {
640 418
            --$this->last;
641 418
            $end = true;
642
        }
643
644 1434
        if (Context::isComment($token, $end)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression PhpMyAdmin\SqlParser\Con...isComment($token, $end) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
645
            // Checking if this comment did not end already (```--\n```).
646 70
            if ($this->str[$this->last] !== "\n") {
647 70
                while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
648 70
                    $token .= $this->str[$this->last];
649
                }
650
            }
651
652
            // Include trailing \n as whitespace token
653 70
            if ($this->last < $this->len) {
654 62
                --$this->last;
655
            }
656
657 70
            return new Token($token, TokenType::Comment, Token::FLAG_COMMENT_SQL);
658
        }
659
660 1434
        $this->last = $iBak;
661
662 1434
        return null;
663
    }
664
665
    /**
666
     * Parses a boolean.
667
     */
668 1418
    public function parseBool(): Token|null
669
    {
670 1418
        if ($this->last + 3 >= $this->len) {
671
            // At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
672
            // required.
673 316
            return null;
674
        }
675
676 1418
        $iBak = $this->last;
677 1418
        $token = $this->str[$this->last] . $this->str[++$this->last]
678 1418
        . $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
679
680 1418
        if (Context::isBool($token)) {
681 4
            return new Token($token, TokenType::Bool);
682
        }
683
684 1418
        if (++$this->last < $this->len) {
685 1414
            $token .= $this->str[$this->last]; // fals_E_
686 1414
            if (Context::isBool($token)) {
687 6
                return new Token($token, TokenType::Bool, 1);
688
            }
689
        }
690
691 1418
        $this->last = $iBak;
692
693 1418
        return null;
694
    }
695
696
    /**
697
     * Parses a number.
698
     */
699 1434
    public function parseNumber(): Token|null
700
    {
701
        // A rudimentary state machine is being used to parse numbers due to
702
        // the various forms of their notation.
703
        //
704
        // Below are the states of the machines and the conditions to change
705
        // the state.
706
        //
707
        //      1 --------------------[ + or - ]-------------------> 1
708
        //      1 -------------------[ 0x or 0X ]------------------> 2
709
        //      1 --------------------[ 0 to 9 ]-------------------> 3
710
        //      1 -----------------------[ . ]---------------------> 4
711
        //      1 -----------------------[ b ]---------------------> 7
712
        //
713
        //      2 --------------------[ 0 to F ]-------------------> 2
714
        //
715
        //      3 --------------------[ 0 to 9 ]-------------------> 3
716
        //      3 -----------------------[ . ]---------------------> 4
717
        //      3 --------------------[ e or E ]-------------------> 5
718
        //
719
        //      4 --------------------[ 0 to 9 ]-------------------> 4
720
        //      4 --------------------[ e or E ]-------------------> 5
721
        //
722
        //      5 ---------------[ + or - or 0 to 9 ]--------------> 6
723
        //
724
        //      7 -----------------------[ ' ]---------------------> 8
725
        //
726
        //      8 --------------------[ 0 or 1 ]-------------------> 8
727
        //      8 -----------------------[ ' ]---------------------> 9
728
        //
729
        // State 1 may be reached by negative numbers.
730
        // State 2 is reached only by hex numbers.
731
        // State 4 is reached only by float numbers.
732
        // State 5 is reached only by numbers in approximate form.
733
        // State 7 is reached only by numbers in bit representation.
734
        //
735
        // Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
736
        // state other than these is invalid.
737
        // Also, negative states are invalid states.
738 1434
        $iBak = $this->last;
739 1434
        $token = '';
740 1434
        $flags = 0;
741 1434
        $state = 1;
742 1434
        for (; $this->last < $this->len; ++$this->last) {
743 1434
            if ($state === 1) {
744 1434
                if ($this->str[$this->last] === '-') {
745 70
                    $flags |= Token::FLAG_NUMBER_NEGATIVE;
746
                } elseif (
747 1434
                    $this->last + 1 < $this->len
748 1434
                    && $this->str[$this->last] === '0'
749 1434
                    && $this->str[$this->last + 1] === 'x'
750
                ) {
751 4
                    $token .= $this->str[$this->last++];
752 4
                    $state = 2;
753 1434
                } elseif ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9') {
754 638
                    $state = 3;
755 1432
                } elseif ($this->str[$this->last] === '.') {
756 224
                    $state = 4;
757 1432
                } elseif ($this->str[$this->last] === 'b') {
758 108
                    $state = 7;
759 1432
                } elseif ($this->str[$this->last] !== '+') {
760
                    // `+` is a valid character in a number.
761 1432
                    break;
762
                }
763 740
            } elseif ($state === 2) {
764 4
                $flags |= Token::FLAG_NUMBER_HEX;
765
                if (
766
                    ! (
767 4
                        ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
768 4
                        || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'F')
769 4
                        || ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'f')
770
                    )
771
                ) {
772 4
                    break;
773
                }
774 740
            } elseif ($state === 3) {
775 578
                if ($this->str[$this->last] === '.') {
776 12
                    $state = 4;
777 576
                } elseif ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
778 2
                    $state = 5;
779
                } elseif (
780 576
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
781 576
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
782
                ) {
783
                    // A number can't be directly followed by a letter
784 10
                    $state = -$state;
785 572
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
786
                    // Just digits and `.`, `e` and `E` are valid characters.
787 562
                    break;
788
                }
789 320
            } elseif ($state === 4) {
790 234
                $flags |= Token::FLAG_NUMBER_FLOAT;
791 234
                if ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
792 14
                    $state = 5;
793
                } elseif (
794 234
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
795 234
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
796
                ) {
797
                    // A number can't be directly followed by a letter
798 174
                    $state = -$state;
799 94
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
800
                    // Just digits, `e` and `E` are valid characters.
801 92
                    break;
802
                }
803 270
            } elseif ($state === 5) {
804 14
                $flags |= Token::FLAG_NUMBER_APPROXIMATE;
805
                if (
806 14
                    $this->str[$this->last] === '+' || $this->str[$this->last] === '-'
807 14
                    || ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
808
                ) {
809 2
                    $state = 6;
810
                } elseif (
811 14
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
812 14
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
813
                ) {
814
                    // A number can't be directly followed by a letter
815 14
                    $state = -$state;
816
                } else {
817
                    break;
818
                }
819 270
            } elseif ($state === 6) {
820 2
                if ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
821
                    // Just digits are valid characters.
822 2
                    break;
823
                }
824 270
            } elseif ($state === 7) {
825 106
                $flags |= Token::FLAG_NUMBER_BINARY;
826 106
                if ($this->str[$this->last] !== '\'') {
827 104
                    break;
828
                }
829
830 2
                $state = 8;
831 184
            } elseif ($state === 8) {
832 2
                if ($this->str[$this->last] === '\'') {
833 2
                    $state = 9;
834 2
                } elseif ($this->str[$this->last] !== '0' && $this->str[$this->last] !== '1') {
835 2
                    break;
836
                }
837 184
            } elseif ($state === 9) {
838 2
                break;
839
            }
840
841 824
            $token .= $this->str[$this->last];
842
        }
843
844 1434
        if ($state === 2 || $state === 3 || ($token !== '.' && $state === 4) || $state === 6 || $state === 9) {
845 638
            --$this->last;
846
847 638
            return new Token($token, TokenType::Number, $flags);
848
        }
849
850 1434
        $this->last = $iBak;
851
852 1434
        return null;
853
    }
854
855
    /**
856
     * Parses a string.
857
     *
858
     * @param string $quote additional starting symbol
859
     *
860
     * @throws LexerException
861
     */
862 1418
    public function parseString(string $quote = ''): Token|null
863
    {
864 1418
        $token = $this->str[$this->last];
865 1418
        $flags = Context::isString($token);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isString() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

865
        $flags = Context::isString(/** @scrutinizer ignore-type */ $token);
Loading history...
866
867 1418
        if (! $flags && $token !== $quote) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
868 1418
            return null;
869
        }
870
871 696
        $quote = $token;
872
873 696
        while (++$this->last < $this->len) {
874
            if (
875 696
                $this->last + 1 < $this->len
876
                && (
877 696
                    ($this->str[$this->last] === $quote && $this->str[$this->last + 1] === $quote)
878 696
                    || ($this->str[$this->last] === '\\' && $quote !== '`')
879
                )
880
            ) {
881 30
                $token .= $this->str[$this->last] . $this->str[++$this->last];
882
            } else {
883 696
                if ($this->str[$this->last] === $quote) {
884 692
                    break;
885
                }
886
887 690
                $token .= $this->str[$this->last];
888
            }
889
        }
890
891 696
        if ($this->last >= $this->len || $this->str[$this->last] !== $quote) {
892 14
            $this->error(
893 14
                sprintf(
894 14
                    Translator::gettext('Ending quote %1$s was expected.'),
895 14
                    $quote,
896 14
                ),
897 14
                '',
898 14
                $this->last,
899 14
            );
900
        } else {
901 692
            $token .= $this->str[$this->last];
902
        }
903
904 696
        return new Token($token, TokenType::String, $flags ?? Token::FLAG_NONE);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $token of PhpMyAdmin\SqlParser\Token::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

904
        return new Token(/** @scrutinizer ignore-type */ $token, TokenType::String, $flags ?? Token::FLAG_NONE);
Loading history...
905
    }
906
907
    /**
908
     * Parses a symbol.
909
     *
910
     * @throws LexerException
911
     */
912 1418
    public function parseSymbol(): Token|null
913
    {
914 1418
        $token = $this->str[$this->last];
915 1418
        $flags = Context::isSymbol($token);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSymbol() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

915
        $flags = Context::isSymbol(/** @scrutinizer ignore-type */ $token);
Loading history...
916
917 1418
        if (! $flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flags of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
918 1416
            return null;
919
        }
920
921 468
        if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
922 122
            if ($this->last + 1 < $this->len && $this->str[++$this->last] === '@') {
923
                // This is a system variable (e.g. `@@hostname`).
924 26
                $token .= $this->str[$this->last++];
925 26
                $flags |= Token::FLAG_SYMBOL_SYSTEM;
926
            }
927 378
        } elseif ($flags & Token::FLAG_SYMBOL_PARAMETER) {
928 18
            if ($token !== '?' && $this->last + 1 < $this->len) {
929 8
                ++$this->last;
930
            }
931
        } else {
932 366
            $token = '';
933
        }
934
935 468
        $str = null;
936
937 468
        if ($this->last < $this->len) {
938 468
            $str = $this->parseString('`');
939
940 468
            if ($str === null) {
941 100
                $str = $this->parseUnknown();
942
943 100
                if ($str === null && ! ($flags & Token::FLAG_SYMBOL_PARAMETER)) {
944 4
                    $this->error('Variable name was expected.', $this->str[$this->last], $this->last);
0 ignored issues
show
Bug introduced by
It seems like $this->str[$this->last] can also be of type null; however, parameter $str of PhpMyAdmin\SqlParser\Lexer::error() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

944
                    $this->error('Variable name was expected.', /** @scrutinizer ignore-type */ $this->str[$this->last], $this->last);
Loading history...
945
                }
946
            }
947
        }
948
949 468
        if ($str !== null) {
950 458
            $token .= $str->token;
951
        }
952
953 468
        return new Token($token, TokenType::Symbol, $flags);
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $token of PhpMyAdmin\SqlParser\Token::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

953
        return new Token(/** @scrutinizer ignore-type */ $token, TokenType::Symbol, $flags);
Loading history...
954
    }
955
956
    /**
957
     * Parses unknown parts of the query.
958
     */
959 1092
    public function parseUnknown(): Token|null
960
    {
961 1092
        $token = $this->str[$this->last];
962 1092
        if (Context::isSeparator($token)) {
0 ignored issues
show
Bug introduced by
It seems like $token can also be of type null; however, parameter $string of PhpMyAdmin\SqlParser\Context::isSeparator() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

962
        if (Context::isSeparator(/** @scrutinizer ignore-type */ $token)) {
Loading history...
963 22
            return null;
964
        }
965
966 1084
        while (++$this->last < $this->len && ! Context::isSeparator($this->str[$this->last])) {
967 1052
            $token .= $this->str[$this->last];
968
969
            // Test if end of token equals the current delimiter. If so, remove it from the token.
970 1052
            if (str_ends_with($token, $this->delimiter)) {
971 4
                $token = substr($token, 0, -$this->delimiterLen);
972 4
                $this->last -= $this->delimiterLen - 1;
973 4
                break;
974
            }
975
        }
976
977 1084
        --$this->last;
978
979 1084
        return new Token($token);
980
    }
981
982
    /**
983
     * Parses the delimiter of the query.
984
     */
985 1434
    public function parseDelimiter(): Token|null
986
    {
987 1434
        $idx = 0;
988
989 1434
        while ($idx < $this->delimiterLen && $this->last + $idx < $this->len) {
990 1434
            if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
991 1434
                return null;
992
            }
993
994 578
            ++$idx;
995
        }
996
997 578
        $this->last += $this->delimiterLen - 1;
998
999 578
        return new Token($this->delimiter, TokenType::Delimiter);
1000
    }
1001
1002 1434
    private function parse(): Token|null
1003
    {
1004
        // It is best to put the parsers in order of their complexity
1005
        // (ascending) and their occurrence rate (descending).
1006
        //
1007
        // Conflicts:
1008
        //
1009
        // 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
1010
        // They fight over delimiter. The delimiter may be a keyword, a
1011
        // number or almost any character which makes the delimiter one of
1012
        // the first tokens that must be parsed.
1013
        //
1014
        // 1. `parseNumber` and `parseOperator`
1015
        // They fight over `+` and `-`.
1016
        //
1017
        // 2. `parseComment` and `parseOperator`
1018
        // They fight over `/` (as in ```/*comment*/``` or ```a / b```)
1019
        //
1020
        // 3. `parseBool` and `parseKeyword`
1021
        // They fight over `TRUE` and `FALSE`.
1022
        //
1023
        // 4. `parseKeyword` and `parseUnknown`
1024
        // They fight over words. `parseUnknown` does not know about
1025
        // keywords.
1026
1027 1434
        return $this->parseDelimiter()
1028 1434
            ?? $this->parseWhitespace()
1029 1434
            ?? $this->parseNumber()
1030 1434
            ?? $this->parseComment()
1031 1434
            ?? $this->parseOperator()
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->parseOperator() targeting PhpMyAdmin\SqlParser\Lexer::parseOperator() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1032 1434
            ?? $this->parseBool()
1033 1434
            ?? $this->parseString()
1034 1434
            ?? $this->parseSymbol()
1035 1434
            ?? $this->parseKeyword()
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->parseKeyword() targeting PhpMyAdmin\SqlParser\Lexer::parseKeyword() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1036 1434
            ?? $this->parseLabel()
1037 1434
            ?? $this->parseUnknown();
1038
    }
1039
}
1040