1 <?php declare(strict_types=1);
6 * This parser is based on a skeleton written by Moriyoshi Koizumi, which in
7 * turn is based on work by Masato Bito.
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;
25 abstract class ParserAbstract implements Parser
27 const SYMBOL_NONE = -1;
30 * The following members will be filled with generated parsing data:
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;
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;
49 protected $YY2TBLSTATE;
50 /** @var int Number of non-leaf states */
51 protected $numNonLeafStates;
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;
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. */
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;
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) */
77 /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */
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. */
82 /** @var int[] Map of non-terminals to the default state to goto after their reduction */
83 protected $gotoDefault;
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;
93 * The following members are part of the parser state:
96 /** @var Lexer Lexer that is used when parsing */
98 /** @var mixed Temporary value containing the result of last semantic action (reduction) */
100 /** @var array Semantic value stack (contains values of tokens and semantic action results) */
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;
111 /** @var ErrorHandler Error handler */
112 protected $errorHandler;
113 /** @var int Error state, used to avoid error floods */
114 protected $errorState;
117 * Initialize $reduceCallbacks map.
119 abstract protected function initReduceCallbacks();
122 * Creates a parser instance.
124 * Options: Currently none.
126 * @param Lexer $lexer A lexer
127 * @param array $options Options array.
129 public function __construct(Lexer $lexer, array $options = []) {
130 $this->lexer = $lexer;
132 if (isset($options['throwOnError'])) {
133 throw new \LogicException(
134 '"throwOnError" is no longer supported, use "errorHandler" instead');
137 $this->initReduceCallbacks();
141 * Parses PHP code into a node tree.
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.
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.
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).
153 public function parse(string $code, ErrorHandler $errorHandler = null) {
154 $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing;
156 $this->lexer->startLexing($code, $this->errorHandler);
157 $result = $this->doParse();
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;
169 protected function doParse() {
170 // We start off with no lookahead-token
171 $symbol = self::SYMBOL_NONE;
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 = [];
178 $this->endAttributes = $endAttributes;
180 // Keep stack of start and end attributes
181 $this->startAttributeStack = [];
182 $this->endAttributeStack = [$endAttributes];
184 // Start off in the initial state and keep a stack of previous states
186 $stateStack = [$state];
188 // Semantic value stack (contains values of tokens and semantic action results)
189 $this->semStack = [];
191 // Current position in the stack(s)
194 $this->errorState = 0;
197 //$this->traceNewState($state, $symbol);
199 if ($this->actionBase[$state] === 0) {
200 $rule = $this->actionDefault[$state];
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);
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;
214 if ($symbol === $this->invalidSymbol) {
215 throw new \RangeException(sprintf(
216 'The lexer returned an invalid token (id=%d, value=%s)',
217 $tokenId, $tokenValue
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;
227 //$this->traceRead($symbol);
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) {
237 * >= numNonLeafStates: shift and reduce
241 * = -YYUNEXPECTED: error
245 //$this->traceShift($symbol);
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;
255 if ($this->errorState) {
259 if ($action < $this->numNonLeafStates) {
263 /* $yyn >= numNonLeafStates means shift-and-reduce */
264 $rule = $action - $this->numNonLeafStates;
269 $rule = $this->actionDefault[$state];
276 //$this->traceAccept();
277 return $this->semValue;
278 } elseif ($rule !== $this->unexpectedTokenRule) {
280 //$this->traceReduce($rule);
283 $this->reduceCallbacks[$rule]($stackPos);
285 if (-1 === $e->getStartLine() && isset($startAttributes['startLine'])) {
286 $e->setStartLine($startAttributes['startLine']);
289 $this->emitError($e);
290 // Can't recover from this type of error
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];
302 $state = $this->gotoDefault[$nonTerminal];
306 $stateStack[$stackPos] = $state;
307 $this->semStack[$stackPos] = $this->semValue;
308 $this->endAttributeStack[$stackPos] = $lastEndAttributes;
311 switch ($this->errorState) {
313 $msg = $this->getErrorMessage($symbol, $state);
314 $this->emitError(new Error($msg, $startAttributes + $endAttributes));
315 // Break missing intentionally
318 $this->errorState = 3;
320 // Pop until error-expecting state uncovered
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
332 $state = $stateStack[--$stackPos];
333 //$this->tracePop($state);
336 //$this->traceShift($this->errorSymbol);
338 $stateStack[$stackPos] = $state = $action;
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];
348 // Reached EOF without recovering from error
352 //$this->traceDiscard($symbol);
353 $symbol = self::SYMBOL_NONE;
358 if ($state < $this->numNonLeafStates) {
362 /* >= numNonLeafStates means shift-and-reduce */
363 $rule = $state - $this->numNonLeafStates;
367 throw new \RuntimeException('Reached end of parser loop');
370 protected function emitError(Error $error) {
371 $this->errorHandler->handleError($error);
375 * Format error message including expected tokens.
377 * @param int $symbol Unexpected symbol
378 * @param int $state State at time of error
380 * @return string Formatted error message
382 protected function getErrorMessage(int $symbol, int $state) : string {
383 $expectedString = '';
384 if ($expected = $this->getExpectedTokens($state)) {
385 $expectedString = ', expecting ' . implode(' or ', $expected);
388 return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
392 * Get limited number of expected tokens in given state.
394 * @param int $state State
396 * @return string[] Expected tokens. If too many, an empty array is returned.
398 protected function getExpectedTokens(int $state) : array {
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
409 if ($this->action[$idx] !== $this->unexpectedTokenRule
410 && $this->action[$idx] !== $this->defaultAction
411 && $symbol !== $this->errorSymbol
413 if (count($expected) === 4) {
414 /* Too many expected tokens */
427 * Tracing functions used for debugging the parser.
431 protected function traceNewState($state, $symbol) {
432 echo '% State ' . $state
433 . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
436 protected function traceRead($symbol) {
437 echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
440 protected function traceShift($symbol) {
441 echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
444 protected function traceAccept() {
445 echo "% Accepted.\n";
448 protected function traceReduce($n) {
449 echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
452 protected function tracePop($state) {
453 echo '% Recovering, uncovered state ' . $state . "\n";
456 protected function traceDiscard($symbol) {
457 echo '% Discard ' . $this->symbolToName[$symbol] . "\n";
462 * Helper functions invoked by semantic actions
466 * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
468 * @param Node\Stmt[] $stmts
469 * @return Node\Stmt[]
471 protected function handleNamespaces(array $stmts) : array {
473 $style = $this->getNamespacingStyle($stmts);
474 if (null === $style) {
475 // not namespaced, nothing to do
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
493 // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
495 $targetStmts =& $resultStmts;
497 foreach ($stmts as $stmt) {
498 if ($stmt instanceof Node\Stmt\Namespace_) {
499 if ($lastNs !== null) {
500 $this->fixupNamespaceAttributes($lastNs);
502 if ($stmt->stmts === null) {
504 $targetStmts =& $stmt->stmts;
505 $resultStmts[] = $stmt;
507 // This handles the invalid case of mixed style namespaces
508 $resultStmts[] = $stmt;
509 $targetStmts =& $resultStmts;
512 } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
513 // __halt_compiler() is not moved into the namespace
514 $resultStmts[] = $stmt;
516 $targetStmts[] = $stmt;
519 if ($lastNs !== null) {
520 $this->fixupNamespaceAttributes($lastNs);
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)) {
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));
545 * Determine namespacing style (semicolon or brace)
547 * @param Node[] $stmts Top-level statements.
549 * @return null|string One of "semicolon", "brace" or null (no namespaces)
551 private function getNamespacingStyle(array $stmts) {
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
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
570 // Treat like semicolon style for namespace normalization
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) {
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)) {
588 /* Everything else if forbidden before namespace declarations */
589 $hasNotAllowedStmts = true;
595 * Fix up parsing of static property calls in PHP 5.
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 "()".
602 * @param Node\Expr\StaticPropertyFetch|Node\Expr\ArrayDimFetch $prop
603 * @param Node\Arg[] $args
604 * @param array $attributes
606 * @return Expr\StaticCall
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) {
616 while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
620 /** @var Expr\StaticPropertyFetch $staticProp */
621 $staticProp = $tmp->var;
623 // Set start attributes to attributes of innermost node
625 $this->fixupStartAttributes($tmp, $staticProp->name);
626 while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
628 $this->fixupStartAttributes($tmp, $staticProp->name);
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);
636 throw new \Exception;
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));
649 protected function handleBuiltinTypes(Name $name) {
660 if (!$name->isUnqualified()) {
664 $lowerName = $name->toLowerString();
665 if (!isset($scalarTypes[$lowerName])) {
669 return new Node\Identifier($lowerName, $name->getAttributes());
673 * Get combined start and end attributes at a stack location
675 * @param int $pos Stack location
677 * @return array Combined start and end attributes
679 protected function getAttributesAt(int $pos) : array {
680 return $this->startAttributeStack[$pos] + $this->endAttributeStack[$pos];
683 protected function parseLNumber($str, $attributes, $allowInvalidOctal = false) {
685 return LNumber::fromString($str, $attributes, $allowInvalidOctal);
686 } catch (Error $error) {
687 $this->emitError($error);
689 return new LNumber(0, $attributes);
694 * Parse a T_NUM_STRING token into either an integer or string node.
696 * @param string $str Number string
697 * @param array $attributes Attributes
699 * @return LNumber|String_ Integer or string node.
701 protected function parseNumString(string $str, array $attributes) {
702 if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) {
703 return new String_($str, $attributes);
708 return new String_($str, $attributes);
711 return new LNumber($num, $attributes);
714 protected function stripIndentation(
715 string $string, int $indentLen, string $indentChar,
716 bool $newlineAtStart, bool $newlineAtEnd, array $attributes
718 if ($indentLen === 0) {
722 $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)';
723 $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])';
724 $regex = '/' . $start . '([ \t]*)(' . $end . ')?/';
725 return preg_replace_callback(
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
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 . ')',
740 return substr($matches[0], strlen($prefix));
746 protected function parseDocString(
747 string $startToken, $contents, string $endToken,
748 array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape
750 $kind = strpos($startToken, "'") === false
751 ? String_::KIND_HEREDOC : String_::KIND_NOWDOC;
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];
758 $result = preg_match('/\A[ \t]*/', $endToken, $matches);
759 assert($result === 1);
760 $indentation = $matches[0];
762 $attributes['kind'] = $kind;
763 $attributes['docLabel'] = $label;
764 $attributes['docIndentation'] = $indentation;
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',
774 // Proceed processing as if this doc string is not indented
778 $indentLen = \strlen($indentation);
779 $indentChar = $indentHasSpaces ? " " : "\t";
781 if (\is_string($contents)) {
782 if ($contents === '') {
783 return new String_('', $attributes);
786 $contents = $this->stripIndentation(
787 $contents, $indentLen, $indentChar, true, true, $attributes
789 $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents);
791 if ($kind === String_::KIND_HEREDOC) {
792 $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape);
795 return new String_($contents, $attributes);
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()
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()
813 $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape);
815 $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value);
817 if ('' === $part->value) {
821 $newContents[] = $part;
823 return new Encapsed($newContents, $attributes);
827 protected function checkModifier($a, $b, $modifierPos) {
828 // Jumping through some hoops here because verifyModifier() is also used elsewhere
830 Class_::verifyModifier($a, $b);
831 } catch (Error $error) {
832 $error->setAttributes($this->getAttributesAt($modifierPos));
833 $this->emitError($error);
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()
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()
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()
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()
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)
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()
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()
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)
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()
916 protected function checkClassMethod(ClassMethod $node, $modifierPos) {
917 if ($node->flags & Class_::MODIFIER_STATIC) {
918 switch ($node->name->toLowerString()) {
920 $this->emitError(new Error(
921 sprintf('Constructor %s() cannot be static', $node->name),
922 $this->getAttributesAt($modifierPos)));
925 $this->emitError(new Error(
926 sprintf('Destructor %s() cannot be static', $node->name),
927 $this->getAttributesAt($modifierPos)));
930 $this->emitError(new Error(
931 sprintf('Clone method %s() cannot be static', $node->name),
932 $this->getAttributesAt($modifierPos)));
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)));
944 if ($node->flags & Class_::MODIFIER_ABSTRACT) {
945 $this->emitError(new Error(
946 "Cannot use 'abstract' as constant modifier",
947 $this->getAttributesAt($modifierPos)));
949 if ($node->flags & Class_::MODIFIER_FINAL) {
950 $this->emitError(new Error(
951 "Cannot use 'final' as constant modifier",
952 $this->getAttributesAt($modifierPos)));
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)));
962 if ($node->flags & Class_::MODIFIER_FINAL) {
963 $this->emitError(new Error('Properties cannot be declared final',
964 $this->getAttributesAt($modifierPos)));
968 protected function checkUseUse(UseUse $node, $namePos) {
969 if ($node->alias && $node->alias->isSpecialClassName()) {
970 $this->emitError(new Error(
972 'Cannot use %s as %s because \'%2$s\' is a special class name',
973 $node->name, $node->alias
975 $this->getAttributesAt($namePos)