Debian Codegraph @

vendor/mck89/peast/lib/Peast/Syntax/Parser.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 * Parser class
14 *
15 * @author Marco Marchiò <[email protected]>
16 */
17 class Parser extends ParserAbstract
18 {
19 use JSX\Parser;
20
21 //Identifier parsing mode constants
22 /**
23 * Everything is allowed as identifier, including keywords, null and booleans
24 */
25 const ID_ALLOW_ALL = 1;
26
27 /**
28 * Keywords, null and booleans are not allowed in any situation
29 */
30 const ID_ALLOW_NOTHING = 2;
31
32 /**
33 * Keywords, null and booleans are not allowed in any situation, future
34 * reserved words are allowed if not in strict mode. Keywords that depend on
35 * parser context are evaluated only if the parser context allows them.
36 */
37 const ID_MIXED = 3;
38
39 /**
40 * Binding identifier parsing rule
41 *
42 * @var int
43 */
44 protected static $bindingIdentifier = self::ID_MIXED;
45
46 /**
47 * Labelled identifier parsing rule
48 *
49 * @var int
50 */
51 protected static $labelledIdentifier = self::ID_MIXED;
52
53 /**
54 * Identifier reference parsing rule
55 *
56 * @var int
57 */
58 protected static $identifierReference = self::ID_MIXED;
59
60 /**
61 * Identifier name parsing rule
62 *
63 * @var int
64 */
65 protected static $identifierName = self::ID_ALLOW_ALL;
66
67 /**
68 * Imported binding parsing rule
69 *
70 * @var int
71 */
72 protected static $importedBinding = self::ID_ALLOW_NOTHING;
73
74 /**
75 * Assignment operators
76 *
77 * @var array
78 */
79 protected $assignmentOperators = array(
80 "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=",
81 "|=", "**=", "&&=", "||=", "??="
82 );
83
84 /**
85 * Logical and binary operators
86 *
87 * @var array
88 */
89 protected $logicalBinaryOperators = array(
90 "??" => 0,
91 "||" => 0,
92 "&&" => 1,
93 "|" => 2,
94 "^" => 3,
95 "&" => 4,
96 "===" => 5, "!==" => 5, "==" => 5, "!=" => 5,
97 "<=" => 6, ">=" => 6, "<" => 6, ">" => 6,
98 "instanceof" => 6, "in" => 6,
99 ">>>" => 7, "<<" => 7, ">>" => 7,
100 "+" => 8, "-" => 8,
101 "*" => 9, "/" => 9, "%" => 9,
102 "**" => 10
103 );
104
105 /**
106 * Unary operators
107 *
108 * @var array
109 */
110 protected $unaryOperators = array(
111 "delete", "void", "typeof", "++", "--", "+", "-", "~", "!"
112 );
113
114 /**
115 * Postfix operators
116 *
117 * @var array
118 */
119 protected $postfixOperators = array("--", "++");
120
121 /**
122 * Array of keywords that depends on a context property
123 *
124 * @var array
125 */
126 protected $contextKeywords = array(
127 "yield" => "allowYield",
128 "await" => "allowAwait"
129 );
130
131 /**
132 * Initializes parser context
133 *
134 * @return void
135 */
136 protected function initContext()
137 {
138 $context = array(
139 "allowReturn" => false,
140 "allowIn" => false,
141 "allowYield" => false,
142 "allowAwait" => false,
143 "inSwitch" => false,
144 "inIteration" => false
145 );
146 //If async/await is not enabled remove the
147 //relative context properties
148 if (!$this->features->asyncAwait) {
149 unset($context["allowAwait"]);
150 unset($this->contextKeywords["await"]);
151 }
152 $this->context = (object) $context;
153 }
154
155 /**
156 * Post initialize operations
157 *
158 * @return void
159 */
160 protected function postInit()
161 {
162 //Remove exponentiation operator if the feature
163 //is not enabled
164 if (!$this->features->exponentiationOperator) {
165 Utils::removeArrayValue(
166 $this->assignmentOperators,
167 "**="
168 );
169 unset($this->logicalBinaryOperators["**"]);
170 }
171
172 //Remove coalescing operator if the feature
173 //is not enabled
174 if (!$this->features->coalescingOperator) {
175 unset($this->logicalBinaryOperators["??"]);
176 }
177
178 //Remove logical assignment operators if the
179 //feature is not enabled
180 if (!$this->features->logicalAssignmentOperators) {
181 foreach (array("&&=", "||=", "??=") as $op) {
182 Utils::removeArrayValue(
183 $this->assignmentOperators,
184 $op
185 );
186 }
187 }
188 }
189
190 /**
191 * Parses the source
192 *
193 * @return Node\Program
194 */
195 public function parse()
196 {
197 if ($this->sourceType === \Peast\Peast::SOURCE_TYPE_MODULE) {
198 $this->scanner->setStrictMode(true);
199 $body = $this->parseModuleItemList();
200 } else {
201 $body = $this->parseStatementList(true);
202 }
203
204 $node = $this->createNode(
205 "Program", $body ?: $this->scanner->getPosition()
206 );
207 $node->setSourceType($this->sourceType);
208 if ($body) {
209 $node->setBody($body);
210 }
211 $program = $this->completeNode($node);
212
213 if ($this->scanner->getToken()) {
214 $this->error();
215 }
216
217 //Execute scanner end operations
218 $this->scanner->consumeEnd();
219
220 //Emit the EndParsing event and pass the resulting program node as
221 //event data
222 $this->eventsEmitter && $this->eventsEmitter->fire(
223 "EndParsing", array($program)
224 );
225
226 return $program;
227 }
228
229 /**
230 * Converts an expression node to a pattern node
231 *
232 * @param Node\Node $node The node to convert
233 *
234 * @return Node\Node
235 */
236 protected function expressionToPattern($node)
237 {
238 if ($node instanceof Node\ArrayExpression) {
239
240 $loc = $node->location;
241 $elems = array();
242 foreach ($node->getElements() as $elem) {
243 $elems[] = $this->expressionToPattern($elem);
244 }
245
246 $retNode = $this->createNode("ArrayPattern", $loc->start);
247 $retNode->setElements($elems);
248 $this->completeNode($retNode, $loc->end);
249
250 } elseif ($node instanceof Node\ObjectExpression) {
251
252 $loc = $node->location;
253 $props = array();
254 foreach ($node->getProperties() as $prop) {
255 $props[] = $this->expressionToPattern($prop);
256 }
257
258 $retNode = $this->createNode("ObjectPattern", $loc->start);
259 $retNode->setProperties($props);
260 $this->completeNode($retNode, $loc->end);
261
262 } elseif ($node instanceof Node\Property) {
263
264 $loc = $node->location;
265 $retNode = $this->createNode(
266 "AssignmentProperty", $loc->start
267 );
268 // If it's a shorthand property convert the value to an assignment
269 // pattern if necessary
270 $value = $node->getValue();
271 $key = $node->getKey();
272 if ($value && $node->getShorthand() &&
273 !$value instanceof Node\AssignmentExpression &&
274 (!$value instanceof Node\Identifier || (
275 $key instanceof Node\Identifier && $key->getName() !== $value->getName()
276 ))) {
277 $loc = $node->location;
278 $valNode = $this->createNode("AssignmentPattern", $loc->start);
279 $valNode->setLeft($key);
280 $valNode->setRight($value);
281 $this->completeNode($valNode, $loc->end);
282 $value = $valNode;
283 } else {
284 $value = $this->expressionToPattern($value);
285 }
286 $retNode->setValue($value);
287 $retNode->setKey($key);
288 $retNode->setMethod($node->getMethod());
289 $retNode->setShorthand($node->getShorthand());
290 $retNode->setComputed($node->getComputed());
291 $this->completeNode($retNode, $loc->end);
292
293 } elseif ($node instanceof Node\SpreadElement) {
294
295 $loc = $node->location;
296 $retNode = $this->createNode("RestElement", $loc->start);
297 $retNode->setArgument(
298 $this->expressionToPattern($node->getArgument())
299 );
300 $this->completeNode($retNode, $loc->end);
301
302 } elseif ($node instanceof Node\AssignmentExpression) {
303
304 $loc = $node->location;
305 $retNode = $this->createNode("AssignmentPattern", $loc->start);
306 $retNode->setLeft($this->expressionToPattern($node->getLeft()));
307 $retNode->setRight($node->getRight());
308 $this->completeNode($retNode, $loc->end);
309
310 } else {
311 $retNode = $node;
312 }
313 return $retNode;
314 }
315
316 /**
317 * Parses a statement list
318 *
319 * @param bool $parseDirectivePrologues True to parse directive prologues
320 *
321 * @return Node\Node[]|null
322 */
323 protected function parseStatementList(
324 $parseDirectivePrologues = false
325 ) {
326 $items = array();
327
328 //Get directive prologues and check if strict mode is present
329 if ($parseDirectivePrologues) {
330 $oldStrictMode = $this->scanner->getStrictMode();
331 if ($directives = $this->parseDirectivePrologues()) {
332 $items = array_merge($items, $directives[0]);
333 //If "use strict" is present enable scanner strict mode
334 if (in_array("use strict", $directives[1])) {
335 $this->scanner->setStrictMode(true);
336 }
337 }
338 }
339
340 while ($item = $this->parseStatementListItem()) {
341 $items[] = $item;
342 }
343
344 //Apply previous strict mode
345 if ($parseDirectivePrologues) {
346 $this->scanner->setStrictMode($oldStrictMode);
347 }
348
349 return count($items) ? $items : null;
350 }
351
352 /**
353 * Parses a statement list item
354 *
355 * @return Node\Statement|Node\Declaration|null
356 */
357 protected function parseStatementListItem()
358 {
359 if ($declaration = $this->parseDeclaration()) {
360 return $declaration;
361 } elseif ($statement = $this->parseStatement()) {
362 return $statement;
363 }
364 return null;
365 }
366
367 /**
368 * Parses a statement
369 *
370 * @return Node\Statement|null
371 */
372 protected function parseStatement()
373 {
374 //Here the token value is checked for performance so that functions won't be
375 //called if not necessary
376 $token = $this->scanner->getToken();
377 if (!$token) {
378 return null;
379 }
380 $val = $token->value;
381 if ($val === "{" && $statement = $this->parseBlock()) {
382 return $statement;
383 } elseif ($val === "var" && $statement = $this->parseVariableStatement()) {
384 return $statement;
385 } elseif ($val === ";" && $statement = $this->parseEmptyStatement()) {
386 return $statement;
387 } elseif ($val === "if" && $statement = $this->parseIfStatement()) {
388 return $statement;
389 } elseif (
390 ($val === "for" || $val === "while" || $val === "do" || $val === "switch") &&
391 $statement = $this->parseBreakableStatement()
392 ) {
393 return $statement;
394 } elseif ($val == "continue" && $statement = $this->parseContinueStatement()) {
395 return $statement;
396 } elseif ($val === "break" && $statement = $this->parseBreakStatement()) {
397 return $statement;
398 } elseif (
399 $this->context->allowReturn && $val === "return" &&
400 $statement = $this->parseReturnStatement()
401 ) {
402 return $statement;
403 } elseif ($val === "with" && $statement = $this->parseWithStatement()) {
404 return $statement;
405 } elseif ($val === "throw" && $statement = $this->parseThrowStatement()) {
406 return $statement;
407 } elseif ($val === "try" && $statement = $this->parseTryStatement()) {
408 return $statement;
409 } elseif ($val === "debugger" && $statement = $this->parseDebuggerStatement()) {
410 return $statement;
411 } elseif ($statement = $this->parseLabelledStatement()) {
412 return $statement;
413 } elseif ($statement = $this->parseExpressionStatement()) {
414 return $statement;
415 }
416 return null;
417 }
418
419 /**
420 * Parses a declaration
421 *
422 * @return Node\Declaration|null
423 */
424 protected function parseDeclaration()
425 {
426 //Here the token value is checked for performance so that functions won't be
427 //called if not necessary
428 $token = $this->scanner->getToken();
429 if (!$token) {
430 return null;
431 }
432 $val = $token->value;
433 if ($declaration = $this->parseFunctionOrGeneratorDeclaration()) {
434 return $declaration;
435 } elseif ($val === "class" && $declaration = $this->parseClassDeclaration()) {
436 return $declaration;
437 } elseif (
438 ($val === "let" || $val === "const") &&
439 $declaration = $this->isolateContext(
440 array("allowIn" => true), "parseLexicalDeclaration"
441 )
442 ) {
443 return $declaration;
444 }
445 return null;
446 }
447
448 /**
449 * Parses a breakable statement
450 *
451 * @return Node\Node|null
452 */
453 protected function parseBreakableStatement()
454 {
455 if ($statement = $this->parseIterationStatement()) {
456 return $statement;
457 } elseif ($statement = $this->parseSwitchStatement()) {
458 return $statement;
459 }
460 return null;
461 }
462
463 /**
464 * Parses a block statement
465 *
466 * @return Node\BlockStatement|null
467 */
468 protected function parseBlock()
469 {
470 if ($token = $this->scanner->consume("{")) {
471
472 $statements = $this->parseStatementList();
473 if ($this->scanner->consume("}")) {
474 $node = $this->createNode("BlockStatement", $token);
475 if ($statements) {
476 $node->setBody($statements);
477 }
478 return $this->completeNode($node);
479 }
480 $this->error();
481 }
482 return null;
483 }
484
485 /**
486 * Parses a module item list
487 *
488 * @return Node\Node[]|null
489 */
490 protected function parseModuleItemList()
491 {
492 $items = array();
493 while ($item = $this->parseModuleItem()) {
494 $items[] = $item;
495 }
496 return count($items) ? $items : null;
497 }
498
499 /**
500 * Parses an empty statement
501 *
502 * @return Node\EmptyStatement|null
503 */
504 protected function parseEmptyStatement()
505 {
506 if ($token = $this->scanner->consume(";")) {
507 $node = $this->createNode("EmptyStatement", $token);
508 return $this->completeNode($node);
509 }
510 return null;
511 }
512
513 /**
514 * Parses a debugger statement
515 *
516 * @return Node\DebuggerStatement|null
517 */
518 protected function parseDebuggerStatement()
519 {
520 if ($token = $this->scanner->consume("debugger")) {
521 $node = $this->createNode("DebuggerStatement", $token);
522 $this->assertEndOfStatement();
523 return $this->completeNode($node);
524 }
525 return null;
526 }
527
528 /**
529 * Parses an if statement
530 *
531 * @return Node\IfStatement|null
532 */
533 protected function parseIfStatement()
534 {
535 if ($token = $this->scanner->consume("if")) {
536
537 if ($this->scanner->consume("(") &&
538 ($test = $this->isolateContext(
539 array("allowIn" => true), "parseExpression"
540 )) &&
541 $this->scanner->consume(")") &&
542 (
543 ($consequent = $this->parseStatement()) ||
544 (!$this->scanner->getStrictMode() &&
545 $consequent = $this->parseFunctionOrGeneratorDeclaration(
546 false, false
547 ))
548 )
549 ) {
550
551 $node = $this->createNode("IfStatement", $token);
552 $node->setTest($test);
553 $node->setConsequent($consequent);
554
555 if ($this->scanner->consume("else")) {
556 if (($alternate = $this->parseStatement()) ||
557 (!$this->scanner->getStrictMode() &&
558 $alternate = $this->parseFunctionOrGeneratorDeclaration(
559 false, false
560 ))
561 ) {
562 $node->setAlternate($alternate);
563 return $this->completeNode($node);
564 }
565 } else {
566 return $this->completeNode($node);
567 }
568 }
569
570 $this->error();
571 }
572 return null;
573 }
574
575 /**
576 * Parses a try-catch statement
577 *
578 * @return Node\TryStatement|null
579 */
580 protected function parseTryStatement()
581 {
582 if ($token = $this->scanner->consume("try")) {
583
584 if ($block = $this->parseBlock()) {
585
586 $node = $this->createNode("TryStatement", $token);
587 $node->setBlock($block);
588
589 if ($handler = $this->parseCatch()) {
590 $node->setHandler($handler);
591 }
592
593 if ($finalizer = $this->parseFinally()) {
594 $node->setFinalizer($finalizer);
595 }
596
597 if ($handler || $finalizer) {
598 return $this->completeNode($node);
599 }
600 }
601
602 $this->error();
603 }
604 return null;
605 }
606
607 /**
608 * Parses the catch block of a try-catch statement
609 *
610 * @return Node\CatchClause|null
611 */
612 protected function parseCatch()
613 {
614 if ($token = $this->scanner->consume("catch")) {
615
616 $node = $this->createNode("CatchClause", $token);
617
618 if ($this->scanner->consume("(")) {
619 if (!($param = $this->parseCatchParameter()) ||
620 !$this->scanner->consume(")")) {
621 $this->error();
622 }
623 $node->setParam($param);
624 } elseif (!$this->features->optionalCatchBinding) {
625 $this->error();
626 }
627
628 if (!($body = $this->parseBlock())) {
629 $this->error();
630 }
631
632 $node->setBody($body);
633
634 return $this->completeNode($node);
635 }
636 return null;
637 }
638
639 /**
640 * Parses the catch parameter of a catch block in a try-catch statement
641 *
642 * @return Node\Node|null
643 */
644 protected function parseCatchParameter()
645 {
646 if ($param = $this->parseIdentifier(static::$bindingIdentifier)) {
647 return $param;
648 } elseif ($param = $this->parseBindingPattern()) {
649 return $param;
650 }
651 return null;
652 }
653
654 /**
655 * Parses a finally block in a try-catch statement
656 *
657 * @return Node\BlockStatement|null
658 */
659 protected function parseFinally()
660 {
661 if ($this->scanner->consume("finally")) {
662
663 if ($block = $this->parseBlock()) {
664 return $block;
665 }
666
667 $this->error();
668 }
669 return null;
670 }
671
672 /**
673 * Parses a continue statement
674 *
675 * @return Node\ContinueStatement|null
676 */
677 protected function parseContinueStatement()
678 {
679 if ($token = $this->scanner->consume("continue")) {
680
681 if (!$this->context->inIteration) {
682 $this->error("Illegal continue statement");
683 }
684
685 $node = $this->createNode("ContinueStatement", $token);
686
687 if ($this->scanner->noLineTerminators() &&
688 ($label = $this->parseIdentifier(static::$labelledIdentifier))
689 ) {
690 $node->setLabel($label);
691 $this->assertEndOfStatement();
692 } else {
693 $this->scanner->consume(";");
694 }
695
696 return $this->completeNode($node);
697 }
698 return null;
699 }
700
701 /**
702 * Parses a break statement
703 *
704 * @return Node\BreakStatement|null
705 */
706 protected function parseBreakStatement()
707 {
708 if ($token = $this->scanner->consume("break")) {
709
710 $node = $this->createNode("BreakStatement", $token);
711
712 if ($this->scanner->noLineTerminators() &&
713 ($label = $this->parseIdentifier(static::$labelledIdentifier))) {
714 $node->setLabel($label);
715 $this->assertEndOfStatement();
716 } else {
717 $this->scanner->consume(";");
718
719 if (!$this->context->inIteration &&
720 !$this->context->inSwitch) {
721 $this->error("Illegal break statement");
722 }
723 }
724
725 return $this->completeNode($node);
726 }
727 return null;
728 }
729
730 /**
731 * Parses a return statement
732 *
733 * @return Node\ReturnStatement|null
734 */
735 protected function parseReturnStatement()
736 {
737 if ($token = $this->scanner->consume("return")) {
738
739 $node = $this->createNode("ReturnStatement", $token);
740
741 if ($this->scanner->noLineTerminators()) {
742 $argument = $this->isolateContext(
743 array("allowIn" => true), "parseExpression"
744 );
745 if ($argument) {
746 $node->setArgument($argument);
747 }
748 }
749
750 $this->assertEndOfStatement();
751
752 return $this->completeNode($node);
753 }
754 return null;
755 }
756
757 /**
758 * Parses a labelled statement
759 *
760 * @return Node\LabeledStatement|null
761 */
762 protected function parseLabelledStatement()
763 {
764 if ($label = $this->parseIdentifier(static::$labelledIdentifier, ":")) {
765
766 $this->scanner->consume(":");
767
768 if (($body = $this->parseStatement()) ||
769 ($body = $this->parseFunctionOrGeneratorDeclaration(
770 false, false
771 ))
772 ) {
773
774 //Labelled functions are not allowed in strict mode
775 if ($body instanceof Node\FunctionDeclaration &&
776 $this->scanner->getStrictMode()) {
777 $this->error(
778 "Labelled functions are not allowed in strict mode"
779 );
780 }
781
782 $node = $this->createNode("LabeledStatement", $label);
783 $node->setLabel($label);
784 $node->setBody($body);
785 return $this->completeNode($node);
786
787 }
788
789 $this->error();
790 }
791 return null;
792 }
793
794 /**
795 * Parses a throw statement
796 *
797 * @return Node\ThrowStatement|null
798 */
799 protected function parseThrowStatement()
800 {
801 if ($token = $this->scanner->consume("throw")) {
802
803 if ($this->scanner->noLineTerminators() &&
804 ($argument = $this->isolateContext(
805 array("allowIn" => true), "parseExpression"
806 ))
807 ) {
808
809 $this->assertEndOfStatement();
810 $node = $this->createNode("ThrowStatement", $token);
811 $node->setArgument($argument);
812 return $this->completeNode($node);
813 }
814
815 $this->error();
816 }
817 return null;
818 }
819
820 /**
821 * Parses a with statement
822 *
823 * @return Node\WithStatement|null
824 */
825 protected function parseWithStatement()
826 {
827 if ($token = $this->scanner->consume("with")) {
828
829 if ($this->scanner->consume("(") &&
830 ($object = $this->isolateContext(
831 array("allowIn" => true), "parseExpression"
832 )) &&
833 $this->scanner->consume(")") &&
834 $body = $this->parseStatement()
835 ) {
836
837 $node = $this->createNode("WithStatement", $token);
838 $node->setObject($object);
839 $node->setBody($body);
840 return $this->completeNode($node);
841 }
842
843 $this->error();
844 }
845 return null;
846 }
847
848 /**
849 * Parses a switch statement
850 *
851 * @return Node\SwitchStatement|null
852 */
853 protected function parseSwitchStatement()
854 {
855 if ($token = $this->scanner->consume("switch")) {
856
857 if ($this->scanner->consume("(") &&
858 ($discriminant = $this->isolateContext(
859 array("allowIn" => true), "parseExpression"
860 )) &&
861 $this->scanner->consume(")") &&
862 ($cases = $this->isolateContext(
863 array("inSwitch" => true), "parseCaseBlock"
864 )) !== null
865 ) {
866
867 $node = $this->createNode("SwitchStatement", $token);
868 $node->setDiscriminant($discriminant);
869 $node->setCases($cases);
870 return $this->completeNode($node);
871 }
872
873 $this->error();
874 }
875 return null;
876 }
877
878 /**
879 * Parses the content of a switch statement
880 *
881 * @return Node\SwitchCase[]|null
882 */
883 protected function parseCaseBlock()
884 {
885 if ($this->scanner->consume("{")) {
886
887 $parsedCasesAll = array(
888 $this->parseCaseClauses(),
889 $this->parseDefaultClause(),
890 $this->parseCaseClauses()
891 );
892
893 if ($this->scanner->consume("}")) {
894 $cases = array();
895 foreach ($parsedCasesAll as $parsedCases) {
896 if ($parsedCases) {
897 if (is_array($parsedCases)) {
898 $cases = array_merge($cases, $parsedCases);
899 } else {
900 $cases[] = $parsedCases;
901 }
902 }
903 }
904 return $cases;
905 } elseif ($this->parseDefaultClause()) {
906 $this->error(
907 "Multiple default clause in switch statement"
908 );
909 } else {
910 $this->error();
911 }
912 }
913 return null;
914 }
915
916 /**
917 * Parses cases in a switch statement
918 *
919 * @return Node\SwitchCase[]|null
920 */
921 protected function parseCaseClauses()
922 {
923 $cases = array();
924 while ($case = $this->parseCaseClause()) {
925 $cases[] = $case;
926 }
927 return count($cases) ? $cases : null;
928 }
929
930 /**
931 * Parses a case in a switch statement
932 *
933 * @return Node\SwitchCase|null
934 */
935 protected function parseCaseClause()
936 {
937 if ($token = $this->scanner->consume("case")) {
938
939 if (($test = $this->isolateContext(
940 array("allowIn" => true), "parseExpression"
941 )) &&
942 $this->scanner->consume(":")
943 ) {
944
945 $node = $this->createNode("SwitchCase", $token);
946 $node->setTest($test);
947
948 if ($consequent = $this->parseStatementList()) {
949 $node->setConsequent($consequent);
950 }
951
952 return $this->completeNode($node);
953 }
954
955 $this->error();
956 }
957 return null;
958 }
959
960 /**
961 * Parses default case in a switch statement
962 *
963 * @return Node\SwitchCase|null
964 */
965 protected function parseDefaultClause()
966 {
967 if ($token = $this->scanner->consume("default")) {
968
969 if ($this->scanner->consume(":")) {
970
971 $node = $this->createNode("SwitchCase", $token);
972
973 if ($consequent = $this->parseStatementList()) {
974 $node->setConsequent($consequent);
975 }
976
977 return $this->completeNode($node);
978 }
979
980 $this->error();
981 }
982 return null;
983 }
984
985 /**
986 * Parses an expression statement
987 *
988 * @return Node\ExpressionStatement|null
989 */
990 protected function parseExpressionStatement()
991 {
992 $lookaheadTokens = array("{", "function", "class", array("let", "["));
993 if ($this->features->asyncAwait) {
994 array_splice(
995 $lookaheadTokens, 3, 0,
996 array(array("async", true))
997 );
998 }
999 if (!$this->scanner->isBefore($lookaheadTokens, true) &&
1000 $expression = $this->isolateContext(
1001 array("allowIn" => true), "parseExpression"
1002 )
1003 ) {
1004
1005 $this->assertEndOfStatement();
1006 $node = $this->createNode("ExpressionStatement", $expression);
1007 $node->setExpression($expression);
1008 return $this->completeNode($node);
1009 }
1010 return null;
1011 }
1012
1013 /**
1014 * Parses a do-while statement
1015 *
1016 * @return Node\DoWhileStatement|null
1017 */
1018 protected function parseDoWhileStatement()
1019 {
1020 if ($token = $this->scanner->consume("do")) {
1021
1022 if (($body = $this->isolateContext(
1023 array("inIteration" => true), "parseStatement"
1024 )) &&
1025 $this->scanner->consume("while") &&
1026 $this->scanner->consume("(") &&
1027 ($test = $this->isolateContext(
1028 array("allowIn" => true), "parseExpression"
1029 )) &&
1030 $this->scanner->consume(")")
1031 ) {
1032
1033 $node = $this->createNode("DoWhileStatement", $token);
1034 $node->setBody($body);
1035 $node->setTest($test);
1036 $node = $this->completeNode($node);
1037 $this->scanner->consume(";");
1038 return $node;
1039 }
1040
1041 $this->error();
1042 }
1043 return null;
1044 }
1045
1046 /**
1047 * Parses a while statement
1048 *
1049 * @return Node\WhileStatement|null
1050 */
1051 protected function parseWhileStatement()
1052 {
1053 if ($token = $this->scanner->consume("while")) {
1054
1055 if ($this->scanner->consume("(") &&
1056 ($test = $this->isolateContext(
1057 array("allowIn" => true), "parseExpression"
1058 )) &&
1059 $this->scanner->consume(")") &&
1060 $body = $this->isolateContext(
1061 array("inIteration" => true), "parseStatement"
1062 )
1063 ) {
1064
1065 $node = $this->createNode("WhileStatement", $token);
1066 $node->setTest($test);
1067 $node->setBody($body);
1068 return $this->completeNode($node);
1069 }
1070
1071 $this->error();
1072 }
1073 return null;
1074 }
1075
1076 /**
1077 * Parses a for(var ...) statement
1078 *
1079 * @param Token $forToken Token that corresponds to the "for" keyword
1080 *
1081 * @return Node\Node|null
1082 */
1083 protected function parseForVarStatement($forToken)
1084 {
1085 if (!($varToken = $this->scanner->consume("var"))) {
1086 return null;
1087 }
1088
1089 $state = $this->scanner->getState();
1090
1091 if (($decl = $this->isolateContext(
1092 array("allowIn" => false), "parseVariableDeclarationList"
1093 )) &&
1094 ($varEndPosition = $this->scanner->getPosition()) &&
1095 $this->scanner->consume(";")
1096 ) {
1097
1098 $init = $this->createNode(
1099 "VariableDeclaration", $varToken
1100 );
1101 $init->setKind($init::KIND_VAR);
1102 $init->setDeclarations($decl);
1103 $init = $this->completeNode($init, $varEndPosition);
1104
1105 $test = $this->isolateContext(
1106 array("allowIn" => true), "parseExpression"
1107 );
1108
1109 if ($this->scanner->consume(";")) {
1110
1111 $update = $this->isolateContext(
1112 array("allowIn" => true), "parseExpression"
1113 );
1114
1115 if ($this->scanner->consume(")") &&
1116 $body = $this->isolateContext(
1117 array("inIteration" => true), "parseStatement"
1118 )
1119 ) {
1120
1121 $node = $this->createNode("ForStatement", $forToken);
1122 $node->setInit($init);
1123 $node->setTest($test);
1124 $node->setUpdate($update);
1125 $node->setBody($body);
1126 return $this->completeNode($node);
1127 }
1128 }
1129 } else {
1130
1131 $this->scanner->setState($state);
1132
1133 if ($decl = $this->parseForBinding()) {
1134
1135 $init = null;
1136 if ($this->features->forInInitializer &&
1137 $decl->getId()->getType() === "Identifier") {
1138 $init = $this->parseInitializer();
1139 }
1140
1141 if ($init) {
1142 $decl->setInit($init);
1143 $decl->location->end = $init->location->end;
1144 }
1145
1146 $left = $this->createNode("VariableDeclaration", $varToken);
1147 $left->setKind($left::KIND_VAR);
1148 $left->setDeclarations(array($decl));
1149 $left = $this->completeNode($left);
1150
1151 if ($this->scanner->consume("in")) {
1152
1153 if ($init && $this->scanner->getStrictMode()) {
1154 $this->error(
1155 "For-in variable initializer not allowed in " .
1156 "strict mode"
1157 );
1158 }
1159
1160 if (($right = $this->isolateContext(
1161 array("allowIn" => true), "parseExpression"
1162 )) &&
1163 $this->scanner->consume(")") &&
1164 $body = $this->isolateContext(
1165 array("inIteration" => true), "parseStatement"
1166 )
1167 ) {
1168
1169 $node = $this->createNode(
1170 "ForInStatement", $forToken
1171 );
1172 $node->setLeft($left);
1173 $node->setRight($right);
1174 $node->setBody($body);
1175 return $this->completeNode($node);
1176 }
1177 } elseif (!$init && $this->scanner->consume("of")) {
1178
1179 if (($right = $this->isolateContext(
1180 array("allowIn" => true), "parseAssignmentExpression"
1181 )) &&
1182 $this->scanner->consume(")") &&
1183 $body = $this->isolateContext(
1184 array("inIteration" => true), "parseStatement"
1185 )
1186 ) {
1187
1188 $node = $this->createNode(
1189 "ForOfStatement", $forToken
1190 );
1191 $node->setLeft($left);
1192 $node->setRight($right);
1193 $node->setBody($body);
1194 return $this->completeNode($node);
1195 }
1196 }
1197 }
1198 }
1199
1200 $this->error();
1201 }
1202
1203 /**
1204 * Parses a for(let ...) or for(const ...) statement
1205 *
1206 * @param Token $forToken Token that corresponds to the "for" keyword
1207 *
1208 * @return Node\Node|null
1209 */
1210 protected function parseForLetConstStatement($forToken)
1211 {
1212 $afterBracketState = $this->scanner->getState();
1213 if (!($init = $this->parseForDeclaration())) {
1214 return null;
1215 }
1216
1217 if ($this->scanner->consume("in")) {
1218 if (($right = $this->isolateContext(
1219 array("allowIn" => true), "parseExpression"
1220 )) &&
1221 $this->scanner->consume(")") &&
1222 $body = $this->isolateContext(
1223 array("inIteration" => true), "parseStatement"
1224 )
1225 ) {
1226
1227 $node = $this->createNode("ForInStatement", $forToken);
1228 $node->setLeft($init);
1229 $node->setRight($right);
1230 $node->setBody($body);
1231 return $this->completeNode($node);
1232 }
1233 } elseif ($this->scanner->consume("of")) {
1234 if (($right = $this->isolateContext(
1235 array("allowIn" => true), "parseAssignmentExpression"
1236 )) &&
1237 $this->scanner->consume(")") &&
1238 $body = $this->isolateContext(
1239 array("inIteration" => true), "parseStatement"
1240 )
1241 ) {
1242
1243 $node = $this->createNode("ForOfStatement", $forToken);
1244 $node->setLeft($init);
1245 $node->setRight($right);
1246 $node->setBody($body);
1247 return $this->completeNode($node);
1248 }
1249 } else {
1250
1251 $this->scanner->setState($afterBracketState);
1252 if ($init = $this->isolateContext(
1253 array("allowIn" => false), "parseLexicalDeclaration"
1254 )
1255 ) {
1256
1257 $test = $this->isolateContext(
1258 array("allowIn" => true), "parseExpression"
1259 );
1260 if ($this->scanner->consume(";")) {
1261
1262 $update = $this->isolateContext(
1263 array("allowIn" => true), "parseExpression"
1264 );
1265
1266 if ($this->scanner->consume(")") &&
1267 $body = $this->isolateContext(
1268 array("inIteration" => true), "parseStatement"
1269 )
1270 ) {
1271
1272 $node = $this->createNode("ForStatement", $forToken);
1273 $node->setInit($init);
1274 $node->setTest($test);
1275 $node->setUpdate($update);
1276 $node->setBody($body);
1277 return $this->completeNode($node);
1278 }
1279 }
1280 }
1281 }
1282
1283 $this->error();
1284 }
1285
1286 /**
1287 * Parses a for statement that does not start with var, let or const
1288 *
1289 * @param Token $forToken Token that corresponds to the "for" keyword
1290 * @param bool $hasAwait True if "for" is followed by "await"
1291 *
1292 * @return Node\Node|null
1293 */
1294 protected function parseForNotVarLetConstStatement($forToken, $hasAwait)
1295 {
1296 $state = $this->scanner->getState();
1297 $notBeforeSB = !$this->scanner->isBefore(array(array("let", "[")), true);
1298
1299 if ($notBeforeSB &&
1300 (($init = $this->isolateContext(
1301 array("allowIn" => false), "parseExpression"
1302 )) || true) &&
1303 $this->scanner->consume(";")
1304 ) {
1305
1306 $test = $this->isolateContext(
1307 array("allowIn" => true), "parseExpression"
1308 );
1309
1310 if ($this->scanner->consume(";")) {
1311
1312 $update = $this->isolateContext(
1313 array("allowIn" => true), "parseExpression"
1314 );
1315
1316 if ($this->scanner->consume(")") &&
1317 $body = $this->isolateContext(
1318 array("inIteration" => true), "parseStatement"
1319 )
1320 ) {
1321
1322 $node = $this->createNode("ForStatement", $forToken);
1323 $node->setInit($init);
1324 $node->setTest($test);
1325 $node->setUpdate($update);
1326 $node->setBody($body);
1327 return $this->completeNode($node);
1328 }
1329 }
1330 } else {
1331
1332 $this->scanner->setState($state);
1333 $beforeLetAsyncOf = $this->scanner->isBefore(array("let", array("async", "of")), true);
1334 $left = $this->parseLeftHandSideExpression();
1335
1336 if ($left && $left->getType() === "ChainExpression") {
1337 $this->error(
1338 "Optional chain can't appear in left-hand side"
1339 );
1340 }
1341
1342 $left = $this->expressionToPattern($left);
1343
1344 if ($notBeforeSB && $left && $this->scanner->consume("in")) {
1345
1346 if (($right = $this->isolateContext(
1347 array("allowIn" => true), "parseExpression"
1348 )) &&
1349 $this->scanner->consume(")") &&
1350 $body = $this->isolateContext(
1351 array("inIteration" => true), "parseStatement"
1352 )
1353 ) {
1354
1355 $node = $this->createNode("ForInStatement", $forToken);
1356 $node->setLeft($left);
1357 $node->setRight($right);
1358 $node->setBody($body);
1359 return $this->completeNode($node);
1360 }
1361 } elseif (($hasAwait || !$beforeLetAsyncOf) &&
1362 $left && $this->scanner->consume("of")
1363 ) {
1364
1365 if (($right = $this->isolateContext(
1366 array("allowIn" => true),
1367 "parseAssignmentExpression"
1368 )) &&
1369 $this->scanner->consume(")") &&
1370 $body = $this->isolateContext(
1371 array("inIteration" => true), "parseStatement"
1372 )
1373 ) {
1374
1375 $node = $this->createNode("ForOfStatement", $forToken);
1376 $node->setLeft($left);
1377 $node->setRight($right);
1378 $node->setBody($body);
1379 return $this->completeNode($node);
1380 }
1381 }
1382 }
1383
1384 $this->error();
1385 }
1386
1387 /**
1388 * Parses do-while, while, for, for-in and for-of statements
1389 *
1390 * @return Node\Node|null
1391 */
1392 protected function parseIterationStatement()
1393 {
1394 if ($node = $this->parseWhileStatement()) {
1395 return $node;
1396 } elseif ($node = $this->parseDoWhileStatement()) {
1397 return $node;
1398 } elseif ($startForToken = $this->scanner->consume("for")) {
1399
1400 $forAwait = false;
1401 if ($this->features->asyncIterationGenerators &&
1402 $this->context->allowAwait &&
1403 $this->scanner->consume("await")
1404 ) {
1405 $forAwait = true;
1406 }
1407
1408 if ($this->scanner->consume("(") && (
1409 ($node = $this->parseForVarStatement($startForToken)) ||
1410 ($node = $this->parseForLetConstStatement($startForToken)) ||
1411 ($node = $this->parseForNotVarLetConstStatement($startForToken, $forAwait)))
1412 ) {
1413 if ($forAwait) {
1414 if (!$node instanceof Node\ForOfStatement) {
1415 $this->error(
1416 "Async iteration is allowed only with for-of statements",
1417 $startForToken->location->start
1418 );
1419 }
1420 $node->setAwait(true);
1421 }
1422 return $node;
1423 }
1424
1425 $this->error();
1426 }
1427
1428 return null;
1429 }
1430
1431 /**
1432 * Checks if an async function can start from the current position. Returns
1433 * the async token or null if not found
1434 *
1435 * @param bool $checkFn If false it won't check if the async keyword is
1436 * followed by "function"
1437 *
1438 * @return Token
1439 */
1440 protected function checkAsyncFunctionStart($checkFn = true)
1441 {
1442 return ($asyncToken = $this->scanner->getToken()) &&
1443 $asyncToken->value === "async" &&
1444 (
1445 !$checkFn ||
1446 (($nextToken = $this->scanner->getNextToken()) &&
1447 $nextToken->value === "function")
1448 ) &&
1449 $this->scanner->noLineTerminators(true) ?
1450 $asyncToken :
1451 null;
1452 }
1453
1454 /**
1455 * Parses function or generator declaration
1456 *
1457 * @param bool $default Default mode
1458 * @param bool $allowGenerator True to allow parsing of generators
1459 *
1460 * @return Node\FunctionDeclaration|null
1461 */
1462 protected function parseFunctionOrGeneratorDeclaration(
1463 $default = false, $allowGenerator = true
1464 ) {
1465 $async = null;
1466 if ($this->features->asyncAwait &&
1467 ($async = $this->checkAsyncFunctionStart())) {
1468 $this->scanner->consumeToken();
1469 if (!$this->features->asyncIterationGenerators) {
1470 $allowGenerator = false;
1471 }
1472 }
1473 if ($token = $this->scanner->consume("function")) {
1474
1475 $generator = $allowGenerator && $this->scanner->consume("*");
1476 $id = $this->parseIdentifier(static::$bindingIdentifier);
1477
1478 if ($generator || $async) {
1479 $flags = array(null);
1480 if ($generator) {
1481 $flags["allowYield"] = true;
1482 }
1483 if ($async) {
1484 $flags["allowAwait"] = true;
1485 }
1486 } else {
1487 $flags = null;
1488 }
1489
1490 if (($default || $id) &&
1491 $this->scanner->consume("(") &&
1492 ($params = $this->isolateContext(
1493 $flags,
1494 "parseFormalParameterList"
1495 )) !== null &&
1496 $this->scanner->consume(")") &&
1497 ($tokenBodyStart = $this->scanner->consume("{")) &&
1498 (($body = $this->isolateContext(
1499 $flags,
1500 "parseFunctionBody"
1501 )) || true) &&
1502 $this->scanner->consume("}")
1503 ) {
1504
1505 $body->location->start = $tokenBodyStart->location->start;
1506 $body->location->end = $this->scanner->getPosition();
1507 $node = $this->createNode(
1508 "FunctionDeclaration",
1509 $async ?: $token
1510 );
1511 if ($id) {
1512 $node->setId($id);
1513 }
1514 $node->setParams($params);
1515 $node->setBody($body);
1516 $node->setGenerator($generator);
1517 $node->setAsync((bool) $async);
1518 return $this->completeNode($node);
1519 }
1520
1521 $this->error();
1522 }
1523 return null;
1524 }
1525
1526 /**
1527 * Parses function or generator expression
1528 *
1529 * @return Node\FunctionExpression|null
1530 */
1531 protected function parseFunctionOrGeneratorExpression()
1532 {
1533 $allowGenerator = true;
1534 $async = false;
1535 if ($this->features->asyncAwait &&
1536 ($async = $this->checkAsyncFunctionStart())) {
1537 $this->scanner->consumeToken();
1538 if (!$this->features->asyncIterationGenerators) {
1539 $allowGenerator = false;
1540 }
1541 }
1542 if ($token = $this->scanner->consume("function")) {
1543
1544 $generator = $allowGenerator && $this->scanner->consume("*");
1545
1546 if ($generator || $async) {
1547 $flags = array(null);
1548 if ($generator) {
1549 $flags["allowYield"] = true;
1550 }
1551 if ($async) {
1552 $flags["allowAwait"] = true;
1553 }
1554 } else {
1555 $flags = null;
1556 }
1557
1558 $id = $this->isolateContext(
1559 $flags,
1560 "parseIdentifier",
1561 array(static::$bindingIdentifier)
1562 );
1563
1564 if ($this->scanner->consume("(") &&
1565 ($params = $this->isolateContext(
1566 $flags,
1567 "parseFormalParameterList"
1568 )) !== null &&
1569 $this->scanner->consume(")") &&
1570 ($tokenBodyStart = $this->scanner->consume("{")) &&
1571 (($body = $this->isolateContext(
1572 $flags,
1573 "parseFunctionBody"
1574 )) || true) &&
1575 $this->scanner->consume("}")
1576 ) {
1577
1578 $body->location->start = $tokenBodyStart->location->start;
1579 $body->location->end = $this->scanner->getPosition();
1580 $node = $this->createNode(
1581 "FunctionExpression",
1582 $async ?: $token
1583 );
1584 $node->setId($id);
1585 $node->setParams($params);
1586 $node->setBody($body);
1587 $node->setGenerator($generator);
1588 $node->setAsync((bool) $async);
1589 return $this->completeNode($node);
1590 }
1591
1592 $this->error();
1593 }
1594 return null;
1595 }
1596
1597 /**
1598 * Parses yield statement
1599 *
1600 * @return Node\YieldExpression|null
1601 */
1602 protected function parseYieldExpression()
1603 {
1604 if ($token = $this->scanner->consume("yield")) {
1605
1606 $node = $this->createNode("YieldExpression", $token);
1607 if ($this->scanner->noLineTerminators()) {
1608
1609 $delegate = $this->scanner->consume("*");
1610 $argument = $this->isolateContext(
1611 array("allowYield" => true), "parseAssignmentExpression"
1612 );
1613 if ($argument) {
1614 $node->setArgument($argument);
1615 $node->setDelegate($delegate);
1616 }
1617 }
1618
1619 return $this->completeNode($node);
1620 }
1621 return null;
1622 }
1623
1624 /**
1625 * Parses a parameter list
1626 *
1627 * @return Node\Node[]|null
1628 */
1629 protected function parseFormalParameterList()
1630 {
1631 $hasComma = false;
1632 $list = array();
1633 while (
1634 ($param = $this->parseBindingRestElement()) ||
1635 $param = $this->parseBindingElement()
1636 ) {
1637 $hasComma = false;
1638 $list[] = $param;
1639 if ($param->getType() === "RestElement") {
1640 break;
1641 } elseif ($this->scanner->consume(",")) {
1642 $hasComma = true;
1643 } else {
1644 break;
1645 }
1646 }
1647 //Check if it ends with a comma, then check if the comma is a trailing comma,
1648 //in that case throw an error if the trailing comma feature is not enabled
1649 if ($hasComma &&
1650 !$this->features->trailingCommaFunctionCallDeclaration) {
1651 $token = $this->scanner->getToken();
1652 if ($token && $token->value === ")") {
1653 $this->error();
1654 }
1655 }
1656 return $list;
1657 }
1658
1659 /**
1660 * Parses a function body
1661 *
1662 * @return Node\BlockStatement[]|null
1663 */
1664 protected function parseFunctionBody()
1665 {
1666 $body = $this->isolateContext(
1667 array(
1668 "allowReturn" => true,
1669 "inSwitch" => false,
1670 "inIteration" => false
1671 ),
1672 "parseStatementList",
1673 array(true)
1674 );
1675 $node = $this->createNode(
1676 "BlockStatement", $body ?: $this->scanner->getPosition()
1677 );
1678 if ($body) {
1679 $node->setBody($body);
1680 }
1681 return $this->completeNode($node);
1682 }
1683
1684 /**
1685 * Parses a class declaration
1686 *
1687 * @param bool $default Default mode
1688 *
1689 * @return Node\ClassDeclaration|null
1690 */
1691 protected function parseClassDeclaration($default = false)
1692 {
1693 if ($token = $this->scanner->consume("class")) {
1694
1695 //Class declarations are strict mode by default
1696 $prevStrict = $this->scanner->getStrictMode();
1697 $this->scanner->setStrictMode(true);
1698
1699 $id = $this->parseIdentifier(static::$bindingIdentifier);
1700 if (($default || $id) &&
1701 $tail = $this->parseClassTail()
1702 ) {
1703
1704 $node = $this->createNode("ClassDeclaration", $token);
1705 if ($id) {
1706 $node->setId($id);
1707 }
1708 if ($tail[0]) {
1709 $node->setSuperClass($tail[0]);
1710 }
1711 $node->setBody($tail[1]);
1712 $this->scanner->setStrictMode($prevStrict);
1713 return $this->completeNode($node);
1714 }
1715
1716 $this->error();
1717 }
1718 return null;
1719 }
1720
1721 /**
1722 * Parses a class expression
1723 *
1724 * @return Node\ClassExpression|null
1725 */
1726 protected function parseClassExpression()
1727 {
1728 if ($token = $this->scanner->consume("class")) {
1729
1730 //Class expressions are strict mode by default
1731 $prevStrict = $this->scanner->getStrictMode();
1732 $this->scanner->setStrictMode(true);
1733
1734 $id = $this->parseIdentifier(static::$bindingIdentifier);
1735 $tail = $this->parseClassTail();
1736 $node = $this->createNode("ClassExpression", $token);
1737 if ($id) {
1738 $node->setId($id);
1739 }
1740 if ($tail[0]) {
1741 $node->setSuperClass($tail[0]);
1742 }
1743 $node->setBody($tail[1]);
1744 $this->scanner->setStrictMode($prevStrict);
1745 return $this->completeNode($node);
1746 }
1747 return null;
1748 }
1749
1750 /**
1751 * Parses the code that comes after the class keyword and class name. The
1752 * return value is an array where the first item is the extended class, if
1753 * any, and the second value is the class body
1754 *
1755 * @return array|null
1756 */
1757 protected function parseClassTail()
1758 {
1759 $heritage = $this->parseClassHeritage();
1760 if ($token = $this->scanner->consume("{")) {
1761
1762 $body = $this->parseClassBody();
1763 if ($this->scanner->consume("}")) {
1764 $body->location->start = $token->location->start;
1765 $body->location->end = $this->scanner->getPosition();
1766 return array($heritage, $body);
1767 }
1768 }
1769 $this->error();
1770 }
1771
1772 /**
1773 * Parses the class extends part
1774 *
1775 * @return Node\Node|null
1776 */
1777 protected function parseClassHeritage()
1778 {
1779 if ($this->scanner->consume("extends")) {
1780
1781 if ($superClass = $this->parseLeftHandSideExpression()) {
1782 return $superClass;
1783 }
1784
1785 $this->error();
1786 }
1787 return null;
1788 }
1789
1790 /**
1791 * Parses the class body
1792 *
1793 * @return Node\ClassBody|null
1794 */
1795 protected function parseClassBody()
1796 {
1797 $body = $this->parseClassElementList();
1798 $node = $this->createNode(
1799 "ClassBody", $body ?: $this->scanner->getPosition()
1800 );
1801 if ($body) {
1802 $node->setBody($body);
1803 }
1804 return $this->completeNode($node);
1805 }
1806
1807 /**
1808 * Parses class elements list
1809 *
1810 * @return Node\MethodDefinition[]|null
1811 */
1812 protected function parseClassElementList()
1813 {
1814 $items = array();
1815 while ($item = $this->parseClassElement()) {
1816 if ($item !== true) {
1817 $items[] = $item;
1818 }
1819 }
1820 return count($items) ? $items : null;
1821 }
1822
1823 /**
1824 * Parses a class elements
1825 *
1826 * @return Node\MethodDefinition|Node\PropertyDefinition|Node\StaticBlock|bool|null
1827 */
1828 protected function parseClassElement()
1829 {
1830 if ($this->scanner->consume(";")) {
1831 return true;
1832 }
1833 if ($this->features->classStaticBlock &&
1834 $this->scanner->isBefore(array(array("static", "{")), true)
1835 ) {
1836 return $this->parseClassStaticBlock();
1837 }
1838 $staticToken = null;
1839 $state = $this->scanner->getState();
1840 //This code handles the case where "static" is the method name
1841 if (!$this->scanner->isBefore(array(array("static", "(")), true)) {
1842 $staticToken = $this->scanner->consume("static");
1843 }
1844 if ($def = $this->parseMethodDefinition()) {
1845 if ($staticToken) {
1846 $def->setStatic(true);
1847 $def->location->start = $staticToken->location->start;
1848 }
1849 return $def;
1850 } else {
1851 if ($this->features->classFields) {
1852 if ($field = $this->parseFieldDefinition()) {
1853 if ($staticToken) {
1854 $field->setStatic(true);
1855 $field->location->start = $staticToken->location->start;
1856 }
1857 } elseif ($staticToken) {
1858 //Handle the case when "static" is the field name
1859 $this->scanner->setState($state);
1860 $field = $this->parseFieldDefinition();
1861 }
1862 return $field;
1863 } elseif ($staticToken) {
1864 $this->error();
1865 }
1866 }
1867
1868 return null;
1869 }
1870
1871 /**
1872 * Parses a let or const declaration
1873 *
1874 * @return Node\VariableDeclaration|null
1875 */
1876 protected function parseLexicalDeclaration()
1877 {
1878 $state = $this->scanner->getState();
1879 if ($token = $this->scanner->consumeOneOf(array("let", "const"))) {
1880
1881 $declarations = $this->charSeparatedListOf(
1882 "parseVariableDeclaration"
1883 );
1884
1885 if ($declarations) {
1886 // "const" requires that all declarations have an initializer
1887 if ($token->value === "const") {
1888 foreach ($declarations as $dec) {
1889 if (!$dec->getInit()) {
1890 $this->error("Missing initializer in const declaration");
1891 }
1892 }
1893 }
1894
1895 $this->assertEndOfStatement();
1896 $node = $this->createNode("VariableDeclaration", $token);
1897 $node->setKind($token->value);
1898 $node->setDeclarations($declarations);
1899 return $this->completeNode($node);
1900 }
1901
1902 // "let" can be used as variable name in non-strict mode
1903 if ($this->scanner->getStrictMode() || $token->value !== "let") {
1904 $this->error();
1905 } else {
1906 $this->scanner->setState($state);
1907 }
1908 }
1909 return null;
1910 }
1911
1912 /**
1913 * Parses a var declaration
1914 *
1915 * @return Node\VariableDeclaration|null
1916 */
1917 protected function parseVariableStatement()
1918 {
1919 if ($token = $this->scanner->consume("var")) {
1920
1921 $declarations = $this->isolateContext(
1922 array("allowIn" => true), "parseVariableDeclarationList"
1923 );
1924 if ($declarations) {
1925 $this->assertEndOfStatement();
1926 $node = $this->createNode("VariableDeclaration", $token);
1927 $node->setKind($node::KIND_VAR);
1928 $node->setDeclarations($declarations);
1929 return $this->completeNode($node);
1930 }
1931
1932 $this->error();
1933 }
1934 return null;
1935 }
1936
1937 /**
1938 * Parses an variable declarations
1939 *
1940 * @return Node\VariableDeclarator[]|null
1941 */
1942 protected function parseVariableDeclarationList()
1943 {
1944 return $this->charSeparatedListOf(
1945 "parseVariableDeclaration"
1946 );
1947 }
1948
1949 /**
1950 * Parses a variable declarations
1951 *
1952 * @return Node\VariableDeclarator|null
1953 */
1954 protected function parseVariableDeclaration()
1955 {
1956 if ($id = $this->parseIdentifier(static::$bindingIdentifier)) {
1957
1958 $node = $this->createNode("VariableDeclarator", $id);
1959 $node->setId($id);
1960 if ($init = $this->parseInitializer()) {
1961 $node->setInit($init);
1962 }
1963 return $this->completeNode($node);
1964
1965 } elseif ($id = $this->parseBindingPattern()) {
1966
1967 if ($init = $this->parseInitializer()) {
1968 $node = $this->createNode("VariableDeclarator", $id);
1969 $node->setId($id);
1970 $node->setInit($init);
1971 return $this->completeNode($node);
1972 }
1973
1974 }
1975 return null;
1976 }
1977
1978 /**
1979 * Parses a let or const declaration in a for statement definition
1980 *
1981 * @return Node\VariableDeclaration|null
1982 */
1983 protected function parseForDeclaration()
1984 {
1985 $state = $this->scanner->getState();
1986 if ($token = $this->scanner->consumeOneOf(array("let", "const"))) {
1987
1988 if ($declaration = $this->parseForBinding()) {
1989
1990 $node = $this->createNode("VariableDeclaration", $token);
1991 $node->setKind($token->value);
1992 $node->setDeclarations(array($declaration));
1993 return $this->completeNode($node);
1994 }
1995
1996 // "let" can be used as variable name in non-strict mode
1997 if ($this->scanner->getStrictMode() || $token->value !== "let") {
1998 $this->error();
1999 } else {
2000 $this->scanner->setState($state);
2001 }
2002 }
2003 return null;
2004 }
2005
2006 /**
2007 * Parses a binding pattern or an identifier that come after a const or let
2008 * declaration in a for statement definition
2009 *
2010 * @return Node\VariableDeclarator|null
2011 */
2012 protected function parseForBinding()
2013 {
2014 if (($id = $this->parseIdentifier(static::$bindingIdentifier)) ||
2015 ($id = $this->parseBindingPattern())
2016 ) {
2017
2018 $node = $this->createNode("VariableDeclarator", $id);
2019 $node->setId($id);
2020 return $this->completeNode($node);
2021 }
2022 return null;
2023 }
2024
2025 /**
2026 * Parses a module item
2027 *
2028 * @return Node\Node|null
2029 */
2030 protected function parseModuleItem()
2031 {
2032 if ($item = $this->parseImportDeclaration()) {
2033 return $item;
2034 } elseif ($item = $this->parseExportDeclaration()) {
2035 return $item;
2036 } elseif (
2037 $item = $this->isolateContext(
2038 array(
2039 "allowYield" => false,
2040 "allowReturn" => false,
2041 "allowAwait" => $this->features->topLevelAwait
2042 ),
2043 "parseStatementListItem"
2044 )
2045 ) {
2046 return $item;
2047 }
2048 return null;
2049 }
2050
2051 /**
2052 * Parses the from keyword and the following string in import and export
2053 * declarations
2054 *
2055 * @return Node\StringLiteral|null
2056 */
2057 protected function parseFromClause()
2058 {
2059 if ($this->scanner->consume("from")) {
2060 if ($spec = $this->parseStringLiteral()) {
2061 return $spec;
2062 }
2063 $this->error();
2064 }
2065 return null;
2066 }
2067
2068 /**
2069 * Parses an export declaration
2070 *
2071 * @return Node\ModuleDeclaration|null
2072 */
2073 protected function parseExportDeclaration()
2074 {
2075 if ($token = $this->scanner->consume("export")) {
2076
2077 if ($this->scanner->consume("*")) {
2078
2079 $exported = null;
2080 if ($this->features->exportedNameInExportAll &&
2081 $this->scanner->consume("as")) {
2082 $exported = $this->parseModuleExportName();
2083 if (!$exported) {
2084 $this->error();
2085 }
2086 }
2087
2088 if ($source = $this->parseFromClause()) {
2089 $node = $this->createNode("ExportAllDeclaration", $token);
2090 $node->setSource($source);
2091 $node->setExported($exported);
2092 if ($this->features->importAttributes &&
2093 ($attrs = $this->parseWithClause())) {
2094 $node->setAttributes($attrs);
2095 }
2096 $this->assertEndOfStatement();
2097 return $this->completeNode($node);
2098 }
2099
2100 } elseif ($this->scanner->consume("default")) {
2101 $lookaheadTokens = array("function", "class");
2102 if ($this->features->asyncAwait) {
2103 $lookaheadTokens[] = array("async", true);
2104 }
2105 if (($declaration = $this->isolateContext(
2106 array("allowAwait" => $this->features->topLevelAwait),
2107 "parseFunctionOrGeneratorDeclaration",
2108 array(true)
2109 )) ||
2110 ($declaration = $this->isolateContext(
2111 array("allowAwait" => $this->features->topLevelAwait),
2112 "parseClassDeclaration",
2113 array(true)
2114 ))
2115 ) {
2116
2117 $node = $this->createNode("ExportDefaultDeclaration", $token);
2118 $node->setDeclaration($declaration);
2119 return $this->completeNode($node);
2120
2121 } elseif (!$this->scanner->isBefore(
2122 $lookaheadTokens,
2123 $this->features->asyncAwait
2124 ) &&
2125 ($declaration = $this->isolateContext(
2126 array("allowIn" => true, "allowAwait" => $this->features->topLevelAwait),
2127 "parseAssignmentExpression"
2128 ))
2129 ) {
2130
2131 $this->assertEndOfStatement();
2132 $node = $this->createNode(
2133 "ExportDefaultDeclaration", $token
2134 );
2135 $node->setDeclaration($declaration);
2136 return $this->completeNode($node);
2137 }
2138
2139 } elseif (($specifiers = $this->parseExportClause()) !== null) {
2140
2141 $node = $this->createNode("ExportNamedDeclaration", $token);
2142 $node->setSpecifiers($specifiers);
2143 if ($source = $this->parseFromClause()) {
2144 $node->setSource($source);
2145 }
2146 if ($this->features->importAttributes &&
2147 ($attrs = $this->parseWithClause())) {
2148 $node->setAttributes($attrs);
2149 }
2150 $this->assertEndOfStatement();
2151 return $this->completeNode($node);
2152
2153 } elseif (
2154 ($dec = $this->isolateContext(
2155 array("allowAwait" => $this->features->topLevelAwait),
2156 "parseVariableStatement"
2157 )) ||
2158 $dec = $this->isolateContext(
2159 array("allowAwait" => $this->features->topLevelAwait),
2160 "parseDeclaration"
2161 )
2162 ) {
2163
2164 $node = $this->createNode("ExportNamedDeclaration", $token);
2165 $node->setDeclaration($dec);
2166 return $this->completeNode($node);
2167 }
2168
2169 $this->error();
2170 }
2171 return null;
2172 }
2173
2174 /**
2175 * Parses an export clause
2176 *
2177 * @return Node\ExportSpecifier[]|null
2178 */
2179 protected function parseExportClause()
2180 {
2181 if ($this->scanner->consume("{")) {
2182
2183 $list = array();
2184 while ($spec = $this->parseExportSpecifier()) {
2185 $list[] = $spec;
2186 if (!$this->scanner->consume(",")) {
2187 break;
2188 }
2189 }
2190
2191 if ($this->scanner->consume("}")) {
2192 return $list;
2193 }
2194
2195 $this->error();
2196 }
2197 return null;
2198 }
2199
2200 /**
2201 * Parses an export specifier
2202 *
2203 * @return Node\ExportSpecifier|null
2204 */
2205 protected function parseExportSpecifier()
2206 {
2207 if ($local = $this->parseModuleExportName()) {
2208
2209 $node = $this->createNode("ExportSpecifier", $local);
2210 $node->setLocal($local);
2211
2212 if ($this->scanner->consume("as")) {
2213
2214 if ($exported = $this->parseModuleExportName()) {
2215 $node->setExported($exported);
2216 return $this->completeNode($node);
2217 }
2218
2219 $this->error();
2220 } else {
2221 $node->setExported($local);
2222 return $this->completeNode($node);
2223 }
2224 }
2225 return null;
2226 }
2227
2228 /**
2229 * Parses an export name
2230 *
2231 * @return Node\Identifier|Node\StringLiteral|null
2232 */
2233 protected function parseModuleExportName()
2234 {
2235 if ($name = $this->parseIdentifier(static::$identifierName)) {
2236 return $name;
2237 } elseif ($this->features->arbitraryModuleNSNames &&
2238 ($name = $this->parseStringLiteral())
2239 ) {
2240 return $name;
2241 }
2242 return null;
2243 }
2244
2245 /**
2246 * Parses an import declaration
2247 *
2248 * @return Node\ModuleDeclaration|null
2249 */
2250 protected function parseImportDeclaration()
2251 {
2252 //Delay parsing of dynamic import so that it is handled
2253 //by the relative method
2254 if ($this->features->dynamicImport &&
2255 $this->scanner->isBefore(array(array("import", "(")), true)) {
2256 return null;
2257 }
2258 //Delay parsing of import.meta so that it is handled
2259 //by the relative method
2260 if ($this->features->importMeta &&
2261 $this->scanner->isBefore(array(array("import", ".")), true)) {
2262 return null;
2263 }
2264 if ($token = $this->scanner->consume("import")) {
2265
2266 if ($source = $this->parseStringLiteral()) {
2267 $attrs = $this->features->importAttributes ?
2268 $this->parseWithClause() : null;
2269 $this->assertEndOfStatement();
2270 $node = $this->createNode("ImportDeclaration", $token);
2271 $node->setSource($source);
2272 if ($attrs) {
2273 $node->setAttributes($attrs);
2274 }
2275 return $this->completeNode($node);
2276
2277 } elseif (($specifiers = $this->parseImportClause()) !== null &&
2278 $source = $this->parseFromClause()
2279 ) {
2280 $attrs = $this->features->importAttributes ?
2281 $this->parseWithClause() : null;
2282 $this->assertEndOfStatement();
2283 $node = $this->createNode("ImportDeclaration", $token);
2284 $node->setSpecifiers($specifiers);
2285 $node->setSource($source);
2286 if ($attrs) {
2287 $node->setAttributes($attrs);
2288 }
2289 return $this->completeNode($node);
2290 }
2291
2292 $this->error();
2293 }
2294 return null;
2295 }
2296
2297 /**
2298 * Parses an import clause
2299 *
2300 * @return array|null
2301 */
2302 protected function parseImportClause()
2303 {
2304 if ($spec = $this->parseNameSpaceImport()) {
2305 return array($spec);
2306 } elseif (($specs = $this->parseNamedImports()) !== null) {
2307 return $specs;
2308 } elseif ($spec = $this->parseIdentifier(static::$importedBinding)) {
2309
2310 $node = $this->createNode("ImportDefaultSpecifier", $spec);
2311 $node->setLocal($spec);
2312 $ret = array($this->completeNode($node));
2313
2314 if ($this->scanner->consume(",")) {
2315
2316 if ($spec = $this->parseNameSpaceImport()) {
2317 $ret[] = $spec;
2318 return $ret;
2319 } elseif (($specs = $this->parseNamedImports()) !== null) {
2320 return array_merge($ret, $specs);
2321 }
2322
2323 $this->error();
2324 } else {
2325 return $ret;
2326 }
2327 }
2328 return null;
2329 }
2330
2331 /**
2332 * Parses a namespace import
2333 *
2334 * @return Node\ImportNamespaceSpecifier|null
2335 */
2336 protected function parseNameSpaceImport()
2337 {
2338 if ($token = $this->scanner->consume("*")) {
2339
2340 if ($this->scanner->consume("as") &&
2341 $local = $this->parseIdentifier(static::$identifierReference)
2342 ) {
2343 $node = $this->createNode("ImportNamespaceSpecifier", $token);
2344 $node->setLocal($local);
2345 return $this->completeNode($node);
2346 }
2347
2348 $this->error();
2349 }
2350 return null;
2351 }
2352
2353 /**
2354 * Parses a named imports
2355 *
2356 * @return Node\ImportSpecifier[]|null
2357 */
2358 protected function parseNamedImports()
2359 {
2360 if ($this->scanner->consume("{")) {
2361
2362 $list = array();
2363 while ($spec = $this->parseImportSpecifier()) {
2364 $list[] = $spec;
2365 if (!$this->scanner->consume(",")) {
2366 break;
2367 }
2368 }
2369
2370 if ($this->scanner->consume("}")) {
2371 return $list;
2372 }
2373
2374 $this->error();
2375 }
2376 return null;
2377 }
2378
2379 /**
2380 * Parses an import specifier
2381 *
2382 * @return Node\ImportSpecifier|null
2383 */
2384 protected function parseImportSpecifier()
2385 {
2386 $requiredAs = false;
2387 $imported = $this->parseIdentifier(static::$importedBinding);
2388 if (!$imported) {
2389 $imported = $this->parseModuleExportName();
2390 if (!$imported) {
2391 return null;
2392 }
2393 $requiredAs = true;
2394 }
2395
2396 $node = $this->createNode("ImportSpecifier", $imported);
2397 $node->setImported($imported);
2398
2399 if ($this->scanner->consume("as")) {
2400
2401 if (!($local = $this->parseIdentifier(static::$importedBinding))) {
2402 $this->error();
2403 }
2404
2405 $node->setLocal($local);
2406
2407 } elseif ($requiredAs) {
2408 $this->error();
2409 } else {
2410 $node->setLocal($imported);
2411 }
2412
2413 return $this->completeNode($node);
2414 }
2415
2416 /**
2417 * Parses a with clause
2418 *
2419 * @return array|null
2420 */
2421 protected function parseWithClause()
2422 {
2423 if ($this->scanner->consume("with")) {
2424 if (!$this->scanner->consume("{")) {
2425 $this->error();
2426 } else {
2427 $list = array();
2428 while (true) {
2429 if ($entry = $this->parseWithEntries()) {
2430 $list[] = $entry;
2431 if (!$this->scanner->consume(",")) {
2432 break;
2433 }
2434 } else {
2435 break;
2436 }
2437 }
2438 if (!$this->scanner->consume("}")) {
2439 $this->error();
2440 }
2441 return $list;
2442 }
2443 }
2444 return null;
2445 }
2446
2447 /**
2448 * Parses a with entry
2449 *
2450 * @return ImportAttribute |null
2451 */
2452 protected function parseWithEntries()
2453 {
2454 if (($key = $this->parseIdentifier(static::$identifierName)) ||
2455 ($key = $this->parseStringLiteral())) {
2456 if ($this->scanner->consume(":") &&
2457 ($value = $this->parseStringLiteral())) {
2458 $node = $this->createNode("ImportAttribute", $key);
2459 $node->setKey($key);
2460 $node->setValue($value);
2461 return $this->completeNode($node);
2462 } else {
2463 $this->error();
2464 }
2465 }
2466 return null;
2467 }
2468
2469 /**
2470 * Parses a binding pattern
2471 *
2472 * @return Node\ArrayPattern|Node\ObjectPattern|null
2473 */
2474 protected function parseBindingPattern()
2475 {
2476 if ($pattern = $this->parseObjectBindingPattern()) {
2477 return $pattern;
2478 } elseif ($pattern = $this->parseArrayBindingPattern()) {
2479 return $pattern;
2480 }
2481 return null;
2482 }
2483
2484 /**
2485 * Parses an elisions sequence. It returns the number of elisions or null
2486 * if no elision has been found
2487 *
2488 * @return int
2489 */
2490 protected function parseElision()
2491 {
2492 $count = 0;
2493 while ($this->scanner->consume(",")) {
2494 $count ++;
2495 }
2496 return $count ?: null;
2497 }
2498
2499 /**
2500 * Parses an array binding pattern
2501 *
2502 * @return Node\ArrayPattern|null
2503 */
2504 protected function parseArrayBindingPattern()
2505 {
2506 if ($token = $this->scanner->consume("[")) {
2507
2508 $elements = array();
2509 while (true) {
2510 if ($elision = $this->parseElision()) {
2511 $elements = array_merge(
2512 $elements, array_fill(0, $elision, null)
2513 );
2514 }
2515 if ($element = $this->parseBindingElement()) {
2516 $elements[] = $element;
2517 if (!$this->scanner->consume(",")) {
2518 break;
2519 }
2520 } elseif ($rest = $this->parseBindingRestElement()) {
2521 $elements[] = $rest;
2522 break;
2523 } else {
2524 break;
2525 }
2526 }
2527
2528 if ($this->scanner->consume("]")) {
2529 $node = $this->createNode("ArrayPattern", $token);
2530 $node->setElements($elements);
2531 return $this->completeNode($node);
2532 }
2533 }
2534 return null;
2535 }
2536
2537 /**
2538 * Parses a rest element
2539 *
2540 * @return Node\RestElement|null
2541 */
2542 protected function parseBindingRestElement()
2543 {
2544 if ($token = $this->scanner->consume("...")) {
2545
2546 if (($argument = $this->parseIdentifier(static::$bindingIdentifier)) ||
2547 ($argument = $this->parseBindingPattern())) {
2548 $node = $this->createNode("RestElement", $token);
2549 $node->setArgument($argument);
2550 return $this->completeNode($node);
2551 }
2552
2553 $this->error();
2554 }
2555 return null;
2556 }
2557
2558 /**
2559 * Parses a binding element
2560 *
2561 * @return Node\AssignmentPattern|Node\Identifier|null
2562 */
2563 protected function parseBindingElement()
2564 {
2565 if ($el = $this->parseSingleNameBinding()) {
2566 return $el;
2567 } elseif ($left = $this->parseBindingPattern()) {
2568
2569 $right = $this->isolateContext(
2570 array("allowIn" => true), "parseInitializer"
2571 );
2572 if ($right) {
2573 $node = $this->createNode("AssignmentPattern", $left);
2574 $node->setLeft($left);
2575 $node->setRight($right);
2576 return $this->completeNode($node);
2577 } else {
2578 return $left;
2579 }
2580 }
2581 return null;
2582 }
2583
2584 /**
2585 * Parses single name binding
2586 *
2587 * @return Node\AssignmentPattern|Node\Identifier|null
2588 */
2589 protected function parseSingleNameBinding()
2590 {
2591 if ($left = $this->parseIdentifier(static::$bindingIdentifier)) {
2592 $right = $this->isolateContext(
2593 array("allowIn" => true), "parseInitializer"
2594 );
2595 if ($right) {
2596 $node = $this->createNode("AssignmentPattern", $left);
2597 $node->setLeft($left);
2598 $node->setRight($right);
2599 return $this->completeNode($node);
2600 } else {
2601 return $left;
2602 }
2603 }
2604 return null;
2605 }
2606
2607 /**
2608 * Parses a property name. The returned value is an array where there first
2609 * element is the property name and the second element is a boolean
2610 * indicating if it's a computed property
2611 *
2612 * @return array|null
2613 */
2614 protected function parsePropertyName()
2615 {
2616 if ($token = $this->scanner->consume("[")) {
2617
2618 if (($name = $this->isolateContext(
2619 array("allowIn" => true), "parseAssignmentExpression"
2620 )) &&
2621 $this->scanner->consume("]")
2622 ) {
2623 return array($name, true, $token);
2624 }
2625
2626 $this->error();
2627 } elseif ($name = $this->parseIdentifier(static::$identifierName)) {
2628 return array($name, false);
2629 } elseif ($name = $this->parseStringLiteral()) {
2630 return array($name, false);
2631 } elseif ($name = $this->parseNumericLiteral()) {
2632 return array($name, false);
2633 }
2634 return null;
2635 }
2636
2637 /**
2638 * Parses a property name. The returned value is an array where there first
2639 * element is the property name and the second element is a boolean
2640 * indicating if it's a computed property
2641 *
2642 * @return array|null
2643 */
2644 protected function parseClassElementName()
2645 {
2646 if (
2647 $this->features->privateMethodsAndFields &&
2648 ($name = $this->parsePrivateIdentifier())
2649 ) {
2650 return array($name, false);
2651 }
2652 return $this->parsePropertyName();
2653 }
2654
2655 /**
2656 * Parses a field definition
2657 *
2658 * @return Node\StaticBlock
2659 */
2660 protected function parseClassStaticBlock()
2661 {
2662 $staticToken = $this->scanner->consume("static");
2663 $this->scanner->consume("{");
2664 $statements = $this->isolateContext(
2665 array("allowAwait" => true), "parseStatementList"
2666 );
2667 if ($this->scanner->consume("}")) {
2668 $node = $this->createNode("StaticBlock", $staticToken);
2669 if ($statements) {
2670 $node->setBody($statements);
2671 }
2672 return $this->completeNode($node);
2673 }
2674 $this->error();
2675 }
2676
2677 /**
2678 * Parses a field definition
2679 *
2680 * @return Node\PropertyDefinition|null
2681 */
2682 protected function parseFieldDefinition()
2683 {
2684 $state = $this->scanner->getState();
2685 if ($prop = $this->parseClassElementName()) {
2686 $value = $this->isolateContext(
2687 array("allowIn" => true), "parseInitializer"
2688 );
2689 $this->assertEndOfStatement();
2690 $node = $this->createNode("PropertyDefinition", $prop);
2691 $node->setKey($prop[0]);
2692 if ($value) {
2693 $node->setValue($value);
2694 }
2695 $node->setComputed($prop[1]);
2696 return $this->completeNode($node);
2697 }
2698 $this->scanner->setState($state);
2699 return null;
2700 }
2701
2702 /**
2703 * Parses a method definition
2704 *
2705 * @return Node\MethodDefinition|null
2706 */
2707 protected function parseMethodDefinition()
2708 {
2709 $state = $this->scanner->getState();
2710 $generator = $error = $async = false;
2711 $position = null;
2712 $kind = Node\MethodDefinition::KIND_METHOD;
2713 if ($token = $this->scanner->consume("get")) {
2714 $position = $token;
2715 $kind = Node\MethodDefinition::KIND_GET;
2716 } elseif ($token = $this->scanner->consume("set")) {
2717 $position = $token;
2718 $kind = Node\MethodDefinition::KIND_SET;
2719 } elseif ($token = $this->scanner->consume("*")) {
2720 $position = $token;
2721 $error = true;
2722 $generator = true;
2723 } elseif ($this->features->asyncAwait &&
2724 ($token = $this->checkAsyncFunctionStart(false))) {
2725 $this->scanner->consumeToken();
2726 $position = $token;
2727 $error = true;
2728 $async = true;
2729 if ($this->features->asyncIterationGenerators &&
2730 ($this->scanner->consume("*"))) {
2731 $generator = true;
2732 }
2733 }
2734
2735 //Handle the case where get, set and async are methods name and not the
2736 //definition of a getter/setter or the start of an async function
2737 if (($kind !== Node\MethodDefinition::KIND_METHOD || ($async && !$generator)) &&
2738 $this->scanner->consume("(")
2739 ) {
2740 $this->scanner->setState($state);
2741 $kind = Node\MethodDefinition::KIND_METHOD;
2742 $error = $async = false;
2743 }
2744
2745 if ($prop = $this->parseClassElementName()) {
2746
2747 if (!$position) {
2748 $position = isset($prop[2]) ? $prop[2] : $prop[0];
2749 }
2750 if ($tokenFn = $this->scanner->consume("(")) {
2751
2752 if ($generator || $async) {
2753 $flags = array(null);
2754 if ($generator) {
2755 $flags["allowYield"] = true;
2756 }
2757 if ($async) {
2758 $flags["allowAwait"] = true;
2759 }
2760 } else {
2761 $flags = null;
2762 }
2763
2764 $error = true;
2765 $params = array();
2766 if ($kind === Node\MethodDefinition::KIND_SET) {
2767 $params = $this->isolateContext(
2768 null, "parseBindingElement"
2769 );
2770 if ($params) {
2771 $params = array($params);
2772 }
2773 } elseif ($kind === Node\MethodDefinition::KIND_METHOD) {
2774 $params = $this->isolateContext(
2775 $flags, "parseFormalParameterList"
2776 );
2777 }
2778
2779 if ($params !== null &&
2780 $this->scanner->consume(")") &&
2781 ($tokenBodyStart = $this->scanner->consume("{")) &&
2782 (($body = $this->isolateContext(
2783 $flags, "parseFunctionBody"
2784 )) || true) &&
2785 $this->scanner->consume("}")
2786 ) {
2787
2788 if ($prop[0] instanceof Node\Identifier &&
2789 $prop[0]->getName() === "constructor"
2790 ) {
2791 $kind = Node\MethodDefinition::KIND_CONSTRUCTOR;
2792 }
2793
2794 $body->location->start = $tokenBodyStart->location->start;
2795 $body->location->end = $this->scanner->getPosition();
2796
2797 $nodeFn = $this->createNode("FunctionExpression", $tokenFn);
2798 $nodeFn->setParams($params);
2799 $nodeFn->setBody($body);
2800 $nodeFn->setGenerator($generator);
2801 $nodeFn->setAsync($async);
2802
2803 $node = $this->createNode("MethodDefinition", $position);
2804 $node->setKey($prop[0]);
2805 $node->setValue($this->completeNode($nodeFn));
2806 $node->setKind($kind);
2807 $node->setComputed($prop[1]);
2808 return $this->completeNode($node);
2809 }
2810 }
2811 }
2812 //Handle the case where "async" is a class field name
2813 elseif ($this->features->classFields && $async && !$generator) {
2814 $this->scanner->setState($state);
2815 $error = $async = false;
2816 }
2817
2818 if ($error) {
2819 $this->error();
2820 } else {
2821 $this->scanner->setState($state);
2822 }
2823 return null;
2824 }
2825
2826 /**
2827 * Parses parameters in an arrow function. If the parameters are wrapped in
2828 * round brackets, the returned value is an array where the first element
2829 * is the parameters list and the second element is the open round brackets,
2830 * this is needed to know the start position
2831 *
2832 * @return Node\Identifier|array|null
2833 */
2834 protected function parseArrowParameters()
2835 {
2836 if ($param = $this->parseIdentifier(static::$bindingIdentifier, "=>")) {
2837 return $param;
2838 } elseif ($token = $this->scanner->consume("(")) {
2839
2840 $params = $this->parseFormalParameterList();
2841
2842 if ($params !== null && $this->scanner->consume(")")) {
2843 return array($params, $token);
2844 }
2845 }
2846 return null;
2847 }
2848
2849 /**
2850 * Parses the body of an arrow function. The returned value is an array
2851 * where the first element is the function body and the second element is
2852 * a boolean indicating if the body is wrapped in curly braces
2853 *
2854 * @param bool $async Async body mode
2855 *
2856 * @return array|null
2857 */
2858 protected function parseConciseBody($async = false)
2859 {
2860 if ($token = $this->scanner->consume("{")) {
2861
2862 if (($body = $this->isolateContext(
2863 $async ? array(null, "allowAwait" => true) : null,
2864 "parseFunctionBody"
2865 )) &&
2866 $this->scanner->consume("}")
2867 ) {
2868 $body->location->start = $token->location->start;
2869 $body->location->end = $this->scanner->getPosition();
2870 return array($body, false);
2871 }
2872
2873 $this->error();
2874 } elseif (!$this->scanner->isBefore(array("{")) &&
2875 $body = $this->isolateContext(
2876 $this->features->asyncAwait ?
2877 array("allowYield" => false, "allowAwait" => $async) :
2878 array("allowYield" => false),
2879 "parseAssignmentExpression"
2880 )
2881 ) {
2882 return array($body, true);
2883 }
2884 return null;
2885 }
2886
2887 /**
2888 * Parses an arrow function
2889 *
2890 * @return Node\ArrowFunctionExpression|null
2891 */
2892 protected function parseArrowFunction()
2893 {
2894 $state = $this->scanner->getState();
2895 $async = false;
2896 if ($this->features->asyncAwait &&
2897 ($async = $this->checkAsyncFunctionStart(false))) {
2898 $this->scanner->consumeToken();
2899 }
2900 if (($params = $this->parseArrowParameters()) !== null) {
2901
2902 if ($this->scanner->noLineTerminators() &&
2903 $this->scanner->consume("=>")
2904 ) {
2905
2906 if ($body = $this->parseConciseBody((bool) $async)) {
2907 if (is_array($params)) {
2908 $pos = $params[1];
2909 $params = $params[0];
2910 } else {
2911 $pos = $params;
2912 $params = array($params);
2913 }
2914 if ($async) {
2915 $pos = $async;
2916 }
2917 $node = $this->createNode("ArrowFunctionExpression", $pos);
2918 $node->setParams($params);
2919 $node->setBody($body[0]);
2920 $node->setExpression($body[1]);
2921 $node->setAsync((bool) $async);
2922 return $this->completeNode($node);
2923 }
2924
2925 $this->error();
2926 }
2927 }
2928 $this->scanner->setState($state);
2929 return null;
2930 }
2931
2932 /**
2933 * Parses an object literal
2934 *
2935 * @return Node\ObjectExpression|null
2936 */
2937 protected function parseObjectLiteral()
2938 {
2939 if ($token = $this->scanner->consume("{")) {
2940
2941 $properties = array();
2942 while ($prop = $this->parsePropertyDefinition()) {
2943 $properties[] = $prop;
2944 if (!$this->scanner->consume(",")) {
2945 break;
2946 }
2947 }
2948
2949 if ($this->scanner->consume("}")) {
2950
2951 $node = $this->createNode("ObjectExpression", $token);
2952 if ($properties) {
2953 $node->setProperties($properties);
2954 }
2955 return $this->completeNode($node);
2956 }
2957
2958 $this->error();
2959 }
2960 return null;
2961 }
2962
2963 /**
2964 * Parses a property in an object literal
2965 *
2966 * @return Node\Property|null
2967 */
2968 protected function parsePropertyDefinition()
2969 {
2970 if ($this->features->restSpreadProperties &&
2971 ($prop = $this->parseSpreadElement())) {
2972 return $prop;
2973 }
2974
2975 $state = $this->scanner->getState();
2976 if (($property = $this->parsePropertyName()) &&
2977 $this->scanner->consume(":")
2978 ) {
2979 $value = $this->isolateContext(
2980 array("allowIn" => true), "parseAssignmentExpression"
2981 );
2982 if ($value) {
2983 $startPos = isset($property[2]) ? $property[2] : $property[0];
2984 $node = $this->createNode("Property", $startPos);
2985 $node->setKey($property[0]);
2986 $node->setValue($value);
2987 $node->setComputed($property[1]);
2988 return $this->completeNode($node);
2989 }
2990
2991 $this->error();
2992
2993 }
2994
2995 $this->scanner->setState($state);
2996 if ($property = $this->parseMethodDefinition()) {
2997
2998 $node = $this->createNode("Property", $property);
2999 $node->setKey($property->getKey());
3000 $node->setValue($property->getValue());
3001 $node->setComputed($property->getComputed());
3002 $kind = $property->getKind();
3003 if ($kind !== Node\MethodDefinition::KIND_GET &&
3004 $kind !== Node\MethodDefinition::KIND_SET
3005 ) {
3006 $node->setMethod(true);
3007 $node->setKind(Node\Property::KIND_INIT);
3008 } else {
3009 $node->setKind($kind);
3010 }
3011 return $this->completeNode($node);
3012
3013 } elseif ($key = $this->parseIdentifier(static::$identifierReference)) {
3014
3015 $node = $this->createNode("Property", $key);
3016 $node->setShorthand(true);
3017 $node->setKey($key);
3018 $value = $this->isolateContext(
3019 array("allowIn" => true), "parseInitializer"
3020 );
3021 $node->setValue($value ?: $key);
3022 return $this->completeNode($node);
3023
3024 }
3025 return null;
3026 }
3027
3028 /**
3029 * Parses an initializer
3030 *
3031 * @return Node\Node|null
3032 */
3033 protected function parseInitializer()
3034 {
3035 if ($this->scanner->consume("=")) {
3036
3037 if ($value = $this->parseAssignmentExpression()) {
3038 return $value;
3039 }
3040
3041 $this->error();
3042 }
3043 return null;
3044 }
3045
3046 /**
3047 * Parses an object binding pattern
3048 *
3049 * @return Node\ObjectPattern|null
3050 */
3051 protected function parseObjectBindingPattern()
3052 {
3053 $state = $this->scanner->getState();
3054 if ($token = $this->scanner->consume("{")) {
3055
3056 $properties = array();
3057 while ($prop = $this->parseBindingProperty()) {
3058 $properties[] = $prop;
3059 if (!$this->scanner->consume(",")) {
3060 break;
3061 }
3062 }
3063
3064 if ($this->features->restSpreadProperties &&
3065 ($rest = $this->parseRestProperty())) {
3066 $properties[] = $rest;
3067 }
3068
3069 if ($this->scanner->consume("}")) {
3070 $node = $this->createNode("ObjectPattern", $token);
3071 if ($properties) {
3072 $node->setProperties($properties);
3073 }
3074 return $this->completeNode($node);
3075 }
3076
3077 $this->scanner->setState($state);
3078 }
3079 return null;
3080 }
3081
3082 /**
3083 * Parses a rest property
3084 *
3085 * @return Node\RestElement|null
3086 */
3087 protected function parseRestProperty()
3088 {
3089 $state = $this->scanner->getState();
3090 if ($token = $this->scanner->consume("...")) {
3091
3092 if ($argument = $this->parseIdentifier(static::$bindingIdentifier)) {
3093 $node = $this->createNode("RestElement", $token);
3094 $node->setArgument($argument);
3095 return $this->completeNode($node);
3096 }
3097
3098 $this->scanner->setState($state);
3099 }
3100 return null;
3101 }
3102
3103 /**
3104 * Parses a property in an object binding pattern
3105 *
3106 * @return Node\AssignmentProperty|null
3107 */
3108 protected function parseBindingProperty()
3109 {
3110 $state = $this->scanner->getState();
3111 if (($key = $this->parsePropertyName()) &&
3112 $this->scanner->consume(":")
3113 ) {
3114
3115 if ($value = $this->parseBindingElement()) {
3116 $startPos = isset($key[2]) ? $key[2] : $key[0];
3117 $node = $this->createNode("AssignmentProperty", $startPos);
3118 $node->setKey($key[0]);
3119 $node->setComputed($key[1]);
3120 $node->setValue($value);
3121 return $this->completeNode($node);
3122 }
3123
3124 $this->scanner->setState($state);
3125 return null;
3126 }
3127
3128 $this->scanner->setState($state);
3129 if ($property = $this->parseSingleNameBinding()) {
3130
3131 $node = $this->createNode("AssignmentProperty", $property);
3132 $node->setShorthand(true);
3133 if ($property instanceof Node\AssignmentPattern) {
3134 $node->setKey($property->getLeft());
3135 } else {
3136 $node->setKey($property);
3137 }
3138 $node->setValue($property);
3139 return $this->completeNode($node);
3140 }
3141 return null;
3142 }
3143
3144 /**
3145 * Parses an expression
3146 *
3147 * @return Node\Node|null
3148 */
3149 protected function parseExpression()
3150 {
3151 $list = $this->charSeparatedListOf("parseAssignmentExpression");
3152
3153 if (!$list) {
3154 return null;
3155 } elseif (count($list) === 1) {
3156 return $list[0];
3157 } else {
3158 $node = $this->createNode("SequenceExpression", $list);
3159 $node->setExpressions($list);
3160 return $this->completeNode($node);
3161 }
3162 }
3163
3164 /**
3165 * Parses an assignment expression
3166 *
3167 * @return Node\Node|null
3168 */
3169 protected function parseAssignmentExpression()
3170 {
3171 if ($expr = $this->parseArrowFunction()) {
3172 return $expr;
3173 } elseif ($this->context->allowYield && $expr = $this->parseYieldExpression()) {
3174 return $expr;
3175 } elseif ($expr = $this->parseConditionalExpression()) {
3176
3177 $exprTypes = array(
3178 "ConditionalExpression", "LogicalExpression",
3179 "BinaryExpression", "UpdateExpression", "UnaryExpression"
3180 );
3181
3182 if (!in_array($expr->getType(), $exprTypes)) {
3183
3184 $operators = $this->assignmentOperators;
3185 if ($operator = $this->scanner->consumeOneOf($operators)) {
3186
3187 if ($expr->getType() === "ChainExpression") {
3188 $this->error(
3189 "Optional chain can't appear in left-hand side"
3190 );
3191 }
3192
3193 $right = $this->parseAssignmentExpression();
3194
3195 if ($right) {
3196 $node = $this->createNode(
3197 "AssignmentExpression", $expr
3198 );
3199 $node->setLeft($this->expressionToPattern($expr));
3200 $node->setOperator($operator->value);
3201 $node->setRight($right);
3202 return $this->completeNode($node);
3203 }
3204 $this->error();
3205 }
3206 }
3207 return $expr;
3208 }
3209 return null;
3210 }
3211
3212 /**
3213 * Parses a conditional expression
3214 *
3215 * @return Node\Node|null
3216 */
3217 protected function parseConditionalExpression()
3218 {
3219 if ($test = $this->parseLogicalBinaryExpression()) {
3220
3221 if ($this->scanner->consume("?")) {
3222
3223 $consequent = $this->isolateContext(
3224 array("allowIn" => true), "parseAssignmentExpression"
3225 );
3226 if ($consequent && $this->scanner->consume(":") &&
3227 $alternate = $this->parseAssignmentExpression()
3228 ) {
3229
3230 $node = $this->createNode("ConditionalExpression", $test);
3231 $node->setTest($test);
3232 $node->setConsequent($consequent);
3233 $node->setAlternate($alternate);
3234 return $this->completeNode($node);
3235 }
3236
3237 $this->error();
3238 } else {
3239 return $test;
3240 }
3241 }
3242 return null;
3243 }
3244
3245 /**
3246 * Parses a logical or a binary expression
3247 *
3248 * @return Node\Node|null
3249 */
3250 protected function parseLogicalBinaryExpression()
3251 {
3252 $operators = $this->logicalBinaryOperators;
3253 if (!$this->context->allowIn) {
3254 unset($operators["in"]);
3255 }
3256
3257 if (!($exp = $this->parseUnaryExpression())) {
3258 if (
3259 !$this->features->classFieldsPrivateIn ||
3260 !$this->context->allowIn
3261 ) {
3262 return null;
3263 }
3264 //Support "#private in x" syntax
3265 $state = $this->scanner->getState();
3266 if (
3267 !($exp = $this->parsePrivateIdentifier()) ||
3268 !$this->scanner->isBefore(array("in"))
3269 ) {
3270 if ($exp) {
3271 $this->scanner->setState($state);
3272 }
3273 return null;
3274 }
3275 }
3276
3277 $list = array($exp);
3278 $coalescingFound = $andOrFound = false;
3279 while ($token = $this->scanner->consumeOneOf(array_keys($operators))) {
3280 $op = $token->value;
3281 // Coalescing and logical expressions can't be used together
3282 if ($op === "??") {
3283 $coalescingFound = true;
3284 } elseif ($op === "&&" || $op === "||") {
3285 $andOrFound = true;
3286 }
3287 if ($coalescingFound && $andOrFound) {
3288 $this->error(
3289 "Logical expressions must be wrapped in parentheses when " .
3290 "inside coalesce expressions"
3291 );
3292 }
3293 if (!($exp = $this->parseUnaryExpression())) {
3294 $this->error();
3295 }
3296 $list[] = $op;
3297 $list[] = $exp;
3298 }
3299
3300 $len = count($list);
3301 if ($len > 1) {
3302 $maxGrade = max($operators);
3303 for ($grade = $maxGrade; $grade >= 0; $grade--) {
3304 $class = $grade < 2 ? "LogicalExpression" : "BinaryExpression";
3305 $r2l = $grade === 10;
3306 //Exponentiation operator must be parsed right to left
3307 if ($r2l) {
3308 $i = $len - 2;
3309 $step = -2;
3310 } else {
3311 $i = 1;
3312 $step = 2;
3313 }
3314 for (; ($r2l && $i > 0) || (!$r2l && $i < $len); $i += $step) {
3315 if ($operators[$list[$i]] === $grade) {
3316 $node = $this->createNode($class, $list[$i - 1]);
3317 $node->setLeft($list[$i - 1]);
3318 $node->setOperator($list[$i]);
3319 $node->setRight($list[$i + 1]);
3320 $node = $this->completeNode(
3321 $node, $list[$i + 1]->location->end
3322 );
3323 array_splice($list, $i - 1, 3, array($node));
3324 if (!$r2l) {
3325 $i -= $step;
3326 }
3327 $len = count($list);
3328 }
3329 }
3330 }
3331 }
3332 return $list[0];
3333 }
3334
3335 /**
3336 * Parses a unary expression
3337 *
3338 * @return Node\Node|null
3339 */
3340 protected function parseUnaryExpression()
3341 {
3342 $operators = $this->unaryOperators;
3343 if ($this->features->asyncAwait && $this->context->allowAwait) {
3344 $operators[] = "await";
3345 }
3346 if ($expr = $this->parsePostfixExpression()) {
3347 return $expr;
3348 } elseif ($token = $this->scanner->consumeOneOf($operators)) {
3349 if ($argument = $this->parseUnaryExpression()) {
3350
3351 $op = $token->value;
3352
3353 //Deleting a variable without accessing its properties is a
3354 //syntax error in strict mode
3355 if ($op === "delete" &&
3356 $this->scanner->getStrictMode() &&
3357 $argument instanceof Node\Identifier) {
3358 $this->error(
3359 "Deleting an unqualified identifier is not allowed in strict mode"
3360 );
3361 }
3362
3363 if ($this->features->asyncAwait && $op === "await") {
3364 $node = $this->createNode("AwaitExpression", $token);
3365 } else {
3366 if ($op === "++" || $op === "--") {
3367 if ($argument->getType() === "ChainExpression") {
3368 $this->error(
3369 "Optional chain can't appear in left-hand side"
3370 );
3371 }
3372 $node = $this->createNode("UpdateExpression", $token);
3373 $node->setPrefix(true);
3374 } else {
3375 $node = $this->createNode("UnaryExpression", $token);
3376 }
3377 $node->setOperator($op);
3378 }
3379 $node->setArgument($argument);
3380 return $this->completeNode($node);
3381 }
3382
3383 $this->error();
3384 }
3385 return null;
3386 }
3387
3388 /**
3389 * Parses a postfix expression
3390 *
3391 * @return Node\Node|null
3392 */
3393 protected function parsePostfixExpression()
3394 {
3395 if ($argument = $this->parseLeftHandSideExpression()) {
3396
3397 if ($this->scanner->noLineTerminators() &&
3398 $token = $this->scanner->consumeOneOf($this->postfixOperators)
3399 ) {
3400
3401 if ($argument->getType() === "ChainExpression") {
3402 $this->error(
3403 "Optional chain can't appear in left-hand side"
3404 );
3405 }
3406
3407 $node = $this->createNode("UpdateExpression", $argument);
3408 $node->setOperator($token->value);
3409 $node->setArgument($argument);
3410 return $this->completeNode($node);
3411 }
3412
3413 return $argument;
3414 }
3415 return null;
3416 }
3417
3418 /**
3419 * Parses a left hand side expression
3420 *
3421 * @return Node\Node|null
3422 */
3423 protected function parseLeftHandSideExpression()
3424 {
3425 $object = null;
3426 $newTokens = array();
3427
3428 //Parse all occurrences of "new"
3429 if ($this->scanner->isBefore(array("new"))) {
3430 while ($newToken = $this->scanner->consume("new")) {
3431 if ($this->scanner->consume(".")) {
3432 //new.target
3433 if (!$this->scanner->consume("target")) {
3434 $this->error();
3435 }
3436 $node = $this->createNode("MetaProperty", $newToken);
3437 $node->setMeta("new");
3438 $node->setProperty("target");
3439 $object = $this->completeNode($node);
3440 break;
3441 }
3442 $newTokens[] = $newToken;
3443 }
3444 } elseif ($this->features->importMeta &&
3445 $this->sourceType === \Peast\Peast::SOURCE_TYPE_MODULE &&
3446 $this->scanner->isBefore(array(array("import", ".")), true)
3447 ) {
3448 //import.meta
3449 $importToken = $this->scanner->consume("import");
3450 $this->scanner->consume(".");
3451 if (!$this->scanner->consume("meta")) {
3452 $this->error();
3453 }
3454 $node = $this->createNode("MetaProperty", $importToken);
3455 $node->setMeta("import");
3456 $node->setProperty("meta");
3457 $object = $this->completeNode($node);
3458 }
3459
3460 $newTokensCount = count($newTokens);
3461
3462 if (!$object &&
3463 !($object = $this->parseSuperPropertyOrCall()) &&
3464 !($this->features->dynamicImport &&
3465 ($object = $this->parseImportCall())
3466 ) &&
3467 !($object = $this->parsePrimaryExpression())
3468 ) {
3469
3470 if ($newTokensCount) {
3471 $this->error();
3472 }
3473 return null;
3474 }
3475
3476 $valid = true;
3477 $optionalChain = false;
3478 $properties = array();
3479 while (true) {
3480 $optional = false;
3481 if ($opToken = $this->scanner->consumeOneOf(array("?.", "."))) {
3482 $isOptChain = $opToken->value == "?.";
3483 if ($isOptChain) {
3484 $optionalChain = $optional = true;
3485 }
3486 if (
3487 ($this->features->privateMethodsAndFields && ($property = $this->parsePrivateIdentifier())) ||
3488 ($property = $this->parseIdentifier(static::$identifierName))
3489 ) {
3490 $valid = true;
3491 $properties[] = array(
3492 "type"=> "id",
3493 "info" => $property,
3494 "optional" => $optional
3495 );
3496 continue;
3497 } else {
3498 $valid = false;
3499 if (!$isOptChain) {
3500 break;
3501 }
3502 }
3503 }
3504 if ($this->scanner->consume("[")) {
3505 if (($property = $this->isolateContext(
3506 array("allowIn" => true), "parseExpression"
3507 )) &&
3508 $this->scanner->consume("]")
3509 ) {
3510 $valid = true;
3511 $properties[] = array(
3512 "type" => "computed",
3513 "info" => array(
3514 $property, $this->scanner->getPosition()
3515 ),
3516 "optional" => $optional
3517 );
3518 } else {
3519 $valid = false;
3520 break;
3521 }
3522 } elseif ($property = $this->parseTemplateLiteral(true)) {
3523 if ($optionalChain) {
3524 $this->error(
3525 "Optional chain can't appear in tagged template expressions"
3526 );
3527 }
3528 $valid = true;
3529 $properties[] = array(
3530 "type"=> "template",
3531 "info" => $property,
3532 "optional" => $optional
3533 );
3534 } elseif (($args = $this->parseArguments()) !== null) {
3535 $valid = true;
3536 $properties[] = array(
3537 "type"=> "args",
3538 "info" => array($args, $this->scanner->getPosition()),
3539 "optional" => $optional
3540 );
3541 } else {
3542 break;
3543 }
3544 }
3545
3546 $propCount = count($properties);
3547
3548 if (!$valid) {
3549 $this->error();
3550 } elseif (!$propCount && !$newTokensCount) {
3551 return $object;
3552 }
3553
3554 $node = null;
3555 $endPos = $object->location->end;
3556 $optionalChainStarted = false;
3557 foreach ($properties as $i => $property) {
3558 $lastNode = $node ?: $object;
3559 if ($property["optional"]) {
3560 $optionalChainStarted = true;
3561 }
3562 if ($property["type"] === "args") {
3563 if ($newTokensCount) {
3564 if ($optionalChainStarted) {
3565 $this->error(
3566 "Optional chain can't appear in new expressions"
3567 );
3568 }
3569 $node = $this->createNode(
3570 "NewExpression", array_pop($newTokens)
3571 );
3572 $newTokensCount--;
3573 } else {
3574 $node = $this->createNode("CallExpression", $lastNode);
3575 $node->setOptional($property["optional"]);
3576 }
3577 $node->setCallee($lastNode);
3578 $node->setArguments($property["info"][0]);
3579 $endPos = $property["info"][1];
3580 } elseif ($property["type"] === "id") {
3581 $node = $this->createNode("MemberExpression", $lastNode);
3582 $node->setObject($lastNode);
3583 $node->setOptional($property["optional"]);
3584 $node->setProperty($property["info"]);
3585 $endPos = $property["info"]->location->end;
3586 } elseif ($property["type"] === "computed") {
3587 $node = $this->createNode("MemberExpression", $lastNode);
3588 $node->setObject($lastNode);
3589 $node->setProperty($property["info"][0]);
3590 $node->setOptional($property["optional"]);
3591 $node->setComputed(true);
3592 $endPos = $property["info"][1];
3593 } elseif ($property["type"] === "template") {
3594 $node = $this->createNode("TaggedTemplateExpression", $object);
3595 $node->setTag($lastNode);
3596 $node->setQuasi($property["info"]);
3597 $endPos = $property["info"]->location->end;
3598 }
3599 $node = $this->completeNode($node, $endPos);
3600 }
3601
3602 //Wrap the result in multiple NewExpression if there are "new" tokens
3603 if ($newTokensCount) {
3604 for ($i = $newTokensCount - 1; $i >= 0; $i--) {
3605 $lastNode = $node ?: $object;
3606 $node = $this->createNode("NewExpression", $newTokens[$i]);
3607 $node->setCallee($lastNode);
3608 $node = $this->completeNode($node);
3609 }
3610 }
3611
3612 //Wrap the result in a chain expression if required
3613 if ($optionalChain) {
3614 $prevNode = $node;
3615 $node = $this->createNode("ChainExpression", $prevNode);
3616 $node->setExpression($prevNode);
3617 $node = $this->completeNode($node);
3618 }
3619
3620 return $node;
3621 }
3622
3623 /**
3624 * Parses a spread element
3625 *
3626 * @return Node\SpreadElement|null
3627 */
3628 protected function parseSpreadElement()
3629 {
3630 if ($token = $this->scanner->consume("...")) {
3631
3632 $argument = $this->isolateContext(
3633 array("allowIn" => true), "parseAssignmentExpression"
3634 );
3635 if ($argument) {
3636 $node = $this->createNode("SpreadElement", $token);
3637 $node->setArgument($argument);
3638 return $this->completeNode($node);
3639 }
3640
3641 $this->error();
3642 }
3643 return null;
3644 }
3645
3646 /**
3647 * Parses an array literal
3648 *
3649 * @return Node\ArrayExpression|null
3650 */
3651 protected function parseArrayLiteral()
3652 {
3653 if ($token = $this->scanner->consume("[")) {
3654
3655 $elements = array();
3656 while (true) {
3657 if ($elision = $this->parseElision()) {
3658 $elements = array_merge(
3659 $elements, array_fill(0, $elision, null)
3660 );
3661 }
3662 if (($element = $this->parseSpreadElement()) ||
3663 ($element = $this->isolateContext(
3664 array("allowIn" => true), "parseAssignmentExpression"
3665 ))
3666 ) {
3667 $elements[] = $element;
3668 if (!$this->scanner->consume(",")) {
3669 break;
3670 }
3671 } else {
3672 break;
3673 }
3674 }
3675
3676 if ($this->scanner->consume("]")) {
3677 $node = $this->createNode("ArrayExpression", $token);
3678 $node->setElements($elements);
3679 return $this->completeNode($node);
3680 }
3681
3682 $this->error();
3683 }
3684 return null;
3685 }
3686
3687 /**
3688 * Parses an arguments list wrapped in round brackets
3689 *
3690 * @return array|null
3691 */
3692 protected function parseArguments()
3693 {
3694 if ($this->scanner->consume("(")) {
3695
3696 if (($args = $this->parseArgumentList()) !== null &&
3697 $this->scanner->consume(")")
3698 ) {
3699 return $args;
3700 }
3701
3702 $this->error();
3703 }
3704 return null;
3705 }
3706
3707 /**
3708 * Parses an arguments list
3709 *
3710 * @return array|null
3711 */
3712 protected function parseArgumentList()
3713 {
3714 $list = array();
3715 $hasComma = false;
3716 while (true) {
3717 $spread = $this->scanner->consume("...");
3718 $exp = $this->isolateContext(
3719 array("allowIn" => true), "parseAssignmentExpression"
3720 );
3721
3722 if (!$exp) {
3723 //If there's no expression and the spread dots have been found
3724 //or there is a trailing comma that is not allowed, throw an
3725 //error
3726 if ($spread ||
3727 ($hasComma &&
3728 !$this->features->trailingCommaFunctionCallDeclaration)) {
3729 $this->error();
3730 }
3731 break;
3732 }
3733
3734 if ($spread) {
3735 $node = $this->createNode("SpreadElement", $spread);
3736 $node->setArgument($exp);
3737 $list[] = $this->completeNode($node);
3738 } else {
3739 $list[] = $exp;
3740 }
3741
3742 if (!$this->scanner->consume(",")) {
3743 break;
3744 }
3745 $hasComma = true;
3746 }
3747 return $list;
3748 }
3749
3750 /**
3751 * Parses a super call or a super property
3752 *
3753 * @return Node\Node|null
3754 */
3755 protected function parseSuperPropertyOrCall()
3756 {
3757 if ($token = $this->scanner->consume("super")) {
3758
3759 $super = $this->completeNode($this->createNode("Super", $token));
3760
3761 if (($args = $this->parseArguments()) !== null) {
3762 $node = $this->createNode("CallExpression", $token);
3763 $node->setArguments($args);
3764 $node->setCallee($super);
3765 return $this->completeNode($node);
3766 }
3767
3768 $node = $this->createNode("MemberExpression", $token);
3769 $node->setObject($super);
3770
3771 if ($this->scanner->consume(".")) {
3772
3773 if ($property = $this->parseIdentifier(static::$identifierName)) {
3774 $node->setProperty($property);
3775 return $this->completeNode($node);
3776 }
3777 } elseif ($this->scanner->consume("[") &&
3778 ($property = $this->isolateContext(
3779 array("allowIn" => true), "parseExpression"
3780 )) &&
3781 $this->scanner->consume("]")
3782 ) {
3783
3784 $node->setProperty($property);
3785 $node->setComputed(true);
3786 return $this->completeNode($node);
3787 }
3788
3789 $this->error();
3790 }
3791 return null;
3792 }
3793
3794 /**
3795 * Parses a primary expression
3796 *
3797 * @return Node\Node|null
3798 */
3799 protected function parsePrimaryExpression()
3800 {
3801 if ($token = $this->scanner->consume("this")) {
3802 $node = $this->createNode("ThisExpression", $token);
3803 return $this->completeNode($node);
3804 } elseif ($exp = $this->parseFunctionOrGeneratorExpression()) {
3805 return $exp;
3806 } elseif ($exp = $this->parseClassExpression()) {
3807 return $exp;
3808 } elseif ($exp = $this->parseIdentifier(static::$identifierReference)) {
3809 return $exp;
3810 } elseif ($exp = $this->parseLiteral()) {
3811 return $exp;
3812 } elseif ($exp = $this->parseArrayLiteral()) {
3813 return $exp;
3814 } elseif ($exp = $this->parseObjectLiteral()) {
3815 return $exp;
3816 } elseif ($exp = $this->parseRegularExpressionLiteral()) {
3817 return $exp;
3818 } elseif ($exp = $this->parseTemplateLiteral()) {
3819 return $exp;
3820 } elseif ($this->jsx && ($exp = $this->parseJSXFragment())) {
3821 return $exp;
3822 } elseif ($this->jsx && ($exp = $this->parseJSXElement())) {
3823 return $exp;
3824 } elseif ($token = $this->scanner->consume("(")) {
3825
3826 if (($exp = $this->isolateContext(
3827 array("allowIn" => true), "parseExpression"
3828 )) &&
3829 $this->scanner->consume(")")
3830 ) {
3831
3832 $node = $this->createNode("ParenthesizedExpression", $token);
3833 $node->setExpression($exp);
3834 return $this->completeNode($node);
3835 }
3836
3837 $this->error();
3838 }
3839 return null;
3840 }
3841
3842 /**
3843 * Parses a private identifier
3844 *
3845 * @return Node\PrivateIdentifier|null
3846 */
3847 protected function parsePrivateIdentifier()
3848 {
3849 $token = $this->scanner->getToken();
3850 if (!$token || $token->type !== Token::TYPE_PRIVATE_IDENTIFIER) {
3851 return null;
3852 }
3853 $this->scanner->consumeToken();
3854 $node = $this->createNode("PrivateIdentifier", $token);
3855 $node->setName(substr($token->value, 1));
3856 return $this->completeNode($node);
3857 }
3858
3859 /**
3860 * Parses an identifier
3861 *
3862 * @param int $mode Parsing mode, one of the id parsing mode
3863 * constants
3864 * @param string $after If a string is passed in this parameter, the
3865 * identifier is parsed only if precedes this string
3866 *
3867 * @return Node\Identifier|null
3868 */
3869 protected function parseIdentifier($mode, $after = null)
3870 {
3871 $token = $this->scanner->getToken();
3872 if (!$token) {
3873 return null;
3874 }
3875 if ($after !== null) {
3876 $next = $this->scanner->getNextToken();
3877 if (!$next || $next->value !== $after) {
3878 return null;
3879 }
3880 }
3881 $type = $token->type;
3882 switch ($type) {
3883 case Token::TYPE_BOOLEAN_LITERAL:
3884 case Token::TYPE_NULL_LITERAL:
3885 if ($mode !== self::ID_ALLOW_ALL) {
3886 return null;
3887 }
3888 break;
3889 case Token::TYPE_KEYWORD:
3890 if ($mode === self::ID_ALLOW_NOTHING) {
3891 return null;
3892 } elseif ($mode === self::ID_MIXED &&
3893 $this->scanner->isStrictModeKeyword($token)
3894 ) {
3895 return null;
3896 }
3897 break;
3898 default:
3899 if ($type !== Token::TYPE_IDENTIFIER) {
3900 return null;
3901 }
3902 break;
3903 }
3904
3905 //Exclude keywords that depend on parser context
3906 $value = $token->value;
3907 if ($mode === self::ID_MIXED &&
3908 isset($this->contextKeywords[$value]) &&
3909 $this->context->{$this->contextKeywords[$value]}
3910 ) {
3911 return null;
3912 }
3913
3914 $this->scanner->consumeToken();
3915 $node = $this->createNode("Identifier", $token);
3916 $node->setRawName($value);
3917 return $this->completeNode($node);
3918 }
3919
3920 /**
3921 * Parses a literal
3922 *
3923 * @return Node\Literal|null
3924 */
3925 protected function parseLiteral()
3926 {
3927 if ($token = $this->scanner->getToken()) {
3928 if ($token->type === Token::TYPE_NULL_LITERAL) {
3929 $this->scanner->consumeToken();
3930 $node = $this->createNode("NullLiteral", $token);
3931 return $this->completeNode($node);
3932 } elseif ($token->type === Token::TYPE_BOOLEAN_LITERAL) {
3933 $this->scanner->consumeToken();
3934 $node = $this->createNode("BooleanLiteral", $token);
3935 $node->setRaw($token->value);
3936 return $this->completeNode($node);
3937 } elseif ($literal = $this->parseStringLiteral()) {
3938 return $literal;
3939 } elseif ($literal = $this->parseNumericLiteral()) {
3940 return $literal;
3941 }
3942 }
3943 return null;
3944 }
3945
3946 /**
3947 * Parses a string literal
3948 *
3949 * @return Node\StringLiteral|null
3950 */
3951 protected function parseStringLiteral()
3952 {
3953 $token = $this->scanner->getToken();
3954 if ($token && $token->type === Token::TYPE_STRING_LITERAL) {
3955 $val = $token->value;
3956 $this->checkInvalidEscapeSequences($val);
3957 $this->scanner->consumeToken();
3958 $node = $this->createNode("StringLiteral", $token);
3959 $node->setRaw($val);
3960 return $this->completeNode($node);
3961 }
3962 return null;
3963 }
3964
3965 /**
3966 * Parses a numeric literal
3967 *
3968 * @return Node\NumericLiteral|Node\BigIntLiteral|null
3969 */
3970 protected function parseNumericLiteral()
3971 {
3972 $token = $this->scanner->getToken();
3973 if ($token && $token->type === Token::TYPE_NUMERIC_LITERAL) {
3974 $val = $token->value;
3975 $this->checkInvalidEscapeSequences($val, true);
3976 $this->scanner->consumeToken();
3977 $node = $this->createNode("NumericLiteral", $token);
3978 $node->setRaw($val);
3979 return $this->completeNode($node);
3980 } elseif ($token && $token->type === Token::TYPE_BIGINT_LITERAL) {
3981 $val = $token->value;
3982 $this->checkInvalidEscapeSequences($val, true);
3983 $this->scanner->consumeToken();
3984 $node = $this->createNode("BigIntLiteral", $token);
3985 $node->setRaw($val);
3986 return $this->completeNode($node);
3987 }
3988 return null;
3989 }
3990
3991 /**
3992 * Parses a template literal
3993 *
3994 * @param bool $tagged True if the template is tagged
3995 *
3996 * @return Node\Literal|null
3997 */
3998 protected function parseTemplateLiteral($tagged = false)
3999 {
4000 $token = $this->scanner->getToken();
4001
4002 if (!$token || $token->type !== Token::TYPE_TEMPLATE) {
4003 return null;
4004 }
4005
4006 //Do not parse templates parts
4007 $val = $token->value;
4008 if ($val[0] !== "`") {
4009 return null;
4010 }
4011
4012 $quasis = $expressions = array();
4013 $valid = false;
4014 do {
4015 $this->scanner->consumeToken();
4016 $val = $token->value;
4017 $this->checkInvalidEscapeSequences($val, false, true, $tagged);
4018 $lastChar = substr($val, -1);
4019
4020 $quasi = $this->createNode("TemplateElement", $token);
4021 $quasi->setRawValue($val);
4022 if ($lastChar === "`") {
4023 $quasi->setTail(true);
4024 $quasis[] = $this->completeNode($quasi);
4025 $valid = true;
4026 break;
4027 } else {
4028 $quasis[] = $this->completeNode($quasi);
4029 $exp = $this->isolateContext(
4030 array("allowIn" => true), "parseExpression"
4031 );
4032 if ($exp) {
4033 $expressions[] = $exp;
4034 } else {
4035 $valid = false;
4036 break;
4037 }
4038 }
4039
4040 $token = $this->scanner->getToken();
4041 } while ($token && $token->type === Token::TYPE_TEMPLATE);
4042
4043 if ($valid) {
4044 $node = $this->createNode("TemplateLiteral", $quasis[0]);
4045 $node->setQuasis($quasis);
4046 $node->setExpressions($expressions);
4047 return $this->completeNode($node);
4048 }
4049
4050 $this->error();
4051 }
4052
4053 /**
4054 * Parses a regular expression literal
4055 *
4056 * @return Node\Literal|null
4057 */
4058 protected function parseRegularExpressionLiteral()
4059 {
4060 if ($token = $this->scanner->reconsumeCurrentTokenAsRegexp()) {
4061 $this->scanner->consumeToken();
4062 $node = $this->createNode("RegExpLiteral", $token);
4063 $node->setRaw($token->value);
4064 return $this->completeNode($node);
4065 }
4066 return null;
4067 }
4068
4069 /**
4070 * Parse directive prologues. The result is an array where the first element
4071 * is the array of parsed nodes and the second element is the array of
4072 * directive prologues values
4073 *
4074 * @return array|null
4075 */
4076 protected function parseDirectivePrologues()
4077 {
4078 $directives = $nodes = array();
4079 while (($token = $this->scanner->getToken()) &&
4080 $token->type === Token::TYPE_STRING_LITERAL
4081 ) {
4082 $directive = substr($token->value, 1, -1);
4083 if ($directive === "use strict") {
4084 $directives[] = $directive;
4085 $directiveNode = $this->parseStringLiteral();
4086 $this->assertEndOfStatement();
4087 $node = $this->createNode("ExpressionStatement", $directiveNode);
4088 $node->setExpression($directiveNode);
4089 $nodes[] = $this->completeNode($node);
4090 } else {
4091 break;
4092 }
4093 }
4094 return count($nodes) ? array($nodes, $directives) : null;
4095 }
4096
4097 /**
4098 * Parses an import call
4099 *
4100 * @return Node\Node|null
4101 */
4102 protected function parseImportCall()
4103 {
4104 if (($token = $this->scanner->consume("import")) &&
4105 $this->scanner->consume("(")) {
4106 $source = $this->isolateContext(
4107 array("allowIn" => true), "parseAssignmentExpression"
4108 );
4109 if ($source) {
4110 $options = null;
4111 if ($this->features->importAttributes &&
4112 $this->scanner->consume(",")) {
4113 $options = $this->isolateContext(
4114 array("allowIn" => true), "parseAssignmentExpression"
4115 );
4116 $this->scanner->consume(",");
4117 }
4118 if ($this->scanner->consume(")")) {
4119 $node = $this->createNode("ImportExpression", $token);
4120 $node->setSource($source);
4121 $node->setOptions($options);
4122 return $this->completeNode($node);
4123 }
4124 }
4125 $this->error();
4126 }
4127 return null;
4128 }
4129
4130 /**
4131 * Checks if the given string or number contains invalid escape sequences
4132 *
4133 * @param string $val Value to check
4134 * @param bool $number True if the value is a number
4135 * @param bool $forceLegacyOctalCheck True to force legacy octal
4136 * form check
4137 * @param bool $taggedTemplate True if the value is a tagged
4138 * template
4139 *
4140 * @return void
4141 */
4142 protected function checkInvalidEscapeSequences(
4143 $val, $number = false, $forceLegacyOctalCheck = false,
4144 $taggedTemplate = false
4145 ) {
4146 if ($this->features->skipEscapeSeqCheckInTaggedTemplates &&
4147 $taggedTemplate) {
4148 return;
4149 }
4150 $checkLegacyOctal = $forceLegacyOctalCheck || $this->scanner->getStrictMode();
4151 if ($number) {
4152 if ($val && $val[0] === "0" && preg_match("#^0[0-9_]+$#", $val)) {
4153 if ($checkLegacyOctal) {
4154 $this->error(
4155 "Octal literals are not allowed in strict mode"
4156 );
4157 }
4158 if ($this->features->numericLiteralSeparator &&
4159 strpos($val, '_') !== false
4160 ) {
4161 $this->error(
4162 "Numeric separators are not allowed in legacy octal numbers"
4163 );
4164 }
4165 }
4166 } elseif (strpos($val, "\\") !== false) {
4167 $hex = "0-9a-fA-F";
4168 $invalidSyntax = array(
4169 "x[$hex]?[^$hex]",
4170 "x[$hex]?$",
4171 "u\{\}",
4172 "u\{(?:[$hex]*[^$hex\}]+)+[$hex]*\}",
4173 "u\{[^\}]*$",
4174 "u(?!{)[$hex]{0,3}[^$hex\{]",
4175 "u[$hex]{0,3}$"
4176 );
4177 if ($checkLegacyOctal) {
4178 $invalidSyntax[] = "\d{2}";
4179 $invalidSyntax[] = "[1-7]";
4180 $invalidSyntax[] = "0[89]";
4181 }
4182 $reg = "#(\\\\+)(" . implode("|", $invalidSyntax) . ")#";
4183 if (preg_match_all($reg, $val, $matches, PREG_SET_ORDER)) {
4184 foreach ($matches as $match) {
4185 if (strlen($match[1]) % 2) {
4186 $first = $match[2][0];
4187 if ($first === "u") {
4188 $err = "Malformed unicode escape sequence";
4189 } elseif ($first === "x") {
4190 $err = "Malformed hexadecimal escape sequence";
4191 } else {
4192 $err = "Octal literals are not allowed in strict mode";
4193 }
4194 $this->error($err);
4195 }
4196 }
4197 }
4198 }
4199 }
4200 }