ParserAbstract.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. /*
  4. * This parser is based on a skeleton written by Moriyoshi Koizumi, which in
  5. * turn is based on work by Masato Bito.
  6. */
  7. use PhpParser\Node\Expr;
  8. use PhpParser\Node\Name;
  9. use PhpParser\Node\Param;
  10. use PhpParser\Node\Scalar\Encapsed;
  11. use PhpParser\Node\Scalar\LNumber;
  12. use PhpParser\Node\Scalar\String_;
  13. use PhpParser\Node\Stmt\Class_;
  14. use PhpParser\Node\Stmt\ClassConst;
  15. use PhpParser\Node\Stmt\ClassMethod;
  16. use PhpParser\Node\Stmt\Interface_;
  17. use PhpParser\Node\Stmt\Namespace_;
  18. use PhpParser\Node\Stmt\Property;
  19. use PhpParser\Node\Stmt\TryCatch;
  20. use PhpParser\Node\Stmt\UseUse;
  21. use PhpParser\Node\VarLikeIdentifier;
  22. abstract class ParserAbstract implements Parser
  23. {
  24. const SYMBOL_NONE = -1;
  25. /*
  26. * The following members will be filled with generated parsing data:
  27. */
  28. /** @var int Size of $tokenToSymbol map */
  29. protected $tokenToSymbolMapSize;
  30. /** @var int Size of $action table */
  31. protected $actionTableSize;
  32. /** @var int Size of $goto table */
  33. protected $gotoTableSize;
  34. /** @var int Symbol number signifying an invalid token */
  35. protected $invalidSymbol;
  36. /** @var int Symbol number of error recovery token */
  37. protected $errorSymbol;
  38. /** @var int Action number signifying default action */
  39. protected $defaultAction;
  40. /** @var int Rule number signifying that an unexpected token was encountered */
  41. protected $unexpectedTokenRule;
  42. protected $YY2TBLSTATE;
  43. /** @var int Number of non-leaf states */
  44. protected $numNonLeafStates;
  45. /** @var int[] Map of lexer tokens to internal symbols */
  46. protected $tokenToSymbol;
  47. /** @var string[] Map of symbols to their names */
  48. protected $symbolToName;
  49. /** @var array Names of the production rules (only necessary for debugging) */
  50. protected $productions;
  51. /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this
  52. * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
  53. action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  54. protected $actionBase;
  55. /** @var int[] Table of actions. Indexed according to $actionBase comment. */
  56. protected $action;
  57. /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
  58. * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  59. protected $actionCheck;
  60. /** @var int[] Map of states to their default action */
  61. protected $actionDefault;
  62. /** @var callable[] Semantic action callbacks */
  63. protected $reduceCallbacks;
  64. /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
  65. * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
  66. protected $gotoBase;
  67. /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */
  68. protected $goto;
  69. /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
  70. * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
  71. protected $gotoCheck;
  72. /** @var int[] Map of non-terminals to the default state to goto after their reduction */
  73. protected $gotoDefault;
  74. /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
  75. * determining the state to goto after reduction. */
  76. protected $ruleToNonTerminal;
  77. /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to
  78. * be popped from the stack(s) on reduction. */
  79. protected $ruleToLength;
  80. /*
  81. * The following members are part of the parser state:
  82. */
  83. /** @var Lexer Lexer that is used when parsing */
  84. protected $lexer;
  85. /** @var mixed Temporary value containing the result of last semantic action (reduction) */
  86. protected $semValue;
  87. /** @var array Semantic value stack (contains values of tokens and semantic action results) */
  88. protected $semStack;
  89. /** @var array[] Start attribute stack */
  90. protected $startAttributeStack;
  91. /** @var array[] End attribute stack */
  92. protected $endAttributeStack;
  93. /** @var array End attributes of last *shifted* token */
  94. protected $endAttributes;
  95. /** @var array Start attributes of last *read* token */
  96. protected $lookaheadStartAttributes;
  97. /** @var ErrorHandler Error handler */
  98. protected $errorHandler;
  99. /** @var int Error state, used to avoid error floods */
  100. protected $errorState;
  101. /**
  102. * Initialize $reduceCallbacks map.
  103. */
  104. abstract protected function initReduceCallbacks();
  105. /**
  106. * Creates a parser instance.
  107. *
  108. * Options: Currently none.
  109. *
  110. * @param Lexer $lexer A lexer
  111. * @param array $options Options array.
  112. */
  113. public function __construct(Lexer $lexer, array $options = []) {
  114. $this->lexer = $lexer;
  115. if (isset($options['throwOnError'])) {
  116. throw new \LogicException(
  117. '"throwOnError" is no longer supported, use "errorHandler" instead');
  118. }
  119. $this->initReduceCallbacks();
  120. }
  121. /**
  122. * Parses PHP code into a node tree.
  123. *
  124. * If a non-throwing error handler is used, the parser will continue parsing after an error
  125. * occurred and attempt to build a partial AST.
  126. *
  127. * @param string $code The source code to parse
  128. * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults
  129. * to ErrorHandler\Throwing.
  130. *
  131. * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and
  132. * the parser was unable to recover from an error).
  133. */
  134. public function parse(string $code, ErrorHandler $errorHandler = null) {
  135. $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing;
  136. $this->lexer->startLexing($code, $this->errorHandler);
  137. $result = $this->doParse();
  138. // Clear out some of the interior state, so we don't hold onto unnecessary
  139. // memory between uses of the parser
  140. $this->startAttributeStack = [];
  141. $this->endAttributeStack = [];
  142. $this->semStack = [];
  143. $this->semValue = null;
  144. return $result;
  145. }
  146. protected function doParse() {
  147. // We start off with no lookahead-token
  148. $symbol = self::SYMBOL_NONE;
  149. // The attributes for a node are taken from the first and last token of the node.
  150. // From the first token only the startAttributes are taken and from the last only
  151. // the endAttributes. Both are merged using the array union operator (+).
  152. $startAttributes = [];
  153. $endAttributes = [];
  154. $this->endAttributes = $endAttributes;
  155. // Keep stack of start and end attributes
  156. $this->startAttributeStack = [];
  157. $this->endAttributeStack = [$endAttributes];
  158. // Start off in the initial state and keep a stack of previous states
  159. $state = 0;
  160. $stateStack = [$state];
  161. // Semantic value stack (contains values of tokens and semantic action results)
  162. $this->semStack = [];
  163. // Current position in the stack(s)
  164. $stackPos = 0;
  165. $this->errorState = 0;
  166. for (;;) {
  167. //$this->traceNewState($state, $symbol);
  168. if ($this->actionBase[$state] === 0) {
  169. $rule = $this->actionDefault[$state];
  170. } else {
  171. if ($symbol === self::SYMBOL_NONE) {
  172. // Fetch the next token id from the lexer and fetch additional info by-ref.
  173. // The end attributes are fetched into a temporary variable and only set once the token is really
  174. // shifted (not during read). Otherwise you would sometimes get off-by-one errors, when a rule is
  175. // reduced after a token was read but not yet shifted.
  176. $tokenId = $this->lexer->getNextToken($tokenValue, $startAttributes, $endAttributes);
  177. // map the lexer token id to the internally used symbols
  178. $symbol = $tokenId >= 0 && $tokenId < $this->tokenToSymbolMapSize
  179. ? $this->tokenToSymbol[$tokenId]
  180. : $this->invalidSymbol;
  181. if ($symbol === $this->invalidSymbol) {
  182. throw new \RangeException(sprintf(
  183. 'The lexer returned an invalid token (id=%d, value=%s)',
  184. $tokenId, $tokenValue
  185. ));
  186. }
  187. // This is necessary to assign some meaningful attributes to /* empty */ productions. They'll get
  188. // the attributes of the next token, even though they don't contain it themselves.
  189. $this->startAttributeStack[$stackPos+1] = $startAttributes;
  190. $this->endAttributeStack[$stackPos+1] = $endAttributes;
  191. $this->lookaheadStartAttributes = $startAttributes;
  192. //$this->traceRead($symbol);
  193. }
  194. $idx = $this->actionBase[$state] + $symbol;
  195. if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)
  196. || ($state < $this->YY2TBLSTATE
  197. && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
  198. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol))
  199. && ($action = $this->action[$idx]) !== $this->defaultAction) {
  200. /*
  201. * >= numNonLeafStates: shift and reduce
  202. * > 0: shift
  203. * = 0: accept
  204. * < 0: reduce
  205. * = -YYUNEXPECTED: error
  206. */
  207. if ($action > 0) {
  208. /* shift */
  209. //$this->traceShift($symbol);
  210. ++$stackPos;
  211. $stateStack[$stackPos] = $state = $action;
  212. $this->semStack[$stackPos] = $tokenValue;
  213. $this->startAttributeStack[$stackPos] = $startAttributes;
  214. $this->endAttributeStack[$stackPos] = $endAttributes;
  215. $this->endAttributes = $endAttributes;
  216. $symbol = self::SYMBOL_NONE;
  217. if ($this->errorState) {
  218. --$this->errorState;
  219. }
  220. if ($action < $this->numNonLeafStates) {
  221. continue;
  222. }
  223. /* $yyn >= numNonLeafStates means shift-and-reduce */
  224. $rule = $action - $this->numNonLeafStates;
  225. } else {
  226. $rule = -$action;
  227. }
  228. } else {
  229. $rule = $this->actionDefault[$state];
  230. }
  231. }
  232. for (;;) {
  233. if ($rule === 0) {
  234. /* accept */
  235. //$this->traceAccept();
  236. return $this->semValue;
  237. } elseif ($rule !== $this->unexpectedTokenRule) {
  238. /* reduce */
  239. //$this->traceReduce($rule);
  240. try {
  241. $this->reduceCallbacks[$rule]($stackPos);
  242. } catch (Error $e) {
  243. if (-1 === $e->getStartLine() && isset($startAttributes['startLine'])) {
  244. $e->setStartLine($startAttributes['startLine']);
  245. }
  246. $this->emitError($e);
  247. // Can't recover from this type of error
  248. return null;
  249. }
  250. /* Goto - shift nonterminal */
  251. $lastEndAttributes = $this->endAttributeStack[$stackPos];
  252. $stackPos -= $this->ruleToLength[$rule];
  253. $nonTerminal = $this->ruleToNonTerminal[$rule];
  254. $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos];
  255. if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) {
  256. $state = $this->goto[$idx];
  257. } else {
  258. $state = $this->gotoDefault[$nonTerminal];
  259. }
  260. ++$stackPos;
  261. $stateStack[$stackPos] = $state;
  262. $this->semStack[$stackPos] = $this->semValue;
  263. $this->endAttributeStack[$stackPos] = $lastEndAttributes;
  264. } else {
  265. /* error */
  266. switch ($this->errorState) {
  267. case 0:
  268. $msg = $this->getErrorMessage($symbol, $state);
  269. $this->emitError(new Error($msg, $startAttributes + $endAttributes));
  270. // Break missing intentionally
  271. case 1:
  272. case 2:
  273. $this->errorState = 3;
  274. // Pop until error-expecting state uncovered
  275. while (!(
  276. (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0
  277. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
  278. || ($state < $this->YY2TBLSTATE
  279. && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0
  280. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
  281. ) || ($action = $this->action[$idx]) === $this->defaultAction) { // Not totally sure about this
  282. if ($stackPos <= 0) {
  283. // Could not recover from error
  284. return null;
  285. }
  286. $state = $stateStack[--$stackPos];
  287. //$this->tracePop($state);
  288. }
  289. //$this->traceShift($this->errorSymbol);
  290. ++$stackPos;
  291. $stateStack[$stackPos] = $state = $action;
  292. // We treat the error symbol as being empty, so we reset the end attributes
  293. // to the end attributes of the last non-error symbol
  294. $this->endAttributeStack[$stackPos] = $this->endAttributeStack[$stackPos - 1];
  295. $this->endAttributes = $this->endAttributeStack[$stackPos - 1];
  296. break;
  297. case 3:
  298. if ($symbol === 0) {
  299. // Reached EOF without recovering from error
  300. return null;
  301. }
  302. //$this->traceDiscard($symbol);
  303. $symbol = self::SYMBOL_NONE;
  304. break 2;
  305. }
  306. }
  307. if ($state < $this->numNonLeafStates) {
  308. break;
  309. }
  310. /* >= numNonLeafStates means shift-and-reduce */
  311. $rule = $state - $this->numNonLeafStates;
  312. }
  313. }
  314. throw new \RuntimeException('Reached end of parser loop');
  315. }
  316. protected function emitError(Error $error) {
  317. $this->errorHandler->handleError($error);
  318. }
  319. /**
  320. * Format error message including expected tokens.
  321. *
  322. * @param int $symbol Unexpected symbol
  323. * @param int $state State at time of error
  324. *
  325. * @return string Formatted error message
  326. */
  327. protected function getErrorMessage(int $symbol, int $state) : string {
  328. $expectedString = '';
  329. if ($expected = $this->getExpectedTokens($state)) {
  330. $expectedString = ', expecting ' . implode(' or ', $expected);
  331. }
  332. return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
  333. }
  334. /**
  335. * Get limited number of expected tokens in given state.
  336. *
  337. * @param int $state State
  338. *
  339. * @return string[] Expected tokens. If too many, an empty array is returned.
  340. */
  341. protected function getExpectedTokens(int $state) : array {
  342. $expected = [];
  343. $base = $this->actionBase[$state];
  344. foreach ($this->symbolToName as $symbol => $name) {
  345. $idx = $base + $symbol;
  346. if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  347. || $state < $this->YY2TBLSTATE
  348. && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
  349. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  350. ) {
  351. if ($this->action[$idx] !== $this->unexpectedTokenRule
  352. && $this->action[$idx] !== $this->defaultAction
  353. && $symbol !== $this->errorSymbol
  354. ) {
  355. if (count($expected) === 4) {
  356. /* Too many expected tokens */
  357. return [];
  358. }
  359. $expected[] = $name;
  360. }
  361. }
  362. }
  363. return $expected;
  364. }
  365. /*
  366. * Tracing functions used for debugging the parser.
  367. */
  368. /*
  369. protected function traceNewState($state, $symbol) {
  370. echo '% State ' . $state
  371. . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
  372. }
  373. protected function traceRead($symbol) {
  374. echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
  375. }
  376. protected function traceShift($symbol) {
  377. echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
  378. }
  379. protected function traceAccept() {
  380. echo "% Accepted.\n";
  381. }
  382. protected function traceReduce($n) {
  383. echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
  384. }
  385. protected function tracePop($state) {
  386. echo '% Recovering, uncovered state ' . $state . "\n";
  387. }
  388. protected function traceDiscard($symbol) {
  389. echo '% Discard ' . $this->symbolToName[$symbol] . "\n";
  390. }
  391. */
  392. /*
  393. * Helper functions invoked by semantic actions
  394. */
  395. /**
  396. * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
  397. *
  398. * @param Node\Stmt[] $stmts
  399. * @return Node\Stmt[]
  400. */
  401. protected function handleNamespaces(array $stmts) : array {
  402. $hasErrored = false;
  403. $style = $this->getNamespacingStyle($stmts);
  404. if (null === $style) {
  405. // not namespaced, nothing to do
  406. return $stmts;
  407. } elseif ('brace' === $style) {
  408. // For braced namespaces we only have to check that there are no invalid statements between the namespaces
  409. $afterFirstNamespace = false;
  410. foreach ($stmts as $stmt) {
  411. if ($stmt instanceof Node\Stmt\Namespace_) {
  412. $afterFirstNamespace = true;
  413. } elseif (!$stmt instanceof Node\Stmt\HaltCompiler
  414. && !$stmt instanceof Node\Stmt\Nop
  415. && $afterFirstNamespace && !$hasErrored) {
  416. $this->emitError(new Error(
  417. 'No code may exist outside of namespace {}', $stmt->getAttributes()));
  418. $hasErrored = true; // Avoid one error for every statement
  419. }
  420. }
  421. return $stmts;
  422. } else {
  423. // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
  424. $resultStmts = [];
  425. $targetStmts =& $resultStmts;
  426. $lastNs = null;
  427. foreach ($stmts as $stmt) {
  428. if ($stmt instanceof Node\Stmt\Namespace_) {
  429. if ($lastNs !== null) {
  430. $this->fixupNamespaceAttributes($lastNs);
  431. }
  432. if ($stmt->stmts === null) {
  433. $stmt->stmts = [];
  434. $targetStmts =& $stmt->stmts;
  435. $resultStmts[] = $stmt;
  436. } else {
  437. // This handles the invalid case of mixed style namespaces
  438. $resultStmts[] = $stmt;
  439. $targetStmts =& $resultStmts;
  440. }
  441. $lastNs = $stmt;
  442. } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
  443. // __halt_compiler() is not moved into the namespace
  444. $resultStmts[] = $stmt;
  445. } else {
  446. $targetStmts[] = $stmt;
  447. }
  448. }
  449. if ($lastNs !== null) {
  450. $this->fixupNamespaceAttributes($lastNs);
  451. }
  452. return $resultStmts;
  453. }
  454. }
  455. private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt) {
  456. // We moved the statements into the namespace node, as such the end of the namespace node
  457. // needs to be extended to the end of the statements.
  458. if (empty($stmt->stmts)) {
  459. return;
  460. }
  461. // We only move the builtin end attributes here. This is the best we can do with the
  462. // knowledge we have.
  463. $endAttributes = ['endLine', 'endFilePos', 'endTokenPos'];
  464. $lastStmt = $stmt->stmts[count($stmt->stmts) - 1];
  465. foreach ($endAttributes as $endAttribute) {
  466. if ($lastStmt->hasAttribute($endAttribute)) {
  467. $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute));
  468. }
  469. }
  470. }
  471. /**
  472. * Determine namespacing style (semicolon or brace)
  473. *
  474. * @param Node[] $stmts Top-level statements.
  475. *
  476. * @return null|string One of "semicolon", "brace" or null (no namespaces)
  477. */
  478. private function getNamespacingStyle(array $stmts) {
  479. $style = null;
  480. $hasNotAllowedStmts = false;
  481. foreach ($stmts as $i => $stmt) {
  482. if ($stmt instanceof Node\Stmt\Namespace_) {
  483. $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
  484. if (null === $style) {
  485. $style = $currentStyle;
  486. if ($hasNotAllowedStmts) {
  487. $this->emitError(new Error(
  488. 'Namespace declaration statement has to be the very first statement in the script',
  489. $stmt->getLine() // Avoid marking the entire namespace as an error
  490. ));
  491. }
  492. } elseif ($style !== $currentStyle) {
  493. $this->emitError(new Error(
  494. 'Cannot mix bracketed namespace declarations with unbracketed namespace declarations',
  495. $stmt->getLine() // Avoid marking the entire namespace as an error
  496. ));
  497. // Treat like semicolon style for namespace normalization
  498. return 'semicolon';
  499. }
  500. continue;
  501. }
  502. /* declare(), __halt_compiler() and nops can be used before a namespace declaration */
  503. if ($stmt instanceof Node\Stmt\Declare_
  504. || $stmt instanceof Node\Stmt\HaltCompiler
  505. || $stmt instanceof Node\Stmt\Nop) {
  506. continue;
  507. }
  508. /* There may be a hashbang line at the very start of the file */
  509. if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) {
  510. continue;
  511. }
  512. /* Everything else if forbidden before namespace declarations */
  513. $hasNotAllowedStmts = true;
  514. }
  515. return $style;
  516. }
  517. /**
  518. * Fix up parsing of static property calls in PHP 5.
  519. *
  520. * In PHP 5 A::$b[c][d] and A::$b[c][d]() have very different interpretation. The former is
  521. * interpreted as (A::$b)[c][d], while the latter is the same as A::{$b[c][d]}(). We parse the
  522. * latter as the former initially and this method fixes the AST into the correct form when we
  523. * encounter the "()".
  524. *
  525. * @param Node\Expr\StaticPropertyFetch|Node\Expr\ArrayDimFetch $prop
  526. * @param Node\Arg[] $args
  527. * @param array $attributes
  528. *
  529. * @return Expr\StaticCall
  530. */
  531. protected function fixupPhp5StaticPropCall($prop, array $args, array $attributes) : Expr\StaticCall {
  532. if ($prop instanceof Node\Expr\StaticPropertyFetch) {
  533. $name = $prop->name instanceof VarLikeIdentifier
  534. ? $prop->name->toString() : $prop->name;
  535. $var = new Expr\Variable($name, $prop->name->getAttributes());
  536. return new Expr\StaticCall($prop->class, $var, $args, $attributes);
  537. } elseif ($prop instanceof Node\Expr\ArrayDimFetch) {
  538. $tmp = $prop;
  539. while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
  540. $tmp = $tmp->var;
  541. }
  542. /** @var Expr\StaticPropertyFetch $staticProp */
  543. $staticProp = $tmp->var;
  544. // Set start attributes to attributes of innermost node
  545. $tmp = $prop;
  546. $this->fixupStartAttributes($tmp, $staticProp->name);
  547. while ($tmp->var instanceof Node\Expr\ArrayDimFetch) {
  548. $tmp = $tmp->var;
  549. $this->fixupStartAttributes($tmp, $staticProp->name);
  550. }
  551. $name = $staticProp->name instanceof VarLikeIdentifier
  552. ? $staticProp->name->toString() : $staticProp->name;
  553. $tmp->var = new Expr\Variable($name, $staticProp->name->getAttributes());
  554. return new Expr\StaticCall($staticProp->class, $prop, $args, $attributes);
  555. } else {
  556. throw new \Exception;
  557. }
  558. }
  559. protected function fixupStartAttributes(Node $to, Node $from) {
  560. $startAttributes = ['startLine', 'startFilePos', 'startTokenPos'];
  561. foreach ($startAttributes as $startAttribute) {
  562. if ($from->hasAttribute($startAttribute)) {
  563. $to->setAttribute($startAttribute, $from->getAttribute($startAttribute));
  564. }
  565. }
  566. }
  567. protected function handleBuiltinTypes(Name $name) {
  568. $scalarTypes = [
  569. 'bool' => true,
  570. 'int' => true,
  571. 'float' => true,
  572. 'string' => true,
  573. 'iterable' => true,
  574. 'void' => true,
  575. 'object' => true,
  576. ];
  577. if (!$name->isUnqualified()) {
  578. return $name;
  579. }
  580. $lowerName = $name->toLowerString();
  581. if (!isset($scalarTypes[$lowerName])) {
  582. return $name;
  583. }
  584. return new Node\Identifier($lowerName, $name->getAttributes());
  585. }
  586. /**
  587. * Get combined start and end attributes at a stack location
  588. *
  589. * @param int $pos Stack location
  590. *
  591. * @return array Combined start and end attributes
  592. */
  593. protected function getAttributesAt(int $pos) : array {
  594. return $this->startAttributeStack[$pos] + $this->endAttributeStack[$pos];
  595. }
  596. protected function parseLNumber($str, $attributes, $allowInvalidOctal = false) {
  597. try {
  598. return LNumber::fromString($str, $attributes, $allowInvalidOctal);
  599. } catch (Error $error) {
  600. $this->emitError($error);
  601. // Use dummy value
  602. return new LNumber(0, $attributes);
  603. }
  604. }
  605. /**
  606. * Parse a T_NUM_STRING token into either an integer or string node.
  607. *
  608. * @param string $str Number string
  609. * @param array $attributes Attributes
  610. *
  611. * @return LNumber|String_ Integer or string node.
  612. */
  613. protected function parseNumString(string $str, array $attributes) {
  614. if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) {
  615. return new String_($str, $attributes);
  616. }
  617. $num = +$str;
  618. if (!is_int($num)) {
  619. return new String_($str, $attributes);
  620. }
  621. return new LNumber($num, $attributes);
  622. }
  623. protected function stripIndentation(
  624. string $string, int $indentLen, string $indentChar,
  625. bool $newlineAtStart, bool $newlineAtEnd, array $attributes
  626. ) {
  627. if ($indentLen === 0) {
  628. return $string;
  629. }
  630. $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)';
  631. $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])';
  632. $regex = '/' . $start . '([ \t]*)(' . $end . ')?/';
  633. return preg_replace_callback(
  634. $regex,
  635. function ($matches) use ($indentLen, $indentChar, $attributes) {
  636. $prefix = substr($matches[1], 0, $indentLen);
  637. if (false !== strpos($prefix, $indentChar === " " ? "\t" : " ")) {
  638. $this->emitError(new Error(
  639. 'Invalid indentation - tabs and spaces cannot be mixed', $attributes
  640. ));
  641. } elseif (strlen($prefix) < $indentLen && !isset($matches[2])) {
  642. $this->emitError(new Error(
  643. 'Invalid body indentation level ' .
  644. '(expecting an indentation level of at least ' . $indentLen . ')',
  645. $attributes
  646. ));
  647. }
  648. return substr($matches[0], strlen($prefix));
  649. },
  650. $string
  651. );
  652. }
  653. protected function parseDocString(
  654. string $startToken, $contents, string $endToken,
  655. array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape
  656. ) {
  657. $kind = strpos($startToken, "'") === false
  658. ? String_::KIND_HEREDOC : String_::KIND_NOWDOC;
  659. $regex = '/\A[bB]?<<<[ \t]*[\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\'"]?(?:\r\n|\n|\r)\z/';
  660. $result = preg_match($regex, $startToken, $matches);
  661. assert($result === 1);
  662. $label = $matches[1];
  663. $result = preg_match('/\A[ \t]*/', $endToken, $matches);
  664. assert($result === 1);
  665. $indentation = $matches[0];
  666. $attributes['kind'] = $kind;
  667. $attributes['docLabel'] = $label;
  668. $attributes['docIndentation'] = $indentation;
  669. $indentHasSpaces = false !== strpos($indentation, " ");
  670. $indentHasTabs = false !== strpos($indentation, "\t");
  671. if ($indentHasSpaces && $indentHasTabs) {
  672. $this->emitError(new Error(
  673. 'Invalid indentation - tabs and spaces cannot be mixed',
  674. $endTokenAttributes
  675. ));
  676. // Proceed processing as if this doc string is not indented
  677. $indentation = '';
  678. }
  679. $indentLen = \strlen($indentation);
  680. $indentChar = $indentHasSpaces ? " " : "\t";
  681. if (\is_string($contents)) {
  682. if ($contents === '') {
  683. return new String_('', $attributes);
  684. }
  685. $contents = $this->stripIndentation(
  686. $contents, $indentLen, $indentChar, true, true, $attributes
  687. );
  688. $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents);
  689. if ($kind === String_::KIND_HEREDOC) {
  690. $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape);
  691. }
  692. return new String_($contents, $attributes);
  693. } else {
  694. assert(count($contents) > 0);
  695. if (!$contents[0] instanceof Node\Scalar\EncapsedStringPart) {
  696. // If there is no leading encapsed string part, pretend there is an empty one
  697. $this->stripIndentation(
  698. '', $indentLen, $indentChar, true, false, $contents[0]->getAttributes()
  699. );
  700. }
  701. $newContents = [];
  702. foreach ($contents as $i => $part) {
  703. if ($part instanceof Node\Scalar\EncapsedStringPart) {
  704. $isLast = $i === \count($contents) - 1;
  705. $part->value = $this->stripIndentation(
  706. $part->value, $indentLen, $indentChar,
  707. $i === 0, $isLast, $part->getAttributes()
  708. );
  709. $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape);
  710. if ($isLast) {
  711. $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value);
  712. }
  713. if ('' === $part->value) {
  714. continue;
  715. }
  716. }
  717. $newContents[] = $part;
  718. }
  719. return new Encapsed($newContents, $attributes);
  720. }
  721. }
  722. protected function checkModifier($a, $b, $modifierPos) {
  723. // Jumping through some hoops here because verifyModifier() is also used elsewhere
  724. try {
  725. Class_::verifyModifier($a, $b);
  726. } catch (Error $error) {
  727. $error->setAttributes($this->getAttributesAt($modifierPos));
  728. $this->emitError($error);
  729. }
  730. }
  731. protected function checkParam(Param $node) {
  732. if ($node->variadic && null !== $node->default) {
  733. $this->emitError(new Error(
  734. 'Variadic parameter cannot have a default value',
  735. $node->default->getAttributes()
  736. ));
  737. }
  738. }
  739. protected function checkTryCatch(TryCatch $node) {
  740. if (empty($node->catches) && null === $node->finally) {
  741. $this->emitError(new Error(
  742. 'Cannot use try without catch or finally', $node->getAttributes()
  743. ));
  744. }
  745. }
  746. protected function checkNamespace(Namespace_ $node) {
  747. if ($node->name && $node->name->isSpecialClassName()) {
  748. $this->emitError(new Error(
  749. sprintf('Cannot use \'%s\' as namespace name', $node->name),
  750. $node->name->getAttributes()
  751. ));
  752. }
  753. if (null !== $node->stmts) {
  754. foreach ($node->stmts as $stmt) {
  755. if ($stmt instanceof Namespace_) {
  756. $this->emitError(new Error(
  757. 'Namespace declarations cannot be nested', $stmt->getAttributes()
  758. ));
  759. }
  760. }
  761. }
  762. }
  763. protected function checkClass(Class_ $node, $namePos) {
  764. if (null !== $node->name && $node->name->isSpecialClassName()) {
  765. $this->emitError(new Error(
  766. sprintf('Cannot use \'%s\' as class name as it is reserved', $node->name),
  767. $this->getAttributesAt($namePos)
  768. ));
  769. }
  770. if ($node->extends && $node->extends->isSpecialClassName()) {
  771. $this->emitError(new Error(
  772. sprintf('Cannot use \'%s\' as class name as it is reserved', $node->extends),
  773. $node->extends->getAttributes()
  774. ));
  775. }
  776. foreach ($node->implements as $interface) {
  777. if ($interface->isSpecialClassName()) {
  778. $this->emitError(new Error(
  779. sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
  780. $interface->getAttributes()
  781. ));
  782. }
  783. }
  784. }
  785. protected function checkInterface(Interface_ $node, $namePos) {
  786. if (null !== $node->name && $node->name->isSpecialClassName()) {
  787. $this->emitError(new Error(
  788. sprintf('Cannot use \'%s\' as class name as it is reserved', $node->name),
  789. $this->getAttributesAt($namePos)
  790. ));
  791. }
  792. foreach ($node->extends as $interface) {
  793. if ($interface->isSpecialClassName()) {
  794. $this->emitError(new Error(
  795. sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
  796. $interface->getAttributes()
  797. ));
  798. }
  799. }
  800. }
  801. protected function checkClassMethod(ClassMethod $node, $modifierPos) {
  802. if ($node->flags & Class_::MODIFIER_STATIC) {
  803. switch ($node->name->toLowerString()) {
  804. case '__construct':
  805. $this->emitError(new Error(
  806. sprintf('Constructor %s() cannot be static', $node->name),
  807. $this->getAttributesAt($modifierPos)));
  808. break;
  809. case '__destruct':
  810. $this->emitError(new Error(
  811. sprintf('Destructor %s() cannot be static', $node->name),
  812. $this->getAttributesAt($modifierPos)));
  813. break;
  814. case '__clone':
  815. $this->emitError(new Error(
  816. sprintf('Clone method %s() cannot be static', $node->name),
  817. $this->getAttributesAt($modifierPos)));
  818. break;
  819. }
  820. }
  821. }
  822. protected function checkClassConst(ClassConst $node, $modifierPos) {
  823. if ($node->flags & Class_::MODIFIER_STATIC) {
  824. $this->emitError(new Error(
  825. "Cannot use 'static' as constant modifier",
  826. $this->getAttributesAt($modifierPos)));
  827. }
  828. if ($node->flags & Class_::MODIFIER_ABSTRACT) {
  829. $this->emitError(new Error(
  830. "Cannot use 'abstract' as constant modifier",
  831. $this->getAttributesAt($modifierPos)));
  832. }
  833. if ($node->flags & Class_::MODIFIER_FINAL) {
  834. $this->emitError(new Error(
  835. "Cannot use 'final' as constant modifier",
  836. $this->getAttributesAt($modifierPos)));
  837. }
  838. }
  839. protected function checkProperty(Property $node, $modifierPos) {
  840. if ($node->flags & Class_::MODIFIER_ABSTRACT) {
  841. $this->emitError(new Error('Properties cannot be declared abstract',
  842. $this->getAttributesAt($modifierPos)));
  843. }
  844. if ($node->flags & Class_::MODIFIER_FINAL) {
  845. $this->emitError(new Error('Properties cannot be declared final',
  846. $this->getAttributesAt($modifierPos)));
  847. }
  848. }
  849. protected function checkUseUse(UseUse $node, $namePos) {
  850. if ($node->alias && $node->alias->isSpecialClassName()) {
  851. $this->emitError(new Error(
  852. sprintf(
  853. 'Cannot use %s as %s because \'%2$s\' is a special class name',
  854. $node->name, $node->alias
  855. ),
  856. $this->getAttributesAt($namePos)
  857. ));
  858. }
  859. }
  860. }