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:
10: use PhpParser\Node\Arg;
11: use PhpParser\Node\Expr;
12: use PhpParser\Node\Expr\Array_;
13: use PhpParser\Node\Expr\Cast\Double;
14: use PhpParser\Node\Identifier;
15: use PhpParser\Node\InterpolatedStringPart;
16: use PhpParser\Node\Name;
17: use PhpParser\Node\Param;
18: use PhpParser\Node\PropertyHook;
19: use PhpParser\Node\Scalar\InterpolatedString;
20: use PhpParser\Node\Scalar\Int_;
21: use PhpParser\Node\Scalar\String_;
22: use PhpParser\Node\Stmt;
23: use PhpParser\Node\Stmt\Class_;
24: use PhpParser\Node\Stmt\ClassConst;
25: use PhpParser\Node\Stmt\ClassMethod;
26: use PhpParser\Node\Stmt\Const_;
27: use PhpParser\Node\Stmt\Else_;
28: use PhpParser\Node\Stmt\ElseIf_;
29: use PhpParser\Node\Stmt\Enum_;
30: use PhpParser\Node\Stmt\Interface_;
31: use PhpParser\Node\Stmt\Namespace_;
32: use PhpParser\Node\Stmt\Nop;
33: use PhpParser\Node\Stmt\Property;
34: use PhpParser\Node\Stmt\TryCatch;
35: use PhpParser\Node\UseItem;
36: use PhpParser\Node\VarLikeIdentifier;
37: use PhpParser\NodeVisitor\CommentAnnotatingVisitor;
38:
39: abstract class ParserAbstract implements Parser {
40: private const SYMBOL_NONE = -1;
41:
42: /** @var Lexer Lexer that is used when parsing */
43: protected Lexer $lexer;
44: /** @var PhpVersion PHP version to target on a best-effort basis */
45: protected PhpVersion $phpVersion;
46:
47: /*
48: * The following members will be filled with generated parsing data:
49: */
50:
51: /** @var int Size of $tokenToSymbol map */
52: protected int $tokenToSymbolMapSize;
53: /** @var int Size of $action table */
54: protected int $actionTableSize;
55: /** @var int Size of $goto table */
56: protected int $gotoTableSize;
57:
58: /** @var int Symbol number signifying an invalid token */
59: protected int $invalidSymbol;
60: /** @var int Symbol number of error recovery token */
61: protected int $errorSymbol;
62: /** @var int Action number signifying default action */
63: protected int $defaultAction;
64: /** @var int Rule number signifying that an unexpected token was encountered */
65: protected int $unexpectedTokenRule;
66:
67: protected int $YY2TBLSTATE;
68: /** @var int Number of non-leaf states */
69: protected int $numNonLeafStates;
70:
71: /** @var int[] Map of PHP token IDs to internal symbols */
72: protected array $phpTokenToSymbol;
73: /** @var array<int, bool> Map of PHP token IDs to drop */
74: protected array $dropTokens;
75: /** @var int[] Map of external symbols (static::T_*) to internal symbols */
76: protected array $tokenToSymbol;
77: /** @var string[] Map of symbols to their names */
78: protected array $symbolToName;
79: /** @var array<int, string> Names of the production rules (only necessary for debugging) */
80: protected array $productions;
81:
82: /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this
83: * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
84: * action is defaulted, i.e. $actionDefault[$state] should be used instead. */
85: protected array $actionBase;
86: /** @var int[] Table of actions. Indexed according to $actionBase comment. */
87: protected array $action;
88: /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
89: * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
90: protected array $actionCheck;
91: /** @var int[] Map of states to their default action */
92: protected array $actionDefault;
93: /** @var callable[] Semantic action callbacks */
94: protected array $reduceCallbacks;
95:
96: /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
97: * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
98: protected array $gotoBase;
99: /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */
100: protected array $goto;
101: /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
102: * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
103: protected array $gotoCheck;
104: /** @var int[] Map of non-terminals to the default state to goto after their reduction */
105: protected array $gotoDefault;
106:
107: /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
108: * determining the state to goto after reduction. */
109: protected array $ruleToNonTerminal;
110: /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to
111: * be popped from the stack(s) on reduction. */
112: protected array $ruleToLength;
113:
114: /*
115: * The following members are part of the parser state:
116: */
117:
118: /** @var mixed Temporary value containing the result of last semantic action (reduction) */
119: protected $semValue;
120: /** @var mixed[] Semantic value stack (contains values of tokens and semantic action results) */
121: protected array $semStack;
122: /** @var int[] Token start position stack */
123: protected array $tokenStartStack;
124: /** @var int[] Token end position stack */
125: protected array $tokenEndStack;
126:
127: /** @var ErrorHandler Error handler */
128: protected ErrorHandler $errorHandler;
129: /** @var int Error state, used to avoid error floods */
130: protected int $errorState;
131:
132: /** @var \SplObjectStorage<Array_, null>|null Array nodes created during parsing, for postprocessing of empty elements. */
133: protected ?\SplObjectStorage $createdArrays;
134:
135: /** @var \SplObjectStorage<Expr\ArrowFunction, null>|null
136: * Arrow functions that are wrapped in parentheses, to enforce the pipe operator parentheses requirements.
137: */
138: protected ?\SplObjectStorage $parenthesizedArrowFunctions;
139:
140: /** @var Token[] Tokens for the current parse */
141: protected array $tokens;
142: /** @var int Current position in token array */
143: protected int $tokenPos;
144:
145: /**
146: * Initialize $reduceCallbacks map.
147: */
148: abstract protected function initReduceCallbacks(): void;
149:
150: /**
151: * Creates a parser instance.
152: *
153: * Options:
154: * * phpVersion: ?PhpVersion,
155: *
156: * @param Lexer $lexer A lexer
157: * @param PhpVersion $phpVersion PHP version to target, defaults to latest supported. This
158: * option is best-effort: Even if specified, parsing will generally assume the latest
159: * supported version and only adjust behavior in minor ways, for example by omitting
160: * errors in older versions and interpreting type hints as a name or identifier depending
161: * on version.
162: */
163: public function __construct(Lexer $lexer, ?PhpVersion $phpVersion = null) {
164: $this->lexer = $lexer;
165: $this->phpVersion = $phpVersion ?? PhpVersion::getNewestSupported();
166:
167: $this->initReduceCallbacks();
168: $this->phpTokenToSymbol = $this->createTokenMap();
169: $this->dropTokens = array_fill_keys(
170: [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], true
171: );
172: }
173:
174: /**
175: * Parses PHP code into a node tree.
176: *
177: * If a non-throwing error handler is used, the parser will continue parsing after an error
178: * occurred and attempt to build a partial AST.
179: *
180: * @param string $code The source code to parse
181: * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults
182: * to ErrorHandler\Throwing.
183: *
184: * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and
185: * the parser was unable to recover from an error).
186: */
187: public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array {
188: $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing();
189: $this->createdArrays = new \SplObjectStorage();
190: $this->parenthesizedArrowFunctions = new \SplObjectStorage();
191:
192: $this->tokens = [];
193: $this->tokens = $this->lexer->tokenize($code, $this->errorHandler);
194: $result = $this->doParse();
195:
196: // Report errors for any empty elements used inside arrays. This is delayed until after the main parse,
197: // because we don't know a priori whether a given array expression will be used in a destructuring context
198: // or not.
199: foreach ($this->createdArrays as $node) {
200: foreach ($node->items as $item) {
201: if ($item->value instanceof Expr\Error) {
202: $this->errorHandler->handleError(
203: new Error('Cannot use empty array elements in arrays', $item->getAttributes()));
204: }
205: }
206: }
207:
208: // Clear out some of the interior state, so we don't hold onto unnecessary
209: // memory between uses of the parser
210: $this->tokenStartStack = [];
211: $this->tokenEndStack = [];
212: $this->semStack = [];
213: $this->semValue = null;
214: $this->createdArrays = null;
215: $this->parenthesizedArrowFunctions = null;
216:
217: if ($result !== null) {
218: $traverser = new NodeTraverser(new CommentAnnotatingVisitor($this->tokens));
219: $traverser->traverse($result);
220: }
221:
222: return $result;
223: }
224:
225: public function getTokens(): array {
226: return $this->tokens;
227: }
228:
229: /** @return Stmt[]|null */
230: protected function doParse(): ?array {
231: // We start off with no lookahead-token
232: $symbol = self::SYMBOL_NONE;
233: $tokenValue = null;
234: $this->tokenPos = -1;
235:
236: // Keep stack of start and end attributes
237: $this->tokenStartStack = [];
238: $this->tokenEndStack = [0];
239:
240: // Start off in the initial state and keep a stack of previous states
241: $state = 0;
242: $stateStack = [$state];
243:
244: // Semantic value stack (contains values of tokens and semantic action results)
245: $this->semStack = [];
246:
247: // Current position in the stack(s)
248: $stackPos = 0;
249:
250: $this->errorState = 0;
251:
252: // Parser tables are read on every iteration: local variables are cheaper to access than properties.
253: $tokens = $this->tokens;
254: $dropTokens = $this->dropTokens;
255: $phpTokenToSymbol = $this->phpTokenToSymbol;
256: $actionBase = $this->actionBase;
257: $actionTableSize = $this->actionTableSize;
258: $actionCheck = $this->actionCheck;
259: $actionTable = $this->action;
260: $defaultAction = $this->defaultAction;
261: $numNonLeafStates = $this->numNonLeafStates;
262: $YY2TBLSTATE = $this->YY2TBLSTATE;
263: $actionDefault = $this->actionDefault;
264: $ruleToLength = $this->ruleToLength;
265: $reduceCallbacks = $this->reduceCallbacks;
266: $ruleToNonTerminal = $this->ruleToNonTerminal;
267: $gotoBase = $this->gotoBase;
268: $gotoCheck = $this->gotoCheck;
269: $gotoTable = $this->goto;
270: $gotoDefault = $this->gotoDefault;
271: $unexpectedTokenRule = $this->unexpectedTokenRule;
272: $errorSymbol = $this->errorSymbol;
273:
274: for (;;) {
275: //$this->traceNewState($state, $symbol);
276:
277: if ($actionBase[$state] === 0) {
278: $rule = $actionDefault[$state];
279: } else {
280: if ($symbol === self::SYMBOL_NONE) {
281: do {
282: $token = $tokens[++$this->tokenPos];
283: $tokenId = $token->id;
284: } while (isset($dropTokens[$tokenId]));
285:
286: // Map the lexer token id to the internally used symbols.
287: $tokenValue = $token->text;
288: if (!isset($phpTokenToSymbol[$tokenId])) {
289: throw new \RangeException(sprintf(
290: 'The lexer returned an invalid token (id=%d, value=%s)',
291: $tokenId, $tokenValue
292: ));
293: }
294: $symbol = $phpTokenToSymbol[$tokenId];
295:
296: //$this->traceRead($symbol);
297: }
298:
299: $idx = $actionBase[$state] + $symbol;
300: // The check table is a list, so a lookup outside of it finds no entry, like the bounds checks
301: if ((($actionCheck[$idx] ?? -1) === $symbol
302: || ($state < $YY2TBLSTATE
303: && ($actionCheck[$idx = $actionBase[$state + $numNonLeafStates] + $symbol] ?? -1) === $symbol))
304: && ($action = $actionTable[$idx]) !== $defaultAction) {
305: /*
306: * >= numNonLeafStates: shift and reduce
307: * > 0: shift
308: * = 0: accept
309: * < 0: reduce
310: * = -YYUNEXPECTED: error
311: */
312: if ($action > 0) {
313: /* shift */
314: //$this->traceShift($symbol);
315:
316: ++$stackPos;
317: $stateStack[$stackPos] = $state = $action;
318: $this->semStack[$stackPos] = $tokenValue;
319: $this->tokenStartStack[$stackPos] = $this->tokenPos;
320: $this->tokenEndStack[$stackPos] = $this->tokenPos;
321: $symbol = self::SYMBOL_NONE;
322:
323: if ($this->errorState) {
324: --$this->errorState;
325: }
326:
327: if ($action < $numNonLeafStates) {
328: continue;
329: }
330:
331: /* $yyn >= numNonLeafStates means shift-and-reduce */
332: $rule = $action - $numNonLeafStates;
333: } else {
334: $rule = -$action;
335: }
336: } else {
337: $rule = $actionDefault[$state];
338: }
339: }
340:
341: for (;;) {
342: if ($rule === 0) {
343: /* accept */
344: //$this->traceAccept();
345: return $this->semValue;
346: }
347: if ($rule !== $unexpectedTokenRule) {
348: /* reduce */
349: //$this->traceReduce($rule);
350:
351: $ruleLength = $ruleToLength[$rule];
352: try {
353: $callback = $reduceCallbacks[$rule];
354: if ($callback !== null) {
355: $callback($this, $stackPos);
356: } elseif ($ruleLength > 1) {
357: $this->semValue = $this->semStack[$stackPos - $ruleLength + 1];
358: }
359: } catch (Error $e) {
360: if (-1 === $e->getStartLine()) {
361: $e->setStartLine($tokens[$this->tokenPos]->line);
362: }
363:
364: $this->emitError($e);
365: // Can't recover from this type of error
366: return null;
367: }
368:
369: /* Goto - shift nonterminal */
370: $stackPos -= $ruleLength;
371: $nonTerminal = $ruleToNonTerminal[$rule];
372: $idx = $gotoBase[$nonTerminal] + $stateStack[$stackPos];
373: if (($gotoCheck[$idx] ?? -1) === $nonTerminal) {
374: $state = $gotoTable[$idx];
375: } else {
376: $state = $gotoDefault[$nonTerminal];
377: }
378:
379: if ($ruleLength === 1) {
380: // The nonterminal replaces its only symbol, which has the same start and end,
381: // and without an action also the same value.
382: ++$stackPos;
383: $stateStack[$stackPos] = $state;
384: if ($callback !== null) {
385: $this->semStack[$stackPos] = $this->semValue;
386: }
387: } else {
388: $lastTokenEnd = $this->tokenEndStack[$stackPos + $ruleLength];
389: ++$stackPos;
390: $stateStack[$stackPos] = $state;
391: $this->semStack[$stackPos] = $this->semValue;
392: $this->tokenEndStack[$stackPos] = $lastTokenEnd;
393: if ($ruleLength === 0) {
394: // Empty productions use the start attributes of the lookahead token.
395: $this->tokenStartStack[$stackPos] = $this->tokenPos;
396: }
397: }
398: } else {
399: /* error */
400: switch ($this->errorState) {
401: case 0:
402: $msg = $this->getErrorMessage($symbol, $state);
403: $this->emitError(new Error($msg, $this->getAttributesForToken($this->tokenPos)));
404: // Break missing intentionally
405: // no break
406: case 1:
407: case 2:
408: $this->errorState = 3;
409:
410: // Pop until error-expecting state uncovered
411: while (!(
412: (($idx = $actionBase[$state] + $errorSymbol) >= 0
413: && $idx < $actionTableSize && $actionCheck[$idx] === $errorSymbol)
414: || ($state < $YY2TBLSTATE
415: && ($idx = $actionBase[$state + $numNonLeafStates] + $errorSymbol) >= 0
416: && $idx < $actionTableSize && $actionCheck[$idx] === $errorSymbol)
417: ) || ($action = $actionTable[$idx]) === $defaultAction) { // Not totally sure about this
418: if ($stackPos <= 0) {
419: // Could not recover from error
420: return null;
421: }
422: $state = $stateStack[--$stackPos];
423: //$this->tracePop($state);
424: }
425:
426: //$this->traceShift($this->errorSymbol);
427: ++$stackPos;
428: $stateStack[$stackPos] = $state = $action;
429:
430: // We treat the error symbol as being empty, so we reset the end attributes
431: // to the end attributes of the last non-error symbol
432: $this->tokenStartStack[$stackPos] = $this->tokenPos;
433: $this->tokenEndStack[$stackPos] = $this->tokenEndStack[$stackPos - 1];
434: break;
435:
436: case 3:
437: if ($symbol === 0) {
438: // Reached EOF without recovering from error
439: return null;
440: }
441:
442: //$this->traceDiscard($symbol);
443: $symbol = self::SYMBOL_NONE;
444: break 2;
445: }
446: }
447:
448: if ($state < $numNonLeafStates) {
449: break;
450: }
451:
452: /* >= numNonLeafStates means shift-and-reduce */
453: $rule = $state - $numNonLeafStates;
454: }
455: }
456: }
457:
458: protected function emitError(Error $error): void {
459: $this->errorHandler->handleError($error);
460: }
461:
462: /**
463: * Format error message including expected tokens.
464: *
465: * @param int $symbol Unexpected symbol
466: * @param int $state State at time of error
467: *
468: * @return string Formatted error message
469: */
470: protected function getErrorMessage(int $symbol, int $state): string {
471: $expectedString = '';
472: if ($expected = $this->getExpectedTokens($state)) {
473: $expectedString = ', expecting ' . implode(' or ', $expected);
474: }
475:
476: return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
477: }
478:
479: /**
480: * Get limited number of expected tokens in given state.
481: *
482: * @param int $state State
483: *
484: * @return string[] Expected tokens. If too many, an empty array is returned.
485: */
486: protected function getExpectedTokens(int $state): array {
487: $expected = [];
488:
489: $base = $this->actionBase[$state];
490: foreach ($this->symbolToName as $symbol => $name) {
491: $idx = $base + $symbol;
492: if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
493: || $state < $this->YY2TBLSTATE
494: && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
495: && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
496: ) {
497: if ($this->action[$idx] !== $this->unexpectedTokenRule
498: && $this->action[$idx] !== $this->defaultAction
499: && $symbol !== $this->errorSymbol
500: ) {
501: if (count($expected) === 4) {
502: /* Too many expected tokens */
503: return [];
504: }
505:
506: $expected[] = $name;
507: }
508: }
509: }
510:
511: return $expected;
512: }
513:
514: /**
515: * Get attributes for a node with the given start and end token positions.
516: *
517: * @param int $tokenStartPos Token position the node starts at
518: * @param int $tokenEndPos Token position the node ends at
519: * @return array<string, mixed> Attributes
520: */
521: protected function getAttributes(int $tokenStartPos, int $tokenEndPos): array {
522: $startToken = $this->tokens[$tokenStartPos];
523: $afterEndToken = $this->tokens[$tokenEndPos + 1];
524: return [
525: 'startLine' => $startToken->line,
526: 'startTokenPos' => $tokenStartPos,
527: 'startFilePos' => $startToken->pos,
528: 'endLine' => $afterEndToken->line,
529: 'endTokenPos' => $tokenEndPos,
530: 'endFilePos' => $afterEndToken->pos - 1,
531: ];
532: }
533:
534: /**
535: * Get attributes for a single token at the given token position.
536: *
537: * @return array<string, mixed> Attributes
538: */
539: protected function getAttributesForToken(int $tokenPos): array {
540: if ($tokenPos < \count($this->tokens) - 1) {
541: return $this->getAttributes($tokenPos, $tokenPos);
542: }
543:
544: // Get attributes for the sentinel token.
545: $token = $this->tokens[$tokenPos];
546: return [
547: 'startLine' => $token->line,
548: 'startTokenPos' => $tokenPos,
549: 'startFilePos' => $token->pos,
550: 'endLine' => $token->line,
551: 'endTokenPos' => $tokenPos,
552: 'endFilePos' => $token->pos,
553: ];
554: }
555:
556: /*
557: * Tracing functions used for debugging the parser.
558: */
559:
560: /*
561: protected function traceNewState($state, $symbol): void {
562: echo '% State ' . $state
563: . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
564: }
565:
566: protected function traceRead($symbol): void {
567: echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
568: }
569:
570: protected function traceShift($symbol): void {
571: echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
572: }
573:
574: protected function traceAccept(): void {
575: echo "% Accepted.\n";
576: }
577:
578: protected function traceReduce($n): void {
579: echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
580: }
581:
582: protected function tracePop($state): void {
583: echo '% Recovering, uncovered state ' . $state . "\n";
584: }
585:
586: protected function traceDiscard($symbol): void {
587: echo '% Discard ' . $this->symbolToName[$symbol] . "\n";
588: }
589: */
590:
591: /*
592: * Helper functions invoked by semantic actions
593: */
594:
595: /**
596: * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
597: *
598: * @param Node\Stmt[] $stmts
599: * @return Node\Stmt[]
600: */
601: protected function handleNamespaces(array $stmts): array {
602: $hasErrored = false;
603: $style = $this->getNamespacingStyle($stmts);
604: if (null === $style) {
605: // not namespaced, nothing to do
606: return $stmts;
607: }
608: if ('brace' === $style) {
609: // For braced namespaces we only have to check that there are no invalid statements between the namespaces
610: $afterFirstNamespace = false;
611: foreach ($stmts as $stmt) {
612: if ($stmt instanceof Node\Stmt\Namespace_) {
613: $afterFirstNamespace = true;
614: } elseif (!$stmt instanceof Node\Stmt\HaltCompiler
615: && !$stmt instanceof Node\Stmt\Nop
616: && $afterFirstNamespace && !$hasErrored) {
617: $this->emitError(new Error(
618: 'No code may exist outside of namespace {}', $stmt->getAttributes()));
619: $hasErrored = true; // Avoid one error for every statement
620: }
621: }
622: return $stmts;
623: } else {
624: // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
625: $resultStmts = [];
626: $targetStmts = &$resultStmts;
627: $lastNs = null;
628: foreach ($stmts as $stmt) {
629: if ($stmt instanceof Node\Stmt\Namespace_) {
630: if ($lastNs !== null) {
631: $this->fixupNamespaceAttributes($lastNs);
632: }
633: if ($stmt->stmts === null) {
634: $stmt->stmts = [];
635: $targetStmts = &$stmt->stmts;
636: $resultStmts[] = $stmt;
637: } else {
638: // This handles the invalid case of mixed style namespaces
639: $resultStmts[] = $stmt;
640: $targetStmts = &$resultStmts;
641: }
642: $lastNs = $stmt;
643: } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
644: // __halt_compiler() is not moved into the namespace
645: $resultStmts[] = $stmt;
646: } else {
647: $targetStmts[] = $stmt;
648: }
649: }
650: if ($lastNs !== null) {
651: $this->fixupNamespaceAttributes($lastNs);
652: }
653: return $resultStmts;
654: }
655: }
656:
657: private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt): void {
658: // We moved the statements into the namespace node, as such the end of the namespace node
659: // needs to be extended to the end of the statements.
660: if (empty($stmt->stmts)) {
661: return;
662: }
663:
664: // We only move the builtin end attributes here. This is the best we can do with the
665: // knowledge we have.
666: $endAttributes = ['endLine', 'endFilePos', 'endTokenPos'];
667: $lastStmt = $stmt->stmts[count($stmt->stmts) - 1];
668: foreach ($endAttributes as $endAttribute) {
669: if ($lastStmt->hasAttribute($endAttribute)) {
670: $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute));
671: }
672: }
673: }
674:
675: /** @return array<string, mixed> */
676: private function getNamespaceErrorAttributes(Namespace_ $node): array {
677: $attrs = $node->getAttributes();
678: // Adjust end attributes to only cover the "namespace" keyword, not the whole namespace.
679: if (isset($attrs['startLine'])) {
680: $attrs['endLine'] = $attrs['startLine'];
681: }
682: if (isset($attrs['startTokenPos'])) {
683: $attrs['endTokenPos'] = $attrs['startTokenPos'];
684: }
685: if (isset($attrs['startFilePos'])) {
686: $attrs['endFilePos'] = $attrs['startFilePos'] + \strlen('namespace') - 1;
687: }
688: return $attrs;
689: }
690:
691: /**
692: * Determine namespacing style (semicolon or brace)
693: *
694: * @param Node[] $stmts Top-level statements.
695: *
696: * @return null|string One of "semicolon", "brace" or null (no namespaces)
697: */
698: private function getNamespacingStyle(array $stmts): ?string {
699: $style = null;
700: $hasNotAllowedStmts = false;
701: foreach ($stmts as $i => $stmt) {
702: if ($stmt instanceof Node\Stmt\Namespace_) {
703: $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
704: if (null === $style) {
705: $style = $currentStyle;
706: if ($hasNotAllowedStmts) {
707: $this->emitError(new Error(
708: 'Namespace declaration statement has to be the very first statement in the script',
709: $this->getNamespaceErrorAttributes($stmt)
710: ));
711: }
712: } elseif ($style !== $currentStyle) {
713: $this->emitError(new Error(
714: 'Cannot mix bracketed namespace declarations with unbracketed namespace declarations',
715: $this->getNamespaceErrorAttributes($stmt)
716: ));
717: // Treat like semicolon style for namespace normalization
718: return 'semicolon';
719: }
720: continue;
721: }
722:
723: /* declare(), __halt_compiler() and nops can be used before a namespace declaration */
724: if ($stmt instanceof Node\Stmt\Declare_
725: || $stmt instanceof Node\Stmt\HaltCompiler
726: || $stmt instanceof Node\Stmt\Nop) {
727: continue;
728: }
729:
730: /* There may be a hashbang line at the very start of the file */
731: if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) {
732: continue;
733: }
734:
735: /* Everything else if forbidden before namespace declarations */
736: $hasNotAllowedStmts = true;
737: }
738: return $style;
739: }
740:
741: /** @return Name|Identifier */
742: protected function handleBuiltinTypes(Name $name) {
743: if (!$name->isUnqualified()) {
744: return $name;
745: }
746:
747: $lowerName = $name->toLowerString();
748: if (!$this->phpVersion->supportsBuiltinType($lowerName)) {
749: return $name;
750: }
751:
752: return new Node\Identifier($lowerName, $name->getAttributes());
753: }
754:
755: /**
756: * Get combined start and end attributes at a stack location
757: *
758: * @param int $stackPos Stack location
759: *
760: * @return array<string, mixed> Combined start and end attributes
761: */
762: protected function getAttributesAt(int $stackPos): array {
763: return $this->getAttributes($this->tokenStartStack[$stackPos], $this->tokenEndStack[$stackPos]);
764: }
765:
766: protected function getFloatCastKind(string $cast): int {
767: $cast = strtolower($cast);
768: if (strpos($cast, 'float') !== false) {
769: return Double::KIND_FLOAT;
770: }
771:
772: if (strpos($cast, 'real') !== false) {
773: return Double::KIND_REAL;
774: }
775:
776: return Double::KIND_DOUBLE;
777: }
778:
779: protected function getIntCastKind(string $cast): int {
780: $cast = strtolower($cast);
781: if (strpos($cast, 'integer') !== false) {
782: return Expr\Cast\Int_::KIND_INTEGER;
783: }
784:
785: return Expr\Cast\Int_::KIND_INT;
786: }
787:
788: protected function getBoolCastKind(string $cast): int {
789: $cast = strtolower($cast);
790: if (strpos($cast, 'boolean') !== false) {
791: return Expr\Cast\Bool_::KIND_BOOLEAN;
792: }
793:
794: return Expr\Cast\Bool_::KIND_BOOL;
795: }
796:
797: protected function getStringCastKind(string $cast): int {
798: $cast = strtolower($cast);
799: if (strpos($cast, 'binary') !== false) {
800: return Expr\Cast\String_::KIND_BINARY;
801: }
802:
803: return Expr\Cast\String_::KIND_STRING;
804: }
805:
806: /** @param array<string, mixed> $attributes */
807: protected function parseLNumber(string $str, array $attributes, bool $allowInvalidOctal = false): Int_ {
808: try {
809: return Int_::fromString($str, $attributes, $allowInvalidOctal);
810: } catch (Error $error) {
811: $this->emitError($error);
812: // Use dummy value
813: return new Int_(0, $attributes);
814: }
815: }
816:
817: /**
818: * Parse a T_NUM_STRING token into either an integer or string node.
819: *
820: * @param string $str Number string
821: * @param array<string, mixed> $attributes Attributes
822: *
823: * @return Int_|String_ Integer or string node.
824: */
825: protected function parseNumString(string $str, array $attributes) {
826: if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) {
827: return new String_($str, $attributes);
828: }
829:
830: $num = +$str;
831: if (!is_int($num)) {
832: return new String_($str, $attributes);
833: }
834:
835: return new Int_($num, $attributes);
836: }
837:
838: /** @param array<string, mixed> $attributes */
839: protected function stripIndentation(
840: string $string, int $indentLen, string $indentChar,
841: bool $newlineAtStart, bool $newlineAtEnd, array $attributes
842: ): string {
843: if ($indentLen === 0) {
844: return $string;
845: }
846:
847: $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)';
848: $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])';
849: $regex = '/' . $start . '([ \t]*)(' . $end . ')?/';
850: return preg_replace_callback(
851: $regex,
852: function ($matches) use ($indentLen, $indentChar, $attributes) {
853: $prefix = substr($matches[1], 0, $indentLen);
854: if (false !== strpos($prefix, $indentChar === " " ? "\t" : " ")) {
855: $this->emitError(new Error(
856: 'Invalid indentation - tabs and spaces cannot be mixed', $attributes
857: ));
858: } elseif (strlen($prefix) < $indentLen && !isset($matches[2])) {
859: $this->emitError(new Error(
860: 'Invalid body indentation level ' .
861: '(expecting an indentation level of at least ' . $indentLen . ')',
862: $attributes
863: ));
864: }
865: return substr($matches[0], strlen($prefix));
866: },
867: $string
868: );
869: }
870:
871: /**
872: * @param string|(Expr|InterpolatedStringPart)[] $contents
873: * @param array<string, mixed> $attributes
874: * @param array<string, mixed> $endTokenAttributes
875: */
876: protected function parseDocString(
877: string $startToken, $contents, string $endToken,
878: array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape
879: ): Expr {
880: $kind = strpos($startToken, "'") === false
881: ? String_::KIND_HEREDOC : String_::KIND_NOWDOC;
882:
883: $regex = '/\A[bB]?<<<[ \t]*[\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\'"]?(?:\r\n|\n|\r)\z/';
884: $result = preg_match($regex, $startToken, $matches);
885: assert($result === 1);
886: $label = $matches[1];
887:
888: $result = preg_match('/\A[ \t]*/', $endToken, $matches);
889: assert($result === 1);
890: $indentation = $matches[0];
891:
892: $attributes['kind'] = $kind;
893: $attributes['docLabel'] = $label;
894: $attributes['docIndentation'] = $indentation;
895:
896: $indentHasSpaces = false !== strpos($indentation, " ");
897: $indentHasTabs = false !== strpos($indentation, "\t");
898: if ($indentHasSpaces && $indentHasTabs) {
899: $this->emitError(new Error(
900: 'Invalid indentation - tabs and spaces cannot be mixed',
901: $endTokenAttributes
902: ));
903:
904: // Proceed processing as if this doc string is not indented
905: $indentation = '';
906: }
907:
908: $indentLen = \strlen($indentation);
909: $indentChar = $indentHasSpaces ? " " : "\t";
910:
911: if (\is_string($contents)) {
912: if ($contents === '') {
913: $attributes['rawValue'] = $contents;
914: return new String_('', $attributes);
915: }
916:
917: $contents = $this->stripIndentation(
918: $contents, $indentLen, $indentChar, true, true, $attributes
919: );
920: $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents);
921: $attributes['rawValue'] = $contents;
922:
923: if ($kind === String_::KIND_HEREDOC) {
924: $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape);
925: }
926:
927: return new String_($contents, $attributes);
928: } else {
929: assert(count($contents) > 0);
930: if (!$contents[0] instanceof Node\InterpolatedStringPart) {
931: // If there is no leading encapsed string part, pretend there is an empty one
932: $this->stripIndentation(
933: '', $indentLen, $indentChar, true, false, $contents[0]->getAttributes()
934: );
935: }
936:
937: $newContents = [];
938: foreach ($contents as $i => $part) {
939: if ($part instanceof Node\InterpolatedStringPart) {
940: $isLast = $i === \count($contents) - 1;
941: $part->value = $this->stripIndentation(
942: $part->value, $indentLen, $indentChar,
943: $i === 0, $isLast, $part->getAttributes()
944: );
945: if ($isLast) {
946: $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value);
947: }
948: $part->setAttribute('rawValue', $part->value);
949: $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape);
950: if ('' === $part->value) {
951: continue;
952: }
953: }
954: $newContents[] = $part;
955: }
956: return new InterpolatedString($newContents, $attributes);
957: }
958: }
959:
960: protected function createCommentFromToken(Token $token, int $tokenPos): Comment {
961: assert($token->id === \T_COMMENT || $token->id == \T_DOC_COMMENT);
962: return \T_DOC_COMMENT === $token->id
963: ? new Comment\Doc($token->text, $token->line, $token->pos, $tokenPos,
964: $token->getEndLine(), $token->getEndPos() - 1, $tokenPos)
965: : new Comment($token->text, $token->line, $token->pos, $tokenPos,
966: $token->getEndLine(), $token->getEndPos() - 1, $tokenPos);
967: }
968:
969: /**
970: * Get last comment before the given token position, if any
971: */
972: protected function getCommentBeforeToken(int $tokenPos): ?Comment {
973: while (--$tokenPos >= 0) {
974: $token = $this->tokens[$tokenPos];
975: if (!isset($this->dropTokens[$token->id])) {
976: break;
977: }
978:
979: if ($token->id === \T_COMMENT || $token->id === \T_DOC_COMMENT) {
980: return $this->createCommentFromToken($token, $tokenPos);
981: }
982: }
983: return null;
984: }
985:
986: /**
987: * Create a zero-length nop to capture preceding comments, if any.
988: */
989: protected function maybeCreateZeroLengthNop(int $tokenPos): ?Nop {
990: $comment = $this->getCommentBeforeToken($tokenPos);
991: if ($comment === null) {
992: return null;
993: }
994:
995: $commentEndLine = $comment->getEndLine();
996: $commentEndFilePos = $comment->getEndFilePos();
997: $commentEndTokenPos = $comment->getEndTokenPos();
998: $attributes = [
999: 'startLine' => $commentEndLine,
1000: 'endLine' => $commentEndLine,
1001: 'startFilePos' => $commentEndFilePos + 1,
1002: 'endFilePos' => $commentEndFilePos,
1003: 'startTokenPos' => $commentEndTokenPos + 1,
1004: 'endTokenPos' => $commentEndTokenPos,
1005: ];
1006: return new Nop($attributes);
1007: }
1008:
1009: protected function maybeCreateNop(int $tokenStartPos, int $tokenEndPos): ?Nop {
1010: if ($this->getCommentBeforeToken($tokenStartPos) === null) {
1011: return null;
1012: }
1013: return new Nop($this->getAttributes($tokenStartPos, $tokenEndPos));
1014: }
1015:
1016: protected function handleHaltCompiler(): string {
1017: // Prevent the lexer from returning any further tokens.
1018: $nextToken = $this->tokens[$this->tokenPos + 1];
1019: $this->tokenPos = \count($this->tokens) - 2;
1020:
1021: // Return text after __halt_compiler.
1022: return $nextToken->id === \T_INLINE_HTML ? $nextToken->text : '';
1023: }
1024:
1025: protected function inlineHtmlHasLeadingNewline(int $stackPos): bool {
1026: $tokenPos = $this->tokenStartStack[$stackPos];
1027: $token = $this->tokens[$tokenPos];
1028: assert($token->id == \T_INLINE_HTML);
1029: if ($tokenPos > 0) {
1030: $prevToken = $this->tokens[$tokenPos - 1];
1031: assert($prevToken->id == \T_CLOSE_TAG);
1032: return false !== strpos($prevToken->text, "\n")
1033: || false !== strpos($prevToken->text, "\r");
1034: }
1035: return true;
1036: }
1037:
1038: /**
1039: * @return array<string, mixed>
1040: */
1041: protected function createEmptyElemAttributes(int $tokenPos): array {
1042: return $this->getAttributesForToken($tokenPos);
1043: }
1044:
1045: protected function fixupArrayDestructuring(Array_ $node): Expr\List_ {
1046: $this->createdArrays->offsetUnset($node);
1047: return new Expr\List_(array_map(function (Node\ArrayItem $item) {
1048: if ($item->value instanceof Expr\Error) {
1049: // We used Error as a placeholder for empty elements, which are legal for destructuring.
1050: return null;
1051: }
1052: if ($item->value instanceof Array_) {
1053: return new Node\ArrayItem(
1054: $this->fixupArrayDestructuring($item->value),
1055: $item->key, $item->byRef, $item->getAttributes());
1056: }
1057: return $item;
1058: }, $node->items), ['kind' => Expr\List_::KIND_ARRAY] + $node->getAttributes());
1059: }
1060:
1061: protected function postprocessList(Expr\List_ $node): void {
1062: foreach ($node->items as $i => $item) {
1063: if ($item->value instanceof Expr\Error) {
1064: // We used Error as a placeholder for empty elements, which are legal for destructuring.
1065: $node->items[$i] = null;
1066: }
1067: }
1068: }
1069:
1070: /** @param ElseIf_|Else_ $node */
1071: protected function fixupAlternativeElse($node): void {
1072: // Make sure a trailing nop statement carrying comments is part of the node.
1073: $numStmts = \count($node->stmts);
1074: if ($numStmts !== 0 && $node->stmts[$numStmts - 1] instanceof Nop) {
1075: $nopAttrs = $node->stmts[$numStmts - 1]->getAttributes();
1076: if (isset($nopAttrs['endLine'])) {
1077: $node->setAttribute('endLine', $nopAttrs['endLine']);
1078: }
1079: if (isset($nopAttrs['endFilePos'])) {
1080: $node->setAttribute('endFilePos', $nopAttrs['endFilePos']);
1081: }
1082: if (isset($nopAttrs['endTokenPos'])) {
1083: $node->setAttribute('endTokenPos', $nopAttrs['endTokenPos']);
1084: }
1085: }
1086: }
1087:
1088: protected function checkClassModifier(int $a, int $b, int $modifierPos): void {
1089: try {
1090: Modifiers::verifyClassModifier($a, $b);
1091: } catch (Error $error) {
1092: $error->setAttributes($this->getAttributesAt($modifierPos));
1093: $this->emitError($error);
1094: }
1095: }
1096:
1097: protected function checkModifier(int $a, int $b, int $modifierPos): void {
1098: // Jumping through some hoops here because verifyModifier() is also used elsewhere
1099: try {
1100: Modifiers::verifyModifier($a, $b);
1101: } catch (Error $error) {
1102: $error->setAttributes($this->getAttributesAt($modifierPos));
1103: $this->emitError($error);
1104: }
1105: }
1106:
1107: protected function checkParam(Param $node): void {
1108: if ($node->variadic && null !== $node->default) {
1109: $this->emitError(new Error(
1110: 'Variadic parameter cannot have a default value',
1111: $node->default->getAttributes()
1112: ));
1113: }
1114:
1115: if ($node->type instanceof Identifier && $node->type->name === 'void') {
1116: $this->emitError(new Error(
1117: 'void cannot be used as a parameter type',
1118: $node->type->getAttributes()
1119: ));
1120: }
1121: }
1122:
1123: protected function checkTryCatch(TryCatch $node): void {
1124: if (empty($node->catches) && null === $node->finally) {
1125: $this->emitError(new Error(
1126: 'Cannot use try without catch or finally', $node->getAttributes()
1127: ));
1128: }
1129: }
1130:
1131: protected function checkNamespace(Namespace_ $node): void {
1132: if (null !== $node->stmts) {
1133: foreach ($node->stmts as $stmt) {
1134: if ($stmt instanceof Namespace_) {
1135: $this->emitError(new Error(
1136: 'Namespace declarations cannot be nested', $stmt->getAttributes()
1137: ));
1138: }
1139: }
1140: }
1141: }
1142:
1143: private function checkClassName(?Identifier $name, int $namePos): void {
1144: if (null !== $name && $name->isSpecialClassName()) {
1145: $this->emitError(new Error(
1146: sprintf('Cannot use \'%s\' as class name as it is reserved', $name),
1147: $this->getAttributesAt($namePos)
1148: ));
1149: }
1150: }
1151:
1152: /** @param Name[] $interfaces */
1153: private function checkImplementedInterfaces(array $interfaces): void {
1154: foreach ($interfaces as $interface) {
1155: if ($interface->isSpecialClassName()) {
1156: $this->emitError(new Error(
1157: sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
1158: $interface->getAttributes()
1159: ));
1160: }
1161: }
1162: }
1163:
1164: protected function checkClass(Class_ $node, int $namePos): void {
1165: $this->checkClassName($node->name, $namePos);
1166:
1167: if ($node->extends && $node->extends->isSpecialClassName()) {
1168: $this->emitError(new Error(
1169: sprintf('Cannot use \'%s\' as class name as it is reserved', $node->extends),
1170: $node->extends->getAttributes()
1171: ));
1172: }
1173:
1174: $this->checkImplementedInterfaces($node->implements);
1175: }
1176:
1177: protected function checkInterface(Interface_ $node, int $namePos): void {
1178: $this->checkClassName($node->name, $namePos);
1179: $this->checkImplementedInterfaces($node->extends);
1180: }
1181:
1182: protected function checkEnum(Enum_ $node, int $namePos): void {
1183: $this->checkClassName($node->name, $namePos);
1184: $this->checkImplementedInterfaces($node->implements);
1185: }
1186:
1187: protected function checkClassMethod(ClassMethod $node, int $modifierPos): void {
1188: if ($node->flags & Modifiers::STATIC) {
1189: switch ($node->name->toLowerString()) {
1190: case '__construct':
1191: $this->emitError(new Error(
1192: sprintf('Constructor %s() cannot be static', $node->name),
1193: $this->getAttributesAt($modifierPos)));
1194: break;
1195: case '__destruct':
1196: $this->emitError(new Error(
1197: sprintf('Destructor %s() cannot be static', $node->name),
1198: $this->getAttributesAt($modifierPos)));
1199: break;
1200: case '__clone':
1201: $this->emitError(new Error(
1202: sprintf('Clone method %s() cannot be static', $node->name),
1203: $this->getAttributesAt($modifierPos)));
1204: break;
1205: }
1206: }
1207:
1208: if ($node->flags & Modifiers::READONLY) {
1209: $this->emitError(new Error(
1210: sprintf('Method %s() cannot be readonly', $node->name),
1211: $this->getAttributesAt($modifierPos)));
1212: }
1213: }
1214:
1215: protected function checkClassConst(ClassConst $node, int $modifierPos): void {
1216: foreach ([Modifiers::STATIC, Modifiers::ABSTRACT, Modifiers::READONLY] as $modifier) {
1217: if ($node->flags & $modifier) {
1218: $this->emitError(new Error(
1219: "Cannot use '" . Modifiers::toString($modifier) . "' as constant modifier",
1220: $this->getAttributesAt($modifierPos)));
1221: }
1222: }
1223: }
1224:
1225: protected function checkUseUse(UseItem $node, int $namePos): void {
1226: if ($node->alias && $node->alias->isSpecialClassName()) {
1227: $this->emitError(new Error(
1228: sprintf(
1229: 'Cannot use %s as %s because \'%2$s\' is a special class name',
1230: $node->name, $node->alias
1231: ),
1232: $this->getAttributesAt($namePos)
1233: ));
1234: }
1235: }
1236:
1237: protected function checkPropertyHooksForMultiProperty(Property $property, int $hookPos): void {
1238: if (count($property->props) > 1) {
1239: $this->emitError(new Error(
1240: 'Cannot use hooks when declaring multiple properties', $this->getAttributesAt($hookPos)));
1241: }
1242: }
1243:
1244: /** @param PropertyHook[] $hooks */
1245: protected function checkEmptyPropertyHookList(array $hooks, int $hookPos): void {
1246: if (empty($hooks)) {
1247: $this->emitError(new Error(
1248: 'Property hook list cannot be empty', $this->getAttributesAt($hookPos)));
1249: }
1250: }
1251:
1252: protected function checkPropertyHook(PropertyHook $hook, ?int $paramListPos): void {
1253: $name = $hook->name->toLowerString();
1254: if ($name !== 'get' && $name !== 'set') {
1255: $this->emitError(new Error(
1256: 'Unknown hook "' . $hook->name . '", expected "get" or "set"',
1257: $hook->name->getAttributes()));
1258: }
1259: if ($name === 'get' && $paramListPos !== null) {
1260: $this->emitError(new Error(
1261: 'get hook must not have a parameter list', $this->getAttributesAt($paramListPos)));
1262: }
1263: }
1264:
1265: protected function checkPropertyHookModifiers(int $a, int $b, int $modifierPos): void {
1266: try {
1267: Modifiers::verifyModifier($a, $b);
1268: } catch (Error $error) {
1269: $error->setAttributes($this->getAttributesAt($modifierPos));
1270: $this->emitError($error);
1271: }
1272:
1273: if ($b != Modifiers::FINAL) {
1274: $this->emitError(new Error(
1275: 'Cannot use the ' . Modifiers::toString($b) . ' modifier on a property hook',
1276: $this->getAttributesAt($modifierPos)));
1277: }
1278: }
1279:
1280: protected function checkConstantAttributes(Const_ $node): void {
1281: if ($node->attrGroups !== [] && count($node->consts) > 1) {
1282: $this->emitError(new Error(
1283: 'Cannot use attributes on multiple constants at once', $node->getAttributes()));
1284: }
1285: }
1286:
1287: protected function checkPipeOperatorParentheses(Expr $node): void {
1288: if ($node instanceof Expr\ArrowFunction && !$this->parenthesizedArrowFunctions->offsetExists($node)) {
1289: $this->emitError(new Error(
1290: 'Arrow functions on the right hand side of |> must be parenthesized', $node->getAttributes()));
1291: }
1292: }
1293:
1294: /**
1295: * @param Property|Param $node
1296: */
1297: protected function addPropertyNameToHooks(Node $node): void {
1298: if ($node instanceof Property) {
1299: $name = $node->props[0]->name->toString();
1300: } else {
1301: $name = $node->var->name;
1302: }
1303: foreach ($node->hooks as $hook) {
1304: $hook->setAttribute('propertyName', $name);
1305: }
1306: }
1307:
1308: /** @param array<Node\Arg|Node\VariadicPlaceholder|Node\ArgPlaceholder> $args */
1309: private function isSimpleExit(array $args): bool {
1310: if (\count($args) === 0) {
1311: return true;
1312: }
1313: if (\count($args) === 1) {
1314: $arg = $args[0];
1315: return $arg instanceof Arg && $arg->name === null &&
1316: $arg->byRef === false && $arg->unpack === false;
1317: }
1318: return false;
1319: }
1320:
1321: /**
1322: * @param array<Node\Arg|Node\VariadicPlaceholder|Node\ArgPlaceholder> $args
1323: * @param array<string, mixed> $attrs
1324: */
1325: protected function createExitExpr(string $name, int $namePos, array $args, array $attrs): Expr {
1326: if ($this->isSimpleExit($args)) {
1327: // Create Exit node for backwards compatibility.
1328: $attrs['kind'] = strtolower($name) === 'exit' ? Expr\Exit_::KIND_EXIT : Expr\Exit_::KIND_DIE;
1329: return new Expr\Exit_(\count($args) === 1 ? $args[0]->value : null, $attrs);
1330: }
1331: return new Expr\FuncCall(new Name($name, $this->getAttributesAt($namePos)), $args, $attrs);
1332: }
1333:
1334: /**
1335: * Creates the token map.
1336: *
1337: * The token map maps the PHP internal token identifiers
1338: * to the identifiers used by the Parser. Additionally it
1339: * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
1340: *
1341: * @return array<int, int> The token map
1342: */
1343: protected function createTokenMap(): array {
1344: $tokenMap = [];
1345:
1346: // Single-char tokens use an identity mapping.
1347: for ($i = 0; $i < 256; ++$i) {
1348: $tokenMap[$i] = $i;
1349: }
1350:
1351: foreach ($this->symbolToName as $name) {
1352: if ($name[0] === 'T') {
1353: $tokenMap[\constant($name)] = constant(static::class . '::' . $name);
1354: }
1355: }
1356:
1357: // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
1358: $tokenMap[\T_OPEN_TAG_WITH_ECHO] = static::T_ECHO;
1359: // T_CLOSE_TAG is equivalent to ';'
1360: $tokenMap[\T_CLOSE_TAG] = ord(';');
1361:
1362: // We have created a map from PHP token IDs to external symbol IDs.
1363: // Now map them to the internal symbol ID.
1364: $fullTokenMap = [];
1365: foreach ($tokenMap as $phpToken => $extSymbol) {
1366: $intSymbol = $this->tokenToSymbol[$extSymbol];
1367: if ($intSymbol === $this->invalidSymbol) {
1368: continue;
1369: }
1370: $fullTokenMap[$phpToken] = $intSymbol;
1371: }
1372:
1373: return $fullTokenMap;
1374: }
1375: }
1376: