Brak opisu

ParserAbstract.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 Action number signifying default action */
  22. protected $defaultAction;
  23. /** @var int Rule number signifying that an unexpected token was encountered */
  24. protected $unexpectedTokenRule;
  25. protected $YY2TBLSTATE;
  26. protected $YYNLSTATES;
  27. /** @var array Map of lexer tokens to internal symbols */
  28. protected $tokenToSymbol;
  29. /** @var array Map of symbols to their names */
  30. protected $symbolToName;
  31. /** @var array Names of the production rules (only necessary for debugging) */
  32. protected $productions;
  33. /** @var array Map of states to a displacement into the $action table. The corresponding action for this
  34. * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the
  35. action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  36. protected $actionBase;
  37. /** @var array Table of actions. Indexed according to $actionBase comment. */
  38. protected $action;
  39. /** @var array Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol
  40. * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */
  41. protected $actionCheck;
  42. /** @var array Map of states to their default action */
  43. protected $actionDefault;
  44. /** @var array Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this
  45. * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */
  46. protected $gotoBase;
  47. /** @var array Table of states to goto after reduction. Indexed according to $gotoBase comment. */
  48. protected $goto;
  49. /** @var array Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal
  50. * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */
  51. protected $gotoCheck;
  52. /** @var array Map of non-terminals to the default state to goto after their reduction */
  53. protected $gotoDefault;
  54. /** @var array Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for
  55. * determining the state to goto after reduction. */
  56. protected $ruleToNonTerminal;
  57. /** @var array Map of rules to the length of their right-hand side, which is the number of elements that have to
  58. * be popped from the stack(s) on reduction. */
  59. protected $ruleToLength;
  60. /*
  61. * The following members are part of the parser state:
  62. */
  63. /** @var Lexer Lexer that is used when parsing */
  64. protected $lexer;
  65. /** @var mixed Temporary value containing the result of last semantic action (reduction) */
  66. protected $semValue;
  67. /** @var array Semantic value stack (contains values of tokens and semantic action results) */
  68. protected $semStack;
  69. /** @var int Position in stacks (state stack, semantic value stack, attribute stack) */
  70. protected $stackPos;
  71. /**
  72. * Creates a parser instance.
  73. *
  74. * @param Lexer $lexer A lexer
  75. */
  76. public function __construct(Lexer $lexer) {
  77. $this->lexer = $lexer;
  78. }
  79. /**
  80. * Parses PHP code into a node tree.
  81. *
  82. * @param string $code The source code to parse
  83. *
  84. * @return Node[] Array of statements
  85. */
  86. public function parse($code) {
  87. $this->lexer->startLexing($code);
  88. // We start off with no lookahead-token
  89. $symbol = self::SYMBOL_NONE;
  90. // The attributes for a node are taken from the first and last token of the node.
  91. // From the first token only the startAttributes are taken and from the last only
  92. // the endAttributes. Both are merged using the array union operator (+).
  93. $startAttributes = array('startLine' => 1);
  94. $endAttributes = array();
  95. // In order to figure out the attributes for the starting token, we have to keep
  96. // them in a stack
  97. $attributeStack = array($startAttributes);
  98. // Start off in the initial state and keep a stack of previous states
  99. $state = 0;
  100. $stateStack = array($state);
  101. // Semantic value stack (contains values of tokens and semantic action results)
  102. $this->semStack = array();
  103. // Current position in the stack(s)
  104. $this->stackPos = 0;
  105. for (;;) {
  106. //$this->traceNewState($state, $symbol);
  107. if ($this->actionBase[$state] == 0) {
  108. $rule = $this->actionDefault[$state];
  109. } else {
  110. if ($symbol === self::SYMBOL_NONE) {
  111. // Fetch the next token id from the lexer and fetch additional info by-ref.
  112. // The end attributes are fetched into a temporary variable and only set once the token is really
  113. // shifted (not during read). Otherwise you would sometimes get off-by-one errors, when a rule is
  114. // reduced after a token was read but not yet shifted.
  115. $tokenId = $this->lexer->getNextToken($tokenValue, $startAttributes, $nextEndAttributes);
  116. // map the lexer token id to the internally used symbols
  117. $symbol = $tokenId >= 0 && $tokenId < $this->tokenToSymbolMapSize
  118. ? $this->tokenToSymbol[$tokenId]
  119. : $this->invalidSymbol;
  120. if ($symbol === $this->invalidSymbol) {
  121. throw new \RangeException(sprintf(
  122. 'The lexer returned an invalid token (id=%d, value=%s)',
  123. $tokenId, $tokenValue
  124. ));
  125. }
  126. $attributeStack[$this->stackPos] = $startAttributes;
  127. //$this->traceRead($symbol);
  128. }
  129. $idx = $this->actionBase[$state] + $symbol;
  130. if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $symbol)
  131. || ($state < $this->YY2TBLSTATE
  132. && ($idx = $this->actionBase[$state + $this->YYNLSTATES] + $symbol) >= 0
  133. && $idx < $this->actionTableSize && $this->actionCheck[$idx] == $symbol))
  134. && ($action = $this->action[$idx]) != $this->defaultAction) {
  135. /*
  136. * >= YYNLSTATES: shift and reduce
  137. * > 0: shift
  138. * = 0: accept
  139. * < 0: reduce
  140. * = -YYUNEXPECTED: error
  141. */
  142. if ($action > 0) {
  143. /* shift */
  144. //$this->traceShift($symbol);
  145. ++$this->stackPos;
  146. $stateStack[$this->stackPos] = $state = $action;
  147. $this->semStack[$this->stackPos] = $tokenValue;
  148. $attributeStack[$this->stackPos] = $startAttributes;
  149. $endAttributes = $nextEndAttributes;
  150. $symbol = self::SYMBOL_NONE;
  151. if ($action < $this->YYNLSTATES)
  152. continue;
  153. /* $yyn >= YYNLSTATES means shift-and-reduce */
  154. $rule = $action - $this->YYNLSTATES;
  155. } else {
  156. $rule = -$action;
  157. }
  158. } else {
  159. $rule = $this->actionDefault[$state];
  160. }
  161. }
  162. for (;;) {
  163. if ($rule === 0) {
  164. /* accept */
  165. //$this->traceAccept();
  166. return $this->semValue;
  167. } elseif ($rule !== $this->unexpectedTokenRule) {
  168. /* reduce */
  169. //$this->traceReduce($rule);
  170. try {
  171. $this->{'reduceRule' . $rule}(
  172. $attributeStack[$this->stackPos - $this->ruleToLength[$rule]]
  173. + $endAttributes
  174. );
  175. } catch (Error $e) {
  176. if (-1 === $e->getRawLine() && isset($startAttributes['startLine'])) {
  177. $e->setRawLine($startAttributes['startLine']);
  178. }
  179. throw $e;
  180. }
  181. /* Goto - shift nonterminal */
  182. $this->stackPos -= $this->ruleToLength[$rule];
  183. $nonTerminal = $this->ruleToNonTerminal[$rule];
  184. $idx = $this->gotoBase[$nonTerminal] + $stateStack[$this->stackPos];
  185. if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] == $nonTerminal) {
  186. $state = $this->goto[$idx];
  187. } else {
  188. $state = $this->gotoDefault[$nonTerminal];
  189. }
  190. ++$this->stackPos;
  191. $stateStack[$this->stackPos] = $state;
  192. $this->semStack[$this->stackPos] = $this->semValue;
  193. $attributeStack[$this->stackPos] = $startAttributes;
  194. if ($state < $this->YYNLSTATES)
  195. break;
  196. /* >= YYNLSTATES means shift-and-reduce */
  197. $rule = $state - $this->YYNLSTATES;
  198. } else {
  199. /* error */
  200. if ($expected = $this->getExpectedTokens($state)) {
  201. $expectedString = ', expecting ' . implode(' or ', $expected);
  202. } else {
  203. $expectedString = '';
  204. }
  205. throw new Error(
  206. 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString,
  207. $startAttributes['startLine']
  208. );
  209. }
  210. }
  211. }
  212. }
  213. protected function getExpectedTokens($state) {
  214. $expected = array();
  215. $base = $this->actionBase[$state];
  216. foreach ($this->symbolToName as $symbol => $name) {
  217. $idx = $base + $symbol;
  218. if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  219. || $state < $this->YY2TBLSTATE
  220. && ($idx = $this->actionBase[$state + $this->YYNLSTATES] + $symbol) >= 0
  221. && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
  222. ) {
  223. if ($this->action[$idx] != $this->unexpectedTokenRule) {
  224. if (count($expected) == 4) {
  225. /* Too many expected tokens */
  226. return array();
  227. }
  228. $expected[] = $name;
  229. }
  230. }
  231. }
  232. return $expected;
  233. }
  234. /*
  235. * Tracing functions used for debugging the parser.
  236. */
  237. protected function traceNewState($state, $symbol) {
  238. echo '% State ' . $state
  239. . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n";
  240. }
  241. protected function traceRead($symbol) {
  242. echo '% Reading ' . $this->symbolToName[$symbol] . "\n";
  243. }
  244. protected function traceShift($symbol) {
  245. echo '% Shift ' . $this->symbolToName[$symbol] . "\n";
  246. }
  247. protected function traceAccept() {
  248. echo "% Accepted.\n";
  249. }
  250. protected function traceReduce($n) {
  251. echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n";
  252. }
  253. /*
  254. * Helper functions invoked by semantic actions
  255. */
  256. /**
  257. * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions.
  258. *
  259. * @param Node[] $stmts
  260. * @return Node[]
  261. */
  262. protected function handleNamespaces(array $stmts) {
  263. $style = $this->getNamespacingStyle($stmts);
  264. if (null === $style) {
  265. // not namespaced, nothing to do
  266. return $stmts;
  267. } elseif ('brace' === $style) {
  268. // For braced namespaces we only have to check that there are no invalid statements between the namespaces
  269. $afterFirstNamespace = false;
  270. foreach ($stmts as $stmt) {
  271. if ($stmt instanceof Node\Stmt\Namespace_) {
  272. $afterFirstNamespace = true;
  273. } elseif (!$stmt instanceof Node\Stmt\HaltCompiler && $afterFirstNamespace) {
  274. throw new Error('No code may exist outside of namespace {}', $stmt->getLine());
  275. }
  276. }
  277. return $stmts;
  278. } else {
  279. // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts
  280. $resultStmts = array();
  281. $targetStmts =& $resultStmts;
  282. foreach ($stmts as $stmt) {
  283. if ($stmt instanceof Node\Stmt\Namespace_) {
  284. $stmt->stmts = array();
  285. $targetStmts =& $stmt->stmts;
  286. $resultStmts[] = $stmt;
  287. } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
  288. // __halt_compiler() is not moved into the namespace
  289. $resultStmts[] = $stmt;
  290. } else {
  291. $targetStmts[] = $stmt;
  292. }
  293. }
  294. return $resultStmts;
  295. }
  296. }
  297. private function getNamespacingStyle(array $stmts) {
  298. $style = null;
  299. $hasNotAllowedStmts = false;
  300. foreach ($stmts as $stmt) {
  301. if ($stmt instanceof Node\Stmt\Namespace_) {
  302. $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
  303. if (null === $style) {
  304. $style = $currentStyle;
  305. if ($hasNotAllowedStmts) {
  306. throw new Error('Namespace declaration statement has to be the very first statement in the script', $stmt->getLine());
  307. }
  308. } elseif ($style !== $currentStyle) {
  309. throw new Error('Cannot mix bracketed namespace declarations with unbracketed namespace declarations', $stmt->getLine());
  310. }
  311. } elseif (!$stmt instanceof Node\Stmt\Declare_ && !$stmt instanceof Node\Stmt\HaltCompiler) {
  312. $hasNotAllowedStmts = true;
  313. }
  314. }
  315. return $style;
  316. }
  317. }