ParserAbstract.php 49 KB

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