ParserAbstract.php 49 KB

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