ParserAbstract.php 39 KB

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