Passed
Pull Request — master (#385)
by
unknown
02:56
created

Lexer::parseWhitespace()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 0
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin\SqlParser;
6
7
use PhpMyAdmin\SqlParser\Exceptions\LexerException;
8
9
use function define;
10
use function defined;
11
use function in_array;
12
use function mb_strlen;
13
use function sprintf;
14
use function str_ends_with;
15
use function strlen;
16
use function substr;
17
18 8
if (! defined('USE_UTF_STRINGS')) {
19
    // NOTE: In previous versions of PHP (5.5 and older) the default
20
    // internal encoding is "ISO-8859-1".
21
    // All `mb_` functions must specify the correct encoding, which is
22
    // 'UTF-8' in order to work properly.
23
24
    /*
25
     * Forces usage of `UtfString` if the string is multibyte.
26
     * `UtfString` may be slower, but it gives better results.
27
     *
28
     * @var bool
29
     */
30 8
    define('USE_UTF_STRINGS', true);
31
}
32
33
/**
34
 * Defines the lexer of the library.
35
 *
36
 * This is one of the most important components, along with the parser.
37
 *
38
 * Depends on context to extract lexemes.
39
 *
40
 * Performs lexical analysis over a SQL statement and splits it in multiple tokens.
41
 *
42
 * The output of the lexer is affected by the context of the SQL statement.
43
 *
44
 * @see Context
45
 */
46
class Lexer extends Core
47
{
48
    /**
49
     * A list of methods that are used in lexing the SQL query.
50
     *
51
     * @var string[]
52
     */
53
    public static $PARSER_METHODS = [
54
        // It is best to put the parsers in order of their complexity
55
        // (ascending) and their occurrence rate (descending).
56
        //
57
        // Conflicts:
58
        //
59
        // 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
60
        // They fight over delimiter. The delimiter may be a keyword, a
61
        // number or almost any character which makes the delimiter one of
62
        // the first tokens that must be parsed.
63
        //
64
        // 1. `parseNumber` and `parseOperator`
65
        // They fight over `+` and `-`.
66
        //
67
        // 2. `parseComment` and `parseOperator`
68
        // They fight over `/` (as in ```/*comment*/``` or ```a / b```)
69
        //
70
        // 3. `parseBool` and `parseKeyword`
71
        // They fight over `TRUE` and `FALSE`.
72
        //
73
        // 4. `parseKeyword` and `parseUnknown`
74
        // They fight over words. `parseUnknown` does not know about
75
        // keywords.
76
77
        'parseDelimiter',
78
        'parseWhitespace',
79
        'parseNumber',
80
        'parseComment',
81
        'parseOperator',
82
        'parseBool',
83
        'parseString',
84
        'parseSymbol',
85
        'parseKeyword',
86
        'parseLabel',
87
        'parseUnknown',
88
    ];
89
90
    /**
91
     * The string to be parsed.
92
     *
93
     * @var string|UtfString
94
     */
95
    public $str = '';
96
97
    /**
98
     * The length of `$str`.
99
     *
100
     * By storing its length, a lot of time is saved, because parsing methods
101
     * would call `strlen` everytime.
102
     *
103
     * @var int
104
     */
105
    public $len = 0;
106
107
    /**
108
     * The index of the last parsed character.
109
     *
110
     * @var int
111
     */
112
    public $last = 0;
113
114
    /**
115
     * Tokens extracted from given strings.
116
     *
117
     * @var TokensList
118
     */
119
    public $list;
120
121
    /**
122
     * The default delimiter. This is used, by default, in all new instances.
123
     *
124
     * @var string
125
     */
126
    public static $DEFAULT_DELIMITER = ';';
127
128
    /**
129
     * Statements delimiter.
130
     * This may change during lexing.
131
     *
132
     * @var string
133
     */
134
    public $delimiter;
135
136
    /**
137
     * The length of the delimiter.
138
     *
139
     * Because `parseDelimiter` can be called a lot, it would perform a lot of
140
     * calls to `strlen`, which might affect performance when the delimiter is
141
     * big.
142
     *
143
     * @var int
144
     */
145
    public $delimiterLen;
146
147
    /**
148
     * Gets the tokens list parsed by a new instance of a lexer.
149
     *
150
     * @param string|UtfString $str       the query to be lexed
151
     * @param bool             $strict    whether strict mode should be
152
     *                                    enabled or not
153
     * @param string           $delimiter the delimiter to be used
154
     *
155
     * @return TokensList
156
     */
157 4
    public static function getTokens($str, $strict = false, $delimiter = null)
158
    {
159 4
        $lexer = new self($str, $strict, $delimiter);
160
161 4
        return $lexer->list;
162
    }
163
164
    /**
165
     * @param string|UtfString $str       the query to be lexed
166
     * @param bool             $strict    whether strict mode should be
167
     *                                    enabled or not
168
     * @param string           $delimiter the delimiter to be used
169
     */
170 2284
    public function __construct($str, $strict = false, $delimiter = null)
171
    {
172
        // `strlen` is used instead of `mb_strlen` because the lexer needs to
173
        // parse each byte of the input.
174 2284
        $len = $str instanceof UtfString ? $str->length() : strlen($str);
175
176
        // For multi-byte strings, a new instance of `UtfString` is
177
        // initialized (only if `UtfString` usage is forced.
178 2284
        if (! $str instanceof UtfString && USE_UTF_STRINGS && $len !== mb_strlen($str, 'UTF-8')) {
179 4
            $str = new UtfString($str);
180
        }
181
182 2284
        $this->str = $str;
183 2284
        $this->len = $str instanceof UtfString ? $str->length() : $len;
184
185 2284
        $this->strict = $strict;
186
187
        // Setting the delimiter.
188 2284
        $this->setDelimiter(! empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER);
189
190 2284
        $this->lex();
191
    }
192
193
    /**
194
     * Sets the delimiter.
195
     *
196
     * @param string $delimiter the new delimiter
197
     *
198
     * @return void
199
     */
200 2284
    public function setDelimiter($delimiter)
201
    {
202 2284
        $this->delimiter = $delimiter;
203 2284
        $this->delimiterLen = strlen($delimiter);
204
    }
205
206
    /**
207
     * Parses the string and extracts lexemes.
208
     *
209
     * @return void
210
     */
211 2284
    public function lex()
212
    {
213
        // TODO: Sometimes, static::parse* functions make unnecessary calls to
214
        // is* functions. For a better performance, some rules can be deduced
215
        // from context.
216
        // For example, in `parseBool` there is no need to compare the token
217
        // every time with `true` and `false`. The first step would be to
218
        // compare with 'true' only and just after that add another letter from
219
        // context and compare again with `false`.
220
        // Another example is `parseComment`.
221
222 2284
        $list = new TokensList();
223
224
        /**
225
         * Last processed token.
226
         *
227
         * @var Token
228
         */
229 2284
        $lastToken = null;
230
231 2284
        for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
232
            /**
233
             * The new token.
234
             *
235
             * @var Token
236
             */
237 2260
            $token = null;
238
239 2260
            foreach (static::$PARSER_METHODS as $method) {
240 2260
                $token = $this->$method();
241
242 2260
                if ($token) {
243 2260
                    break;
244
                }
245
            }
246
247 2260
            if ($token === null) {
248
                // @assert($this->last === $lastIdx);
249 8
                $token = new Token($this->str[$this->last]);
250 8
                $this->error('Unexpected character.', $this->str[$this->last], $this->last);
251
            } elseif (
252
                $lastToken !== null
253 2260
                && $token->type === Token::TYPE_SYMBOL
254 2260
                && $token->flags & Token::FLAG_SYMBOL_VARIABLE
255
                && (
256 148
                    $lastToken->type === Token::TYPE_STRING
257
                    || (
258 124
                        $lastToken->type === Token::TYPE_SYMBOL
259 2260
                        && $lastToken->flags & Token::FLAG_SYMBOL_BACKTICK
260
                    )
261
                )
262
            ) {
263
                // Handles ```... FROM 'user'@'%' ...```.
264 52
                $lastToken->token .= $token->token;
265 52
                $lastToken->type = Token::TYPE_SYMBOL;
266 52
                $lastToken->flags = Token::FLAG_SYMBOL_USER;
267 52
                $lastToken->value .= '@' . $token->value;
268 52
                continue;
269
            } elseif (
270
                $lastToken !== null
271 2260
                && $token->type === Token::TYPE_KEYWORD
272 2260
                && $lastToken->type === Token::TYPE_OPERATOR
273 2260
                && $lastToken->value === '.'
274
            ) {
275
                // Handles ```... tbl.FROM ...```. In this case, FROM is not
276
                // a reserved word.
277 32
                $token->type = Token::TYPE_NONE;
278 32
                $token->flags = 0;
279 32
                $token->value = $token->token;
280
            }
281
282 2260
            $token->position = $lastIdx;
283
284 2260
            $list->tokens[$list->count++] = $token;
285
286
            // Handling delimiters.
287 2260
            if ($token->type === Token::TYPE_NONE && $token->value === 'DELIMITER') {
288 32
                if ($this->last + 1 >= $this->len) {
289 4
                    $this->error('Expected whitespace(s) before delimiter.', '', $this->last + 1);
290 4
                    continue;
291
                }
292
293
                // Skipping last R (from `delimiteR`) and whitespaces between
294
                // the keyword `DELIMITER` and the actual delimiter.
295 28
                $pos = ++$this->last;
296 28
                $token = $this->parseWhitespace();
297
298 28
                if ($token !== null) {
299 24
                    $token->position = $pos;
300 24
                    $list->tokens[$list->count++] = $token;
301
                }
302
303
                // Preparing the token that holds the new delimiter.
304 28
                if ($this->last + 1 >= $this->len) {
305 4
                    $this->error('Expected delimiter.', '', $this->last + 1);
306 4
                    continue;
307
                }
308
309 24
                $pos = $this->last + 1;
310
311
                // Parsing the delimiter.
312 24
                $this->delimiter = null;
313 24
                $delimiterLen = 0;
314
                while (
315 24
                    ++$this->last < $this->len
316 24
                    && ! Context::isWhitespace($this->str[$this->last])
317 24
                    && $delimiterLen < 15
318
                ) {
319 20
                    $this->delimiter .= $this->str[$this->last];
320 20
                    ++$delimiterLen;
321
                }
322
323 24
                if (empty($this->delimiter)) {
324 4
                    $this->error('Expected delimiter.', '', $this->last);
325 4
                    $this->delimiter = ';';
326
                }
327
328 24
                --$this->last;
329
330
                // Saving the delimiter and its token.
331 24
                $this->delimiterLen = strlen($this->delimiter);
332 24
                $token = new Token($this->delimiter, Token::TYPE_DELIMITER);
333 24
                $token->position = $pos;
334 24
                $list->tokens[$list->count++] = $token;
335
            }
336
337 2252
            $lastToken = $token;
338
        }
339
340
        // Adding a final delimiter to mark the ending.
341 2284
        $list->tokens[$list->count++] = new Token(null, Token::TYPE_DELIMITER);
342
343
        // Saving the tokens list.
344 2284
        $this->list = $list;
345
346 2284
        $this->solveAmbiguityOnStarOperator();
347 2284
        $this->solveAmbiguityOnFunctionKeywords();
348
    }
349
350
    /**
351
     * Resolves the ambiguity when dealing with the "*" operator.
352
     *
353
     * In SQL statements, the "*" operator can be an arithmetic operator (like in 2*3) or an SQL wildcard (like in
354
     * SELECT a.* FROM ...). To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
355
     * comments, right after the "*" position. The "*" is for sure an SQL wildcard if the next token found is any of:
356
     * - "FROM" (the FROM keyword like in "SELECT * FROM...");
357
     * - "USING" (the USING keyword like in "DELETE table_name.* USING...");
358
     * - "," (a comma separator like in "SELECT *, field FROM...");
359
     * - ")" (a closing parenthesis like in "COUNT(*)").
360
     * This methods will change the flag of the "*" tokens when any of those condition above is true. Otherwise, the
361
     * default flag (arithmetic) will be kept.
362
     */
363 2284
    private function solveAmbiguityOnStarOperator(): void
364
    {
365 2284
        $iBak = $this->list->idx;
366 2284
        while (($starToken = $this->list->getNextOfTypeAndValue(Token::TYPE_OPERATOR, '*')) !== null) {
367
            // getNext() already gets rid of whitespaces and comments.
368 352
            $next = $this->list->getNext();
369
370 352
            if ($next === null) {
371
                continue;
372
            }
373
374
            if (
375 352
                ($next->type !== Token::TYPE_KEYWORD || ! in_array($next->value, ['FROM', 'USING'], true))
376 352
                && ($next->type !== Token::TYPE_OPERATOR || ! in_array($next->value, [',', ')'], true))
377
            ) {
378 28
                continue;
379
            }
380
381 328
            $starToken->flags = Token::FLAG_OPERATOR_SQL;
382
        }
383
384 2284
        $this->list->idx = $iBak;
385
    }
386
387
    /**
388
     * Resolves the ambiguity when dealing with the functions keywords.
389
     *
390
     * In SQL statements, the function keywords might be used as table names or columns names.
391
     * To solve this ambiguity, the solution is to find the next token, excluding whitespaces and
392
     * comments, right after the function keyword position. The function keyword is for sure used
393
     * as column name or table name if the next token found is any of:
394
     *
395
     * - "FROM" (the FROM keyword like in "SELECT Country x, AverageSalary avg FROM...");
396
     * - "WHERE" (the WHERE keyword like in "DELETE FROM emp x WHERE x.salary = 20");
397
     * - "SET" (the SET keyword like in "UPDATE Country x, City y set x.Name=x.Name");
398
     * - "," (a comma separator like 'x,' in "UPDATE Country x, City y set x.Name=x.Name");
399
     * - "." (a dot separator like in "x.asset_id FROM (SELECT evt.asset_id FROM evt)".
400
     * - "NULL" (when used as a table alias like in "avg.col FROM (SELECT ev.col FROM ev) avg").
401
     *
402
     * This method will change the flag of the function keyword tokens when any of those
403
     * condition above is true. Otherwise, the
404
     * default flag (function keyword) will be kept.
405
     */
406 2284
    private function solveAmbiguityOnFunctionKeywords(): void
407
    {
408 2284
        $iBak = $this->list->idx;
409 2284
        $keywordFunction = Token::TYPE_KEYWORD | Token::FLAG_KEYWORD_FUNCTION;
410 2284
        while (($keywordToken = $this->list->getNextOfTypeAndFlag(Token::TYPE_KEYWORD, $keywordFunction)) !== null) {
411 272
            $next = $this->list->getNext();
412
            if (
413 272
                ($next->type !== Token::TYPE_KEYWORD || ! in_array($next->value, ['FROM', 'SET', 'WHERE'], true))
414 272
                && ($next->type !== Token::TYPE_OPERATOR || ! in_array($next->value, ['.', ','], true))
415 272
                && ($next->value !== null)
416
            ) {
417 256
                continue;
418
            }
419
420 16
            $keywordToken->type = Token::TYPE_NONE;
421 16
            $keywordToken->flags = Token::TYPE_NONE;
422 16
            $keywordToken->keyword = $keywordToken->value;
423
        }
424
425 2284
        $this->list->idx = $iBak;
426
    }
427
428
    /**
429
     * Creates a new error log.
430
     *
431
     * @param string $msg  the error message
432
     * @param string $str  the character that produced the error
433
     * @param int    $pos  the position of the character
434
     * @param int    $code the code of the error
435
     *
436
     * @return void
437
     *
438
     * @throws LexerException throws the exception, if strict mode is enabled.
439
     */
440 68
    public function error($msg, $str = '', $pos = 0, $code = 0)
441
    {
442 68
        $error = new LexerException(
443 68
            Translator::gettext($msg),
444
            $str,
445
            $pos,
446
            $code
447
        );
448 68
        parent::error($error);
449
    }
450
451
    /**
452
     * Parses a keyword.
453
     *
454
     * @return Token|null
455
     */
456 2224
    public function parseKeyword()
457
    {
458 2224
        $token = '';
459
460
        /**
461
         * Value to be returned.
462
         *
463
         * @var Token
464
         */
465 2224
        $ret = null;
466
467
        /**
468
         * The value of `$this->last` where `$token` ends in `$this->str`.
469
         */
470 2224
        $iEnd = $this->last;
471
472
        /**
473
         * Whether last parsed character is a whitespace.
474
         *
475
         * @var bool
476
         */
477 2224
        $lastSpace = false;
478
479 2224
        for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
480
            // Composed keywords shouldn't have more than one whitespace between
481
            // keywords.
482 2224
            if (Context::isWhitespace($this->str[$this->last])) {
483 2176
                if ($lastSpace) {
484 376
                    --$j; // The size of the keyword didn't increase.
485 376
                    continue;
486
                }
487
488 2176
                $lastSpace = true;
489
            } else {
490 2224
                $lastSpace = false;
491
            }
492
493 2224
            $token .= $this->str[$this->last];
494 2224
            $flags = Context::isKeyword($token);
495
496 2224
            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...
497 2224
                continue;
498
            }
499
500 2156
            $ret = new Token($token, Token::TYPE_KEYWORD, $flags);
501 2156
            $iEnd = $this->last;
502
503
            // We don't break so we find longest keyword.
504
            // For example, `OR` and `ORDER` have a common prefix `OR`.
505
            // If we stopped at `OR`, the parsing would be invalid.
506
        }
507
508 2224
        $this->last = $iEnd;
509
510 2224
        return $ret;
511
    }
512
513
    /**
514
     * Parses a label.
515
     *
516
     * @return Token|null
517
     */
518 1648
    public function parseLabel()
519
    {
520 1648
        $token = '';
521
522
        /**
523
         * Value to be returned.
524
         *
525
         * @var Token
526
         */
527 1648
        $ret = null;
528
529
        /**
530
         * The value of `$this->last` where `$token` ends in `$this->str`.
531
         */
532 1648
        $iEnd = $this->last;
533 1648
        for ($j = 1; $j < Context::LABEL_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
534 1648
            if ($this->str[$this->last] === ':' && $j > 1) {
535
                // End of label
536 8
                $token .= $this->str[$this->last];
537 8
                $ret = new Token($token, Token::TYPE_LABEL);
538 8
                $iEnd = $this->last;
539 8
                break;
540
            }
541
542 1648
            if (Context::isWhitespace($this->str[$this->last]) && $j > 1) {
543
                // Whitespace between label and :
544
                // The size of the keyword didn't increase.
545 1280
                --$j;
546 1648
            } elseif (Context::isSeparator($this->str[$this->last])) {
547
                // Any other separator
548 1272
                break;
549
            }
550
551 1644
            $token .= $this->str[$this->last];
552
        }
553
554 1648
        $this->last = $iEnd;
555
556 1648
        return $ret;
557
    }
558
559
    /**
560
     * Parses an operator.
561
     *
562
     * @return Token|null
563
     */
564 2260
    public function parseOperator()
565
    {
566 2260
        $token = '';
567
568
        /**
569
         * Value to be returned.
570
         *
571
         * @var Token
572
         */
573 2260
        $ret = null;
574
575
        /**
576
         * The value of `$this->last` where `$token` ends in `$this->str`.
577
         */
578 2260
        $iEnd = $this->last;
579
580 2260
        for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
581 2260
            $token .= $this->str[$this->last];
582 2260
            $flags = Context::isOperator($token);
583
584 2260
            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...
585 2252
                continue;
586
            }
587
588 1604
            $ret = new Token($token, Token::TYPE_OPERATOR, $flags);
589 1604
            $iEnd = $this->last;
590
        }
591
592 2260
        $this->last = $iEnd;
593
594 2260
        return $ret;
595
    }
596
597
    /**
598
     * Parses a whitespace.
599
     *
600
     * @return Token|null
601
     */
602 2260
    public function parseWhitespace()
603
    {
604 2260
        $token = $this->str[$this->last];
605
606 2260
        if (! Context::isWhitespace($token)) {
607 2260
            return null;
608
        }
609
610 2208
        while (++$this->last < $this->len && Context::isWhitespace($this->str[$this->last])) {
611 376
            $token .= $this->str[$this->last];
612
        }
613
614 2208
        --$this->last;
615
616 2208
        return new Token($token, Token::TYPE_WHITESPACE);
617
    }
618
619
    /**
620
     * Parses a comment.
621
     *
622
     * @return Token|null
623
     */
624 2260
    public function parseComment()
625
    {
626 2260
        $iBak = $this->last;
627 2260
        $token = $this->str[$this->last];
628
629
        // Bash style comments. (#comment\n)
630 2260
        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...
631 12
            while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
632 12
                $token .= $this->str[$this->last];
633
            }
634
635
            // Include trailing \n as whitespace token
636 12
            if ($this->last < $this->len) {
637 12
                --$this->last;
638
            }
639
640 12
            return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_BASH);
641
        }
642
643
        // C style comments. (/*comment*\/)
644 2260
        if (++$this->last < $this->len) {
645 2252
            $token .= $this->str[$this->last];
646 2252
            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...
647
                // There might be a conflict with "*" operator here, when string is "*/*".
648
                // This can occurs in the following statements:
649
                // - "SELECT */* comment */ FROM ..."
650
                // - "SELECT 2*/* comment */3 AS `six`;"
651 132
                $next = $this->last + 1;
652 132
                if (($next < $this->len) && $this->str[$next] === '*') {
653
                    // Conflict in "*/*": first "*" was not for ending a comment.
654
                    // Stop here and let other parsing method define the true behavior of that first star.
655 4
                    $this->last = $iBak;
656
657 4
                    return null;
658
                }
659
660 132
                $flags = Token::FLAG_COMMENT_C;
661
662
                // This comment already ended. It may be a part of a
663
                // previous MySQL specific command.
664 132
                if ($token === '*/') {
665 12
                    return new Token($token, Token::TYPE_COMMENT, $flags);
666
                }
667
668
                // Checking if this is a MySQL-specific command.
669 132
                if ($this->last + 1 < $this->len && $this->str[$this->last + 1] === '!') {
670 12
                    $flags |= Token::FLAG_COMMENT_MYSQL_CMD;
671 12
                    $token .= $this->str[++$this->last];
672
673
                    while (
674 12
                        ++$this->last < $this->len
675 12
                        && $this->str[$this->last] >= '0'
676 12
                        && $this->str[$this->last] <= '9'
677
                    ) {
678 8
                        $token .= $this->str[$this->last];
679
                    }
680
681 12
                    --$this->last;
682
683
                    // We split this comment and parse only its beginning
684
                    // here.
685 12
                    return new Token($token, Token::TYPE_COMMENT, $flags);
686
                }
687
688
                // Parsing the comment.
689
                while (
690 128
                    ++$this->last < $this->len
691
                    && (
692 128
                        $this->str[$this->last - 1] !== '*'
693 128
                        || $this->str[$this->last] !== '/'
694
                    )
695
                ) {
696 128
                    $token .= $this->str[$this->last];
697
                }
698
699
                // Adding the ending.
700 128
                if ($this->last < $this->len) {
701 128
                    $token .= $this->str[$this->last];
702
                }
703
704 128
                return new Token($token, Token::TYPE_COMMENT, $flags);
705
            }
706
        }
707
708
        // SQL style comments. (-- comment\n)
709 2260
        if (++$this->last < $this->len) {
710 2248
            $token .= $this->str[$this->last];
711 2248
            $end = false;
712
        } else {
713 716
            --$this->last;
714 716
            $end = true;
715
        }
716
717 2260
        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...
718
            // Checking if this comment did not end already (```--\n```).
719 96
            if ($this->str[$this->last] !== "\n") {
720 96
                while (++$this->last < $this->len && $this->str[$this->last] !== "\n") {
721 96
                    $token .= $this->str[$this->last];
722
                }
723
            }
724
725
            // Include trailing \n as whitespace token
726 96
            if ($this->last < $this->len) {
727 80
                --$this->last;
728
            }
729
730 96
            return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_SQL);
731
        }
732
733 2260
        $this->last = $iBak;
734
735 2260
        return null;
736
    }
737
738
    /**
739
     * Parses a boolean.
740
     *
741
     * @return Token|null
742
     */
743 2228
    public function parseBool()
744
    {
745 2228
        if ($this->last + 3 >= $this->len) {
746
            // At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
747
            // required.
748 552
            return null;
749
        }
750
751 2228
        $iBak = $this->last;
752 2228
        $token = $this->str[$this->last] . $this->str[++$this->last]
753 2228
        . $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
754
755 2228
        if (Context::isBool($token)) {
756 8
            return new Token($token, Token::TYPE_BOOL);
757
        }
758
759 2228
        if (++$this->last < $this->len) {
760 2224
            $token .= $this->str[$this->last]; // fals_E_
761 2224
            if (Context::isBool($token)) {
762 12
                return new Token($token, Token::TYPE_BOOL, 1);
763
            }
764
        }
765
766 2228
        $this->last = $iBak;
767
768 2228
        return null;
769
    }
770
771
    /**
772
     * Parses a number.
773
     *
774
     * @return Token|null
775
     */
776 2260
    public function parseNumber()
777
    {
778
        // A rudimentary state machine is being used to parse numbers due to
779
        // the various forms of their notation.
780
        //
781
        // Below are the states of the machines and the conditions to change
782
        // the state.
783
        //
784
        //      1 --------------------[ + or - ]-------------------> 1
785
        //      1 -------------------[ 0x or 0X ]------------------> 2
786
        //      1 --------------------[ 0 to 9 ]-------------------> 3
787
        //      1 -----------------------[ . ]---------------------> 4
788
        //      1 -----------------------[ b ]---------------------> 7
789
        //
790
        //      2 --------------------[ 0 to F ]-------------------> 2
791
        //
792
        //      3 --------------------[ 0 to 9 ]-------------------> 3
793
        //      3 -----------------------[ . ]---------------------> 4
794
        //      3 --------------------[ e or E ]-------------------> 5
795
        //
796
        //      4 --------------------[ 0 to 9 ]-------------------> 4
797
        //      4 --------------------[ e or E ]-------------------> 5
798
        //
799
        //      5 ---------------[ + or - or 0 to 9 ]--------------> 6
800
        //
801
        //      7 -----------------------[ ' ]---------------------> 8
802
        //
803
        //      8 --------------------[ 0 or 1 ]-------------------> 8
804
        //      8 -----------------------[ ' ]---------------------> 9
805
        //
806
        // State 1 may be reached by negative numbers.
807
        // State 2 is reached only by hex numbers.
808
        // State 4 is reached only by float numbers.
809
        // State 5 is reached only by numbers in approximate form.
810
        // State 7 is reached only by numbers in bit representation.
811
        //
812
        // Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
813
        // state other than these is invalid.
814
        // Also, negative states are invalid states.
815 2260
        $iBak = $this->last;
816 2260
        $token = '';
817 2260
        $flags = 0;
818 2260
        $state = 1;
819 2260
        for (; $this->last < $this->len; ++$this->last) {
820 2260
            if ($state === 1) {
821 2260
                if ($this->str[$this->last] === '-') {
822 96
                    $flags |= Token::FLAG_NUMBER_NEGATIVE;
823
                } elseif (
824 2260
                    $this->last + 1 < $this->len
825 2260
                    && $this->str[$this->last] === '0'
826
                    && (
827 132
                        $this->str[$this->last + 1] === 'x'
828 2260
                        || $this->str[$this->last + 1] === 'X'
829
                    )
830
                ) {
831 8
                    $token .= $this->str[$this->last++];
832 8
                    $state = 2;
833 2260
                } elseif ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9') {
834 1040
                    $state = 3;
835 2260
                } elseif ($this->str[$this->last] === '.') {
836 344
                    $state = 4;
837 2260
                } elseif ($this->str[$this->last] === 'b') {
838 172
                    $state = 7;
839 2260
                } elseif ($this->str[$this->last] !== '+') {
840
                    // `+` is a valid character in a number.
841 2260
                    break;
842
                }
843 1172
            } elseif ($state === 2) {
844 8
                $flags |= Token::FLAG_NUMBER_HEX;
845
                if (
846
                    ! (
847 8
                        ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
848 8
                        || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'F')
849 8
                        || ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'f')
850
                    )
851
                ) {
852 8
                    break;
853
                }
854 1172
            } elseif ($state === 3) {
855 936
                if ($this->str[$this->last] === '.') {
856 24
                    $state = 4;
857 932
                } elseif ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
858 4
                    $state = 5;
859
                } elseif (
860 932
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
861 932
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
862
                ) {
863
                    // A number can't be directly followed by a letter
864 12
                    $state = -$state;
865 928
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
866
                    // Just digits and `.`, `e` and `E` are valid characters.
867 936
                    break;
868
                }
869 500
            } elseif ($state === 4) {
870 364
                $flags |= Token::FLAG_NUMBER_FLOAT;
871 364
                if ($this->str[$this->last] === 'e' || $this->str[$this->last] === 'E') {
872 28
                    $state = 5;
873
                } elseif (
874 364
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
875 364
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
876
                ) {
877
                    // A number can't be directly followed by a letter
878 252
                    $state = -$state;
879 160
                } elseif ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
880
                    // Just digits, `e` and `E` are valid characters.
881 364
                    break;
882
                }
883 404
            } elseif ($state === 5) {
884 28
                $flags |= Token::FLAG_NUMBER_APPROXIMATE;
885
                if (
886 28
                    $this->str[$this->last] === '+' || $this->str[$this->last] === '-'
887 28
                    || ($this->str[$this->last] >= '0' && $this->str[$this->last] <= '9')
888
                ) {
889 4
                    $state = 6;
890
                } elseif (
891 28
                    ($this->str[$this->last] >= 'a' && $this->str[$this->last] <= 'z')
892 28
                    || ($this->str[$this->last] >= 'A' && $this->str[$this->last] <= 'Z')
893
                ) {
894
                    // A number can't be directly followed by a letter
895 28
                    $state = -$state;
896
                } else {
897 28
                    break;
898
                }
899 404
            } elseif ($state === 6) {
900 4
                if ($this->str[$this->last] < '0' || $this->str[$this->last] > '9') {
901
                    // Just digits are valid characters.
902 4
                    break;
903
                }
904 404
            } elseif ($state === 7) {
905 168
                $flags |= Token::FLAG_NUMBER_BINARY;
906 168
                if ($this->str[$this->last] !== '\'') {
907 164
                    break;
908
                }
909
910 4
                $state = 8;
911 264
            } elseif ($state === 8) {
912 4
                if ($this->str[$this->last] === '\'') {
913 4
                    $state = 9;
914 4
                } elseif ($this->str[$this->last] !== '0' && $this->str[$this->last] !== '1') {
915 4
                    break;
916
                }
917 264
            } elseif ($state === 9) {
918 4
                break;
919
            }
920
921 1304
            $token .= $this->str[$this->last];
922
        }
923
924 2260
        if ($state === 2 || $state === 3 || ($token !== '.' && $state === 4) || $state === 6 || $state === 9) {
925 1040
            --$this->last;
926
927 1040
            return new Token($token, Token::TYPE_NUMBER, $flags);
928
        }
929
930 2260
        $this->last = $iBak;
931
932 2260
        return null;
933
    }
934
935
    /**
936
     * Parses a string.
937
     *
938
     * @param string $quote additional starting symbol
939
     *
940
     * @return Token|null
941
     *
942
     * @throws LexerException
943
     */
944 2228
    public function parseString($quote = '')
945
    {
946 2228
        $token = $this->str[$this->last];
947 2228
        $flags = Context::isString($token);
948
949 2228
        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...
950 2228
            return null;
951
        }
952
953 1100
        $quote = $token;
954
955 1100
        while (++$this->last < $this->len) {
956
            if (
957 1100
                $this->last + 1 < $this->len
958
                && (
959 1096
                    ($this->str[$this->last] === $quote && $this->str[$this->last + 1] === $quote)
960 1100
                    || ($this->str[$this->last] === '\\' && $quote !== '`')
961
                )
962
            ) {
963 48
                $token .= $this->str[$this->last] . $this->str[++$this->last];
964
            } else {
965 1100
                if ($this->str[$this->last] === $quote) {
966 1092
                    break;
967
                }
968
969 1092
                $token .= $this->str[$this->last];
970
            }
971
        }
972
973 1100
        if ($this->last >= $this->len || $this->str[$this->last] !== $quote) {
974 28
            $this->error(
975 28
                sprintf(
976 28
                    Translator::gettext('Ending quote %1$s was expected.'),
977
                    $quote
978
                ),
979
                '',
980 28
                $this->last
981
            );
982
        } else {
983 1092
            $token .= $this->str[$this->last];
984
        }
985
986 1100
        return new Token($token, Token::TYPE_STRING, $flags);
987
    }
988
989
    /**
990
     * Parses a symbol.
991
     *
992
     * @return Token|null
993
     *
994
     * @throws LexerException
995
     */
996 2228
    public function parseSymbol()
997
    {
998 2228
        $token = $this->str[$this->last];
999 2228
        $flags = Context::isSymbol($token);
1000
1001 2228
        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...
1002 2224
            return null;
1003
        }
1004
1005 700
        if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
1006 148
            if ($this->last + 1 < $this->len && $this->str[++$this->last] === '@') {
1007
                // This is a system variable (e.g. `@@hostname`).
1008 8
                $token .= $this->str[$this->last++];
1009 148
                $flags |= Token::FLAG_SYMBOL_SYSTEM;
1010
            }
1011 596
        } elseif ($flags & Token::FLAG_SYMBOL_PARAMETER) {
1012 12
            if ($token !== '?' && $this->last + 1 < $this->len) {
1013 12
                ++$this->last;
1014
            }
1015
        } else {
1016 588
            $token = '';
1017
        }
1018
1019 700
        $str = null;
1020
1021 700
        if ($this->last < $this->len) {
1022 700
            $str = $this->parseString('`');
1023
1024 700
            if ($str === null) {
1025 108
                $str = $this->parseUnknown();
1026
1027 108
                if ($str === null) {
1028 12
                    $this->error('Variable name was expected.', $this->str[$this->last], $this->last);
1029
                }
1030
            }
1031
        }
1032
1033 700
        if ($str !== null) {
1034 692
            $token .= $str->token;
1035
        }
1036
1037 700
        return new Token($token, Token::TYPE_SYMBOL, $flags);
1038
    }
1039
1040
    /**
1041
     * Parses unknown parts of the query.
1042
     *
1043
     * @return Token|null
1044
     */
1045 1672
    public function parseUnknown()
1046
    {
1047 1672
        $token = $this->str[$this->last];
1048 1672
        if (Context::isSeparator($token)) {
1049 20
            return null;
1050
        }
1051
1052 1668
        while (++$this->last < $this->len && ! Context::isSeparator($this->str[$this->last])) {
1053 1624
            $token .= $this->str[$this->last];
1054
1055
            // Test if end of token equals the current delimiter. If so, remove it from the token.
1056 1624
            if (str_ends_with($token, $this->delimiter)) {
1057 4
                $token = substr($token, 0, -$this->delimiterLen);
1058 4
                $this->last -= $this->delimiterLen - 1;
1059 4
                break;
1060
            }
1061
        }
1062
1063 1668
        --$this->last;
1064
1065 1668
        return new Token($token);
1066
    }
1067
1068
    /**
1069
     * Parses the delimiter of the query.
1070
     *
1071
     * @return Token|null
1072
     */
1073 2260
    public function parseDelimiter()
1074
    {
1075 2260
        $idx = 0;
1076
1077 2260
        while ($idx < $this->delimiterLen && $this->last + $idx < $this->len) {
1078 2260
            if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
1079 2260
                return null;
1080
            }
1081
1082 760
            ++$idx;
1083
        }
1084
1085 760
        $this->last += $this->delimiterLen - 1;
1086
1087 760
        return new Token($this->delimiter, Token::TYPE_DELIMITER);
1088
    }
1089
}
1090