annotate vendor/nikic/php-parser/lib/PhpParser/Lexer.php @ 2:92f882872392

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