Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. return null !== error_get_last();
  126. }
  127. protected function handleErrors(ErrorHandler $errorHandler) {
  128. if (!$this->errorMayHaveOccurred()) {
  129. return;
  130. }
  131. // PHP's error handling for token_get_all() is rather bad, so if we want detailed
  132. // error information we need to compute it ourselves. Invalid character errors are
  133. // detected by finding "gaps" in the token array. Unterminated comments are detected
  134. // by checking if a trailing comment has a "*/" at the end.
  135. $filePos = 0;
  136. $line = 1;
  137. $numTokens = \count($this->tokens);
  138. for ($i = 0; $i < $numTokens; $i++) {
  139. $token = $this->tokens[$i];
  140. // Since PHP 7.4 invalid characters are represented by a T_BAD_CHARACTER token.
  141. // In this case we only need to emit an error.
  142. if ($token[0] === \T_BAD_CHARACTER) {
  143. $this->handleInvalidCharacterRange($filePos, $filePos + 1, $line, $errorHandler);
  144. }
  145. $tokenValue = \is_string($token) ? $token : $token[1];
  146. $tokenLen = \strlen($tokenValue);
  147. if (substr($this->code, $filePos, $tokenLen) !== $tokenValue) {
  148. // Something is missing, must be an invalid character
  149. $nextFilePos = strpos($this->code, $tokenValue, $filePos);
  150. $badCharTokens = $this->handleInvalidCharacterRange(
  151. $filePos, $nextFilePos, $line, $errorHandler);
  152. $filePos = (int) $nextFilePos;
  153. array_splice($this->tokens, $i, 0, $badCharTokens);
  154. $numTokens += \count($badCharTokens);
  155. $i += \count($badCharTokens);
  156. }
  157. $filePos += $tokenLen;
  158. $line += substr_count($tokenValue, "\n");
  159. }
  160. if ($filePos !== \strlen($this->code)) {
  161. if (substr($this->code, $filePos, 2) === '/*') {
  162. // Unlike PHP, HHVM will drop unterminated comments entirely
  163. $comment = substr($this->code, $filePos);
  164. $errorHandler->handleError(new Error('Unterminated comment', [
  165. 'startLine' => $line,
  166. 'endLine' => $line + substr_count($comment, "\n"),
  167. 'startFilePos' => $filePos,
  168. 'endFilePos' => $filePos + \strlen($comment),
  169. ]));
  170. // Emulate the PHP behavior
  171. $isDocComment = isset($comment[3]) && $comment[3] === '*';
  172. $this->tokens[] = [$isDocComment ? \T_DOC_COMMENT : \T_COMMENT, $comment, $line];
  173. } else {
  174. // Invalid characters at the end of the input
  175. $badCharTokens = $this->handleInvalidCharacterRange(
  176. $filePos, \strlen($this->code), $line, $errorHandler);
  177. $this->tokens = array_merge($this->tokens, $badCharTokens);
  178. }
  179. return;
  180. }
  181. if (count($this->tokens) > 0) {
  182. // Check for unterminated comment
  183. $lastToken = $this->tokens[count($this->tokens) - 1];
  184. if ($this->isUnterminatedComment($lastToken)) {
  185. $errorHandler->handleError(new Error('Unterminated comment', [
  186. 'startLine' => $line - substr_count($lastToken[1], "\n"),
  187. 'endLine' => $line,
  188. 'startFilePos' => $filePos - \strlen($lastToken[1]),
  189. 'endFilePos' => $filePos,
  190. ]));
  191. }
  192. }
  193. }
  194. /**
  195. * Fetches the next token.
  196. *
  197. * The available attributes are determined by the 'usedAttributes' option, which can
  198. * be specified in the constructor. The following attributes are supported:
  199. *
  200. * * 'comments' => Array of PhpParser\Comment or PhpParser\Comment\Doc instances,
  201. * representing all comments that occurred between the previous
  202. * non-discarded token and the current one.
  203. * * 'startLine' => Line in which the node starts.
  204. * * 'endLine' => Line in which the node ends.
  205. * * 'startTokenPos' => Offset into the token array of the first token in the node.
  206. * * 'endTokenPos' => Offset into the token array of the last token in the node.
  207. * * 'startFilePos' => Offset into the code string of the first character that is part of the node.
  208. * * 'endFilePos' => Offset into the code string of the last character that is part of the node.
  209. *
  210. * @param mixed $value Variable to store token content in
  211. * @param mixed $startAttributes Variable to store start attributes in
  212. * @param mixed $endAttributes Variable to store end attributes in
  213. *
  214. * @return int Token id
  215. */
  216. public function getNextToken(&$value = null, &$startAttributes = null, &$endAttributes = null) : int {
  217. $startAttributes = [];
  218. $endAttributes = [];
  219. while (1) {
  220. if (isset($this->tokens[++$this->pos])) {
  221. $token = $this->tokens[$this->pos];
  222. } else {
  223. // EOF token with ID 0
  224. $token = "\0";
  225. }
  226. if ($this->attributeStartLineUsed) {
  227. $startAttributes['startLine'] = $this->line;
  228. }
  229. if ($this->attributeStartTokenPosUsed) {
  230. $startAttributes['startTokenPos'] = $this->pos;
  231. }
  232. if ($this->attributeStartFilePosUsed) {
  233. $startAttributes['startFilePos'] = $this->filePos;
  234. }
  235. if (\is_string($token)) {
  236. $value = $token;
  237. if (isset($token[1])) {
  238. // bug in token_get_all
  239. $this->filePos += 2;
  240. $id = ord('"');
  241. } else {
  242. $this->filePos += 1;
  243. $id = ord($token);
  244. }
  245. } elseif (!isset($this->dropTokens[$token[0]])) {
  246. $value = $token[1];
  247. $id = $this->tokenMap[$token[0]];
  248. if (\T_CLOSE_TAG === $token[0]) {
  249. $this->prevCloseTagHasNewline = false !== strpos($token[1], "\n");
  250. } elseif (\T_INLINE_HTML === $token[0]) {
  251. $startAttributes['hasLeadingNewline'] = $this->prevCloseTagHasNewline;
  252. }
  253. $this->line += substr_count($value, "\n");
  254. $this->filePos += \strlen($value);
  255. } else {
  256. if (\T_COMMENT === $token[0] || \T_DOC_COMMENT === $token[0]) {
  257. if ($this->attributeCommentsUsed) {
  258. $comment = \T_DOC_COMMENT === $token[0]
  259. ? new Comment\Doc($token[1], $this->line, $this->filePos, $this->pos)
  260. : new Comment($token[1], $this->line, $this->filePos, $this->pos);
  261. $startAttributes['comments'][] = $comment;
  262. }
  263. }
  264. $this->line += substr_count($token[1], "\n");
  265. $this->filePos += \strlen($token[1]);
  266. continue;
  267. }
  268. if ($this->attributeEndLineUsed) {
  269. $endAttributes['endLine'] = $this->line;
  270. }
  271. if ($this->attributeEndTokenPosUsed) {
  272. $endAttributes['endTokenPos'] = $this->pos;
  273. }
  274. if ($this->attributeEndFilePosUsed) {
  275. $endAttributes['endFilePos'] = $this->filePos - 1;
  276. }
  277. return $id;
  278. }
  279. throw new \RuntimeException('Reached end of lexer loop');
  280. }
  281. /**
  282. * Returns the token array for current code.
  283. *
  284. * The token array is in the same format as provided by the
  285. * token_get_all() function and does not discard tokens (i.e.
  286. * whitespace and comments are included). The token position
  287. * attributes are against this token array.
  288. *
  289. * @return array Array of tokens in token_get_all() format
  290. */
  291. public function getTokens() : array {
  292. return $this->tokens;
  293. }
  294. /**
  295. * Handles __halt_compiler() by returning the text after it.
  296. *
  297. * @return string Remaining text
  298. */
  299. public function handleHaltCompiler() : string {
  300. // text after T_HALT_COMPILER, still including ();
  301. $textAfter = substr($this->code, $this->filePos);
  302. // ensure that it is followed by ();
  303. // this simplifies the situation, by not allowing any comments
  304. // in between of the tokens.
  305. if (!preg_match('~^\s*\(\s*\)\s*(?:;|\?>\r?\n?)~', $textAfter, $matches)) {
  306. throw new Error('__HALT_COMPILER must be followed by "();"');
  307. }
  308. // prevent the lexer from returning any further tokens
  309. $this->pos = count($this->tokens);
  310. // return with (); removed
  311. return substr($textAfter, strlen($matches[0]));
  312. }
  313. /**
  314. * Creates the token map.
  315. *
  316. * The token map maps the PHP internal token identifiers
  317. * to the identifiers used by the Parser. Additionally it
  318. * maps T_OPEN_TAG_WITH_ECHO to T_ECHO and T_CLOSE_TAG to ';'.
  319. *
  320. * @return array The token map
  321. */
  322. protected function createTokenMap() : array {
  323. $tokenMap = [];
  324. // 256 is the minimum possible token number, as everything below
  325. // it is an ASCII value
  326. for ($i = 256; $i < 1000; ++$i) {
  327. if (\T_DOUBLE_COLON === $i) {
  328. // T_DOUBLE_COLON is equivalent to T_PAAMAYIM_NEKUDOTAYIM
  329. $tokenMap[$i] = Tokens::T_PAAMAYIM_NEKUDOTAYIM;
  330. } elseif(\T_OPEN_TAG_WITH_ECHO === $i) {
  331. // T_OPEN_TAG_WITH_ECHO with dropped T_OPEN_TAG results in T_ECHO
  332. $tokenMap[$i] = Tokens::T_ECHO;
  333. } elseif(\T_CLOSE_TAG === $i) {
  334. // T_CLOSE_TAG is equivalent to ';'
  335. $tokenMap[$i] = ord(';');
  336. } elseif ('UNKNOWN' !== $name = token_name($i)) {
  337. if ('T_HASHBANG' === $name) {
  338. // HHVM uses a special token for #! hashbang lines
  339. $tokenMap[$i] = Tokens::T_INLINE_HTML;
  340. } elseif (defined($name = Tokens::class . '::' . $name)) {
  341. // Other tokens can be mapped directly
  342. $tokenMap[$i] = constant($name);
  343. }
  344. }
  345. }
  346. // HHVM uses a special token for numbers that overflow to double
  347. if (defined('T_ONUMBER')) {
  348. $tokenMap[\T_ONUMBER] = Tokens::T_DNUMBER;
  349. }
  350. // HHVM also has a separate token for the __COMPILER_HALT_OFFSET__ constant
  351. if (defined('T_COMPILER_HALT_OFFSET')) {
  352. $tokenMap[\T_COMPILER_HALT_OFFSET] = Tokens::T_STRING;
  353. }
  354. return $tokenMap;
  355. }
  356. }