Debian Codegraph @

vendor/mck89/peast/lib/Peast/Syntax/Scanner.php

raw
1 <?php
2 /**
3 * This file is part of the Peast package
4 *
5 * (c) Marco Marchiò <[email protected]>
6 *
7 * For the full copyright and license information refer to the LICENSE file
8 * distributed with this source code
9 */
10 namespace Peast\Syntax;
11
12 /**
13 * Base class for scanners.
14 *
15 * @author Marco Marchiò <[email protected]>
16 */
17 class Scanner
18 {
19 use JSX\Scanner;
20
21 /**
22 * Scanner features
23 *
24 * @var Features
25 */
26 protected $features;
27
28 /**
29 * Current column
30 *
31 * @var int
32 */
33 protected $column = 0;
34
35 /**
36 * Current line
37 *
38 * @var int
39 */
40 protected $line = 1;
41
42 /**
43 * Current index
44 *
45 * @var int
46 */
47 protected $index = 0;
48
49 /**
50 * Source length
51 *
52 * @var int
53 */
54 protected $length;
55
56 /**
57 * Source characters
58 *
59 * @var array
60 */
61 protected $source;
62
63 /**
64 * Consumed position
65 *
66 * @var Position
67 */
68 protected $position;
69
70 /**
71 * Current token
72 *
73 * @var Token
74 */
75 protected $currentToken;
76
77 /**
78 * Next token
79 *
80 * @var Token
81 */
82 protected $nextToken;
83
84 /**
85 * Strict mode flag
86 *
87 * @var bool
88 */
89 protected $strictMode = false;
90
91 /**
92 * True to register tokens in the tokens array
93 *
94 * @var bool
95 */
96 protected $registerTokens = false;
97
98 /**
99 * Module mode
100 *
101 * @var bool
102 */
103 protected $isModule = false;
104
105 /**
106 * Comments handling
107 *
108 * @var bool
109 */
110 protected $comments = false;
111
112 /**
113 * Internal JSX scan flag
114 *
115 * @var bool
116 */
117 protected $jsx = false;
118
119 /**
120 * Registered tokens array
121 *
122 * @var array
123 */
124 protected $tokens = array();
125
126 /**
127 * Comments to tokens map
128 *
129 * @var array
130 */
131 protected $commentsMap = array();
132
133 /**
134 * Events emitter
135 *
136 * @var EventsEmitter
137 */
138 protected $eventsEmitter;
139
140 /**
141 * Regex to match identifiers starts
142 *
143 * @var string
144 */
145 protected $idStartRegex = "/[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\x{1885}\x{1886}\x{2118}\x{212E}\x{309B}\x{309C}]/u";
146
147 /**
148 * Regex to match identifiers parts
149 *
150 * @var string
151 */
152 protected $idPartRegex = "/[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\x{1885}\x{1886}\x{2118}\x{212E}\x{309B}\x{309C}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{00B7}\x{0387}\x{1369}\x{136A}\x{136B}\x{136C}\x{136D}\x{136E}\x{136F}\x{1370}\x{1371}\x{19DA}\x{200C}\x{200D}]/u";
153
154 /**
155 * Keywords array
156 *
157 * @var array
158 */
159 protected $keywords = array(
160 "break", "do", "in", "typeof", "case", "else", "instanceof", "var",
161 "catch", "export", "new", "void", "class", "extends", "return", "while",
162 "const", "finally", "super", "with", "continue", "for", "switch",
163 "debugger", "function", "this", "default", "if", "throw",
164 "delete", "import", "try", "enum", "await"
165 );
166
167 /**
168 * Array of words that are keywords only in strict mode
169 *
170 * @var array
171 */
172 protected $strictModeKeywords = array(
173 "implements", "interface", "package", "private", "protected", "public",
174 "static", "let", "yield"
175 );
176
177 /**
178 * Punctuators array
179 *
180 * @var array
181 */
182 protected $punctuators = array(
183 ".", ";", ",", "<", ">", "<=", ">=", "==", "!=", "===", "!==", "+",
184 "-", "*", "%", "++", "--", "<<", ">>", ">>>", "&", "|", "^", "!", "~",
185 "&&", "||", "?", ":", "=", "+=", "-=", "*=", "%=", "<<=", ">>=", ">>>=",
186 "&=", "|=", "^=", "=>", "...", "/", "/=", "**", "**=", "??", "?.",
187 "&&=", "||=", "??="
188 );
189
190 /**
191 * Punctuators LSM
192 *
193 * @var LSM
194 */
195 protected $punctuatorsLSM;
196
197 /**
198 * Strings stops LSM
199 *
200 * @var LSM
201 */
202 protected $stringsStopsLSM;
203
204 /**
205 * Brackets array
206 *
207 * @var array
208 */
209 protected $brackets = array(
210 "(" => "", "[" => "", "{" => "", ")" => "(", "]" => "[", "}" => "{"
211 );
212
213 /**
214 * Open brackets array
215 *
216 * @var array
217 */
218 protected $openBrackets = array();
219
220 /**
221 * Open templates array
222 *
223 * @var array
224 */
225 protected $openTemplates = array();
226
227 /**
228 * Whitespaces array
229 *
230 * @var array
231 */
232 protected $whitespaces = array(
233 " ", "\t", "\n", "\r", "\f", "\v", 0x00A0, 0xFEFF, 0x00A0,
234 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006,
235 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0x2028,
236 0x2029
237 );
238
239 /**
240 * Line terminators characters array
241 *
242 * @var array
243 *
244 * @static
245 */
246 public static $lineTerminatorsChars = array("\n", "\r", 0x2028, 0x2029);
247
248 /**
249 * Line terminators sequences array
250 *
251 * @var array
252 *
253 * @static
254 */
255 public static $lineTerminatorsSequences = array("\r\n");
256
257 /**
258 * Regex to split texts using valid ES line terminators
259 *
260 * @var array
261 */
262 protected $linesSplitter;
263
264 /**
265 * Concatenation of line terminators characters and line terminators
266 * sequences
267 *
268 * @var array
269 */
270 protected $lineTerminators;
271
272 /**
273 * Properties to copy when getting the scanner state
274 *
275 * @var array
276 */
277 protected $stateProps = array("position", "index", "column", "line",
278 "currentToken", "nextToken", "strictMode",
279 "openBrackets", "openTemplates",
280 "commentsMap");
281
282 /**
283 * Decimal numbers
284 *
285 * @var array
286 */
287 protected $numbers = array("0", "1", "2", "3", "4", "5", "6", "7", "8",
288 "9");
289
290 /**
291 * Hexadecimal numbers
292 *
293 * @var array
294 */
295 protected $xnumbers = array("0", "1", "2", "3", "4", "5", "6", "7", "8",
296 "9", "a", "b", "c", "d", "e", "f", "A", "B",
297 "C", "D", "E", "F");
298
299 /**
300 * Octal numbers
301 *
302 * @var array
303 */
304 protected $onumbers = array("0", "1", "2", "3", "4", "5", "6", "7");
305
306 /**
307 * Binary numbers
308 *
309 * @var array
310 */
311 protected $bnumbers = array("0", "1");
312
313 /**
314 * Class constructor
315 *
316 * @param string $source Source code
317 * @param Features $features Scanner features
318 * @param array $options Parsing options
319 */
320 function __construct(
321 $source, Features $features, $options
322 ) {
323 $this->features = $features;
324
325 $encoding = isset($options["sourceEncoding"]) ?
326 $options["sourceEncoding"] :
327 null;
328
329 //Strip BOM characters from the source
330 $this->stripBOM($source, $encoding);
331
332 //Convert to UTF8 if needed
333 if ($encoding && !preg_match("/UTF-?8/i", $encoding)) {
334 $source = mb_convert_encoding($source, "UTF-8", $encoding);
335 }
336
337 //Instead of using mb_substr for each character, split the source
338 //into an array of UTF8 characters for performance reasons
339 $this->source = Utils::stringToUTF8Array(
340 $source,
341 !isset($options["strictEncoding"]) || $options["strictEncoding"]
342 );
343 $this->length = count($this->source);
344
345 //Convert character codes to UTF8 characters in whitespaces and line
346 //terminators
347 $this->lineTerminators = array_merge(
348 self::$lineTerminatorsSequences, self::$lineTerminatorsChars
349 );
350 foreach (array("whitespaces", "lineTerminators") as $key) {
351 foreach ($this->$key as $i => $char) {
352 if (is_int($char)) {
353 $this->{$key}[$i] = Utils::unicodeToUtf8($char);
354 }
355 }
356 }
357
358 //Remove exponentiation operator if the feature
359 //is not enabled
360 if (!$this->features->exponentiationOperator) {
361 Utils::removeArrayValue($this->punctuators, "**");
362 Utils::removeArrayValue($this->punctuators, "**=");
363 }
364
365 if (!$this->features->optionalChaining) {
366 Utils::removeArrayValue($this->punctuators, "?.");
367 }
368
369 //Remove logical assignment operators if the feature
370 //is not enabled
371 if (!$this->features->logicalAssignmentOperators) {
372 Utils::removeArrayValue($this->punctuators, "&&=");
373 Utils::removeArrayValue($this->punctuators, "||=");
374 Utils::removeArrayValue($this->punctuators, "??=");
375 }
376
377 //Create a LSM for punctuators array
378 $this->punctuatorsLSM = new LSM($this->punctuators);
379
380 //Create a LSM for strings stops
381 $this->stringsStopsLSM = new LSM($this->lineTerminators, true);
382
383 //Allow paragraph and line separators in strings
384 if ($this->features->paragraphLineSepInStrings) {
385 $this->stringsStopsLSM->remove(Utils::unicodeToUtf8(0x2028));
386 $this->stringsStopsLSM->remove(Utils::unicodeToUtf8(0x2029));
387 }
388
389 //Remove await as keyword if async/await is enabled
390 if ($this->features->asyncAwait) {
391 Utils::removeArrayValue($this->keywords, "await");
392 }
393
394 $this->linesSplitter = "/" .
395 implode("|", $this->lineTerminators) .
396 "/uS";
397 $this->position = new Position(0, 0, 0);
398 }
399
400 /**
401 * Strips BOM characters from the source and detects source encoding if not
402 * given by the user
403 *
404 * @param string $source Source
405 * @param string $encoding User specified encoding
406 */
407 public function stripBOM(&$source, &$encoding)
408 {
409 $boms = array(
410 "\xEF" => array(array("\xBB", "\xBF"), "UTF-8"),
411 "\xFE" => array(array("\xFF"), "UTF-16BE"),
412 "\xFF" => array(array("\xFE"), "UTF-16LE"),
413 );
414 if (!isset($source[0]) || !isset($boms[$source[0]])) {
415 return;
416 }
417 $bom = $boms[$source[0]];
418 $l = count($bom[0]);
419 for ($i = 0; $i < $l; $i++) {
420 if (!isset($source[$i + 1]) || $source[$i + 1] !== $bom[0][$i]) {
421 return;
422 }
423 }
424 $source = substr($source, $l + 1);
425 if (!$encoding) {
426 $encoding = $bom[1];
427 }
428 }
429
430 /**
431 * Enables or disables module scanning mode
432 *
433 * @param bool $enable True to enable module scanning mode, false to disable it
434 *
435 * @return $this
436 */
437 public function enableModuleMode($enable = true)
438 {
439 $this->isModule = $enable;
440 return $this;
441 }
442
443 /**
444 * Enables or disables comments handling
445 *
446 * @param bool $enable True to enable comments handling, false to disable it
447 *
448 * @return $this
449 */
450 public function enableComments($enable = true)
451 {
452 $this->comments = $enable;
453 return $this;
454 }
455
456 /**
457 * Enables or disables tokens registration in the token array
458 *
459 * @param bool $enable True to enable token registration, false to disable it
460 *
461 * @return $this
462 */
463 public function enableTokenRegistration($enable = true)
464 {
465 $this->registerTokens = $enable;
466 return $this;
467 }
468
469 /**
470 * Return registered tokens
471 *
472 * @return array
473 */
474 public function getTokens()
475 {
476 return $this->tokens;
477 }
478
479 /**
480 * Returns the scanner's event emitter
481 *
482 * @return EventsEmitter
483 */
484 public function getEventsEmitter()
485 {
486 if (!$this->eventsEmitter) {
487 //The event emitter is created here so that it won't exist if not
488 //necessary
489 $this->eventsEmitter = new EventsEmitter;
490 }
491 return $this->eventsEmitter;
492 }
493
494 /**
495 * Enables or disables strict mode
496 *
497 * @param bool $strictMode Strict mode state
498 *
499 * @return $this
500 */
501 public function setStrictMode($strictMode)
502 {
503 $this->strictMode = $strictMode;
504 return $this;
505 }
506
507 /**
508 * Return strict mode state
509 *
510 * @return bool
511 */
512 public function getStrictMode()
513 {
514 return $this->strictMode;
515 }
516
517 /**
518 * Checks if the given token is a keyword in the current strict mode state
519 *
520 * @param Token $token Token to checks
521 *
522 * @return bool
523 */
524 public function isStrictModeKeyword($token)
525 {
526 return $token->type === Token::TYPE_KEYWORD &&
527 (in_array($token->value, $this->keywords) || (
528 $this->strictMode &&
529 in_array($token->value, $this->strictModeKeywords)));
530 }
531
532 /**
533 * Returns the current scanner state
534 *
535 * @return array
536 */
537 public function getState()
538 {
539 //Consume current and next tokens so that they wont' be parsed again
540 //if the state is restored. If the current token is a slash the next
541 //token isn't parsed, this prevents some edge cases where a regexp
542 //that contains something that can be interpreted as a comment causes
543 //the content to be parsed as a real comment too
544 $token = $this->currentToken ?: $this->getToken();
545 if ($token && $token->value !== "/") {
546 $this->getNextToken();
547 }
548 $state = array();
549 foreach ($this->stateProps as $prop) {
550 $state[$prop] = $this->$prop;
551 }
552 if ($this->registerTokens) {
553 $state["tokensNum"] = count($this->tokens);
554 }
555 //Emit the FreezeState event and pass the given state so that listeners
556 //attached to this event can add data
557 $this->eventsEmitter && $this->eventsEmitter->fire(
558 "FreezeState", array(&$state)
559 );
560 return $state;
561 }
562
563 /**
564 * Sets the current scanner state
565 *
566 * @param array $state State
567 *
568 * @return $this
569 */
570 public function setState($state)
571 {
572 if ($this->registerTokens) {
573 //Check if tokens have been added
574 if (isset($this->tokens[$state["tokensNum"]])) {
575 //Remove all added tokens
576 for ($i = count($this->tokens) - 1; $i >= $state["tokensNum"]; $i--) {
577 array_pop($this->tokens);
578 }
579 }
580 unset($state["tokensNum"]);
581 }
582 //Emit the ResetState event and pass the given state
583 $this->eventsEmitter && $this->eventsEmitter->fire(
584 "ResetState", array(&$state)
585 );
586 foreach ($state as $key => $value) {
587 $this->$key = $value;
588 }
589 return $this;
590 }
591
592 /**
593 * Returns current scanner state
594 *
595 * @param bool $scanPosition By default this method returns the scanner
596 * consumed position, if this parameter is true
597 * the scanned position will be returned
598 *
599 * @return Position
600 */
601 public function getPosition($scanPosition = false)
602 {
603 if ($scanPosition) {
604 return new Position($this->line, $this->column, $this->index);
605 } else {
606 return $this->position;
607 }
608 }
609
610 /**
611 * Sets the current scan position at the given one
612 *
613 * @param Position $position Position at which the scan position will be set
614 *
615 * @return $this
616 */
617 public function setScanPosition(Position $position)
618 {
619 $this->line = $position->getLine();
620 $this->column = $position->getColumn();
621 $this->index = $position->getIndex();
622 return $this;
623 }
624
625 /**
626 * Return the character at the given index in the source code or null if the
627 * end is reached.
628 *
629 * @param int $index Index, if not given it will use the current index
630 *
631 * @return string|null
632 */
633 public function charAt($index = null)
634 {
635 if ($index === null) {
636 $index = $this->index;
637 }
638 return $index < $this->length ? $this->source[$index] : null;
639 }
640
641 /**
642 * Throws a syntax error
643 *
644 * @param string $message Error message
645 *
646 * @return void
647 *
648 * @throws Exception
649 */
650 protected function error($message = null)
651 {
652 if (!$message) {
653 $message = "Unexpected " . $this->charAt();
654 }
655 throw new Exception($message, $this->getPosition(true));
656 }
657
658 /**
659 * Consumes the current token
660 *
661 * @return $this
662 */
663 public function consumeToken()
664 {
665 //Move the scanner position to the end of the current position
666 $this->position = $this->currentToken->location->end;
667
668 //Before consume the token, consume comments associated with it
669 if ($this->comments) {
670 $this->consumeCommentsForCurrentToken();
671 }
672
673 //Register the token if required
674 if ($this->registerTokens) {
675 $this->tokens[] = $this->currentToken;
676 }
677
678 //Emit the TokenConsumed event for the consumed token
679 $this->eventsEmitter && $this->eventsEmitter->fire(
680 "TokenConsumed", array($this->currentToken)
681 );
682
683 $this->currentToken = $this->nextToken;
684 $this->nextToken = null;
685 return $this;
686 }
687
688 /**
689 * Checks if the given string is matched, if so it consumes the token
690 *
691 * @param string $expected String to check
692 *
693 * @return Token|null
694 */
695 public function consume($expected)
696 {
697 //Do not call getToken if there's already a pending token for
698 //performance reasons
699 $token = $this->currentToken ?: $this->getToken();
700 if ($token && $token->value === $expected) {
701 $this->consumeToken();
702 return $token;
703 }
704 return null;
705 }
706
707 /**
708 * Checks if one of the given strings is matched, if so it consumes the
709 * token
710 *
711 * @param array $expected Strings to check
712 *
713 * @return Token|null
714 */
715 public function consumeOneOf($expected)
716 {
717 //Do not call getToken if there's already a pending token for
718 //performance reasons
719 $token = $this->currentToken ?: $this->getToken();
720 if ($token && in_array($token->value, $expected)) {
721 $this->consumeToken();
722 return $token;
723 }
724 return null;
725 }
726
727 /**
728 * Checks that there are not line terminators following the current scan
729 * position before next token
730 *
731 * @param bool $nextToken By default it checks the current token position
732 * relative to the current position, if this
733 * parameter is true the check will be done relative
734 * to the next token
735 *
736 * @return bool
737 */
738 public function noLineTerminators($nextToken = false)
739 {
740 if ($nextToken) {
741 $nextToken = $this->getNextToken();
742 $refLine = !$nextToken ? null :
743 $nextToken->location->end->getLine();
744 } else {
745 $refLine = $this->getPosition()->getLine();
746 }
747 $token = $this->currentToken ?: $this->getToken();
748 return $token &&
749 $token->location->start->getLine() === $refLine;
750 }
751
752 /**
753 * Checks if one of the given strings follows the current scan position
754 *
755 * @param string|array $expected String or array of strings to check
756 * @param bool $nextToken This parameter must be true if the first
757 * parameter is an array so that it will
758 * check also next tokens
759 *
760 * @return bool
761 */
762 public function isBefore($expected, $nextToken = false)
763 {
764 $token = $this->currentToken ?: $this->getToken();
765 if (!$token) {
766 return false;
767 } elseif (in_array($token->value, $expected)) {
768 return true;
769 } elseif (!$nextToken) {
770 return false;
771 }
772 if (!$this->getNextToken()) {
773 return false;
774 }
775 foreach ($expected as $val) {
776 if (!is_array($val) || $val[0] !== $token->value) {
777 continue;
778 }
779 //If the second value in the array is true check that the current
780 //token is not followed by line terminators, otherwise compare its
781 //value to the next token
782 if (($val[1] === true && $this->noLineTerminators(true)) ||
783 ($val[1] !== true && $val[1] === $this->nextToken->value)) {
784 return true;
785 }
786 }
787 return false;
788 }
789
790 /**
791 * Returns the next token
792 *
793 * @return Token|null
794 */
795 public function getNextToken()
796 {
797 if (!$this->nextToken) {
798 $token = $this->currentToken ?: $this->getToken();
799 $this->currentToken = null;
800 $this->nextToken = $this->getToken(true);
801 $this->currentToken = $token;
802 }
803 return $this->nextToken;
804 }
805
806 /**
807 * Returns the current token
808 *
809 * @param bool $skipEOFChecks True to skip end of file checks
810 * even if the end is reached
811 *
812 * @return Token|null
813 */
814 public function getToken($skipEOFChecks = false)
815 {
816 //The current token is returned until consumed
817 if ($this->currentToken) {
818 return $this->currentToken;
819 }
820
821 $comments = $this->skipWhitespacesAndComments();
822
823 //Emit the TokenCreated event for all the comments found
824 if ($comments) {
825 foreach ($comments as $comment) {
826 $this->eventsEmitter && $this->eventsEmitter->fire(
827 "TokenCreated", array($comment)
828 );
829 }
830 }
831
832 //When the end of the source is reached
833 if ($this->index >= $this->length) {
834 //Check if there are open brackets
835 if (!$skipEOFChecks) {
836 foreach ($this->openBrackets as $bracket => $num) {
837 if ($num) {
838 $this->error("Unclosed $bracket");
839 }
840 }
841
842 //Check if there are open templates
843 if (count($this->openTemplates)) {
844 $this->error("Unterminated template");
845 }
846 }
847
848 //Register comments and consume them
849 if ($this->comments && $comments) {
850 $this->commentsForCurrentToken($comments);
851 }
852
853 //Emit the EndReached event when at the end of the source
854 $this->eventsEmitter && $this->eventsEmitter->fire(
855 "EndReached"
856 );
857
858 return null;
859 }
860
861 $startPosition = $this->getPosition(true);
862 $origException = null;
863 try {
864
865 //Try to match a token
866 if (
867 ($this->jsx && ($token = $this->scanJSXIdentifier())) ||
868 ($token = $this->scanTemplate()) ||
869 ($token = $this->scanNumber()) ||
870 ($this->jsx && ($token = $this->scanJSXPunctuator())) ||
871 ($token = $this->scanPunctuator()) ||
872 ($token = $this->scanKeywordOrIdentifier()) ||
873 ($this->jsx && ($token = $this->scanJSXString())) ||
874 ($token = $this->scanString())
875 ) {
876 //Set the token start and end positions
877 $token->location->start = $startPosition;
878 $token->location->end = $this->getPosition(true);
879 $this->currentToken = $token;
880
881 //Register comments if required
882 if ($this->comments && $comments) {
883 $this->commentsForCurrentToken($comments);
884 }
885
886 //Emit the TokenCreated event for the token just created
887 $this->eventsEmitter && $this->eventsEmitter->fire(
888 "TokenCreated", array($this->currentToken)
889 );
890
891 return $this->currentToken;
892 }
893
894 } catch (Exception $e) {
895 $origException = $e;
896 }
897
898 //If last token was "/" do not throw an error if the token has not be
899 //recognized since it can be the first character in a regexp and it will
900 //be consumed when the current token will be reconsumed as a regexp
901 if ($this->isAfterSlash($startPosition)) {
902 $this->setScanPosition($startPosition);
903 return null;
904 }
905
906 //No valid token found. If there was a scan error, throw the same
907 //exception again, otherwise throw a new error
908 if ($origException) {
909 throw $origException;
910 }
911 $this->error();
912 }
913
914 /**
915 * Executes the operations to handle the end of the source scanning
916 *
917 * @return $this
918 */
919 public function consumeEnd()
920 {
921 //Consume final comments
922 if ($this->comments) {
923 $this->consumeCommentsForCurrentToken();
924 }
925
926 //Emit the EndReached event when at the end of the source
927 $this->eventsEmitter && $this->eventsEmitter->fire(
928 "EndReached"
929 );
930
931 return $this;
932 }
933
934 /**
935 * Gets or sets comments for the current token. If the parameter is an
936 * array it associates the given comments array to the current node,
937 * otherwise comments for the current token are returned
938 *
939 * @param array $comments Comments array
940 *
941 * @return array
942 */
943 protected function commentsForCurrentToken($comments = null)
944 {
945 $id = $this->currentToken ? spl_object_hash($this->currentToken) : "";
946 if ($comments !== null) {
947 $this->commentsMap[$id] = $comments;
948 } elseif (isset($this->commentsMap[$id])) {
949 $comments = $this->commentsMap[$id];
950 unset($this->commentsMap[$id]);
951 }
952 return $comments;
953 }
954
955 /**
956 * Consumes comment tokens associated with the current token
957 *
958 * @return $this
959 */
960 protected function consumeCommentsForCurrentToken()
961 {
962 $comments = $this->commentsForCurrentToken();
963 if ($comments && ($this->registerTokens || $this->eventsEmitter)) {
964 foreach ($comments as $comment) {
965 //Register the token if required
966 if ($this->registerTokens) {
967 $this->tokens[] = $comment;
968 }
969 //Emit the TokenConsumed event for the comment
970 $this->eventsEmitter && $this->eventsEmitter->fire(
971 "TokenConsumed", array($comment)
972 );
973 }
974 }
975 return $this;
976 }
977
978 /**
979 * Checks if the given position follows a slash.
980 *
981 * @param Position $position Position to check
982 *
983 * @return bool
984 */
985 protected function isAfterSlash($position)
986 {
987 //Start from the previous index and loop until the begin of the file is reached
988 $idx = $position->getIndex() - 1;
989 while ($idx >= 0) {
990 //Get the char at the index to check
991 $char = $this->charAt($idx);
992 //If the char is actually a slash check that it's not a multiline comment closing slash
993 if ($char === "/") {
994 return $idx === 0 || $this->charAt($idx - 1) !== "*";
995 }
996 //Skip whitespaces but not line terminators since regexps can't be multiline
997 elseif (in_array($char, $this->whitespaces) && !in_array($char, $this->lineTerminators)) {
998 $idx--;
999 }
1000 //If "/=" is found, return true, this is the only operator that needs a special treatment
1001 //since it can be also the start of a regex
1002 elseif ($char === "=" && $this->charAt($idx - 1) === "/") {
1003 return true;
1004 }
1005 //Different character, return
1006 else {
1007 break;
1008 }
1009 }
1010 return false;
1011 }
1012
1013 /**
1014 * Tries to reconsume the current token as a regexp if possible
1015 *
1016 * @return Token|null
1017 */
1018 public function reconsumeCurrentTokenAsRegexp()
1019 {
1020 $token = $this->currentToken ?: $this->getToken();
1021 $value = $token ? $token->value : null;
1022
1023 //Check if the token starts with "/"
1024 if (!$value || $value[0] !== "/") {
1025 return null;
1026 }
1027
1028 //Reset the scanner position to the token's start position
1029 $startPosition = $token->location->start;
1030 $this->setScanPosition($startPosition);
1031
1032 $buffer = "/";
1033 $this->index++;
1034 $this->column++;
1035 $inClass = false;
1036 while (true) {
1037 //In a characters class the delimiter "/" is allowed without escape,
1038 //so the characters class must be closed before closing the regexp
1039 $stops = $inClass ? array("]") : array("/", "[");
1040 $tempBuffer = $this->consumeUntil($stops);
1041 if ($tempBuffer === null) {
1042 if ($inClass) {
1043 $this->error(
1044 "Unterminated character class in regexp"
1045 );
1046 } else {
1047 $this->error("Unterminated regexp");
1048 }
1049 }
1050 $buffer .= $tempBuffer[0];
1051 if ($tempBuffer[1] === "/") {
1052 break;
1053 } else {
1054 $inClass = $tempBuffer[1] === "[";
1055 }
1056 }
1057
1058 //Flags
1059 while (($char = $this->charAt()) !== null) {
1060 $lower = strtolower($char);
1061 if ($lower >= "a" && $lower <= "z") {
1062 $buffer .= $char;
1063 $this->index++;
1064 $this->column++;
1065 } else {
1066 break;
1067 }
1068 }
1069
1070 //If next token has already been parsed and it's a bracket exclude it
1071 //from the count of open brackets
1072 if ($this->nextToken) {
1073 $nextVal = $this->nextToken->value;
1074 if (isset($this->brackets[$nextVal]) &&
1075 isset($this->openBrackets[$nextVal])
1076 ) {
1077 if ($this->brackets[$nextVal]) {
1078 $this->openBrackets[$nextVal]++;
1079 } else {
1080 $this->openBrackets[$nextVal]--;
1081 }
1082 }
1083 $this->nextToken = null;
1084 }
1085
1086 //If comments handling is enabled, get the comments associated with the
1087 //current token
1088 $comments = $this->comments ? $this->commentsForCurrentToken() : null;
1089
1090 //Replace the current token with a regexp token
1091 $token = new Token(Token::TYPE_REGULAR_EXPRESSION, $buffer);
1092 $token->location->start = $startPosition;
1093 $token->location->end = $this->getPosition(true);
1094 $this->currentToken = $token;
1095
1096 if ($comments) {
1097 //Attach the comments to the new current token
1098 $this->commentsForCurrentToken($comments);
1099 }
1100
1101 return $this->currentToken;
1102 }
1103
1104 /**
1105 * Skips whitespaces and comments from the current scan position. If
1106 * comments handling is enabled, the array of parsed comments
1107 *
1108 * @return array
1109 */
1110 protected function skipWhitespacesAndComments()
1111 {
1112 $comments = [];
1113 $content = "";
1114 $secStartIdx = $this->index;
1115 while (($char = $this->charAt()) !== null) {
1116 //Whitespace
1117 if (in_array($char, $this->whitespaces)) {
1118
1119 $content .= $char;
1120 $this->index++;
1121
1122 } elseif ($char === "/" || $char === "#") {
1123
1124 $nextChar = $this->charAt($this->index + 1);
1125
1126 if ($char === "#") {
1127 //Hashbang comment. This will be parsed only if hashbang comments are enabled
1128 //and if it appears at the beginning of the code
1129 $valid = $nextChar === "!" && $this->features->hashbangComments && !$this->index;
1130 } else {
1131 $valid = $nextChar === "/" || $nextChar === "*";
1132 }
1133
1134 //Comment
1135 if ($valid) {
1136
1137 //If comments must be handled, empty the current content too
1138 //and get the comment start position
1139 if ($this->comments) {
1140 if ($content !== "") {
1141 $this->adjustColumnAndLine($content);
1142 $content = "";
1143 }
1144 $start = $this->getPosition(true);
1145 }
1146
1147 $inline = $nextChar !== "*";
1148 $this->index += 2;
1149 $content .= $char . $nextChar;
1150
1151 while (true) {
1152 $char = $this->charAt();
1153
1154 if ($char === null) {
1155 if (!$inline) {
1156 //If the end of the source has been reached and
1157 //a multiline comment is still open, it's an
1158 //error
1159 $this->error("Unterminated comment");
1160 }
1161 $isEnd = true;
1162 } else {
1163 $content .= $char;
1164 $this->index++;
1165 $isEnd = $inline ?
1166 //Inline comment
1167 in_array($char, $this->lineTerminators) :
1168 //Multiline comment
1169 $char === "*" && $this->charAt() === "/";
1170 }
1171
1172 if ($isEnd) {
1173 if (!$inline) {
1174 $content .= "/";
1175 $this->index++;
1176 }
1177 if ($this->comments) {
1178 //For inline comments the closing line
1179 //terminator must be excluded from comment text
1180 if ($inline && $char !== null) {
1181 $this->index--;
1182 $content = substr($content, 0, -strlen($char));
1183 }
1184 $this->adjustColumnAndLine($content);
1185 $token = new Token(Token::TYPE_COMMENT, $content);
1186 $token->location->start = $start;
1187 $token->location->end = $this->getPosition(true);
1188 $comments[] = $token;
1189 //For inline comments the new content contains
1190 //the closing line terminator since the char has
1191 //already been processed
1192 $content = "";
1193 if ($inline && $char !== null) {
1194 $content = $char;
1195 $this->index++;
1196 }
1197 }
1198 break;
1199 }
1200 }
1201
1202 } else {
1203 break;
1204 }
1205
1206 } elseif (!$this->isModule && $char === "<" &&
1207 $this->charAt($this->index + 1) === "!" &&
1208 $this->charAt($this->index + 2) === "-" &&
1209 $this->charAt($this->index + 3) === "-"
1210 ) {
1211
1212 //If comments must be handled, empty the current content too
1213 //and get the comment start position
1214 if ($this->comments) {
1215 if ($content !== "") {
1216 $this->adjustColumnAndLine($content);
1217 $content = "";
1218 }
1219 $start = $this->getPosition(true);
1220 }
1221
1222 //Open html comment
1223 $this->index += 4;
1224 $content .= "<!--";
1225 while (true) {
1226 $char = $this->charAt();
1227 if ($char === null) {
1228 $isEnd = true;
1229 } else {
1230 $content .= $char;
1231 $this->index++;
1232 $isEnd = in_array($char, $this->lineTerminators);
1233 }
1234 if ($isEnd) {
1235 if ($this->comments) {
1236 //Remove the closing line terminator from the
1237 //comment text
1238 if ($char !== null) {
1239 $this->index--;
1240 $content = substr($content, 0, -strlen($char));
1241 }
1242 $this->adjustColumnAndLine($content);
1243 $token = new Token(Token::TYPE_COMMENT, $content);
1244 $token->location->start = $start;
1245 $token->location->end = $this->getPosition(true);
1246 $comments[] = $token;
1247 $content = "";
1248 if ($char !== null) {
1249 $content = $char;
1250 $this->index++;
1251 }
1252 }
1253 break;
1254 }
1255 }
1256
1257 } elseif (!$this->isModule && $char === "-" &&
1258 $this->charAt($this->index + 1) === "-" &&
1259 $this->charAt($this->index + 2) === ">"
1260 ) {
1261
1262 //Close html comment
1263 //Check if it is on it's own line
1264 $allow = false;
1265 if (!$secStartIdx) {
1266 $allow = true;
1267 } else {
1268 for ($index = $this->index - 1; $index >= $secStartIdx; $index--) {
1269 if (in_array($this->charAt($index), $this->lineTerminators)) {
1270 $allow = true;
1271 break;
1272 }
1273 }
1274 }
1275 if ($allow) {
1276
1277 //If comments must be handled, empty the current content too
1278 //and get the comment start position
1279 if ($this->comments) {
1280 if ($content !== "") {
1281 $this->adjustColumnAndLine($content);
1282 $content = "";
1283 }
1284 $start = $this->getPosition(true);
1285 }
1286
1287 $this->index += 3;
1288 $content .= "-->";
1289 while (true) {
1290 $char = $this->charAt();
1291
1292 if ($char === null) {
1293 $isEnd = true;
1294 } else {
1295 $content .= $char;
1296 $this->index++;
1297 $isEnd = in_array($char, $this->lineTerminators);
1298 }
1299
1300 if ($isEnd) {
1301 if ($this->comments) {
1302 //Remove the closing line terminator from the
1303 //comment text
1304 if ($char !== null) {
1305 $this->index--;
1306 $content = substr($content, 0, -strlen($char));
1307 }
1308 $this->adjustColumnAndLine($content);
1309 $token = new Token(Token::TYPE_COMMENT, $content);
1310 $token->location->start = $start;
1311 $token->location->end = $this->getPosition(true);
1312 $comments[] = $token;
1313 $content = "";
1314 if ($char !== null) {
1315 $content = $char;
1316 $this->index++;
1317 }
1318 }
1319 break;
1320 }
1321 }
1322 } else {
1323 break;
1324 }
1325
1326 } else {
1327 break;
1328 }
1329 }
1330
1331 if ($content !== "") {
1332 $this->adjustColumnAndLine($content);
1333 }
1334
1335 return $comments;
1336 }
1337
1338 /**
1339 * String scanning method
1340 *
1341 * @param bool $handleEscape True to handle escaping
1342 *
1343 * @return Token|null
1344 */
1345 protected function scanString($handleEscape = true)
1346 {
1347 $char = $this->charAt();
1348 if ($char === "'" || $char === '"') {
1349 $this->index++;
1350 $this->column++;
1351 //Add the quote to the LSM and then remove it after consuming
1352 $this->stringsStopsLSM->add($char);
1353 $buffer = $this->consumeUntil($this->stringsStopsLSM, $handleEscape);
1354 $this->stringsStopsLSM->remove($char);
1355 if ($buffer === null || $buffer[1] !== $char) {
1356 $this->error("Unterminated string");
1357 }
1358 return new Token(Token::TYPE_STRING_LITERAL, $char . $buffer[0]);
1359 }
1360
1361 return null;
1362 }
1363
1364 /**
1365 * Template scanning method
1366 *
1367 * @return Token|null
1368 */
1369 protected function scanTemplate()
1370 {
1371 $char = $this->charAt();
1372
1373 //Get the current number of open curly brackets
1374 $openCurly = isset($this->openBrackets["{"]) ?
1375 $this->openBrackets["{"] :
1376 0;
1377
1378 //If the character is a curly bracket check and the number of open
1379 //curly brackets matches the last number in the open templates stack,
1380 //then the bracket closes the open template expression
1381 $endExpression = false;
1382 if ($char === "}") {
1383 $len = count($this->openTemplates);
1384 if ($len && $this->openTemplates[$len - 1] === $openCurly) {
1385 $endExpression = true;
1386 array_pop($this->openTemplates);
1387 }
1388 }
1389
1390 if ($char === "`" || $endExpression) {
1391 $this->index++;
1392 $this->column++;
1393 $buffer = $char;
1394 while (true) {
1395 $tempBuffer = $this->consumeUntil(array("`", "$"));
1396 if (!$tempBuffer) {
1397 $this->error("Unterminated template");
1398 }
1399 $buffer .= $tempBuffer[0];
1400 if ($tempBuffer[1] !== "$" || $this->charAt() === "{") {
1401 //If "${" is found it's a new template expression, register
1402 //the current number of open curly brackets in the open
1403 //templates stack
1404 if ($tempBuffer[1] === "$") {
1405 $this->index++;
1406 $this->column++;
1407 $buffer .= "{";
1408 $this->openTemplates[] = $openCurly;
1409 }
1410 break;
1411 }
1412 }
1413 return new Token(Token::TYPE_TEMPLATE, $buffer);
1414 }
1415
1416 return null;
1417 }
1418
1419 /**
1420 * Number scanning method
1421 *
1422 * @return Token|null
1423 */
1424 protected function scanNumber()
1425 {
1426 //Numbers can start with a decimal number or with a dot (.5)
1427 $char = $this->charAt();
1428 if (!(($char >= "0" && $char <= "9") || $char === ".")) {
1429 return null;
1430 }
1431
1432 $buffer = "";
1433 $allowedDecimals = true;
1434
1435 //Parse the integer part
1436 if ($char !== ".") {
1437
1438 //Consume all decimal numbers
1439 $buffer = $this->consumeNumbers();
1440 $char = $this->charAt();
1441
1442 if ($this->features->bigInt && $char === "n") {
1443 $this->index++;
1444 $this->column++;
1445 return new Token(Token::TYPE_BIGINT_LITERAL, $buffer . $char);
1446 }
1447
1448 $lower = $char !== null ? strtolower($char) : null;
1449
1450 //Handle hexadecimal (0x), octal (0o) and binary (0b) forms
1451 if ($buffer === "0" && $lower !== null &&
1452 isset($this->{$lower . "numbers"})
1453 ) {
1454
1455 $this->index++;
1456 $this->column++;
1457 $tempBuffer = $this->consumeNumbers($lower);
1458 if ($tempBuffer === null) {
1459 $this->error("Missing numbers after 0$char");
1460 }
1461 $buffer .= $char . $tempBuffer;
1462
1463 //Check that there are not numbers left
1464 if ($this->consumeNumbers() !== null) {
1465 $this->error();
1466 }
1467
1468 if ($this->features->bigInt && $this->charAt() === "n") {
1469 $this->index++;
1470 $this->column++;
1471 return new Token(Token::TYPE_BIGINT_LITERAL, $buffer . $char);
1472 }
1473
1474 return new Token(Token::TYPE_NUMERIC_LITERAL, $buffer);
1475 }
1476
1477 //Consume exponent part if present
1478 if ($tempBuffer = $this->consumeExponentPart()) {
1479 $buffer .= $tempBuffer;
1480 $allowedDecimals = false;
1481 }
1482 }
1483
1484 //Parse the decimal part
1485 if ($allowedDecimals && $this->charAt() === ".") {
1486
1487 //Consume the dot
1488 $this->index++;
1489 $this->column++;
1490 $buffer .= ".";
1491
1492 //Consume all decimal numbers
1493 $tempBuffer = $this->consumeNumbers();
1494 $buffer .= $tempBuffer;
1495
1496 //If the buffer contains only the dot it should be parsed as
1497 //punctuator
1498 if ($buffer === ".") {
1499 $this->index--;
1500 $this->column--;
1501 return null;
1502 }
1503
1504 //Consume exponent part if present
1505 if (($tempBuffer = $this->consumeExponentPart()) !== null) {
1506 $buffer .= $tempBuffer;
1507 }
1508 }
1509
1510 return new Token(Token::TYPE_NUMERIC_LITERAL, $buffer);
1511 }
1512
1513 /**
1514 * Consumes the maximum number of digits
1515 *
1516 * @param string $type Digits type (decimal, hexadecimal, etc...)
1517 * @param int $max Maximum number of digits to match
1518 *
1519 * @return string|null
1520 */
1521 protected function consumeNumbers($type = "", $max = null)
1522 {
1523 $buffer = "";
1524 $char = $this->charAt();
1525 $count = 0;
1526 $extra = $this->features->numericLiteralSeparator ? "_" : "";
1527 while (
1528 in_array($char, $this->{$type . "numbers"}) ||
1529 ($count && $char === $extra)
1530 ) {
1531 $buffer .= $char;
1532 $this->index++;
1533 $this->column++;
1534 $count ++;
1535 if ($count === $max) {
1536 break;
1537 }
1538 $char = $this->charAt();
1539 }
1540 if ($count && substr($buffer, -1) === "_") {
1541 $this->error(
1542 "Numeric separators are not allowed at the end of a number"
1543 );
1544 }
1545 return $count ? $buffer : null;
1546 }
1547
1548 /**
1549 * Consumes the exponent part of a number
1550 *
1551 * @return string|null
1552 */
1553 protected function consumeExponentPart()
1554 {
1555 $buffer = "";
1556 $char = $this->charAt();
1557 if ($char !== null && strtolower($char) === "e") {
1558 $this->index++;
1559 $this->column++;
1560 $buffer .= $char;
1561 $char = $this->charAt();
1562 if ($char === "+" || $char === "-") {
1563 $this->index++;
1564 $this->column++;
1565 $buffer .= $char;
1566 }
1567 $tempBuffer = $this->consumeNumbers();
1568 if ($tempBuffer === null) {
1569 $this->error("Missing exponent");
1570 }
1571 $buffer .= $tempBuffer;
1572 }
1573 return $buffer;
1574 }
1575
1576 /**
1577 * Punctuator scanning method
1578 *
1579 * @return Token|null
1580 */
1581 protected function scanPunctuator()
1582 {
1583 $token = null;
1584 $char = $this->charAt();
1585
1586 //Check if the next char is a bracket
1587 if (isset($this->brackets[$char])) {
1588 //Check if it is a closing bracket
1589 if ($this->brackets[$char]) {
1590 $openBracket = $this->brackets[$char];
1591 //Check if there is a corresponding open bracket
1592 if (!isset($this->openBrackets[$openBracket]) ||
1593 !$this->openBrackets[$openBracket]
1594 ) {
1595 if (!$this->isAfterSlash($this->getPosition(true))) {
1596 $this->error();
1597 }
1598 } else {
1599 $this->openBrackets[$openBracket]--;
1600 }
1601 } else {
1602 if (!isset($this->openBrackets[$char])) {
1603 $this->openBrackets[$char] = 0;
1604 }
1605 $this->openBrackets[$char]++;
1606 }
1607 $this->index++;
1608 $this->column++;
1609 $token = new Token(Token::TYPE_PUNCTUATOR, $char);
1610 } elseif (
1611 //Try to match the longest punctuator
1612 $match = $this->punctuatorsLSM->match($this, $this->index, $char)
1613 ) {
1614 //Optional chaining punctuator cannot appear before a number, in this
1615 //case only the question mark must be consumed
1616 if ($match[1] === "?." &&
1617 ($nextChar = $this->charAt($this->index + $match[0])) !== null &&
1618 $nextChar >= "0" && $nextChar <= "9"
1619 ) {
1620 $match = array(1, "?");
1621 }
1622 $this->index += $match[0];
1623 $this->column += $match[0];
1624 $token = new Token(Token::TYPE_PUNCTUATOR, $match[1]);
1625 }
1626 return $token;
1627 }
1628
1629 /**
1630 * Keywords and identifiers scanning method
1631 *
1632 * @return Token|null
1633 */
1634 protected function scanKeywordOrIdentifier()
1635 {
1636 //Check private identifier start character
1637 if ($private = $this->features->privateMethodsAndFields && $this->charAt() === "#") {
1638 $this->index++;
1639 $this->column++;
1640 }
1641
1642 //Consume the maximum number of characters that are unicode escape
1643 //sequences or valid identifier starts (only the first character) or
1644 //parts
1645 $buffer = "";
1646 $start = true;
1647 while (($char = $this->charAt()) !== null) {
1648 if (
1649 ($char >= "a" && $char <= "z") ||
1650 ($char >= "A" && $char <= "Z") ||
1651 $char === "_" || $char === "$" ||
1652 (!$start && $char >= "0" && $char <= "9") ||
1653 $this->isIdentifierChar($char, $start)
1654 ) {
1655 $buffer .= $char;
1656 $this->index++;
1657 $this->column++;
1658 } elseif ($char === "\\" && ($seq = $this->consumeUnicodeEscapeSequence())) {
1659 //Verify that it's a valid character
1660 if (!$this->isIdentifierChar($seq[1], $start)) {
1661 break;
1662 }
1663 $buffer .= $seq[0];
1664 } else {
1665 break;
1666 }
1667 $start = false;
1668 }
1669
1670 //Identify token type
1671 if ($buffer === "") {
1672 //Unconsume the hash if nothing was found after that
1673 if ($private) {
1674 $this->index--;
1675 $this->column--;
1676 }
1677 return null;
1678 } elseif ($private) {
1679 $type = Token::TYPE_PRIVATE_IDENTIFIER;
1680 $buffer = "#" . $buffer;
1681 } elseif ($buffer === "null") {
1682 $type = Token::TYPE_NULL_LITERAL;
1683 } elseif ($buffer === "true" || $buffer === "false") {
1684 $type = Token::TYPE_BOOLEAN_LITERAL;
1685 } elseif (in_array($buffer, $this->keywords) ||
1686 in_array($buffer, $this->strictModeKeywords)
1687 ) {
1688 $type = Token::TYPE_KEYWORD;
1689 } else {
1690 $type = Token::TYPE_IDENTIFIER;
1691 }
1692
1693 return new Token($type, $buffer);
1694 }
1695
1696 /**
1697 * Consumes an unicode escape sequence
1698 *
1699 * @return array|null
1700 */
1701 protected function consumeUnicodeEscapeSequence()
1702 {
1703 if ($this->charAt() !== "\\" ||
1704 $this->charAt($this->index + 1) !== "u"
1705 ) {
1706 return null;
1707 }
1708
1709 $startIndex = $this->index;
1710 $startColumn = $this->column;
1711 $this->index += 2;
1712 $this->column += 2;
1713 $brackets = false;
1714 if ($this->charAt() === "{") {
1715 //\u{FFF}
1716 $brackets = true;
1717 $this->index++;
1718 $this->column++;
1719 $code = $this->consumeNumbers("x");
1720 if ($code && $this->charAt() !== "}") {
1721 $code = null;
1722 } else {
1723 $this->index++;
1724 $this->column++;
1725 }
1726 } else {
1727 //\uFFFF
1728 $code = $this->consumeNumbers("x", 4);
1729 if ($code && strlen($code) !== 4) {
1730 $code = null;
1731 }
1732 }
1733
1734 //Unconsume everything if the format is invalid
1735 if ($code === null) {
1736 $this->index = $startIndex;
1737 $this->column = $startColumn;
1738 return null;
1739 }
1740
1741 //Return an array where the first element is the matched sequence
1742 //and the second one is the decoded character
1743 return array(
1744 $brackets ? "\\u{" . $code . "}" : "\\u" . $code,
1745 Utils::unicodeToUtf8(hexdec($code))
1746 );
1747 }
1748
1749 /**
1750 * Checks if the given character is valid for an identifier
1751 *
1752 * @param string $char Character to check
1753 * @param bool $start If true it will check that the character is
1754 * valid to start an identifier
1755 *
1756 * @return bool
1757 */
1758 protected function isIdentifierChar($char, $start = true)
1759 {
1760 return ($char >= "a" && $char <= "z") ||
1761 ($char >= "A" && $char <= "Z") ||
1762 $char === "_" || $char === "$" ||
1763 (!$start && $char >= "0" && $char <= "9") ||
1764 preg_match($start ? $this->idStartRegex : $this->idPartRegex, $char);
1765 }
1766
1767 /**
1768 * Increases columns and lines count according to the given string
1769 *
1770 * @param string $buffer String to analyze
1771 *
1772 * @return void
1773 */
1774 protected function adjustColumnAndLine($buffer)
1775 {
1776 $lines = preg_split($this->linesSplitter, $buffer);
1777 $linesCount = count($lines) - 1;
1778 $this->line += $linesCount;
1779 $columns = mb_strlen($lines[$linesCount], "UTF-8");
1780 if ($linesCount) {
1781 $this->column = $columns;
1782 } else {
1783 $this->column += $columns;
1784 }
1785 }
1786
1787 /**
1788 * Consumes characters until one of the given characters is found
1789 *
1790 * @param array|LSM $stops Characters to search
1791 * @param bool $handleEscape True to handle escaping
1792 * @param bool $collectStop True to include the stop character
1793 *
1794 * @return array|null
1795 */
1796 protected function consumeUntil(
1797 $stops, $handleEscape = true, $collectStop = true
1798 ) {
1799 $isLSM = $stops instanceof LSM;
1800 $buffer = "";
1801 $escaped = false;
1802 while (($char = $this->charAt()) !== null) {
1803 $incrIndex = 1;
1804 $isStop = false;
1805 if ($isLSM) {
1806 $m = $stops->match($this, $this->index, $char);
1807 if ($m) {
1808 $isStop = true;
1809 $incrIndex = $m[0];
1810 $char = $m[1];
1811 }
1812 } else {
1813 $isStop = in_array($char, $stops);
1814 }
1815 $validStop = $isStop && !$escaped;
1816 if (!$validStop || $collectStop) {
1817 $this->index += $incrIndex;
1818 $buffer .= $char;
1819 }
1820 if ($validStop) {
1821 if (!$collectStop && $buffer === "") {
1822 return null;
1823 }
1824 $this->adjustColumnAndLine($buffer);
1825 return array($buffer, $char);
1826 } elseif (!$escaped && $char === "\\" && $handleEscape) {
1827 $escaped = true;
1828 } else {
1829 $escaped = false;
1830 }
1831 }
1832 return null;
1833 }
1834 }