Lexer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace PhpParser;
  3. class Lexer
  4. {
  5. protected $code;
  6. protected $tokens;
  7. protected $pos;
  8. protected $line;
  9. protected $filePos;
  10. protected $tokenMap;
  11. protected $dropTokens;
  12. protected $usedAttributes;
  13. /**
  14. * Creates a Lexer.
  15. *
  16. * @param array $options Options array. Currently only the 'usedAttributes' option is supported,
  17. * which is an array of attributes to add to the AST nodes. Possible attributes
  18. * are: 'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos',
  19. * 'startFilePos', 'endFilePos'. The option defaults to the first three.
  20. * For more info see getNextToken() docs.
  21. */
  22. public function __construct(array $options = array()) {
  23. // map from internal tokens to PhpParser tokens
  24. $this->tokenMap = $this->createTokenMap();
  25. // map of tokens to drop while lexing (the map is only used for isset lookup,
  26. // that's why the value is simply set to 1; the value is never actually used.)
  27. $this->dropTokens = array_fill_keys(array(T_WHITESPACE, T_OPEN_TAG), 1);
  28. // the usedAttributes member is a map of the used attribute names to a dummy
  29. // value (here "true")
  30. $options += array(
  31. 'usedAttributes' => array('comments', 'startLine', 'endLine'),
  32. );
  33. $this->usedAttributes = array_fill_keys($options['usedAttributes'], true);
  34. }
  35. /**
  36. * Initializes the lexer for lexing the provided source code.
  37. *
  38. * @param string $code The source code to lex
  39. *
  40. * @throws Error on lexing errors (unterminated comment or unexpected character)
  41. */
  42. public function startLexing($code) {
  43. $scream = ini_set('xdebug.scream', '0');
  44. $this->resetErrors();
  45. $this->tokens = @token_get_all($code);
  46. $this->handleErrors();
  47. if (false !== $scream) {
  48. ini_set('xdebug.scream', $scream);
  49. }
  50. $this->code = $code; // keep the code around for __halt_compiler() handling
  51. $this->pos = -1;
  52. $this->line = 1;
  53. $this->filePos = 0;
  54. }
  55. protected function resetErrors() {
  56. // set error_get_last() to defined state by forcing an undefined variable error
  57. set_error_handler(function() { return false; }, 0);
  58. @$undefinedVariable;
  59. restore_error_handler();
  60. }
  61. protected function handleErrors() {
  62. $error = error_get_last();
  63. if (preg_match(
  64. '~^Unterminated comment starting line ([0-9]+)$~',
  65. $error['message'], $matches
  66. )) {
  67. throw new Error('Unterminated comment', (int) $matches[1]);
  68. }
  69. if (preg_match(
  70. '~^Unexpected character in input: \'(.)\' \(ASCII=([0-9]+)\)~s',
  71. $error['message'], $matches
  72. )) {
  73. throw new Error(sprintf(
  74. 'Unexpected character "%s" (ASCII %d)',
  75. $matches[1], $matches[2]
  76. ));
  77. }
  78. // PHP cuts error message after null byte, so need special case
  79. if (preg_match('~^Unexpected character in input: \'$~', $error['message'])) {
  80. throw new Error('Unexpected null byte');
  81. }
  82. }
  83. /**
  84. * Fetches the next token.
  85. *
  86. * The available attributes are determined by the 'usedAttributes' option, which can
  87. * be specified in the constructor. The following attributes are supported:
  88. *
  89. * * 'comments' => Array of PhpParser\Comment or PhpParser\Comment\Doc instances,
  90. * representing all comments that occurred between the previous
  91. * non-discarded token and the current one.
  92. * * 'startLine' => Line in which the node starts.
  93. * * 'endLine' => Line in which the node ends.
  94. * * 'startTokenPos' => Offset into the token array of the first token in the node.
  95. * * 'endTokenPos' => Offset into the token array of the last token in the node.
  96. * * 'startFilePos' => Offset into the code string of the first character that is part of the node.
  97. * * 'endFilePos' => Offset into the code string of the last character that is part of the node
  98. *
  99. * @param mixed $value Variable to store token content in
  100. * @param mixed $startAttributes Variable to store start attributes in
  101. * @param mixed $endAttributes Variable to store end attributes in
  102. *
  103. * @return int Token id
  104. */
  105. public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) {
  106. $startAttributes = array();
  107. $endAttributes = array();
  108. while (1) {
  109. if (isset($this->tokens[++$this->pos])) {
  110. $token = $this->tokens[$this->pos];
  111. } else {
  112. // EOF token with ID 0
  113. $token = "\0";
  114. }
  115. if (isset($this->usedAttributes['startTokenPos'])) {
  116. $startAttributes['startTokenPos'] = $this->pos;
  117. }
  118. if (isset($this->usedAttributes['startFilePos'])) {
  119. $startAttributes['startFilePos'] = $this->filePos;
  120. }
  121. if (is_string($token)) {
  122. // bug in token_get_all
  123. if ('b"' === $token) {
  124. $value = 'b"';
  125. $this->filePos += 2;
  126. $id = ord('"');
  127. } else {
  128. $value = $token;
  129. $this->filePos += 1;
  130. $id = ord($token);
  131. }
  132. if (isset($this->usedAttributes['startLine'])) {
  133. $startAttributes['startLine'] = $this->line;
  134. }
  135. if (isset($this->usedAttributes['endLine'])) {
  136. $endAttributes['endLine'] = $this->line;
  137. }
  138. if (isset($this->usedAttributes['endTokenPos'])) {
  139. $endAttributes['endTokenPos'] = $this->pos;
  140. }
  141. if (isset($this->usedAttributes['endFilePos'])) {
  142. $endAttributes['endFilePos'] = $this->filePos - 1;
  143. }
  144. return $id;
  145. } else {
  146. $this->line += substr_count($token[1], "\n");
  147. $this->filePos += strlen($token[1]);
  148. if (T_COMMENT === $token[0]) {
  149. if (isset($this->usedAttributes['comments'])) {
  150. $startAttributes['comments'][] = new Comment($token[1], $token[2]);
  151. }
  152. } elseif (T_DOC_COMMENT === $token[0]) {
  153. if (isset($this->usedAttributes['comments'])) {
  154. $startAttributes['comments'][] = new Comment\Doc($token[1], $token[2]);
  155. }
  156. } elseif (!isset($this->dropTokens[$token[0]])) {
  157. $value = $token[1];
  158. if (isset($this->usedAttributes['startLine'])) {
  159. $startAttributes['startLine'] = $token[2];
  160. }
  161. if (isset($this->usedAttributes['endLine'])) {
  162. $endAttributes['endLine'] = $this->line;
  163. }
  164. if (isset($this->usedAttributes['endTokenPos'])) {
  165. $endAttributes['endTokenPos'] = $this->pos;
  166. }
  167. if (isset($this->usedAttributes['endFilePos'])) {
  168. $endAttributes['endFilePos'] = $this->filePos - 1;
  169. }
  170. return $this->tokenMap[$token[0]];
  171. }
  172. }
  173. }
  174. throw new \RuntimeException('Reached end of lexer loop');
  175. }
  176. /**
  177. * Returns the token array for current code.
  178. *
  179. * The token array is in the same format as provided by the
  180. * token_get_all() function and does not discard tokens (i.e.
  181. * whitespace and comments are included). The token position
  182. * attributes are against this token array.
  183. *
  184. * @return array Array of tokens in token_get_all() format
  185. */
  186. public function getTokens() {
  187. return $this->tokens;
  188. }
  189. /**
  190. * Handles __halt_compiler() by returning the text after it.
  191. *
  192. * @return string Remaining text
  193. */
  194. public function handleHaltCompiler() {
  195. // text after T_HALT_COMPILER, still including ();
  196. $textAfter = substr($this->code, $this->filePos);
  197. // ensure that it is followed by ();
  198. // this simplifies the situation, by not allowing any comments
  199. // in between of the tokens.
  200. if (!preg_match('~^\s*\(\s*\)\s*(?:;|\?>\r?\n?)~', $textAfter, $matches)) {
  201. throw new Error('__HALT_COMPILER must be followed by "();"');
  202. }
  203. // prevent the lexer from returning any further tokens
  204. $this->pos = count($this->tokens);
  205. // return with (); removed
  206. return (string) substr($textAfter, strlen($matches[0])); // (string) converts false to ''
  207. }
  208. /**
  209. * Creates the token map.
  210. *
  211. * The token map maps the PHP internal token identifiers
  212. * to the identifiers used by the Parser. Additionally it
  213. * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
  214. *
  215. * @return array The token map
  216. */
  217. protected function createTokenMap() {
  218. $tokenMap = array();
  219. // 256 is the minimum possible token number, as everything below
  220. // it is an ASCII value
  221. for ($i = 256; $i < 1000; ++$i) {
  222. if (T_DOUBLE_COLON === $i) {
  223. // T_DOUBLE_COLON is equivalent to T_PAAMAYIM_NEKUDOTAYIM
  224. $tokenMap[$i] = Parser::T_PAAMAYIM_NEKUDOTAYIM;
  225. } elseif(T_OPEN_TAG_WITH_ECHO === $i) {
  226. // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
  227. $tokenMap[$i] = Parser::T_ECHO;
  228. } elseif(T_CLOSE_TAG === $i) {
  229. // T_CLOSE_TAG is equivalent to ';'
  230. $tokenMap[$i] = ord(';');
  231. } elseif ('UNKNOWN' !== $name = token_name($i)) {
  232. if ('T_HASHBANG' === $name) {
  233. // HHVM uses a special token for #! hashbang lines
  234. $tokenMap[$i] = Parser::T_INLINE_HTML;
  235. } else if (defined($name = 'PhpParser\Parser::' . $name)) {
  236. // Other tokens can be mapped directly
  237. $tokenMap[$i] = constant($name);
  238. }
  239. }
  240. }
  241. // HHVM uses a special token for numbers that overflow to double
  242. if (defined('T_ONUMBER')) {
  243. $tokenMap[T_ONUMBER] = Parser::T_DNUMBER;
  244. }
  245. // HHVM also has a separate token for the __COMPILER_HALT_OFFSET__ constant
  246. if (defined('T_COMPILER_HALT_OFFSET')) {
  247. $tokenMap[T_COMPILER_HALT_OFFSET] = Parser::T_STRING;
  248. }
  249. return $tokenMap;
  250. }
  251. }