8b7bba83f51f9d99d6efade9180a18e6e2a010dd
[yaffs-website] / vendor / nikic / php-parser / lib / PhpParser / ParserAbstract.php
1 <?php declare(strict_types=1);
2
3 namespace PhpParser;
4
5 /*
6  * This parser is based on a skeleton written by Moriyoshi Koizumi, which in
7  * turn is based on work by Masato Bito.
8  */
9 use PhpParser\Node\Expr;
10 use PhpParser\Node\Name;
11 use PhpParser\Node\Param;
12 use PhpParser\Node\Scalar\Encapsed;
13 use PhpParser\Node\Scalar\LNumber;
14 use PhpParser\Node\Scalar\String_;
15 use PhpParser\Node\Stmt\Class_;
16 use PhpParser\Node\Stmt\ClassConst;
17 use PhpParser\Node\Stmt\ClassMethod;
18 use PhpParser\Node\Stmt\Interface_;
19 use PhpParser\Node\Stmt\Namespace_;
20 use PhpParser\Node\Stmt\Property;
21 use PhpParser\Node\Stmt\TryCatch;
22 use PhpParser\Node\Stmt\UseUse;
23 use PhpParser\Node\VarLikeIdentifier;
24
25 abstract class ParserAbstract implements Parser
26 {
27     const SYMBOL_NONE = -1;
28
29     /*
30      * The following members will be filled with generated parsing data:
31      */
32
33     /** @var int Size of $tokenToSymbol map */
34     protected $tokenToSymbolMapSize;
35     /** @var int Size of $action table */
36     protected $actionTableSize;
37     /** @var int Size of $goto table */
38     protected $gotoTableSize;
39
40     /** @var int Symbol number signifying an invalid token */
41     protected $invalidSymbol;
42     /** @var int Symbol number of error recovery token */
43     protected $errorSymbol;
44     /** @var int Action number signifying default action */
45     protected $defaultAction;
46     /** @var int Rule number signifying that an unexpected token was encountered */
47     protected $unexpectedTokenRule;
48
49     protected $YY2TBLSTATE;
50     /** @var int Number of non-leaf states */
51     protected $numNonLeafStates;
52
53     /** @var int[] Map of lexer tokens to internal symbols */
54     protected $tokenToSymbol;
55     /** @var string[] Map of symbols to their names */
56     protected $symbolToName;
57     /** @var array Names of the production rules (only necessary for debugging) */
58     protected $productions;
59
60     /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this
61      *             state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
62                    action is defaulted, i.e. $actionDefault[$state] should be used instead. */
63     protected $actionBase;
64     /** @var int[] Table of actions. Indexed according to $actionBase comment. */
65     protected $action;
66     /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
67      *             then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
68     protected $actionCheck;
69     /** @var int[] Map of states to their default action */
70     protected $actionDefault;
71     /** @var callable[] Semantic action callbacks */
72     protected $reduceCallbacks;
73
74     /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
75      *             non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
76     protected $gotoBase;
77     /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */
78     protected $goto;
79     /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
80      *             then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
81     protected $gotoCheck;
82     /** @var int[] Map of non-terminals to the default state to goto after their reduction */
83     protected $gotoDefault;
84
85     /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
86      *             determining the state to goto after reduction. */
87     protected $ruleToNonTerminal;
88     /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to
89      *             be popped from the stack(s) on reduction. */
90     protected $ruleToLength;
91
92     /*
93      * The following members are part of the parser state:
94      */
95
96     /** @var Lexer Lexer that is used when parsing */
97     protected $lexer;
98     /** @var mixed Temporary value containing the result of last semantic action (reduction) */
99     protected $semValue;
100     /** @var array Semantic value stack (contains values of tokens and semantic action results) */
101     protected $semStack;
102     /** @var array[] Start attribute stack */
103     protected $startAttributeStack;
104     /** @var array[] End attribute stack */
105     protected $endAttributeStack;
106     /** @var array End attributes of last *shifted* token */
107     protected $endAttributes;
108     /** @var array Start attributes of last *read* token */
109     protected $lookaheadStartAttributes;
110
111     /** @var ErrorHandler Error handler */
112     protected $errorHandler;
113     /** @var int Error state, used to avoid error floods */
114     protected $errorState;
115
116     /**
117      * Initialize $reduceCallbacks map.
118      */
119     abstract protected function initReduceCallbacks();
120
121     /**
122      * Creates a parser instance.
123      *
124      * Options: Currently none.
125      *
126      * @param Lexer $lexer A lexer
127      * @param array $options Options array.
128      */
129     public function __construct(Lexer $lexer, array $options = []) {
130         $this->lexer = $lexer;
131
132         if (isset($options['throwOnError'])) {
133             throw new \LogicException(
134                 '"throwOnError" is no longer supported, use "errorHandler" instead');
135         }
136
137         $this->initReduceCallbacks();
138     }
139
140     /**
141      * Parses PHP code into a node tree.
142      *
143      * If a non-throwing error handler is used, the parser will continue parsing after an error
144      * occurred and attempt to build a partial AST.
145      *
146      * @param string $code The source code to parse
147      * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults
148      *                                        to ErrorHandler\Throwing.
149      *
150      * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and
151      *                          the parser was unable to recover from an error).
152      */
153     public function parse(string $code, ErrorHandler $errorHandler = null) {
154         $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing;
155
156         $this->lexer->startLexing($code, $this->errorHandler);
157         $result = $this->doParse();
158
159         // Clear out some of the interior state, so we don't hold onto unnecessary
160         // memory between uses of the parser
161         $this->startAttributeStack = [];
162         $this->endAttributeStack = [];
163         $this->semStack = [];
164         $this->semValue = null;
165
166         return $result;
167     }
168
169     protected function doParse() {
170         // We start off with no lookahead-token
171         $symbol = self::SYMBOL_NONE;
172
173         // The attributes for a node are taken from the first and last token of the node.
174         // From the first token only the startAttributes are taken and from the last only
175         // the endAttributes. Both are merged using the array union operator (+).
176         $startAttributes = [];
177         $endAttributes = [];
178         $this->endAttributes = $endAttributes;
179
180         // Keep stack of start and end attributes
181         $this->startAttributeStack = [];
182         $this->endAttributeStack = [$endAttributes];
183
184         // Start off in the initial state and keep a stack of previous states
185         $state = 0;
186         $stateStack = [$state];
187
188         // Semantic value stack (contains values of tokens and semantic action results)
189         $this->semStack = [];
190
191         // Current position in the stack(s)
192         $stackPos = 0;
193
194         $this->errorState = 0;
195
196         for (;;) {
197             //$this->traceNewState($state, $symbol);
198
199             if ($this->actionBase[$state] === 0) {
200                 $rule = $this->actionDefault[$state];
201             } else {
202                 if ($symbol === self::SYMBOL_NONE) {
203                     // Fetch the next token id from the lexer and fetch additional info by-ref.
204                     // The end attributes are fetched into a temporary variable and only set once the token is really
205                     // shifted (not during read). Otherwise you would sometimes get off-by-one errors, when a rule is
206                     // reduced after a token was read but not yet shifted.
207                     $tokenId = $this->lexer->getNextToken($tokenValue, $startAttributes, $endAttributes);
208
209                     // map the lexer token id to the internally used symbols
210                     $symbol = $tokenId >= 0 && $tokenId < $this->tokenToSymbolMapSize
211                         ? $this->tokenToSymbol[$tokenId]
212                         : $this->invalidSymbol;
213
214                     if ($symbol === $this->invalidSymbol) {
215                         throw new \RangeException(sprintf(
216                             'The lexer returned an invalid token (id=%d, value=%s)',
217                             $tokenId, $tokenValue
218                         ));
219                     }
220
221                     // This is necessary to assign some meaningful attributes to /* empty */ productions. They'll get
222                     // the attributes of the next token, even though they don't contain it themselves.
223                     $this->startAttributeStack[$stackPos+1] = $startAttributes;
224                     $this->endAttributeStack[$stackPos+1] = $endAttributes;
225                     $this->lookaheadStartAttributes = $startAttributes;
226
227                     //$this->traceRead($symbol);
228                 }
229
230                 $idx = $this->actionBase[$state] + $symbol;
231                 if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)
232                      || ($state < $this->YY2TBLSTATE
233                          && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
234                          && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol))
235                     && ($action = $this->action[$idx]) !== $this->defaultAction) {
236                     /*
237                      * >= numNonLeafStates: shift and reduce
238                      * > 0: shift
239                      * = 0: accept
240                      * < 0: reduce
241                      * = -YYUNEXPECTED: error
242                      */
243                     if ($action > 0) {
244                         /* shift */
245                         //$this->traceShift($symbol);
246
247                         ++$stackPos;
248                         $stateStack[$stackPos] = $state = $action;
249                         $this->semStack[$stackPos] = $tokenValue;
250                         $this->startAttributeStack[$stackPos] = $startAttributes;
251                         $this->endAttributeStack[$stackPos] = $endAttributes;
252                         $this->endAttributes = $endAttributes;
253                         $symbol = self::SYMBOL_NONE;
254
255                         if ($this->errorState) {
256                             --$this->errorState;
257                         }
258
259                         if ($action < $this->numNonLeafStates) {
260                             continue;
261                         }
262
263                         /* $yyn >= numNonLeafStates means shift-and-reduce */
264                         $rule = $action - $this->numNonLeafStates;
265                     } else {
266                         $rule = -$action;
267                     }
268                 } else {
269                     $rule = $this->actionDefault[$state];
270                 }
271             }
272
273             for (;;) {
274                 if ($rule === 0) {
275                     /* accept */
276                     //$this->traceAccept();
277                     return $this->semValue;
278                 } elseif ($rule !== $this->unexpectedTokenRule) {
279                     /* reduce */
280                     //$this->traceReduce($rule);
281
282                     try {
283                         $this->reduceCallbacks[$rule]($stackPos);
284                     } catch (Error $e) {
285                         if (-1 === $e->getStartLine() && isset($startAttributes['startLine'])) {
286                             $e->setStartLine($startAttributes['startLine']);
287                         }
288
289                         $this->emitError($e);
290                         // Can't recover from this type of error
291                         return null;
292                     }
293
294                     /* Goto - shift nonterminal */
295                     $lastEndAttributes = $this->endAttributeStack[$stackPos];
296                     $stackPos -= $this->ruleToLength[$rule];
297                     $nonTerminal = $this->ruleToNonTerminal[$rule];
298                     $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos];
299                     if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) {
300                         $state = $this->goto[$idx];
301                     } else {
302                         $state = $this->gotoDefault[$nonTerminal];
303                     }
304
305                     ++$stackPos;
306                     $stateStack[$stackPos]     = $state;
307                     $this->semStack[$stackPos] = $this->semValue;
308                     $this->endAttributeStack[$stackPos] = $lastEndAttributes;
309                 } else {
310                     /* error */
311                     switch ($this->errorState) {
312                         case 0:
313                             $msg = $this->getErrorMessage($symbol, $state);
314                             $this->emitError(new Error($msg, $startAttributes + $endAttributes));
315                             // Break missing intentionally
316                         case 1:
317                         case 2:
318                             $this->errorState = 3;
319
320                             // Pop until error-expecting state uncovered
321                             while (!(
322                                 (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0
323                                     && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
324                                 || ($state < $this->YY2TBLSTATE
325                                     && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0
326                                     && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
327                             ) || ($action = $this->action[$idx]) === $this->defaultAction) { // Not totally sure about this
328                                 if ($stackPos <= 0) {
329                                     // Could not recover from error
330                                     return null;
331                                 }
332                                 $state = $stateStack[--$stackPos];
333                                 //$this->tracePop($state);
334                             }
335
336                             //$this->traceShift($this->errorSymbol);
337                             ++$stackPos;
338                             $stateStack[$stackPos] = $state = $action;
339
340                             // We treat the error symbol as being empty, so we reset the end attributes
341                             // to the end attributes of the last non-error symbol
342                             $this->endAttributeStack[$stackPos] = $this->endAttributeStack[$stackPos - 1];
343                             $this->endAttributes = $this->endAttributeStack[$stackPos - 1];
344                             break;
345
346                         case 3:
347                             if ($symbol === 0) {
348                                 // Reached EOF without recovering from error
349                                 return null;
350                             }
351
352                             //$this->traceDiscard($symbol);
353                             $symbol = self::SYMBOL_NONE;
354                             break 2;
355                     }
356                 }
357
358                 if ($state < $this->numNonLeafStates) {
359                     break;
360                 }
361
362                 /* >= numNonLeafStates means shift-and-reduce */
363                 $rule = $state - $this->numNonLeafStates;
364             }
365         }
366
367         throw new \RuntimeException('Reached end of parser loop');
368     }
369
370     protected function emitError(Error $error) {
371         $this->errorHandler->handleError($error);
372     }
373
374     /**
375      * Format error message including expected tokens.
376      *
377      * @param int $symbol Unexpected symbol
378      * @param int $state  State at time of error
379      *
380      * @return string Formatted error message
381      */
382     protected function getErrorMessage(int $symbol, int $state) : string {
383         $expectedString = '';
384         if ($expected = $this->getExpectedTokens($state)) {
385             $expectedString = ', expecting ' . implode(' or ', $expected);
386         }
387
388         return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
389     }
390
391     /**
392      * Get limited number of expected tokens in given state.
393      *
394      * @param int $state State
395      *
396      * @return string[] Expected tokens. If too many, an empty array is returned.
397      */
398     protected function getExpectedTokens(int $state) : array {
399         $expected = [];
400
401         $base = $this->actionBase[$state];
402         foreach ($this->symbolToName as $symbol => $name) {
403             $idx = $base + $symbol;
404             if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
405                 || $state < $this->YY2TBLSTATE
406                 && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
407                 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
408             ) {
409                 if ($this->action[$idx] !== $this->unexpectedTokenRule
410                     && $this->action[$idx] !== $this->defaultAction
411                     && $symbol !== $this->errorSymbol
412                 ) {
413                     if (count($expected) === 4) {
414                         /* Too many expected tokens */
415                         return [];
416                     }
417
418                     $expected[] = $name;
419                 }
420             }
421         }
422
423         return $expected;
424     }
425
426     /*
427      * Tracing functions used for debugging the parser.
428      */
429
430     /*
431     protected function traceNewState($state, $symbol) {
432         echo '% State ' . $state
433             . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
434     }
435
436     protected function traceRead($symbol) {
437         echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
438     }
439
440     protected function traceShift($symbol) {
441         echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
442     }
443
444     protected function traceAccept() {
445         echo "% Accepted.\n";
446     }
447
448     protected function traceReduce($n) {
449         echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
450     }
451
452     protected function tracePop($state) {
453         echo '% Recovering, uncovered state ' . $state . "\n";
454     }
455
456     protected function traceDiscard($symbol) {
457         echo '% Discard ' . $this->symbolToName[$symbol] . "\n";
458     }
459     */
460
461     /*
462      * Helper functions invoked by semantic actions
463      */
464
465     /**
466      * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
467      *
468      * @param Node\Stmt[] $stmts
469      * @return Node\Stmt[]
470      */
471     protected function handleNamespaces(array $stmts) : array {
472         $hasErrored = false;
473         $style = $this->getNamespacingStyle($stmts);
474         if (null === $style) {
475             // not namespaced, nothing to do
476             return $stmts;
477         } elseif ('brace' === $style) {
478             // For braced namespaces we only have to check that there are no invalid statements between the namespaces
479             $afterFirstNamespace = false;
480             foreach ($stmts as $stmt) {
481                 if ($stmt instanceof Node\Stmt\Namespace_) {
482                     $afterFirstNamespace = true;
483                 } elseif (!$stmt instanceof Node\Stmt\HaltCompiler
484                         && !$stmt instanceof Node\Stmt\Nop
485                         && $afterFirstNamespace && !$hasErrored) {
486                     $this->emitError(new Error(
487                         'No code may exist outside of namespace {}', $stmt->getAttributes()));
488                     $hasErrored = true; // Avoid one error for every statement
489                 }
490             }
491             return $stmts;
492         } else {
493             // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
494             $resultStmts = [];
495             $targetStmts =& $resultStmts;
496             $lastNs = null;
497             foreach ($stmts as $stmt) {
498                 if ($stmt instanceof Node\Stmt\Namespace_) {
499                     if ($lastNs !== null) {
500                         $this->fixupNamespaceAttributes($lastNs);
501                     }
502                     if ($stmt->stmts === null) {
503                         $stmt->stmts = [];
504                         $targetStmts =& $stmt->stmts;
505                         $resultStmts[] = $stmt;
506                     } else {
507                         // This handles the invalid case of mixed style namespaces
508                         $resultStmts[] = $stmt;
509                         $targetStmts =& $resultStmts;
510                     }
511                     $lastNs = $stmt;
512                 } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
513                     // __halt_compiler() is not moved into the namespace
514                     $resultStmts[] = $stmt;
515                 } else {
516                     $targetStmts[] = $stmt;
517                 }
518             }
519             if ($lastNs !== null) {
520                 $this->fixupNamespaceAttributes($lastNs);
521             }
522             return $resultStmts;
523         }
524     }
525
526     private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt) {
527         // We moved the statements into the namespace node, as such the end of the namespace node
528         // needs to be extended to the end of the statements.
529         if (empty($stmt->stmts)) {
530             return;
531         }
532
533         // We only move the builtin end attributes here. This is the best we can do with the
534         // knowledge we have.
535         $endAttributes = ['endLine', 'endFilePos', 'endTokenPos'];
536         $lastStmt = $stmt->stmts[count($stmt->stmts) - 1];
537         foreach ($endAttributes as $endAttribute) {
538             if ($lastStmt->hasAttribute($endAttribute)) {
539                 $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute));
540             }
541         }
542     }
543
544     /**
545      * Determine namespacing style (semicolon or brace)
546      *
547      * @param Node[] $stmts Top-level statements.
548      *
549      * @return null|string One of "semicolon", "brace" or null (no namespaces)
550      */
551     private function getNamespacingStyle(array $stmts) {
552         $style = null;
553         $hasNotAllowedStmts = false;
554         foreach ($stmts as $i => $stmt) {
555             if ($stmt instanceof Node\Stmt\Namespace_) {
556                 $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
557                 if (null === $style) {
558                     $style = $currentStyle;
559                     if ($hasNotAllowedStmts) {
560                         $this->emitError(new Error(
561                             'Namespace declaration statement has to be the very first statement in the script',
562                             $stmt->getLine() // Avoid marking the entire namespace as an error
563                         ));
564                     }
565                 } elseif ($style !== $currentStyle) {
566                     $this->emitError(new Error(
567                         'Cannot mix bracketed namespace declarations with unbracketed namespace declarations',
568                         $stmt->getLine() // Avoid marking the entire namespace as an error
569                     ));
570                     // Treat like semicolon style for namespace normalization
571                     return 'semicolon';
572                 }
573                 continue;
574             }
575
576             /* declare(), __halt_compiler() and nops can be used before a namespace declaration */
577             if ($stmt instanceof Node\Stmt\Declare_
578                 || $stmt instanceof Node\Stmt\HaltCompiler
579                 || $stmt instanceof Node\Stmt\Nop) {
580                 continue;
581             }
582
583             /* There may be a hashbang line at the very start of the file */
584             if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) {
585                 continue;
586             }
587
588             /* Everything else if forbidden before namespace declarations */
589             $hasNotAllowedStmts = true;
590         }
591         return $style;
592     }
593
594     /**
595      * Fix up parsing of static property calls in PHP 5.
596      *
597      * In PHP 5 A::$b[c][d] and A::$b[c][d]() have very different interpretation. The former is
598      * interpreted as (A::$b)[c][d], while the latter is the same as A::{$b[c][d]}(). We parse the
599      * latter as the former initially and this method fixes the AST into the correct form when we
600      * encounter the "()".
601      *
602      * @param  Node\Expr\StaticPropertyFetch|Node\Expr\ArrayDimFetch $prop
603      * @param  Node\Arg[] $args
604      * @param  array      $attributes
605      *
606      * @return Expr\StaticCall
607      */
608     protected function fixupPhp5StaticPropCall($prop, array $args, array $attributes) : Expr\StaticCall {
609         if ($prop instanceof Node\Expr\StaticPropertyFetch) {
610             $name = $prop->name instanceof VarLikeIdentifier
611                 ? $prop->name->toString() : $prop->name;
612             $var = new Expr\Variable($name, $prop->name->getAttributes());
613             return new Expr\StaticCall($prop->class, $var, $args, $attributes);
614         } elseif ($prop instanceof Node\Expr\ArrayDimFetch) {
615             $tmp = $prop;
616             while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
617                 $tmp = $tmp->var;
618             }
619
620             /** @var Expr\StaticPropertyFetch $staticProp */
621             $staticProp = $tmp->var;
622
623             // Set start attributes to attributes of innermost node
624             $tmp = $prop;
625             $this->fixupStartAttributes($tmp, $staticProp->name);
626             while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
627                 $tmp = $tmp->var;
628                 $this->fixupStartAttributes($tmp, $staticProp->name);
629             }
630
631             $name = $staticProp->name instanceof VarLikeIdentifier
632                 ? $staticProp->name->toString() : $staticProp->name;
633             $tmp->var = new Expr\Variable($name, $staticProp->name->getAttributes());
634             return new Expr\StaticCall($staticProp->class, $prop, $args, $attributes);
635         } else {
636             throw new \Exception;
637         }
638     }
639
640     protected function fixupStartAttributes(Node $to, Node $from) {
641         $startAttributes = ['startLine', 'startFilePos', 'startTokenPos'];
642         foreach ($startAttributes as $startAttribute) {
643             if ($from->hasAttribute($startAttribute)) {
644                 $to->setAttribute($startAttribute, $from->getAttribute($startAttribute));
645             }
646         }
647     }
648
649     protected function handleBuiltinTypes(Name $name) {
650         $scalarTypes = [
651             'bool'     => true,
652             'int'      => true,
653             'float'    => true,
654             'string'   => true,
655             'iterable' => true,
656             'void'     => true,
657             'object'   => true,
658         ];
659
660         if (!$name->isUnqualified()) {
661             return $name;
662         }
663
664         $lowerName = $name->toLowerString();
665         if (!isset($scalarTypes[$lowerName])) {
666             return $name;
667         }
668
669         return new Node\Identifier($lowerName, $name->getAttributes());
670     }
671
672     /**
673      * Get combined start and end attributes at a stack location
674      *
675      * @param int $pos Stack location
676      *
677      * @return array Combined start and end attributes
678      */
679     protected function getAttributesAt(int $pos) : array {
680         return $this->startAttributeStack[$pos] + $this->endAttributeStack[$pos];
681     }
682
683     protected function parseLNumber($str, $attributes, $allowInvalidOctal = false) {
684         try {
685             return LNumber::fromString($str, $attributes, $allowInvalidOctal);
686         } catch (Error $error) {
687             $this->emitError($error);
688             // Use dummy value
689             return new LNumber(0, $attributes);
690         }
691     }
692
693     /**
694      * Parse a T_NUM_STRING token into either an integer or string node.
695      *
696      * @param string $str        Number string
697      * @param array  $attributes Attributes
698      *
699      * @return LNumber|String_ Integer or string node.
700      */
701     protected function parseNumString(string $str, array $attributes) {
702         if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) {
703             return new String_($str, $attributes);
704         }
705
706         $num = +$str;
707         if (!is_int($num)) {
708             return new String_($str, $attributes);
709         }
710
711         return new LNumber($num, $attributes);
712     }
713
714     protected function stripIndentation(
715         string $string, int $indentLen, string $indentChar,
716         bool $newlineAtStart, bool $newlineAtEnd, array $attributes
717     ) {
718         if ($indentLen === 0) {
719             return $string;
720         }
721
722         $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)';
723         $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])';
724         $regex = '/' . $start . '([ \t]*)(' . $end . ')?/';
725         return preg_replace_callback(
726             $regex,
727             function ($matches) use ($indentLen, $indentChar, $attributes) {
728                 $prefix = substr($matches[1], 0, $indentLen);
729                 if (false !== strpos($prefix, $indentChar === " " ? "\t" : " ")) {
730                     $this->emitError(new Error(
731                         'Invalid indentation - tabs and spaces cannot be mixed', $attributes
732                     ));
733                 } elseif (strlen($prefix) < $indentLen && !isset($matches[2])) {
734                     $this->emitError(new Error(
735                         'Invalid body indentation level ' .
736                         '(expecting an indentation level of at least ' . $indentLen . ')',
737                         $attributes
738                     ));
739                 }
740                 return substr($matches[0], strlen($prefix));
741             },
742             $string
743         );
744     }
745
746     protected function parseDocString(
747         string $startToken, $contents, string $endToken,
748         array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape
749     ) {
750         $kind = strpos($startToken, "'") === false
751             ? String_::KIND_HEREDOC : String_::KIND_NOWDOC;
752
753         $regex = '/\A[bB]?<<<[ \t]*[\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\'"]?(?:\r\n|\n|\r)\z/';
754         $result = preg_match($regex, $startToken, $matches);
755         assert($result === 1);
756         $label = $matches[1];
757
758         $result = preg_match('/\A[ \t]*/', $endToken, $matches);
759         assert($result === 1);
760         $indentation = $matches[0];
761
762         $attributes['kind'] = $kind;
763         $attributes['docLabel'] = $label;
764         $attributes['docIndentation'] = $indentation;
765
766         $indentHasSpaces = false !== strpos($indentation, " ");
767         $indentHasTabs = false !== strpos($indentation, "\t");
768         if ($indentHasSpaces && $indentHasTabs) {
769             $this->emitError(new Error(
770                 'Invalid indentation - tabs and spaces cannot be mixed',
771                 $endTokenAttributes
772             ));
773
774             // Proceed processing as if this doc string is not indented
775             $indentation = '';
776         }
777
778         $indentLen = \strlen($indentation);
779         $indentChar = $indentHasSpaces ? " " : "\t";
780
781         if (\is_string($contents)) {
782             if ($contents === '') {
783                 return new String_('', $attributes);
784             }
785
786             $contents = $this->stripIndentation(
787                 $contents, $indentLen, $indentChar, true, true, $attributes
788             );
789             $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents);
790
791             if ($kind === String_::KIND_HEREDOC) {
792                 $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape);
793             }
794
795             return new String_($contents, $attributes);
796         } else {
797             assert(count($contents) > 0);
798             if (!$contents[0] instanceof Node\Scalar\EncapsedStringPart) {
799                 // If there is no leading encapsed string part, pretend there is an empty one
800                 $this->stripIndentation(
801                     '', $indentLen, $indentChar, true, false, $contents[0]->getAttributes()
802                 );
803             }
804
805             $newContents = [];
806             foreach ($contents as $i => $part) {
807                 if ($part instanceof Node\Scalar\EncapsedStringPart) {
808                     $isLast = $i === \count($contents) - 1;
809                     $part->value = $this->stripIndentation(
810                         $part->value, $indentLen, $indentChar,
811                         $i === 0, $isLast, $part->getAttributes()
812                     );
813                     $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape);
814                     if ($isLast) {
815                         $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value);
816                     }
817                     if ('' === $part->value) {
818                         continue;
819                     }
820                 }
821                 $newContents[] = $part;
822             }
823             return new Encapsed($newContents, $attributes);
824         }
825     }
826
827     protected function checkModifier($a, $b, $modifierPos) {
828         // Jumping through some hoops here because verifyModifier() is also used elsewhere
829         try {
830             Class_::verifyModifier($a, $b);
831         } catch (Error $error) {
832             $error->setAttributes($this->getAttributesAt($modifierPos));
833             $this->emitError($error);
834         }
835     }
836
837     protected function checkParam(Param $node) {
838         if ($node->variadic && null !== $node->default) {
839             $this->emitError(new Error(
840                 'Variadic parameter cannot have a default value',
841                 $node->default->getAttributes()
842             ));
843         }
844     }
845
846     protected function checkTryCatch(TryCatch $node) {
847         if (empty($node->catches) && null === $node->finally) {
848             $this->emitError(new Error(
849                 'Cannot use try without catch or finally', $node->getAttributes()
850             ));
851         }
852     }
853
854     protected function checkNamespace(Namespace_ $node) {
855         if ($node->name && $node->name->isSpecialClassName()) {
856             $this->emitError(new Error(
857                 sprintf('Cannot use \'%s\' as namespace name', $node->name),
858                 $node->name->getAttributes()
859             ));
860         }
861
862         if (null !== $node->stmts) {
863             foreach ($node->stmts as $stmt) {
864                 if ($stmt instanceof Namespace_) {
865                     $this->emitError(new Error(
866                         'Namespace declarations cannot be nested', $stmt->getAttributes()
867                     ));
868                 }
869             }
870         }
871     }
872
873     protected function checkClass(Class_ $node, $namePos) {
874         if (null !== $node->name && $node->name->isSpecialClassName()) {
875             $this->emitError(new Error(
876                 sprintf('Cannot use \'%s\' as class name as it is reserved', $node->name),
877                 $this->getAttributesAt($namePos)
878             ));
879         }
880
881         if ($node->extends && $node->extends->isSpecialClassName()) {
882             $this->emitError(new Error(
883                 sprintf('Cannot use \'%s\' as class name as it is reserved', $node->extends),
884                 $node->extends->getAttributes()
885             ));
886         }
887
888         foreach ($node->implements as $interface) {
889             if ($interface->isSpecialClassName()) {
890                 $this->emitError(new Error(
891                     sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
892                     $interface->getAttributes()
893                 ));
894             }
895         }
896     }
897
898     protected function checkInterface(Interface_ $node, $namePos) {
899         if (null !== $node->name && $node->name->isSpecialClassName()) {
900             $this->emitError(new Error(
901                 sprintf('Cannot use \'%s\' as class name as it is reserved', $node->name),
902                 $this->getAttributesAt($namePos)
903             ));
904         }
905
906         foreach ($node->extends as $interface) {
907             if ($interface->isSpecialClassName()) {
908                 $this->emitError(new Error(
909                     sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
910                     $interface->getAttributes()
911                 ));
912             }
913         }
914     }
915
916     protected function checkClassMethod(ClassMethod $node, $modifierPos) {
917         if ($node->flags & Class_::MODIFIER_STATIC) {
918             switch ($node->name->toLowerString()) {
919                 case '__construct':
920                     $this->emitError(new Error(
921                         sprintf('Constructor %s() cannot be static', $node->name),
922                         $this->getAttributesAt($modifierPos)));
923                     break;
924                 case '__destruct':
925                     $this->emitError(new Error(
926                         sprintf('Destructor %s() cannot be static', $node->name),
927                         $this->getAttributesAt($modifierPos)));
928                     break;
929                 case '__clone':
930                     $this->emitError(new Error(
931                         sprintf('Clone method %s() cannot be static', $node->name),
932                         $this->getAttributesAt($modifierPos)));
933                     break;
934             }
935         }
936     }
937
938     protected function checkClassConst(ClassConst $node, $modifierPos) {
939         if ($node->flags & Class_::MODIFIER_STATIC) {
940             $this->emitError(new Error(
941                 "Cannot use 'static' as constant modifier",
942                 $this->getAttributesAt($modifierPos)));
943         }
944         if ($node->flags & Class_::MODIFIER_ABSTRACT) {
945             $this->emitError(new Error(
946                 "Cannot use 'abstract' as constant modifier",
947                 $this->getAttributesAt($modifierPos)));
948         }
949         if ($node->flags & Class_::MODIFIER_FINAL) {
950             $this->emitError(new Error(
951                 "Cannot use 'final' as constant modifier",
952                 $this->getAttributesAt($modifierPos)));
953         }
954     }
955
956     protected function checkProperty(Property $node, $modifierPos) {
957         if ($node->flags & Class_::MODIFIER_ABSTRACT) {
958             $this->emitError(new Error('Properties cannot be declared abstract',
959                 $this->getAttributesAt($modifierPos)));
960         }
961
962         if ($node->flags & Class_::MODIFIER_FINAL) {
963             $this->emitError(new Error('Properties cannot be declared final',
964                 $this->getAttributesAt($modifierPos)));
965         }
966     }
967
968     protected function checkUseUse(UseUse $node, $namePos) {
969         if ($node->alias && $node->alias->isSpecialClassName()) {
970             $this->emitError(new Error(
971                 sprintf(
972                     'Cannot use %s as %s because \'%2$s\' is a special class name',
973                     $node->name, $node->alias
974                 ),
975                 $this->getAttributesAt($namePos)
976             ));
977         }
978     }
979 }