Lexer.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. protected $identifierTokens;
  15. private $attributeStartLineUsed;
  16. private $attributeEndLineUsed;
  17. private $attributeStartTokenPosUsed;
  18. private $attributeEndTokenPosUsed;
  19. private $attributeStartFilePosUsed;
  20. private $attributeEndFilePosUsed;
  21. private $attributeCommentsUsed;
  22. /**
  23. * Creates a Lexer.
  24. *
  25. * @param array $options Options array. Currently only the 'usedAttributes' option is supported,
  26. * which is an array of attributes to add to the AST nodes. Possible
  27. * attributes are: 'comments', 'startLine', 'endLine', 'startTokenPos',
  28. * 'endTokenPos', 'startFilePos', 'endFilePos'. The option defaults to the
  29. * first three. For more info see getNextToken() docs.
  30. */
  31. public function __construct(array $options = []) {
  32. // Create Map from internal tokens to PhpParser tokens.
  33. $this->defineCompatibilityTokens();
  34. $this->tokenMap = $this->createTokenMap();
  35. $this->identifierTokens = $this->createIdentifierTokenMap();
  36. // map of tokens to drop while lexing (the map is only used for isset lookup,
  37. // that's why the value is simply set to 1; the value is never actually used.)
  38. $this->dropTokens = array_fill_keys(
  39. [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], 1
  40. );
  41. $defaultAttributes = ['comments', 'startLine', 'endLine'];
  42. $usedAttributes = array_fill_keys($options['usedAttributes'] ?? $defaultAttributes, true);
  43. // Create individual boolean properties to make these checks faster.
  44. $this->attributeStartLineUsed = isset($usedAttributes['startLine']);
  45. $this->attributeEndLineUsed = isset($usedAttributes['endLine']);
  46. $this->attributeStartTokenPosUsed = isset($usedAttributes['startTokenPos']);
  47. $this->attributeEndTokenPosUsed = isset($usedAttributes['endTokenPos']);
  48. $this->attributeStartFilePosUsed = isset($usedAttributes['startFilePos']);
  49. $this->attributeEndFilePosUsed = isset($usedAttributes['endFilePos']);
  50. $this->attributeCommentsUsed = isset($usedAttributes['comments']);
  51. }
  52. /**
  53. * Initializes the lexer for lexing the provided source code.
  54. *
  55. * This function does not throw if lexing errors occur. Instead, errors may be retrieved using
  56. * the getErrors() method.
  57. *
  58. * @param string $code The source code to lex
  59. * @param ErrorHandler|null $errorHandler Error handler to use for lexing errors. Defaults to
  60. * ErrorHandler\Throwing
  61. */
  62. public function startLexing(string $code, ErrorHandler $errorHandler = null) {
  63. if (null === $errorHandler) {
  64. $errorHandler = new ErrorHandler\Throwing();
  65. }
  66. $this->code = $code; // keep the code around for __halt_compiler() handling
  67. $this->pos = -1;
  68. $this->line = 1;
  69. $this->filePos = 0;
  70. // If inline HTML occurs without preceding code, treat it as if it had a leading newline.
  71. // This ensures proper composability, because having a newline is the "safe" assumption.
  72. $this->prevCloseTagHasNewline = true;
  73. $scream = ini_set('xdebug.scream', '0');
  74. error_clear_last();
  75. $this->tokens = @token_get_all($code);
  76. $this->postprocessTokens($errorHandler);
  77. if (false !== $scream) {
  78. ini_set('xdebug.scream', $scream);
  79. }
  80. }
  81. private function handleInvalidCharacterRange($start, $end, $line, ErrorHandler $errorHandler) {
  82. $tokens = [];
  83. for ($i = $start; $i < $end; $i++) {
  84. $chr = $this->code[$i];
  85. if ($chr === "\0") {
  86. // PHP cuts error message after null byte, so need special case
  87. $errorMsg = 'Unexpected null byte';
  88. } else {
  89. $errorMsg = sprintf(
  90. 'Unexpected character "%s" (ASCII %d)', $chr, ord($chr)
  91. );
  92. }
  93. $tokens[] = [\T_BAD_CHARACTER, $chr, $line];
  94. $errorHandler->handleError(new Error($errorMsg, [
  95. 'startLine' => $line,
  96. 'endLine' => $line,
  97. 'startFilePos' => $i,
  98. 'endFilePos' => $i,
  99. ]));
  100. }
  101. return $tokens;
  102. }
  103. /**
  104. * Check whether comment token is unterminated.
  105. *
  106. * @return bool
  107. */
  108. private function isUnterminatedComment($token) : bool {
  109. return ($token[0] === \T_COMMENT || $token[0] === \T_DOC_COMMENT)
  110. && substr($token[1], 0, 2) === '/*'
  111. && substr($token[1], -2) !== '*/';
  112. }
  113. protected function postprocessTokens(ErrorHandler $errorHandler) {
  114. // PHP's error handling for token_get_all() is rather bad, so if we want detailed
  115. // error information we need to compute it ourselves. Invalid character errors are
  116. // detected by finding "gaps" in the token array. Unterminated comments are detected
  117. // by checking if a trailing comment has a "*/" at the end.
  118. //
  119. // Additionally, we canonicalize to the PHP 8 comment format here, which does not include
  120. // the trailing whitespace anymore.
  121. //
  122. // We also canonicalize to the PHP 8 T_NAME_* tokens.
  123. $filePos = 0;
  124. $line = 1;
  125. $numTokens = \count($this->tokens);
  126. for ($i = 0; $i < $numTokens; $i++) {
  127. $token = $this->tokens[$i];
  128. // Since PHP 7.4 invalid characters are represented by a T_BAD_CHARACTER token.
  129. // In this case we only need to emit an error.
  130. if ($token[0] === \T_BAD_CHARACTER) {
  131. $this->handleInvalidCharacterRange($filePos, $filePos + 1, $line, $errorHandler);
  132. }
  133. if ($token[0] === \T_COMMENT && substr($token[1], 0, 2) !== '/*'
  134. && preg_match('/(\r\n|\n|\r)$/D', $token[1], $matches)) {
  135. $trailingNewline = $matches[0];
  136. $token[1] = substr($token[1], 0, -strlen($trailingNewline));
  137. $this->tokens[$i] = $token;
  138. if (isset($this->tokens[$i + 1]) && $this->tokens[$i + 1][0] === \T_WHITESPACE) {
  139. // Move trailing newline into following T_WHITESPACE token, if it already exists.
  140. $this->tokens[$i + 1][1] = $trailingNewline . $this->tokens[$i + 1][1];
  141. $this->tokens[$i + 1][2]--;
  142. } else {
  143. // Otherwise, we need to create a new T_WHITESPACE token.
  144. array_splice($this->tokens, $i + 1, 0, [
  145. [\T_WHITESPACE, $trailingNewline, $line],
  146. ]);
  147. $numTokens++;
  148. }
  149. }
  150. // Emulate PHP 8 T_NAME_* tokens, by combining sequences of T_NS_SEPARATOR and T_STRING
  151. // into a single token.
  152. if (\is_array($token)
  153. && ($token[0] === \T_NS_SEPARATOR || isset($this->identifierTokens[$token[0]]))) {
  154. $lastWasSeparator = $token[0] === \T_NS_SEPARATOR;
  155. $text = $token[1];
  156. for ($j = $i + 1; isset($this->tokens[$j]); $j++) {
  157. if ($lastWasSeparator) {
  158. if (!isset($this->identifierTokens[$this->tokens[$j][0]])) {
  159. break;
  160. }
  161. $lastWasSeparator = false;
  162. } else {
  163. if ($this->tokens[$j][0] !== \T_NS_SEPARATOR) {
  164. break;
  165. }
  166. $lastWasSeparator = true;
  167. }
  168. $text .= $this->tokens[$j][1];
  169. }
  170. if ($lastWasSeparator) {
  171. // Trailing separator is not part of the name.
  172. $j--;
  173. $text = substr($text, 0, -1);
  174. }
  175. if ($j > $i + 1) {
  176. if ($token[0] === \T_NS_SEPARATOR) {
  177. $type = \T_NAME_FULLY_QUALIFIED;
  178. } else if ($token[0] === \T_NAMESPACE) {
  179. $type = \T_NAME_RELATIVE;
  180. } else {
  181. $type = \T_NAME_QUALIFIED;
  182. }
  183. $token = [$type, $text, $line];
  184. array_splice($this->tokens, $i, $j - $i, [$token]);
  185. $numTokens -= $j - $i - 1;
  186. }
  187. }
  188. $tokenValue = \is_string($token) ? $token : $token[1];
  189. $tokenLen = \strlen($tokenValue);
  190. if (substr($this->code, $filePos, $tokenLen) !== $tokenValue) {
  191. // Something is missing, must be an invalid character
  192. $nextFilePos = strpos($this->code, $tokenValue, $filePos);
  193. $badCharTokens = $this->handleInvalidCharacterRange(
  194. $filePos, $nextFilePos, $line, $errorHandler);
  195. $filePos = (int) $nextFilePos;
  196. array_splice($this->tokens, $i, 0, $badCharTokens);
  197. $numTokens += \count($badCharTokens);
  198. $i += \count($badCharTokens);
  199. }
  200. $filePos += $tokenLen;
  201. $line += substr_count($tokenValue, "\n");
  202. }
  203. if ($filePos !== \strlen($this->code)) {
  204. if (substr($this->code, $filePos, 2) === '/*') {
  205. // Unlike PHP, HHVM will drop unterminated comments entirely
  206. $comment = substr($this->code, $filePos);
  207. $errorHandler->handleError(new Error('Unterminated comment', [
  208. 'startLine' => $line,
  209. 'endLine' => $line + substr_count($comment, "\n"),
  210. 'startFilePos' => $filePos,
  211. 'endFilePos' => $filePos + \strlen($comment),
  212. ]));
  213. // Emulate the PHP behavior
  214. $isDocComment = isset($comment[3]) && $comment[3] === '*';
  215. $this->tokens[] = [$isDocComment ? \T_DOC_COMMENT : \T_COMMENT, $comment, $line];
  216. } else {
  217. // Invalid characters at the end of the input
  218. $badCharTokens = $this->handleInvalidCharacterRange(
  219. $filePos, \strlen($this->code), $line, $errorHandler);
  220. $this->tokens = array_merge($this->tokens, $badCharTokens);
  221. }
  222. return;
  223. }
  224. if (count($this->tokens) > 0) {
  225. // Check for unterminated comment
  226. $lastToken = $this->tokens[count($this->tokens) - 1];
  227. if ($this->isUnterminatedComment($lastToken)) {
  228. $errorHandler->handleError(new Error('Unterminated comment', [
  229. 'startLine' => $line - substr_count($lastToken[1], "\n"),
  230. 'endLine' => $line,
  231. 'startFilePos' => $filePos - \strlen($lastToken[1]),
  232. 'endFilePos' => $filePos,
  233. ]));
  234. }
  235. }
  236. }
  237. /**
  238. * Fetches the next token.
  239. *
  240. * The available attributes are determined by the 'usedAttributes' option, which can
  241. * be specified in the constructor. The following attributes are supported:
  242. *
  243. * * 'comments' => Array of PhpParser\Comment or PhpParser\Comment\Doc instances,
  244. * representing all comments that occurred between the previous
  245. * non-discarded token and the current one.
  246. * * 'startLine' => Line in which the node starts.
  247. * * 'endLine' => Line in which the node ends.
  248. * * 'startTokenPos' => Offset into the token array of the first token in the node.
  249. * * 'endTokenPos' => Offset into the token array of the last token in the node.
  250. * * 'startFilePos' => Offset into the code string of the first character that is part of the node.
  251. * * 'endFilePos' => Offset into the code string of the last character that is part of the node.
  252. *
  253. * @param mixed $value Variable to store token content in
  254. * @param mixed $startAttributes Variable to store start attributes in
  255. * @param mixed $endAttributes Variable to store end attributes in
  256. *
  257. * @return int Token id
  258. */
  259. public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) : int {
  260. $startAttributes = [];
  261. $endAttributes = [];
  262. while (1) {
  263. if (isset($this->tokens[++$this->pos])) {
  264. $token = $this->tokens[$this->pos];
  265. } else {
  266. // EOF token with ID 0
  267. $token = "\0";
  268. }
  269. if ($this->attributeStartLineUsed) {
  270. $startAttributes['startLine'] = $this->line;
  271. }
  272. if ($this->attributeStartTokenPosUsed) {
  273. $startAttributes['startTokenPos'] = $this->pos;
  274. }
  275. if ($this->attributeStartFilePosUsed) {
  276. $startAttributes['startFilePos'] = $this->filePos;
  277. }
  278. if (\is_string($token)) {
  279. $value = $token;
  280. if (isset($token[1])) {
  281. // bug in token_get_all
  282. $this->filePos += 2;
  283. $id = ord('"');
  284. } else {
  285. $this->filePos += 1;
  286. $id = ord($token);
  287. }
  288. } elseif (!isset($this->dropTokens[$token[0]])) {
  289. $value = $token[1];
  290. $id = $this->tokenMap[$token[0]];
  291. if (\T_CLOSE_TAG === $token[0]) {
  292. $this->prevCloseTagHasNewline = false !== strpos($token[1], "\n");
  293. } elseif (\T_INLINE_HTML === $token[0]) {
  294. $startAttributes['hasLeadingNewline'] = $this->prevCloseTagHasNewline;
  295. }
  296. $this->line += substr_count($value, "\n");
  297. $this->filePos += \strlen($value);
  298. } else {
  299. $origLine = $this->line;
  300. $origFilePos = $this->filePos;
  301. $this->line += substr_count($token[1], "\n");
  302. $this->filePos += \strlen($token[1]);
  303. if (\T_COMMENT === $token[0] || \T_DOC_COMMENT === $token[0]) {
  304. if ($this->attributeCommentsUsed) {
  305. $comment = \T_DOC_COMMENT === $token[0]
  306. ? new Comment\Doc($token[1],
  307. $origLine, $origFilePos, $this->pos,
  308. $this->line, $this->filePos - 1, $this->pos)
  309. : new Comment($token[1],
  310. $origLine, $origFilePos, $this->pos,
  311. $this->line, $this->filePos - 1, $this->pos);
  312. $startAttributes['comments'][] = $comment;
  313. }
  314. }
  315. continue;
  316. }
  317. if ($this->attributeEndLineUsed) {
  318. $endAttributes['endLine'] = $this->line;
  319. }
  320. if ($this->attributeEndTokenPosUsed) {
  321. $endAttributes['endTokenPos'] = $this->pos;
  322. }
  323. if ($this->attributeEndFilePosUsed) {
  324. $endAttributes['endFilePos'] = $this->filePos - 1;
  325. }
  326. return $id;
  327. }
  328. throw new \RuntimeException('Reached end of lexer loop');
  329. }
  330. /**
  331. * Returns the token array for current code.
  332. *
  333. * The token array is in the same format as provided by the
  334. * token_get_all() function and does not discard tokens (i.e.
  335. * whitespace and comments are included). The token position
  336. * attributes are against this token array.
  337. *
  338. * @return array Array of tokens in token_get_all() format
  339. */
  340. public function getTokens() : array {
  341. return $this->tokens;
  342. }
  343. /**
  344. * Handles __halt_compiler() by returning the text after it.
  345. *
  346. * @return string Remaining text
  347. */
  348. public function handleHaltCompiler() : string {
  349. // text after T_HALT_COMPILER, still including ();
  350. $textAfter = substr($this->code, $this->filePos);
  351. // ensure that it is followed by ();
  352. // this simplifies the situation, by not allowing any comments
  353. // in between of the tokens.
  354. if (!preg_match('~^\s*\(\s*\)\s*(?:;|\?>\r?\n?)~', $textAfter, $matches)) {
  355. throw new Error('__HALT_COMPILER must be followed by "();"');
  356. }
  357. // prevent the lexer from returning any further tokens
  358. $this->pos = count($this->tokens);
  359. // return with (); removed
  360. return substr($textAfter, strlen($matches[0]));
  361. }
  362. private function defineCompatibilityTokens() {
  363. static $compatTokensDefined = false;
  364. if ($compatTokensDefined) {
  365. return;
  366. }
  367. $compatTokens = [
  368. // PHP 7.4
  369. 'T_BAD_CHARACTER',
  370. 'T_FN',
  371. 'T_COALESCE_EQUAL',
  372. // PHP 8.0
  373. 'T_NAME_QUALIFIED',
  374. 'T_NAME_FULLY_QUALIFIED',
  375. 'T_NAME_RELATIVE',
  376. 'T_MATCH',
  377. 'T_NULLSAFE_OBJECT_OPERATOR',
  378. 'T_ATTRIBUTE',
  379. ];
  380. // PHP-Parser might be used together with another library that also emulates some or all
  381. // of these tokens. Perform a sanity-check that all already defined tokens have been
  382. // assigned a unique ID.
  383. $usedTokenIds = [];
  384. foreach ($compatTokens as $token) {
  385. if (\defined($token)) {
  386. $tokenId = \constant($token);
  387. $clashingToken = $usedTokenIds[$tokenId] ?? null;
  388. if ($clashingToken !== null) {
  389. throw new \Error(sprintf(
  390. 'Token %s has same ID as token %s, ' .
  391. 'you may be using a library with broken token emulation',
  392. $token, $clashingToken
  393. ));
  394. }
  395. $usedTokenIds[$tokenId] = $token;
  396. }
  397. }
  398. // Now define any tokens that have not yet been emulated. Try to assign IDs from -1
  399. // downwards, but skip any IDs that may already be in use.
  400. $newTokenId = -1;
  401. foreach ($compatTokens as $token) {
  402. if (!\defined($token)) {
  403. while (isset($usedTokenIds[$newTokenId])) {
  404. $newTokenId--;
  405. }
  406. \define($token, $newTokenId);
  407. $newTokenId--;
  408. }
  409. }
  410. $compatTokensDefined = true;
  411. }
  412. /**
  413. * Creates the token map.
  414. *
  415. * The token map maps the PHP internal token identifiers
  416. * to the identifiers used by the Parser. Additionally it
  417. * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
  418. *
  419. * @return array The token map
  420. */
  421. protected function createTokenMap() : array {
  422. $tokenMap = [];
  423. // 256 is the minimum possible token number, as everything below
  424. // it is an ASCII value
  425. for ($i = 256; $i < 1000; ++$i) {
  426. if (\T_DOUBLE_COLON === $i) {
  427. // T_DOUBLE_COLON is equivalent to T_PAAMAYIM_NEKUDOTAYIM
  428. $tokenMap[$i] = Tokens::T_PAAMAYIM_NEKUDOTAYIM;
  429. } elseif(\T_OPEN_TAG_WITH_ECHO === $i) {
  430. // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
  431. $tokenMap[$i] = Tokens::T_ECHO;
  432. } elseif(\T_CLOSE_TAG === $i) {
  433. // T_CLOSE_TAG is equivalent to ';'
  434. $tokenMap[$i] = ord(';');
  435. } elseif ('UNKNOWN' !== $name = token_name($i)) {
  436. if ('T_HASHBANG' === $name) {
  437. // HHVM uses a special token for #! hashbang lines
  438. $tokenMap[$i] = Tokens::T_INLINE_HTML;
  439. } elseif (defined($name = Tokens::class . '::' . $name)) {
  440. // Other tokens can be mapped directly
  441. $tokenMap[$i] = constant($name);
  442. }
  443. }
  444. }
  445. // HHVM uses a special token for numbers that overflow to double
  446. if (defined('T_ONUMBER')) {
  447. $tokenMap[\T_ONUMBER] = Tokens::T_DNUMBER;
  448. }
  449. // HHVM also has a separate token for the __COMPILER_HALT_OFFSET__ constant
  450. if (defined('T_COMPILER_HALT_OFFSET')) {
  451. $tokenMap[\T_COMPILER_HALT_OFFSET] = Tokens::T_STRING;
  452. }
  453. // Assign tokens for which we define compatibility constants, as token_name() does not know them.
  454. $tokenMap[\T_FN] = Tokens::T_FN;
  455. $tokenMap[\T_COALESCE_EQUAL] = Tokens::T_COALESCE_EQUAL;
  456. $tokenMap[\T_NAME_QUALIFIED] = Tokens::T_NAME_QUALIFIED;
  457. $tokenMap[\T_NAME_FULLY_QUALIFIED] = Tokens::T_NAME_FULLY_QUALIFIED;
  458. $tokenMap[\T_NAME_RELATIVE] = Tokens::T_NAME_RELATIVE;
  459. $tokenMap[\T_MATCH] = Tokens::T_MATCH;
  460. $tokenMap[\T_NULLSAFE_OBJECT_OPERATOR] = Tokens::T_NULLSAFE_OBJECT_OPERATOR;
  461. $tokenMap[\T_ATTRIBUTE] = Tokens::T_ATTRIBUTE;
  462. return $tokenMap;
  463. }
  464. private function createIdentifierTokenMap(): array {
  465. // Based on semi_reserved production.
  466. return array_fill_keys([
  467. \T_STRING,
  468. \T_STATIC, \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC,
  469. \T_INCLUDE, \T_INCLUDE_ONCE, \T_EVAL, \T_REQUIRE, \T_REQUIRE_ONCE, \T_LOGICAL_OR, \T_LOGICAL_XOR, \T_LOGICAL_AND,
  470. \T_INSTANCEOF, \T_NEW, \T_CLONE, \T_EXIT, \T_IF, \T_ELSEIF, \T_ELSE, \T_ENDIF, \T_ECHO, \T_DO, \T_WHILE,
  471. \T_ENDWHILE, \T_FOR, \T_ENDFOR, \T_FOREACH, \T_ENDFOREACH, \T_DECLARE, \T_ENDDECLARE, \T_AS, \T_TRY, \T_CATCH,
  472. \T_FINALLY, \T_THROW, \T_USE, \T_INSTEADOF, \T_GLOBAL, \T_VAR, \T_UNSET, \T_ISSET, \T_EMPTY, \T_CONTINUE, \T_GOTO,
  473. \T_FUNCTION, \T_CONST, \T_RETURN, \T_PRINT, \T_YIELD, \T_LIST, \T_SWITCH, \T_ENDSWITCH, \T_CASE, \T_DEFAULT,
  474. \T_BREAK, \T_ARRAY, \T_CALLABLE, \T_EXTENDS, \T_IMPLEMENTS, \T_NAMESPACE, \T_TRAIT, \T_INTERFACE, \T_CLASS,
  475. \T_CLASS_C, \T_TRAIT_C, \T_FUNC_C, \T_METHOD_C, \T_LINE, \T_FILE, \T_DIR, \T_NS_C, \T_HALT_COMPILER, \T_FN,
  476. \T_MATCH,
  477. ], true);
  478. }
  479. }