ParserAbstract.php 52 KB

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