ParserAbstract.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  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. abstract class ParserAbstract
  8. {
  9. const SYMBOL_NONE = -1;
  10. /*
  11. * The following members will be filled with generated parsing data:
  12. */
  13. /** @var int Size of $tokenToSymbol map */
  14. protected $tokenToSymbolMapSize;
  15. /** @var int Size of $action table */
  16. protected $actionTableSize;
  17. /** @var int Size of $goto table */
  18. protected $gotoTableSize;
  19. /** @var int Symbol number signifying an invalid token */
  20. protected $invalidSymbol;
  21. /** @var int Symbol number of error recovery token */
  22. protected $errorSymbol;
  23. /** @var int Action number signifying default action */
  24. protected $defaultAction;
  25. /** @var int Rule number signifying that an unexpected token was encountered */
  26. protected $unexpectedTokenRule;
  27. protected $YY2TBLSTATE;
  28. protected $YYNLSTATES;
  29. /** @var array Map of lexer tokens to internal symbols */
  30. protected $tokenToSymbol;
  31. /** @var array Map of symbols to their names */
  32. protected $symbolToName;
  33. /** @var array Names of the production rules (only necessary for debugging) */
  34. protected $productions;
  35. /** @var array Map of states to a displacement into the $action table. The corresponding action for this
  36. * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
  37. action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  38. protected $actionBase;
  39. /** @var array Table of actions. Indexed according to $actionBase comment. */
  40. protected $action;
  41. /** @var array Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
  42. * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  43. protected $actionCheck;
  44. /** @var array Map of states to their default action */
  45. protected $actionDefault;
  46. /** @var array Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
  47. * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
  48. protected $gotoBase;
  49. /** @var array Table of states to goto after reduction. Indexed according to $gotoBase comment. */
  50. protected $goto;
  51. /** @var array Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
  52. * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
  53. protected $gotoCheck;
  54. /** @var array Map of non-terminals to the default state to goto after their reduction */
  55. protected $gotoDefault;
  56. /** @var array Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
  57. * determining the state to goto after reduction. */
  58. protected $ruleToNonTerminal;
  59. /** @var array Map of rules to the length of their right-hand side, which is the number of elements that have to
  60. * be popped from the stack(s) on reduction. */
  61. protected $ruleToLength;
  62. /*
  63. * The following members are part of the parser state:
  64. */
  65. /** @var Lexer Lexer that is used when parsing */
  66. protected $lexer;
  67. /** @var mixed Temporary value containing the result of last semantic action (reduction) */
  68. protected $semValue;
  69. /** @var int Position in stacks (state stack, semantic value stack, attribute stack) */
  70. protected $stackPos;
  71. /** @var array Semantic value stack (contains values of tokens and semantic action results) */
  72. protected $semStack;
  73. /** @var array[] Start attribute stack */
  74. protected $startAttributeStack;
  75. /** @var array End attributes of last *shifted* token */
  76. protected $endAttributes;
  77. /** @var bool Whether to throw on first error */
  78. protected $throwOnError;
  79. /** @var Error[] Errors collected during last parse */
  80. protected $errors;
  81. /**
  82. * Creates a parser instance.
  83. *
  84. * @param Lexer $lexer A lexer
  85. * @param array $options Options array. The boolean 'throwOnError' option determines whether an exception should be
  86. * thrown on first error, or if the parser should try to continue parsing the remaining code
  87. * and build a partial AST.
  88. */
  89. public function __construct(Lexer $lexer, array $options = array()) {
  90. $this->lexer = $lexer;
  91. $this->errors = array();
  92. $this->throwOnError = isset($options['throwOnError']) ? $options['throwOnError'] : true;
  93. }
  94. /**
  95. * Get array of errors that occurred during the last parse.
  96. *
  97. * This method may only return multiple errors if the 'throwOnError' option is disabled.
  98. *
  99. * @return Error[]
  100. */
  101. public function getErrors() {
  102. return $this->errors;
  103. }
  104. /**
  105. * Parses PHP code into a node tree.
  106. *
  107. * @param string $code The source code to parse
  108. *
  109. * @return Node[]|null Array of statements (or null if the 'throwOnError' option is disabled and the parser was
  110. * unable to recover from an error).
  111. */
  112. public function parse($code) {
  113. $this->lexer->startLexing($code);
  114. $this->errors = array();
  115. // We start off with no lookahead-token
  116. $symbol = self::SYMBOL_NONE;
  117. // The attributes for a node are taken from the first and last token of the node.
  118. // From the first token only the startAttributes are taken and from the last only
  119. // the endAttributes. Both are merged using the array union operator (+).
  120. $startAttributes = '*POISON';
  121. $endAttributes = '*POISON';
  122. $this->endAttributes = $endAttributes;
  123. // In order to figure out the attributes for the starting token, we have to keep
  124. // them in a stack
  125. $this->startAttributeStack = array();
  126. // Start off in the initial state and keep a stack of previous states
  127. $state = 0;
  128. $stateStack = array($state);
  129. // Semantic value stack (contains values of tokens and semantic action results)
  130. $this->semStack = array();
  131. // Current position in the stack(s)
  132. $this->stackPos = 0;
  133. $errorState = 0;
  134. for (;;) {
  135. //$this->traceNewState($state, $symbol);
  136. if ($this->actionBase[$state] == 0) {
  137. $rule = $this->actionDefault[$state];
  138. } else {
  139. if ($symbol === self::SYMBOL_NONE) {
  140. // Fetch the next token id from the lexer and fetch additional info by-ref.
  141. // The end attributes are fetched into a temporary variable and only set once the token is really
  142. // shifted (not during read). Otherwise you would sometimes get off-by-one errors, when a rule is
  143. // reduced after a token was read but not yet shifted.
  144. $tokenId = $this->lexer->getNextToken($tokenValue, $startAttributes, $endAttributes);
  145. // map the lexer token id to the internally used symbols
  146. $symbol = $tokenId >= 0 && $tokenId < $this->tokenToSymbolMapSize
  147. ? $this->tokenToSymbol[$tokenId]
  148. : $this->invalidSymbol;
  149. if ($symbol === $this->invalidSymbol) {
  150. throw new \RangeException(sprintf(
  151. 'The lexer returned an invalid token (id=%d, value=%s)',
  152. $tokenId, $tokenValue
  153. ));
  154. }
  155. // This is necessary to assign some meaningful attributes to /* empty */ productions. They'll get
  156. // the attributes of the next token, even though they don't contain it themselves.
  157. $this->startAttributeStack[$this->stackPos+1] = $startAttributes;
  158. //$this->traceRead($symbol);
  159. }
  160. $idx = $this->actionBase[$state] + $symbol;
  161. if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $symbol)
  162. || ($state < $this->YY2TBLSTATE
  163. && ($idx = $this->actionBase[$state + $this->YYNLSTATES] + $symbol) >= 0
  164. && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $symbol))
  165. && ($action = $this->action[$idx]) != $this->defaultAction) {
  166. /*
  167. * >= YYNLSTATES: shift and reduce
  168. * > 0: shift
  169. * = 0: accept
  170. * < 0: reduce
  171. * = -YYUNEXPECTED: error
  172. */
  173. if ($action > 0) {
  174. /* shift */
  175. //$this->traceShift($symbol);
  176. ++$this->stackPos;
  177. $stateStack[$this->stackPos] = $state = $action;
  178. $this->semStack[$this->stackPos] = $tokenValue;
  179. $this->startAttributeStack[$this->stackPos] = $startAttributes;
  180. $this->endAttributes = $endAttributes;
  181. $symbol = self::SYMBOL_NONE;
  182. if ($errorState) {
  183. --$errorState;
  184. }
  185. if ($action < $this->YYNLSTATES) {
  186. continue;
  187. }
  188. /* $yyn >= YYNLSTATES means shift-and-reduce */
  189. $rule = $action - $this->YYNLSTATES;
  190. } else {
  191. $rule = -$action;
  192. }
  193. } else {
  194. $rule = $this->actionDefault[$state];
  195. }
  196. }
  197. for (;;) {
  198. if ($rule === 0) {
  199. /* accept */
  200. //$this->traceAccept();
  201. return $this->semValue;
  202. } elseif ($rule !== $this->unexpectedTokenRule) {
  203. /* reduce */
  204. //$this->traceReduce($rule);
  205. try {
  206. $this->{'reduceRule' . $rule}();
  207. } catch (Error $e) {
  208. if (-1 === $e->getStartLine() && isset($startAttributes['startLine'])) {
  209. $e->setStartLine($startAttributes['startLine']);
  210. }
  211. $this->errors[] = $e;
  212. if ($this->throwOnError) {
  213. throw $e;
  214. } else {
  215. // Currently can't recover from "special" errors
  216. return null;
  217. }
  218. }
  219. /* Goto - shift nonterminal */
  220. $this->stackPos -= $this->ruleToLength[$rule];
  221. $nonTerminal = $this->ruleToNonTerminal[$rule];
  222. $idx = $this->gotoBase[$nonTerminal] + $stateStack[$this->stackPos];
  223. if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] == $nonTerminal) {
  224. $state = $this->goto[$idx];
  225. } else {
  226. $state = $this->gotoDefault[$nonTerminal];
  227. }
  228. ++$this->stackPos;
  229. $stateStack[$this->stackPos] = $state;
  230. $this->semStack[$this->stackPos] = $this->semValue;
  231. } else {
  232. /* error */
  233. switch ($errorState) {
  234. case 0:
  235. $msg = $this->getErrorMessage($symbol, $state);
  236. $error = new Error($msg, $startAttributes + $endAttributes);
  237. $this->errors[] = $error;
  238. if ($this->throwOnError) {
  239. throw $error;
  240. }
  241. // Break missing intentionally
  242. case 1:
  243. case 2:
  244. $errorState = 3;
  245. // Pop until error-expecting state uncovered
  246. while (!(
  247. (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0
  248. && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $this->errorSymbol)
  249. || ($state < $this->YY2TBLSTATE
  250. && ($idx = $this->actionBase[$state + $this->YYNLSTATES] + $this->errorSymbol) >= 0
  251. && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $this->errorSymbol)
  252. ) || ($action = $this->action[$idx]) == $this->defaultAction) { // Not totally sure about this
  253. if ($this->stackPos <= 0) {
  254. // Could not recover from error
  255. return null;
  256. }
  257. $state = $stateStack[--$this->stackPos];
  258. //$this->tracePop($state);
  259. }
  260. //$this->traceShift($this->errorSymbol);
  261. $stateStack[++$this->stackPos] = $state = $action;
  262. break;
  263. case 3:
  264. if ($symbol === 0) {
  265. // Reached EOF without recovering from error
  266. return null;
  267. }
  268. //$this->traceDiscard($symbol);
  269. $symbol = self::SYMBOL_NONE;
  270. break 2;
  271. }
  272. }
  273. if ($state < $this->YYNLSTATES) {
  274. break;
  275. }
  276. /* >= YYNLSTATES means shift-and-reduce */
  277. $rule = $state - $this->YYNLSTATES;
  278. }
  279. }
  280. throw new \RuntimeException('Reached end of parser loop');
  281. }
  282. protected function getErrorMessage($symbol, $state) {
  283. $expectedString = '';
  284. if ($expected = $this->getExpectedTokens($state)) {
  285. $expectedString = ', expecting ' . implode(' or ', $expected);
  286. }
  287. return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
  288. }
  289. protected function getExpectedTokens($state) {
  290. $expected = array();
  291. $base = $this->actionBase[$state];
  292. foreach ($this->symbolToName as $symbol => $name) {
  293. $idx = $base + $symbol;
  294. if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  295. || $state < $this->YY2TBLSTATE
  296. && ($idx = $this->actionBase[$state + $this->YYNLSTATES] + $symbol) >= 0
  297. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  298. ) {
  299. if ($this->action[$idx] != $this->unexpectedTokenRule) {
  300. if (count($expected) == 4) {
  301. /* Too many expected tokens */
  302. return array();
  303. }
  304. $expected[] = $name;
  305. }
  306. }
  307. }
  308. return $expected;
  309. }
  310. /*
  311. * Tracing functions used for debugging the parser.
  312. */
  313. /*
  314. protected function traceNewState($state, $symbol) {
  315. echo '% State ' . $state
  316. . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
  317. }
  318. protected function traceRead($symbol) {
  319. echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
  320. }
  321. protected function traceShift($symbol) {
  322. echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
  323. }
  324. protected function traceAccept() {
  325. echo "% Accepted.\n";
  326. }
  327. protected function traceReduce($n) {
  328. echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
  329. }
  330. protected function tracePop($state) {
  331. echo '% Recovering, uncovered state ' . $state . "\n";
  332. }
  333. protected function traceDiscard($symbol) {
  334. echo '% Discard ' . $this->symbolToName[$symbol] . "\n";
  335. }
  336. */
  337. /*
  338. * Helper functions invoked by semantic actions
  339. */
  340. /**
  341. * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
  342. *
  343. * @param Node[] $stmts
  344. * @return Node[]
  345. */
  346. protected function handleNamespaces(array $stmts) {
  347. $style = $this->getNamespacingStyle($stmts);
  348. if (null === $style) {
  349. // not namespaced, nothing to do
  350. return $stmts;
  351. } elseif ('brace' === $style) {
  352. // For braced namespaces we only have to check that there are no invalid statements between the namespaces
  353. $afterFirstNamespace = false;
  354. foreach ($stmts as $stmt) {
  355. if ($stmt instanceof Node\Stmt\Namespace_) {
  356. $afterFirstNamespace = true;
  357. } elseif (!$stmt instanceof Node\Stmt\HaltCompiler && $afterFirstNamespace) {
  358. throw new Error('No code may exist outside of namespace {}', $stmt->getLine());
  359. }
  360. }
  361. return $stmts;
  362. } else {
  363. // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
  364. $resultStmts = array();
  365. $targetStmts =& $resultStmts;
  366. foreach ($stmts as $stmt) {
  367. if ($stmt instanceof Node\Stmt\Namespace_) {
  368. $stmt->stmts = array();
  369. $targetStmts =& $stmt->stmts;
  370. $resultStmts[] = $stmt;
  371. } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
  372. // __halt_compiler() is not moved into the namespace
  373. $resultStmts[] = $stmt;
  374. } else {
  375. $targetStmts[] = $stmt;
  376. }
  377. }
  378. return $resultStmts;
  379. }
  380. }
  381. private function getNamespacingStyle(array $stmts) {
  382. $style = null;
  383. $hasNotAllowedStmts = false;
  384. foreach ($stmts as $stmt) {
  385. if ($stmt instanceof Node\Stmt\Namespace_) {
  386. $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
  387. if (null === $style) {
  388. $style = $currentStyle;
  389. if ($hasNotAllowedStmts) {
  390. throw new Error('Namespace declaration statement has to be the very first statement in the script', $stmt->getLine());
  391. }
  392. } elseif ($style !== $currentStyle) {
  393. throw new Error('Cannot mix bracketed namespace declarations with unbracketed namespace declarations', $stmt->getLine());
  394. }
  395. } elseif (!$stmt instanceof Node\Stmt\Declare_ && !$stmt instanceof Node\Stmt\HaltCompiler) {
  396. $hasNotAllowedStmts = true;
  397. }
  398. }
  399. return $style;
  400. }
  401. }