ParserAbstract.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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\Node\VarLikeIdentifier;
  33. use PhpParser\NodeVisitor\CommentAnnotatingVisitor;
  34. abstract class ParserAbstract implements Parser {
  35. private const SYMBOL_NONE = -1;
  36. /** @var Lexer Lexer that is used when parsing */
  37. protected Lexer $lexer;
  38. /** @var PhpVersion PHP version to target on a best-effort basis */
  39. protected PhpVersion $phpVersion;
  40. /*
  41. * The following members will be filled with generated parsing data:
  42. */
  43. /** @var int Size of $tokenToSymbol map */
  44. protected int $tokenToSymbolMapSize;
  45. /** @var int Size of $action table */
  46. protected int $actionTableSize;
  47. /** @var int Size of $goto table */
  48. protected int $gotoTableSize;
  49. /** @var int Symbol number signifying an invalid token */
  50. protected int $invalidSymbol;
  51. /** @var int Symbol number of error recovery token */
  52. protected int $errorSymbol;
  53. /** @var int Action number signifying default action */
  54. protected int $defaultAction;
  55. /** @var int Rule number signifying that an unexpected token was encountered */
  56. protected int $unexpectedTokenRule;
  57. protected int $YY2TBLSTATE;
  58. /** @var int Number of non-leaf states */
  59. protected int $numNonLeafStates;
  60. /** @var int[] Map of PHP token IDs to internal symbols */
  61. protected array $phpTokenToSymbol;
  62. /** @var array<int, bool> Map of PHP token IDs to drop */
  63. protected array $dropTokens;
  64. /** @var int[] Map of external symbols (static::T_*) to internal symbols */
  65. protected array $tokenToSymbol;
  66. /** @var string[] Map of symbols to their names */
  67. protected array $symbolToName;
  68. /** @var array<int, string> Names of the production rules (only necessary for debugging) */
  69. protected array $productions;
  70. /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this
  71. * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
  72. * action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  73. protected array $actionBase;
  74. /** @var int[] Table of actions. Indexed according to $actionBase comment. */
  75. protected array $action;
  76. /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
  77. * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  78. protected array $actionCheck;
  79. /** @var int[] Map of states to their default action */
  80. protected array $actionDefault;
  81. /** @var callable[] Semantic action callbacks */
  82. protected array $reduceCallbacks;
  83. /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
  84. * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
  85. protected array $gotoBase;
  86. /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */
  87. protected array $goto;
  88. /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
  89. * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
  90. protected array $gotoCheck;
  91. /** @var int[] Map of non-terminals to the default state to goto after their reduction */
  92. protected array $gotoDefault;
  93. /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
  94. * determining the state to goto after reduction. */
  95. protected array $ruleToNonTerminal;
  96. /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to
  97. * be popped from the stack(s) on reduction. */
  98. protected array $ruleToLength;
  99. /*
  100. * The following members are part of the parser state:
  101. */
  102. /** @var mixed Temporary value containing the result of last semantic action (reduction) */
  103. protected $semValue;
  104. /** @var mixed[] Semantic value stack (contains values of tokens and semantic action results) */
  105. protected array $semStack;
  106. /** @var int[] Token start position stack */
  107. protected array $tokenStartStack;
  108. /** @var int[] Token end position stack */
  109. protected array $tokenEndStack;
  110. /** @var ErrorHandler Error handler */
  111. protected ErrorHandler $errorHandler;
  112. /** @var int Error state, used to avoid error floods */
  113. protected int $errorState;
  114. /** @var \SplObjectStorage<Array_, null>|null Array nodes created during parsing, for postprocessing of empty elements. */
  115. protected ?\SplObjectStorage $createdArrays;
  116. /** @var Token[] Tokens for the current parse */
  117. protected array $tokens;
  118. /** @var int Current position in token array */
  119. protected int $tokenPos;
  120. /**
  121. * Initialize $reduceCallbacks map.
  122. */
  123. abstract protected function initReduceCallbacks(): void;
  124. /**
  125. * Creates a parser instance.
  126. *
  127. * Options:
  128. * * phpVersion: ?PhpVersion,
  129. *
  130. * @param Lexer $lexer A lexer
  131. * @param PhpVersion $phpVersion PHP version to target, defaults to latest supported. This
  132. * option is best-effort: Even if specified, parsing will generally assume the latest
  133. * supported version and only adjust behavior in minor ways, for example by omitting
  134. * errors in older versions and interpreting type hints as a name or identifier depending
  135. * on version.
  136. */
  137. public function __construct(Lexer $lexer, ?PhpVersion $phpVersion = null) {
  138. $this->lexer = $lexer;
  139. $this->phpVersion = $phpVersion ?? PhpVersion::getNewestSupported();
  140. $this->initReduceCallbacks();
  141. $this->phpTokenToSymbol = $this->createTokenMap();
  142. $this->dropTokens = array_fill_keys(
  143. [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], true
  144. );
  145. }
  146. /**
  147. * Parses PHP code into a node tree.
  148. *
  149. * If a non-throwing error handler is used, the parser will continue parsing after an error
  150. * occurred and attempt to build a partial AST.
  151. *
  152. * @param string $code The source code to parse
  153. * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults
  154. * to ErrorHandler\Throwing.
  155. *
  156. * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and
  157. * the parser was unable to recover from an error).
  158. */
  159. public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array {
  160. $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing();
  161. $this->createdArrays = new \SplObjectStorage();
  162. $this->tokens = $this->lexer->tokenize($code, $this->errorHandler);
  163. $result = $this->doParse();
  164. // Report errors for any empty elements used inside arrays. This is delayed until after the main parse,
  165. // because we don't know a priori whether a given array expression will be used in a destructuring context
  166. // or not.
  167. foreach ($this->createdArrays as $node) {
  168. foreach ($node->items as $item) {
  169. if ($item->value instanceof Expr\Error) {
  170. $this->errorHandler->handleError(
  171. new Error('Cannot use empty array elements in arrays', $item->getAttributes()));
  172. }
  173. }
  174. }
  175. // Clear out some of the interior state, so we don't hold onto unnecessary
  176. // memory between uses of the parser
  177. $this->tokenStartStack = [];
  178. $this->tokenEndStack = [];
  179. $this->semStack = [];
  180. $this->semValue = null;
  181. $this->createdArrays = null;
  182. if ($result !== null) {
  183. $traverser = new NodeTraverser(new CommentAnnotatingVisitor($this->tokens));
  184. $traverser->traverse($result);
  185. }
  186. return $result;
  187. }
  188. public function getTokens(): array {
  189. return $this->tokens;
  190. }
  191. /** @return Stmt[]|null */
  192. protected function doParse(): ?array {
  193. // We start off with no lookahead-token
  194. $symbol = self::SYMBOL_NONE;
  195. $tokenValue = null;
  196. $this->tokenPos = -1;
  197. // Keep stack of start and end attributes
  198. $this->tokenStartStack = [];
  199. $this->tokenEndStack = [0];
  200. // Start off in the initial state and keep a stack of previous states
  201. $state = 0;
  202. $stateStack = [$state];
  203. // Semantic value stack (contains values of tokens and semantic action results)
  204. $this->semStack = [];
  205. // Current position in the stack(s)
  206. $stackPos = 0;
  207. $this->errorState = 0;
  208. for (;;) {
  209. //$this->traceNewState($state, $symbol);
  210. if ($this->actionBase[$state] === 0) {
  211. $rule = $this->actionDefault[$state];
  212. } else {
  213. if ($symbol === self::SYMBOL_NONE) {
  214. do {
  215. $token = $this->tokens[++$this->tokenPos];
  216. $tokenId = $token->id;
  217. } while (isset($this->dropTokens[$tokenId]));
  218. // Map the lexer token id to the internally used symbols.
  219. $tokenValue = $token->text;
  220. if (!isset($this->phpTokenToSymbol[$tokenId])) {
  221. throw new \RangeException(sprintf(
  222. 'The lexer returned an invalid token (id=%d, value=%s)',
  223. $tokenId, $tokenValue
  224. ));
  225. }
  226. $symbol = $this->phpTokenToSymbol[$tokenId];
  227. //$this->traceRead($symbol);
  228. }
  229. $idx = $this->actionBase[$state] + $symbol;
  230. if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)
  231. || ($state < $this->YY2TBLSTATE
  232. && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
  233. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol))
  234. && ($action = $this->action[$idx]) !== $this->defaultAction) {
  235. /*
  236. * >= numNonLeafStates: shift and reduce
  237. * > 0: shift
  238. * = 0: accept
  239. * < 0: reduce
  240. * = -YYUNEXPECTED: error
  241. */
  242. if ($action > 0) {
  243. /* shift */
  244. //$this->traceShift($symbol);
  245. ++$stackPos;
  246. $stateStack[$stackPos] = $state = $action;
  247. $this->semStack[$stackPos] = $tokenValue;
  248. $this->tokenStartStack[$stackPos] = $this->tokenPos;
  249. $this->tokenEndStack[$stackPos] = $this->tokenPos;
  250. $symbol = self::SYMBOL_NONE;
  251. if ($this->errorState) {
  252. --$this->errorState;
  253. }
  254. if ($action < $this->numNonLeafStates) {
  255. continue;
  256. }
  257. /* $yyn >= numNonLeafStates means shift-and-reduce */
  258. $rule = $action - $this->numNonLeafStates;
  259. } else {
  260. $rule = -$action;
  261. }
  262. } else {
  263. $rule = $this->actionDefault[$state];
  264. }
  265. }
  266. for (;;) {
  267. if ($rule === 0) {
  268. /* accept */
  269. //$this->traceAccept();
  270. return $this->semValue;
  271. }
  272. if ($rule !== $this->unexpectedTokenRule) {
  273. /* reduce */
  274. //$this->traceReduce($rule);
  275. $ruleLength = $this->ruleToLength[$rule];
  276. try {
  277. $callback = $this->reduceCallbacks[$rule];
  278. if ($callback !== null) {
  279. $callback($this, $stackPos);
  280. } elseif ($ruleLength > 0) {
  281. $this->semValue = $this->semStack[$stackPos - $ruleLength + 1];
  282. }
  283. } catch (Error $e) {
  284. if (-1 === $e->getStartLine()) {
  285. $e->setStartLine($this->tokens[$this->tokenPos]->line);
  286. }
  287. $this->emitError($e);
  288. // Can't recover from this type of error
  289. return null;
  290. }
  291. /* Goto - shift nonterminal */
  292. $lastTokenEnd = $this->tokenEndStack[$stackPos];
  293. $stackPos -= $ruleLength;
  294. $nonTerminal = $this->ruleToNonTerminal[$rule];
  295. $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos];
  296. if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) {
  297. $state = $this->goto[$idx];
  298. } else {
  299. $state = $this->gotoDefault[$nonTerminal];
  300. }
  301. ++$stackPos;
  302. $stateStack[$stackPos] = $state;
  303. $this->semStack[$stackPos] = $this->semValue;
  304. $this->tokenEndStack[$stackPos] = $lastTokenEnd;
  305. if ($ruleLength === 0) {
  306. // Empty productions use the start attributes of the lookahead token.
  307. $this->tokenStartStack[$stackPos] = $this->tokenPos;
  308. }
  309. } else {
  310. /* error */
  311. switch ($this->errorState) {
  312. case 0:
  313. $msg = $this->getErrorMessage($symbol, $state);
  314. $this->emitError(new Error($msg, $this->getAttributesForToken($this->tokenPos)));
  315. // Break missing intentionally
  316. // no break
  317. case 1:
  318. case 2:
  319. $this->errorState = 3;
  320. // Pop until error-expecting state uncovered
  321. while (!(
  322. (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0
  323. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
  324. || ($state < $this->YY2TBLSTATE
  325. && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0
  326. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
  327. ) || ($action = $this->action[$idx]) === $this->defaultAction) { // Not totally sure about this
  328. if ($stackPos <= 0) {
  329. // Could not recover from error
  330. return null;
  331. }
  332. $state = $stateStack[--$stackPos];
  333. //$this->tracePop($state);
  334. }
  335. //$this->traceShift($this->errorSymbol);
  336. ++$stackPos;
  337. $stateStack[$stackPos] = $state = $action;
  338. // We treat the error symbol as being empty, so we reset the end attributes
  339. // to the end attributes of the last non-error symbol
  340. $this->tokenStartStack[$stackPos] = $this->tokenPos;
  341. $this->tokenEndStack[$stackPos] = $this->tokenEndStack[$stackPos - 1];
  342. break;
  343. case 3:
  344. if ($symbol === 0) {
  345. // Reached EOF without recovering from error
  346. return null;
  347. }
  348. //$this->traceDiscard($symbol);
  349. $symbol = self::SYMBOL_NONE;
  350. break 2;
  351. }
  352. }
  353. if ($state < $this->numNonLeafStates) {
  354. break;
  355. }
  356. /* >= numNonLeafStates means shift-and-reduce */
  357. $rule = $state - $this->numNonLeafStates;
  358. }
  359. }
  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. protected function checkPropertyHooksForMultiProperty(Property $property, int $hookPos): void {
  1026. if (count($property->props) > 1) {
  1027. $this->emitError(new Error(
  1028. 'Cannot use hooks when declaring multiple properties', $this->getAttributesAt($hookPos)));
  1029. }
  1030. }
  1031. /** @param PropertyHook[] $hooks */
  1032. protected function checkEmptyPropertyHookList(array $hooks, int $hookPos): void {
  1033. if (empty($hooks)) {
  1034. $this->emitError(new Error(
  1035. 'Property hook list cannot be empty', $this->getAttributesAt($hookPos)));
  1036. }
  1037. }
  1038. protected function checkPropertyHook(PropertyHook $hook, ?int $paramListPos): void {
  1039. $name = $hook->name->toLowerString();
  1040. if ($name !== 'get' && $name !== 'set') {
  1041. $this->emitError(new Error(
  1042. 'Unknown hook "' . $hook->name . '", expected "get" or "set"',
  1043. $hook->name->getAttributes()));
  1044. }
  1045. if ($name === 'get' && $paramListPos !== null) {
  1046. $this->emitError(new Error(
  1047. 'get hook must not have a parameter list', $this->getAttributesAt($paramListPos)));
  1048. }
  1049. }
  1050. protected function checkPropertyHookModifiers(int $a, int $b, int $modifierPos): void {
  1051. try {
  1052. Modifiers::verifyModifier($a, $b);
  1053. } catch (Error $error) {
  1054. $error->setAttributes($this->getAttributesAt($modifierPos));
  1055. $this->emitError($error);
  1056. }
  1057. if ($b != Modifiers::FINAL) {
  1058. $this->emitError(new Error(
  1059. 'Cannot use the ' . Modifiers::toString($b) . ' modifier on a property hook',
  1060. $this->getAttributesAt($modifierPos)));
  1061. }
  1062. }
  1063. /**
  1064. * @param Property|Param $node
  1065. */
  1066. protected function addPropertyNameToHooks(Node $node): void {
  1067. if ($node instanceof Property) {
  1068. $name = $node->props[0]->name->toString();
  1069. } else {
  1070. $name = $node->var->name;
  1071. }
  1072. foreach ($node->hooks as $hook) {
  1073. $hook->setAttribute('propertyName', $name);
  1074. }
  1075. }
  1076. /** @param array<Node\Arg|Node\VariadicPlaceholder> $args */
  1077. private function isSimpleExit(array $args): bool {
  1078. if (\count($args) === 0) {
  1079. return true;
  1080. }
  1081. if (\count($args) === 1) {
  1082. $arg = $args[0];
  1083. return $arg instanceof Arg && $arg->name === null &&
  1084. $arg->byRef === false && $arg->unpack === false;
  1085. }
  1086. return false;
  1087. }
  1088. /**
  1089. * @param array<Node\Arg|Node\VariadicPlaceholder> $args
  1090. * @param array<string, mixed> $attrs
  1091. */
  1092. protected function createExitExpr(string $name, int $namePos, array $args, array $attrs): Expr {
  1093. if ($this->isSimpleExit($args)) {
  1094. // Create Exit node for backwards compatibility.
  1095. $attrs['kind'] = strtolower($name) === 'exit' ? Expr\Exit_::KIND_EXIT : Expr\Exit_::KIND_DIE;
  1096. return new Expr\Exit_(\count($args) === 1 ? $args[0]->value : null, $attrs);
  1097. }
  1098. return new Expr\FuncCall(new Name($name, $this->getAttributesAt($namePos)), $args, $attrs);
  1099. }
  1100. /**
  1101. * Creates the token map.
  1102. *
  1103. * The token map maps the PHP internal token identifiers
  1104. * to the identifiers used by the Parser. Additionally it
  1105. * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
  1106. *
  1107. * @return array<int, int> The token map
  1108. */
  1109. protected function createTokenMap(): array {
  1110. $tokenMap = [];
  1111. // Single-char tokens use an identity mapping.
  1112. for ($i = 0; $i < 256; ++$i) {
  1113. $tokenMap[$i] = $i;
  1114. }
  1115. foreach ($this->symbolToName as $name) {
  1116. if ($name[0] === 'T') {
  1117. $tokenMap[\constant($name)] = constant(static::class . '::' . $name);
  1118. }
  1119. }
  1120. // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
  1121. $tokenMap[\T_OPEN_TAG_WITH_ECHO] = static::T_ECHO;
  1122. // T_CLOSE_TAG is equivalent to ';'
  1123. $tokenMap[\T_CLOSE_TAG] = ord(';');
  1124. // We have created a map from PHP token IDs to external symbol IDs.
  1125. // Now map them to the internal symbol ID.
  1126. $fullTokenMap = [];
  1127. foreach ($tokenMap as $phpToken => $extSymbol) {
  1128. $intSymbol = $this->tokenToSymbol[$extSymbol];
  1129. if ($intSymbol === $this->invalidSymbol) {
  1130. continue;
  1131. }
  1132. $fullTokenMap[$phpToken] = $intSymbol;
  1133. }
  1134. return $fullTokenMap;
  1135. }
  1136. }