Lexer.php 22 KB

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