Lexer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Parser\Tokens;
  4. class Lexer
  5. {
  6. protected $code;
  7. protected $tokens;
  8. protected $pos;
  9. protected $line;
  10. protected $filePos;
  11. protected $prevCloseTagHasNewline;
  12. protected $tokenMap;
  13. protected $dropTokens;
  14. private $attributeStartLineUsed;
  15. private $attributeEndLineUsed;
  16. private $attributeStartTokenPosUsed;
  17. private $attributeEndTokenPosUsed;
  18. private $attributeStartFilePosUsed;
  19. private $attributeEndFilePosUsed;
  20. private $attributeCommentsUsed;
  21. /**
  22. * Creates a Lexer.
  23. *
  24. * @param array $options Options array. Currently only the 'usedAttributes' option is supported,
  25. * which is an array of attributes to add to the AST nodes. Possible
  26. * attributes are: 'comments', 'startLine', 'endLine', 'startTokenPos',
  27. * 'endTokenPos', 'startFilePos', 'endFilePos'. The option defaults to the
  28. * first three. For more info see getNextToken() docs.
  29. */
  30. public function __construct(array $options = []) {
  31. // map from internal tokens to PhpParser tokens
  32. $this->tokenMap = $this->createTokenMap();
  33. // Compatibility define for PHP < 7.4
  34. if (!defined('T_BAD_CHARACTER')) {
  35. \define('T_BAD_CHARACTER', -1);
  36. }
  37. // map of tokens to drop while lexing (the map is only used for isset lookup,
  38. // that's why the value is simply set to 1; the value is never actually used.)
  39. $this->dropTokens = array_fill_keys(
  40. [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], 1
  41. );
  42. $defaultAttributes = ['comments', 'startLine', 'endLine'];
  43. $usedAttributes = array_fill_keys($options['usedAttributes'] ?? $defaultAttributes, true);
  44. // Create individual boolean properties to make these checks faster.
  45. $this->attributeStartLineUsed = isset($usedAttributes['startLine']);
  46. $this->attributeEndLineUsed = isset($usedAttributes['endLine']);
  47. $this->attributeStartTokenPosUsed = isset($usedAttributes['startTokenPos']);
  48. $this->attributeEndTokenPosUsed = isset($usedAttributes['endTokenPos']);
  49. $this->attributeStartFilePosUsed = isset($usedAttributes['startFilePos']);
  50. $this->attributeEndFilePosUsed = isset($usedAttributes['endFilePos']);
  51. $this->attributeCommentsUsed = isset($usedAttributes['comments']);
  52. }
  53. /**
  54. * Initializes the lexer for lexing the provided source code.
  55. *
  56. * This function does not throw if lexing errors occur. Instead, errors may be retrieved using
  57. * the getErrors() method.
  58. *
  59. * @param string $code The source code to lex
  60. * @param ErrorHandler|null $errorHandler Error handler to use for lexing errors. Defaults to
  61. * ErrorHandler\Throwing
  62. */
  63. public function startLexing(string $code, ErrorHandler $errorHandler = null) {
  64. if (null === $errorHandler) {
  65. $errorHandler = new ErrorHandler\Throwing();
  66. }
  67. $this->code = $code; // keep the code around for __halt_compiler() handling
  68. $this->pos = -1;
  69. $this->line = 1;
  70. $this->filePos = 0;
  71. // If inline HTML occurs without preceding code, treat it as if it had a leading newline.
  72. // This ensures proper composability, because having a newline is the "safe" assumption.
  73. $this->prevCloseTagHasNewline = true;
  74. $scream = ini_set('xdebug.scream', '0');
  75. error_clear_last();
  76. $this->tokens = @token_get_all($code);
  77. $this->handleErrors($errorHandler);
  78. if (false !== $scream) {
  79. ini_set('xdebug.scream', $scream);
  80. }
  81. }
  82. private function handleInvalidCharacterRange($start, $end, $line, ErrorHandler $errorHandler) {
  83. $tokens = [];
  84. for ($i = $start; $i < $end; $i++) {
  85. $chr = $this->code[$i];
  86. if ($chr === "\0") {
  87. // PHP cuts error message after null byte, so need special case
  88. $errorMsg = 'Unexpected null byte';
  89. } else {
  90. $errorMsg = sprintf(
  91. 'Unexpected character "%s" (ASCII %d)', $chr, ord($chr)
  92. );
  93. }
  94. $tokens[] = [\T_BAD_CHARACTER, $chr, $line];
  95. $errorHandler->handleError(new Error($errorMsg, [
  96. 'startLine' => $line,
  97. 'endLine' => $line,
  98. 'startFilePos' => $i,
  99. 'endFilePos' => $i,
  100. ]));
  101. }
  102. return $tokens;
  103. }
  104. /**
  105. * Check whether comment token is unterminated.
  106. *
  107. * @return bool
  108. */
  109. private function isUnterminatedComment($token) : bool {
  110. return ($token[0] === \T_COMMENT || $token[0] === \T_DOC_COMMENT)
  111. && substr($token[1], 0, 2) === '/*'
  112. && substr($token[1], -2) !== '*/';
  113. }
  114. /**
  115. * Check whether an error *may* have occurred during tokenization.
  116. *
  117. * @return bool
  118. */
  119. private function errorMayHaveOccurred() : bool {
  120. if (defined('HHVM_VERSION')) {
  121. // In HHVM token_get_all() does not throw warnings, so we need to conservatively
  122. // assume that an error occurred
  123. return true;
  124. }
  125. if (PHP_VERSION_ID >= 80000) {
  126. // PHP 8 converts the "bad character" case into a parse error, rather than treating
  127. // it as a lexing warning. To preserve previous behavior, we need to assume that an
  128. // error occurred.
  129. // TODO: We should handle this the same way as PHP 8: Only generate T_BAD_CHARACTER
  130. // token here (for older PHP versions) and leave generationg of the actual parse error
  131. // to the parser. This will also save the full token scan on PHP 8 here.
  132. return true;
  133. }
  134. return null !== error_get_last();
  135. }
  136. protected function handleErrors(ErrorHandler $errorHandler) {
  137. if (!$this->errorMayHaveOccurred()) {
  138. return;
  139. }
  140. // PHP's error handling for token_get_all() is rather bad, so if we want detailed
  141. // error information we need to compute it ourselves. Invalid character errors are
  142. // detected by finding "gaps" in the token array. Unterminated comments are detected
  143. // by checking if a trailing comment has a "*/" at the end.
  144. $filePos = 0;
  145. $line = 1;
  146. $numTokens = \count($this->tokens);
  147. for ($i = 0; $i < $numTokens; $i++) {
  148. $token = $this->tokens[$i];
  149. // Since PHP 7.4 invalid characters are represented by a T_BAD_CHARACTER token.
  150. // In this case we only need to emit an error.
  151. if ($token[0] === \T_BAD_CHARACTER) {
  152. $this->handleInvalidCharacterRange($filePos, $filePos + 1, $line, $errorHandler);
  153. }
  154. $tokenValue = \is_string($token) ? $token : $token[1];
  155. $tokenLen = \strlen($tokenValue);
  156. if (substr($this->code, $filePos, $tokenLen) !== $tokenValue) {
  157. // Something is missing, must be an invalid character
  158. $nextFilePos = strpos($this->code, $tokenValue, $filePos);
  159. $badCharTokens = $this->handleInvalidCharacterRange(
  160. $filePos, $nextFilePos, $line, $errorHandler);
  161. $filePos = (int) $nextFilePos;
  162. array_splice($this->tokens, $i, 0, $badCharTokens);
  163. $numTokens += \count($badCharTokens);
  164. $i += \count($badCharTokens);
  165. }
  166. $filePos += $tokenLen;
  167. $line += substr_count($tokenValue, "\n");
  168. }
  169. if ($filePos !== \strlen($this->code)) {
  170. if (substr($this->code, $filePos, 2) === '/*') {
  171. // Unlike PHP, HHVM will drop unterminated comments entirely
  172. $comment = substr($this->code, $filePos);
  173. $errorHandler->handleError(new Error('Unterminated comment', [
  174. 'startLine' => $line,
  175. 'endLine' => $line + substr_count($comment, "\n"),
  176. 'startFilePos' => $filePos,
  177. 'endFilePos' => $filePos + \strlen($comment),
  178. ]));
  179. // Emulate the PHP behavior
  180. $isDocComment = isset($comment[3]) && $comment[3] === '*';
  181. $this->tokens[] = [$isDocComment ? \T_DOC_COMMENT : \T_COMMENT, $comment, $line];
  182. } else {
  183. // Invalid characters at the end of the input
  184. $badCharTokens = $this->handleInvalidCharacterRange(
  185. $filePos, \strlen($this->code), $line, $errorHandler);
  186. $this->tokens = array_merge($this->tokens, $badCharTokens);
  187. }
  188. return;
  189. }
  190. if (count($this->tokens) > 0) {
  191. // Check for unterminated comment
  192. $lastToken = $this->tokens[count($this->tokens) - 1];
  193. if ($this->isUnterminatedComment($lastToken)) {
  194. $errorHandler->handleError(new Error('Unterminated comment', [
  195. 'startLine' => $line - substr_count($lastToken[1], "\n"),
  196. 'endLine' => $line,
  197. 'startFilePos' => $filePos - \strlen($lastToken[1]),
  198. 'endFilePos' => $filePos,
  199. ]));
  200. }
  201. }
  202. }
  203. /**
  204. * Fetches the next token.
  205. *
  206. * The available attributes are determined by the 'usedAttributes' option, which can
  207. * be specified in the constructor. The following attributes are supported:
  208. *
  209. * * 'comments' => Array of PhpParser\Comment or PhpParser\Comment\Doc instances,
  210. * representing all comments that occurred between the previous
  211. * non-discarded token and the current one.
  212. * * 'startLine' => Line in which the node starts.
  213. * * 'endLine' => Line in which the node ends.
  214. * * 'startTokenPos' => Offset into the token array of the first token in the node.
  215. * * 'endTokenPos' => Offset into the token array of the last token in the node.
  216. * * 'startFilePos' => Offset into the code string of the first character that is part of the node.
  217. * * 'endFilePos' => Offset into the code string of the last character that is part of the node.
  218. *
  219. * @param mixed $value Variable to store token content in
  220. * @param mixed $startAttributes Variable to store start attributes in
  221. * @param mixed $endAttributes Variable to store end attributes in
  222. *
  223. * @return int Token id
  224. */
  225. public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) : int {
  226. $startAttributes = [];
  227. $endAttributes = [];
  228. while (1) {
  229. if (isset($this->tokens[++$this->pos])) {
  230. $token = $this->tokens[$this->pos];
  231. } else {
  232. // EOF token with ID 0
  233. $token = "\0";
  234. }
  235. if ($this->attributeStartLineUsed) {
  236. $startAttributes['startLine'] = $this->line;
  237. }
  238. if ($this->attributeStartTokenPosUsed) {
  239. $startAttributes['startTokenPos'] = $this->pos;
  240. }
  241. if ($this->attributeStartFilePosUsed) {
  242. $startAttributes['startFilePos'] = $this->filePos;
  243. }
  244. if (\is_string($token)) {
  245. $value = $token;
  246. if (isset($token[1])) {
  247. // bug in token_get_all
  248. $this->filePos += 2;
  249. $id = ord('"');
  250. } else {
  251. $this->filePos += 1;
  252. $id = ord($token);
  253. }
  254. } elseif (!isset($this->dropTokens[$token[0]])) {
  255. $value = $token[1];
  256. $id = $this->tokenMap[$token[0]];
  257. if (\T_CLOSE_TAG === $token[0]) {
  258. $this->prevCloseTagHasNewline = false !== strpos($token[1], "\n");
  259. } elseif (\T_INLINE_HTML === $token[0]) {
  260. $startAttributes['hasLeadingNewline'] = $this->prevCloseTagHasNewline;
  261. }
  262. $this->line += substr_count($value, "\n");
  263. $this->filePos += \strlen($value);
  264. } else {
  265. if (\T_COMMENT === $token[0] || \T_DOC_COMMENT === $token[0]) {
  266. if ($this->attributeCommentsUsed) {
  267. $comment = \T_DOC_COMMENT === $token[0]
  268. ? new Comment\Doc($token[1], $this->line, $this->filePos, $this->pos)
  269. : new Comment($token[1], $this->line, $this->filePos, $this->pos);
  270. $startAttributes['comments'][] = $comment;
  271. }
  272. }
  273. $this->line += substr_count($token[1], "\n");
  274. $this->filePos += \strlen($token[1]);
  275. continue;
  276. }
  277. if ($this->attributeEndLineUsed) {
  278. $endAttributes['endLine'] = $this->line;
  279. }
  280. if ($this->attributeEndTokenPosUsed) {
  281. $endAttributes['endTokenPos'] = $this->pos;
  282. }
  283. if ($this->attributeEndFilePosUsed) {
  284. $endAttributes['endFilePos'] = $this->filePos - 1;
  285. }
  286. return $id;
  287. }
  288. throw new \RuntimeException('Reached end of lexer loop');
  289. }
  290. /**
  291. * Returns the token array for current code.
  292. *
  293. * The token array is in the same format as provided by the
  294. * token_get_all() function and does not discard tokens (i.e.
  295. * whitespace and comments are included). The token position
  296. * attributes are against this token array.
  297. *
  298. * @return array Array of tokens in token_get_all() format
  299. */
  300. public function getTokens() : array {
  301. return $this->tokens;
  302. }
  303. /**
  304. * Handles __halt_compiler() by returning the text after it.
  305. *
  306. * @return string Remaining text
  307. */
  308. public function handleHaltCompiler() : string {
  309. // text after T_HALT_COMPILER, still including ();
  310. $textAfter = substr($this->code, $this->filePos);
  311. // ensure that it is followed by ();
  312. // this simplifies the situation, by not allowing any comments
  313. // in between of the tokens.
  314. if (!preg_match('~^\s*\(\s*\)\s*(?:;|\?>\r?\n?)~', $textAfter, $matches)) {
  315. throw new Error('__HALT_COMPILER must be followed by "();"');
  316. }
  317. // prevent the lexer from returning any further tokens
  318. $this->pos = count($this->tokens);
  319. // return with (); removed
  320. return substr($textAfter, strlen($matches[0]));
  321. }
  322. /**
  323. * Creates the token map.
  324. *
  325. * The token map maps the PHP internal token identifiers
  326. * to the identifiers used by the Parser. Additionally it
  327. * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
  328. *
  329. * @return array The token map
  330. */
  331. protected function createTokenMap() : array {
  332. $tokenMap = [];
  333. // 256 is the minimum possible token number, as everything below
  334. // it is an ASCII value
  335. for ($i = 256; $i < 1000; ++$i) {
  336. if (\T_DOUBLE_COLON === $i) {
  337. // T_DOUBLE_COLON is equivalent to T_PAAMAYIM_NEKUDOTAYIM
  338. $tokenMap[$i] = Tokens::T_PAAMAYIM_NEKUDOTAYIM;
  339. } elseif(\T_OPEN_TAG_WITH_ECHO === $i) {
  340. // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
  341. $tokenMap[$i] = Tokens::T_ECHO;
  342. } elseif(\T_CLOSE_TAG === $i) {
  343. // T_CLOSE_TAG is equivalent to ';'
  344. $tokenMap[$i] = ord(';');
  345. } elseif ('UNKNOWN' !== $name = token_name($i)) {
  346. if ('T_HASHBANG' === $name) {
  347. // HHVM uses a special token for #! hashbang lines
  348. $tokenMap[$i] = Tokens::T_INLINE_HTML;
  349. } elseif (defined($name = Tokens::class . '::' . $name)) {
  350. // Other tokens can be mapped directly
  351. $tokenMap[$i] = constant($name);
  352. }
  353. }
  354. }
  355. // HHVM uses a special token for numbers that overflow to double
  356. if (defined('T_ONUMBER')) {
  357. $tokenMap[\T_ONUMBER] = Tokens::T_DNUMBER;
  358. }
  359. // HHVM also has a separate token for the __COMPILER_HALT_OFFSET__ constant
  360. if (defined('T_COMPILER_HALT_OFFSET')) {
  361. $tokenMap[\T_COMPILER_HALT_OFFSET] = Tokens::T_STRING;
  362. }
  363. return $tokenMap;
  364. }
  365. }