12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 |
- <?php declare(strict_types=1);
- namespace PhpParser;
- use PhpParser\Node\Expr;
- use PhpParser\Node\Expr\Array_;
- use PhpParser\Node\Expr\Cast\Double;
- use PhpParser\Node\Identifier;
- use PhpParser\Node\InterpolatedStringPart;
- use PhpParser\Node\Name;
- use PhpParser\Node\Param;
- use PhpParser\Node\Scalar\InterpolatedString;
- use PhpParser\Node\Scalar\Int_;
- use PhpParser\Node\Scalar\String_;
- use PhpParser\Node\Stmt;
- use PhpParser\Node\Stmt\Class_;
- use PhpParser\Node\Stmt\ClassConst;
- use PhpParser\Node\Stmt\ClassMethod;
- use PhpParser\Node\Stmt\Else_;
- use PhpParser\Node\Stmt\ElseIf_;
- use PhpParser\Node\Stmt\Enum_;
- use PhpParser\Node\Stmt\Interface_;
- use PhpParser\Node\Stmt\Namespace_;
- use PhpParser\Node\Stmt\Nop;
- use PhpParser\Node\Stmt\Property;
- use PhpParser\Node\Stmt\TryCatch;
- use PhpParser\Node\UseItem;
- use PhpParser\NodeVisitor\CommentAnnotatingVisitor;
- abstract class ParserAbstract implements Parser {
- private const SYMBOL_NONE = -1;
-
- protected Lexer $lexer;
-
- protected PhpVersion $phpVersion;
-
-
- protected int $tokenToSymbolMapSize;
-
- protected int $actionTableSize;
-
- protected int $gotoTableSize;
-
- protected int $invalidSymbol;
-
- protected int $errorSymbol;
-
- protected int $defaultAction;
-
- protected int $unexpectedTokenRule;
- protected int $YY2TBLSTATE;
-
- protected int $numNonLeafStates;
-
- protected array $phpTokenToSymbol;
-
- protected array $dropTokens;
-
- protected array $tokenToSymbol;
-
- protected array $symbolToName;
-
- protected array $productions;
-
- protected array $actionBase;
-
- protected array $action;
-
- protected array $actionCheck;
-
- protected array $actionDefault;
-
- protected array $reduceCallbacks;
-
- protected array $gotoBase;
-
- protected array $goto;
-
- protected array $gotoCheck;
-
- protected array $gotoDefault;
-
- protected array $ruleToNonTerminal;
-
- protected array $ruleToLength;
-
-
- protected $semValue;
-
- protected array $semStack;
-
- protected array $tokenStartStack;
-
- protected array $tokenEndStack;
-
- protected ErrorHandler $errorHandler;
-
- protected int $errorState;
-
- protected ?\SplObjectStorage $createdArrays;
-
- protected array $tokens;
-
- protected int $tokenPos;
-
- abstract protected function initReduceCallbacks(): void;
-
- public function __construct(Lexer $lexer, ?PhpVersion $phpVersion = null) {
- $this->lexer = $lexer;
- $this->phpVersion = $phpVersion ?? PhpVersion::getNewestSupported();
- $this->initReduceCallbacks();
- $this->phpTokenToSymbol = $this->createTokenMap();
- $this->dropTokens = array_fill_keys(
- [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], true
- );
- }
-
- public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array {
- $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing();
- $this->createdArrays = new \SplObjectStorage();
- $this->tokens = $this->lexer->tokenize($code, $this->errorHandler);
- $result = $this->doParse();
-
-
-
- foreach ($this->createdArrays as $node) {
- foreach ($node->items as $item) {
- if ($item->value instanceof Expr\Error) {
- $this->errorHandler->handleError(
- new Error('Cannot use empty array elements in arrays', $item->getAttributes()));
- }
- }
- }
-
-
- $this->tokenStartStack = [];
- $this->tokenEndStack = [];
- $this->semStack = [];
- $this->semValue = null;
- $this->createdArrays = null;
- if ($result !== null) {
- $traverser = new NodeTraverser(new CommentAnnotatingVisitor($this->tokens));
- $traverser->traverse($result);
- }
- return $result;
- }
- public function getTokens(): array {
- return $this->tokens;
- }
-
- protected function doParse(): ?array {
-
- $symbol = self::SYMBOL_NONE;
- $tokenValue = null;
- $this->tokenPos = -1;
-
- $this->tokenStartStack = [];
- $this->tokenEndStack = [0];
-
- $state = 0;
- $stateStack = [$state];
-
- $this->semStack = [];
-
- $stackPos = 0;
- $this->errorState = 0;
- for (;;) {
-
- if ($this->actionBase[$state] === 0) {
- $rule = $this->actionDefault[$state];
- } else {
- if ($symbol === self::SYMBOL_NONE) {
- do {
- $token = $this->tokens[++$this->tokenPos];
- $tokenId = $token->id;
- } while (isset($this->dropTokens[$tokenId]));
-
- $tokenValue = $token->text;
- if (!isset($this->phpTokenToSymbol[$tokenId])) {
- throw new \RangeException(sprintf(
- 'The lexer returned an invalid token (id=%d, value=%s)',
- $tokenId, $tokenValue
- ));
- }
- $symbol = $this->phpTokenToSymbol[$tokenId];
-
- }
- $idx = $this->actionBase[$state] + $symbol;
- if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)
- || ($state < $this->YY2TBLSTATE
- && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
- && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol))
- && ($action = $this->action[$idx]) !== $this->defaultAction) {
-
- if ($action > 0) {
-
-
- ++$stackPos;
- $stateStack[$stackPos] = $state = $action;
- $this->semStack[$stackPos] = $tokenValue;
- $this->tokenStartStack[$stackPos] = $this->tokenPos;
- $this->tokenEndStack[$stackPos] = $this->tokenPos;
- $symbol = self::SYMBOL_NONE;
- if ($this->errorState) {
- --$this->errorState;
- }
- if ($action < $this->numNonLeafStates) {
- continue;
- }
-
- $rule = $action - $this->numNonLeafStates;
- } else {
- $rule = -$action;
- }
- } else {
- $rule = $this->actionDefault[$state];
- }
- }
- for (;;) {
- if ($rule === 0) {
-
-
- return $this->semValue;
- }
- if ($rule !== $this->unexpectedTokenRule) {
-
-
- $ruleLength = $this->ruleToLength[$rule];
- try {
- $callback = $this->reduceCallbacks[$rule];
- if ($callback !== null) {
- $callback($stackPos);
- } elseif ($ruleLength > 0) {
- $this->semValue = $this->semStack[$stackPos - $ruleLength + 1];
- }
- } catch (Error $e) {
- if (-1 === $e->getStartLine()) {
- $e->setStartLine($this->tokens[$this->tokenPos]->line);
- }
- $this->emitError($e);
-
- return null;
- }
-
- $lastTokenEnd = $this->tokenEndStack[$stackPos];
- $stackPos -= $ruleLength;
- $nonTerminal = $this->ruleToNonTerminal[$rule];
- $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos];
- if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) {
- $state = $this->goto[$idx];
- } else {
- $state = $this->gotoDefault[$nonTerminal];
- }
- ++$stackPos;
- $stateStack[$stackPos] = $state;
- $this->semStack[$stackPos] = $this->semValue;
- $this->tokenEndStack[$stackPos] = $lastTokenEnd;
- if ($ruleLength === 0) {
-
- $this->tokenStartStack[$stackPos] = $this->tokenPos;
- }
- } else {
-
- switch ($this->errorState) {
- case 0:
- $msg = $this->getErrorMessage($symbol, $state);
- $this->emitError(new Error($msg, $this->getAttributesForToken($this->tokenPos)));
-
-
- case 1:
- case 2:
- $this->errorState = 3;
-
- while (!(
- (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0
- && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
- || ($state < $this->YY2TBLSTATE
- && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0
- && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol)
- ) || ($action = $this->action[$idx]) === $this->defaultAction) {
- if ($stackPos <= 0) {
-
- return null;
- }
- $state = $stateStack[--$stackPos];
-
- }
-
- ++$stackPos;
- $stateStack[$stackPos] = $state = $action;
-
-
- $this->tokenStartStack[$stackPos] = $this->tokenPos;
- $this->tokenEndStack[$stackPos] = $this->tokenEndStack[$stackPos - 1];
- break;
- case 3:
- if ($symbol === 0) {
-
- return null;
- }
-
- $symbol = self::SYMBOL_NONE;
- break 2;
- }
- }
- if ($state < $this->numNonLeafStates) {
- break;
- }
-
- $rule = $state - $this->numNonLeafStates;
- }
- }
- throw new \RuntimeException('Reached end of parser loop');
- }
- protected function emitError(Error $error): void {
- $this->errorHandler->handleError($error);
- }
-
- protected function getErrorMessage(int $symbol, int $state): string {
- $expectedString = '';
- if ($expected = $this->getExpectedTokens($state)) {
- $expectedString = ', expecting ' . implode(' or ', $expected);
- }
- return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString;
- }
-
- protected function getExpectedTokens(int $state): array {
- $expected = [];
- $base = $this->actionBase[$state];
- foreach ($this->symbolToName as $symbol => $name) {
- $idx = $base + $symbol;
- if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
- || $state < $this->YY2TBLSTATE
- && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0
- && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol
- ) {
- if ($this->action[$idx] !== $this->unexpectedTokenRule
- && $this->action[$idx] !== $this->defaultAction
- && $symbol !== $this->errorSymbol
- ) {
- if (count($expected) === 4) {
-
- return [];
- }
- $expected[] = $name;
- }
- }
- }
- return $expected;
- }
-
- protected function getAttributes(int $tokenStartPos, int $tokenEndPos): array {
- $startToken = $this->tokens[$tokenStartPos];
- $afterEndToken = $this->tokens[$tokenEndPos + 1];
- return [
- 'startLine' => $startToken->line,
- 'startTokenPos' => $tokenStartPos,
- 'startFilePos' => $startToken->pos,
- 'endLine' => $afterEndToken->line,
- 'endTokenPos' => $tokenEndPos,
- 'endFilePos' => $afterEndToken->pos - 1,
- ];
- }
-
- protected function getAttributesForToken(int $tokenPos): array {
- if ($tokenPos < \count($this->tokens) - 1) {
- return $this->getAttributes($tokenPos, $tokenPos);
- }
-
- $token = $this->tokens[$tokenPos];
- return [
- 'startLine' => $token->line,
- 'startTokenPos' => $tokenPos,
- 'startFilePos' => $token->pos,
- 'endLine' => $token->line,
- 'endTokenPos' => $tokenPos,
- 'endFilePos' => $token->pos,
- ];
- }
-
-
-
-
- protected function handleNamespaces(array $stmts): array {
- $hasErrored = false;
- $style = $this->getNamespacingStyle($stmts);
- if (null === $style) {
-
- return $stmts;
- }
- if ('brace' === $style) {
-
- $afterFirstNamespace = false;
- foreach ($stmts as $stmt) {
- if ($stmt instanceof Node\Stmt\Namespace_) {
- $afterFirstNamespace = true;
- } elseif (!$stmt instanceof Node\Stmt\HaltCompiler
- && !$stmt instanceof Node\Stmt\Nop
- && $afterFirstNamespace && !$hasErrored) {
- $this->emitError(new Error(
- 'No code may exist outside of namespace {}', $stmt->getAttributes()));
- $hasErrored = true;
- }
- }
- return $stmts;
- } else {
-
- $resultStmts = [];
- $targetStmts = &$resultStmts;
- $lastNs = null;
- foreach ($stmts as $stmt) {
- if ($stmt instanceof Node\Stmt\Namespace_) {
- if ($lastNs !== null) {
- $this->fixupNamespaceAttributes($lastNs);
- }
- if ($stmt->stmts === null) {
- $stmt->stmts = [];
- $targetStmts = &$stmt->stmts;
- $resultStmts[] = $stmt;
- } else {
-
- $resultStmts[] = $stmt;
- $targetStmts = &$resultStmts;
- }
- $lastNs = $stmt;
- } elseif ($stmt instanceof Node\Stmt\HaltCompiler) {
-
- $resultStmts[] = $stmt;
- } else {
- $targetStmts[] = $stmt;
- }
- }
- if ($lastNs !== null) {
- $this->fixupNamespaceAttributes($lastNs);
- }
- return $resultStmts;
- }
- }
- private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt): void {
-
-
- if (empty($stmt->stmts)) {
- return;
- }
-
-
- $endAttributes = ['endLine', 'endFilePos', 'endTokenPos'];
- $lastStmt = $stmt->stmts[count($stmt->stmts) - 1];
- foreach ($endAttributes as $endAttribute) {
- if ($lastStmt->hasAttribute($endAttribute)) {
- $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute));
- }
- }
- }
-
- private function getNamespaceErrorAttributes(Namespace_ $node): array {
- $attrs = $node->getAttributes();
-
- if (isset($attrs['startLine'])) {
- $attrs['endLine'] = $attrs['startLine'];
- }
- if (isset($attrs['startTokenPos'])) {
- $attrs['endTokenPos'] = $attrs['startTokenPos'];
- }
- if (isset($attrs['startFilePos'])) {
- $attrs['endFilePos'] = $attrs['startFilePos'] + \strlen('namespace') - 1;
- }
- return $attrs;
- }
-
- private function getNamespacingStyle(array $stmts): ?string {
- $style = null;
- $hasNotAllowedStmts = false;
- foreach ($stmts as $i => $stmt) {
- if ($stmt instanceof Node\Stmt\Namespace_) {
- $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace';
- if (null === $style) {
- $style = $currentStyle;
- if ($hasNotAllowedStmts) {
- $this->emitError(new Error(
- 'Namespace declaration statement has to be the very first statement in the script',
- $this->getNamespaceErrorAttributes($stmt)
- ));
- }
- } elseif ($style !== $currentStyle) {
- $this->emitError(new Error(
- 'Cannot mix bracketed namespace declarations with unbracketed namespace declarations',
- $this->getNamespaceErrorAttributes($stmt)
- ));
-
- return 'semicolon';
- }
- continue;
- }
-
- if ($stmt instanceof Node\Stmt\Declare_
- || $stmt instanceof Node\Stmt\HaltCompiler
- || $stmt instanceof Node\Stmt\Nop) {
- continue;
- }
-
- if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) {
- continue;
- }
-
- $hasNotAllowedStmts = true;
- }
- return $style;
- }
-
- protected function handleBuiltinTypes(Name $name) {
- if (!$name->isUnqualified()) {
- return $name;
- }
- $lowerName = $name->toLowerString();
- if (!$this->phpVersion->supportsBuiltinType($lowerName)) {
- return $name;
- }
- return new Node\Identifier($lowerName, $name->getAttributes());
- }
-
- protected function getAttributesAt(int $stackPos): array {
- return $this->getAttributes($this->tokenStartStack[$stackPos], $this->tokenEndStack[$stackPos]);
- }
- protected function getFloatCastKind(string $cast): int {
- $cast = strtolower($cast);
- if (strpos($cast, 'float') !== false) {
- return Double::KIND_FLOAT;
- }
- if (strpos($cast, 'real') !== false) {
- return Double::KIND_REAL;
- }
- return Double::KIND_DOUBLE;
- }
-
- protected function parseLNumber(string $str, array $attributes, bool $allowInvalidOctal = false): Int_ {
- try {
- return Int_::fromString($str, $attributes, $allowInvalidOctal);
- } catch (Error $error) {
- $this->emitError($error);
-
- return new Int_(0, $attributes);
- }
- }
-
- protected function parseNumString(string $str, array $attributes) {
- if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) {
- return new String_($str, $attributes);
- }
- $num = +$str;
- if (!is_int($num)) {
- return new String_($str, $attributes);
- }
- return new Int_($num, $attributes);
- }
-
- protected function stripIndentation(
- string $string, int $indentLen, string $indentChar,
- bool $newlineAtStart, bool $newlineAtEnd, array $attributes
- ): string {
- if ($indentLen === 0) {
- return $string;
- }
- $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)';
- $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])';
- $regex = '/' . $start . '([ \t]*)(' . $end . ')?/';
- return preg_replace_callback(
- $regex,
- function ($matches) use ($indentLen, $indentChar, $attributes) {
- $prefix = substr($matches[1], 0, $indentLen);
- if (false !== strpos($prefix, $indentChar === " " ? "\t" : " ")) {
- $this->emitError(new Error(
- 'Invalid indentation - tabs and spaces cannot be mixed', $attributes
- ));
- } elseif (strlen($prefix) < $indentLen && !isset($matches[2])) {
- $this->emitError(new Error(
- 'Invalid body indentation level ' .
- '(expecting an indentation level of at least ' . $indentLen . ')',
- $attributes
- ));
- }
- return substr($matches[0], strlen($prefix));
- },
- $string
- );
- }
-
- protected function parseDocString(
- string $startToken, $contents, string $endToken,
- array $attributes, array $endTokenAttributes, bool $parseUnicodeEscape
- ): Expr {
- $kind = strpos($startToken, "'") === false
- ? String_::KIND_HEREDOC : String_::KIND_NOWDOC;
- $regex = '/\A[bB]?<<<[ \t]*[\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\'"]?(?:\r\n|\n|\r)\z/';
- $result = preg_match($regex, $startToken, $matches);
- assert($result === 1);
- $label = $matches[1];
- $result = preg_match('/\A[ \t]*/', $endToken, $matches);
- assert($result === 1);
- $indentation = $matches[0];
- $attributes['kind'] = $kind;
- $attributes['docLabel'] = $label;
- $attributes['docIndentation'] = $indentation;
- $indentHasSpaces = false !== strpos($indentation, " ");
- $indentHasTabs = false !== strpos($indentation, "\t");
- if ($indentHasSpaces && $indentHasTabs) {
- $this->emitError(new Error(
- 'Invalid indentation - tabs and spaces cannot be mixed',
- $endTokenAttributes
- ));
-
- $indentation = '';
- }
- $indentLen = \strlen($indentation);
- $indentChar = $indentHasSpaces ? " " : "\t";
- if (\is_string($contents)) {
- if ($contents === '') {
- $attributes['rawValue'] = $contents;
- return new String_('', $attributes);
- }
- $contents = $this->stripIndentation(
- $contents, $indentLen, $indentChar, true, true, $attributes
- );
- $contents = preg_replace('~(\r\n|\n|\r)\z~', '', $contents);
- $attributes['rawValue'] = $contents;
- if ($kind === String_::KIND_HEREDOC) {
- $contents = String_::parseEscapeSequences($contents, null, $parseUnicodeEscape);
- }
- return new String_($contents, $attributes);
- } else {
- assert(count($contents) > 0);
- if (!$contents[0] instanceof Node\InterpolatedStringPart) {
-
- $this->stripIndentation(
- '', $indentLen, $indentChar, true, false, $contents[0]->getAttributes()
- );
- }
- $newContents = [];
- foreach ($contents as $i => $part) {
- if ($part instanceof Node\InterpolatedStringPart) {
- $isLast = $i === \count($contents) - 1;
- $part->value = $this->stripIndentation(
- $part->value, $indentLen, $indentChar,
- $i === 0, $isLast, $part->getAttributes()
- );
- if ($isLast) {
- $part->value = preg_replace('~(\r\n|\n|\r)\z~', '', $part->value);
- }
- $part->setAttribute('rawValue', $part->value);
- $part->value = String_::parseEscapeSequences($part->value, null, $parseUnicodeEscape);
- if ('' === $part->value) {
- continue;
- }
- }
- $newContents[] = $part;
- }
- return new InterpolatedString($newContents, $attributes);
- }
- }
- protected function createCommentFromToken(Token $token, int $tokenPos): Comment {
- assert($token->id === \T_COMMENT || $token->id == \T_DOC_COMMENT);
- return \T_DOC_COMMENT === $token->id
- ? new Comment\Doc($token->text, $token->line, $token->pos, $tokenPos,
- $token->getEndLine(), $token->getEndPos() - 1, $tokenPos)
- : new Comment($token->text, $token->line, $token->pos, $tokenPos,
- $token->getEndLine(), $token->getEndPos() - 1, $tokenPos);
- }
-
- protected function getCommentBeforeToken(int $tokenPos): ?Comment {
- while (--$tokenPos >= 0) {
- $token = $this->tokens[$tokenPos];
- if (!isset($this->dropTokens[$token->id])) {
- break;
- }
- if ($token->id === \T_COMMENT || $token->id === \T_DOC_COMMENT) {
- return $this->createCommentFromToken($token, $tokenPos);
- }
- }
- return null;
- }
-
- protected function maybeCreateZeroLengthNop(int $tokenPos): ?Nop {
- $comment = $this->getCommentBeforeToken($tokenPos);
- if ($comment === null) {
- return null;
- }
- $commentEndLine = $comment->getEndLine();
- $commentEndFilePos = $comment->getEndFilePos();
- $commentEndTokenPos = $comment->getEndTokenPos();
- $attributes = [
- 'startLine' => $commentEndLine,
- 'endLine' => $commentEndLine,
- 'startFilePos' => $commentEndFilePos + 1,
- 'endFilePos' => $commentEndFilePos,
- 'startTokenPos' => $commentEndTokenPos + 1,
- 'endTokenPos' => $commentEndTokenPos,
- ];
- return new Nop($attributes);
- }
- protected function maybeCreateNop(int $tokenStartPos, int $tokenEndPos): ?Nop {
- if ($this->getCommentBeforeToken($tokenStartPos) === null) {
- return null;
- }
- return new Nop($this->getAttributes($tokenStartPos, $tokenEndPos));
- }
- protected function handleHaltCompiler(): string {
-
- $nextToken = $this->tokens[$this->tokenPos + 1];
- $this->tokenPos = \count($this->tokens) - 2;
-
- return $nextToken->id === \T_INLINE_HTML ? $nextToken->text : '';
- }
- protected function inlineHtmlHasLeadingNewline(int $stackPos): bool {
- $tokenPos = $this->tokenStartStack[$stackPos];
- $token = $this->tokens[$tokenPos];
- assert($token->id == \T_INLINE_HTML);
- if ($tokenPos > 0) {
- $prevToken = $this->tokens[$tokenPos - 1];
- assert($prevToken->id == \T_CLOSE_TAG);
- return false !== strpos($prevToken->text, "\n")
- || false !== strpos($prevToken->text, "\r");
- }
- return true;
- }
-
- protected function createEmptyElemAttributes(int $tokenPos): array {
- return $this->getAttributesForToken($tokenPos);
- }
- protected function fixupArrayDestructuring(Array_ $node): Expr\List_ {
- $this->createdArrays->detach($node);
- return new Expr\List_(array_map(function (Node\ArrayItem $item) {
- if ($item->value instanceof Expr\Error) {
-
- return null;
- }
- if ($item->value instanceof Array_) {
- return new Node\ArrayItem(
- $this->fixupArrayDestructuring($item->value),
- $item->key, $item->byRef, $item->getAttributes());
- }
- return $item;
- }, $node->items), ['kind' => Expr\List_::KIND_ARRAY] + $node->getAttributes());
- }
- protected function postprocessList(Expr\List_ $node): void {
- foreach ($node->items as $i => $item) {
- if ($item->value instanceof Expr\Error) {
-
- $node->items[$i] = null;
- }
- }
- }
-
- protected function fixupAlternativeElse($node): void {
-
- $numStmts = \count($node->stmts);
- if ($numStmts !== 0 && $node->stmts[$numStmts - 1] instanceof Nop) {
- $nopAttrs = $node->stmts[$numStmts - 1]->getAttributes();
- if (isset($nopAttrs['endLine'])) {
- $node->setAttribute('endLine', $nopAttrs['endLine']);
- }
- if (isset($nopAttrs['endFilePos'])) {
- $node->setAttribute('endFilePos', $nopAttrs['endFilePos']);
- }
- if (isset($nopAttrs['endTokenPos'])) {
- $node->setAttribute('endTokenPos', $nopAttrs['endTokenPos']);
- }
- }
- }
- protected function checkClassModifier(int $a, int $b, int $modifierPos): void {
- try {
- Modifiers::verifyClassModifier($a, $b);
- } catch (Error $error) {
- $error->setAttributes($this->getAttributesAt($modifierPos));
- $this->emitError($error);
- }
- }
- protected function checkModifier(int $a, int $b, int $modifierPos): void {
-
- try {
- Modifiers::verifyModifier($a, $b);
- } catch (Error $error) {
- $error->setAttributes($this->getAttributesAt($modifierPos));
- $this->emitError($error);
- }
- }
- protected function checkParam(Param $node): void {
- if ($node->variadic && null !== $node->default) {
- $this->emitError(new Error(
- 'Variadic parameter cannot have a default value',
- $node->default->getAttributes()
- ));
- }
- }
- protected function checkTryCatch(TryCatch $node): void {
- if (empty($node->catches) && null === $node->finally) {
- $this->emitError(new Error(
- 'Cannot use try without catch or finally', $node->getAttributes()
- ));
- }
- }
- protected function checkNamespace(Namespace_ $node): void {
- if (null !== $node->stmts) {
- foreach ($node->stmts as $stmt) {
- if ($stmt instanceof Namespace_) {
- $this->emitError(new Error(
- 'Namespace declarations cannot be nested', $stmt->getAttributes()
- ));
- }
- }
- }
- }
- private function checkClassName(?Identifier $name, int $namePos): void {
- if (null !== $name && $name->isSpecialClassName()) {
- $this->emitError(new Error(
- sprintf('Cannot use \'%s\' as class name as it is reserved', $name),
- $this->getAttributesAt($namePos)
- ));
- }
- }
-
- private function checkImplementedInterfaces(array $interfaces): void {
- foreach ($interfaces as $interface) {
- if ($interface->isSpecialClassName()) {
- $this->emitError(new Error(
- sprintf('Cannot use \'%s\' as interface name as it is reserved', $interface),
- $interface->getAttributes()
- ));
- }
- }
- }
- protected function checkClass(Class_ $node, int $namePos): void {
- $this->checkClassName($node->name, $namePos);
- if ($node->extends && $node->extends->isSpecialClassName()) {
- $this->emitError(new Error(
- sprintf('Cannot use \'%s\' as class name as it is reserved', $node->extends),
- $node->extends->getAttributes()
- ));
- }
- $this->checkImplementedInterfaces($node->implements);
- }
- protected function checkInterface(Interface_ $node, int $namePos): void {
- $this->checkClassName($node->name, $namePos);
- $this->checkImplementedInterfaces($node->extends);
- }
- protected function checkEnum(Enum_ $node, int $namePos): void {
- $this->checkClassName($node->name, $namePos);
- $this->checkImplementedInterfaces($node->implements);
- }
- protected function checkClassMethod(ClassMethod $node, int $modifierPos): void {
- if ($node->flags & Modifiers::STATIC) {
- switch ($node->name->toLowerString()) {
- case '__construct':
- $this->emitError(new Error(
- sprintf('Constructor %s() cannot be static', $node->name),
- $this->getAttributesAt($modifierPos)));
- break;
- case '__destruct':
- $this->emitError(new Error(
- sprintf('Destructor %s() cannot be static', $node->name),
- $this->getAttributesAt($modifierPos)));
- break;
- case '__clone':
- $this->emitError(new Error(
- sprintf('Clone method %s() cannot be static', $node->name),
- $this->getAttributesAt($modifierPos)));
- break;
- }
- }
- if ($node->flags & Modifiers::READONLY) {
- $this->emitError(new Error(
- sprintf('Method %s() cannot be readonly', $node->name),
- $this->getAttributesAt($modifierPos)));
- }
- }
- protected function checkClassConst(ClassConst $node, int $modifierPos): void {
- if ($node->flags & Modifiers::STATIC) {
- $this->emitError(new Error(
- "Cannot use 'static' as constant modifier",
- $this->getAttributesAt($modifierPos)));
- }
- if ($node->flags & Modifiers::ABSTRACT) {
- $this->emitError(new Error(
- "Cannot use 'abstract' as constant modifier",
- $this->getAttributesAt($modifierPos)));
- }
- if ($node->flags & Modifiers::READONLY) {
- $this->emitError(new Error(
- "Cannot use 'readonly' as constant modifier",
- $this->getAttributesAt($modifierPos)));
- }
- }
- protected function checkProperty(Property $node, int $modifierPos): void {
- if ($node->flags & Modifiers::ABSTRACT) {
- $this->emitError(new Error('Properties cannot be declared abstract',
- $this->getAttributesAt($modifierPos)));
- }
- if ($node->flags & Modifiers::FINAL) {
- $this->emitError(new Error('Properties cannot be declared final',
- $this->getAttributesAt($modifierPos)));
- }
- }
- protected function checkUseUse(UseItem $node, int $namePos): void {
- if ($node->alias && $node->alias->isSpecialClassName()) {
- $this->emitError(new Error(
- sprintf(
- 'Cannot use %s as %s because \'%2$s\' is a special class name',
- $node->name, $node->alias
- ),
- $this->getAttributesAt($namePos)
- ));
- }
- }
-
- protected function createTokenMap(): array {
- $tokenMap = [];
- for ($i = 0; $i < 1000; ++$i) {
- if ($i < 256) {
-
- $tokenMap[$i] = $i;
- } elseif (\T_DOUBLE_COLON === $i) {
-
- $tokenMap[$i] = static::T_PAAMAYIM_NEKUDOTAYIM;
- } elseif (\T_OPEN_TAG_WITH_ECHO === $i) {
-
- $tokenMap[$i] = static::T_ECHO;
- } elseif (\T_CLOSE_TAG === $i) {
-
- $tokenMap[$i] = ord(';');
- } elseif ('UNKNOWN' !== $name = token_name($i)) {
- if (defined($name = static::class . '::' . $name)) {
-
- $tokenMap[$i] = constant($name);
- }
- }
- }
-
- $tokenMap[\T_FN] = static::T_FN;
- $tokenMap[\T_COALESCE_EQUAL] = static::T_COALESCE_EQUAL;
- $tokenMap[\T_NAME_QUALIFIED] = static::T_NAME_QUALIFIED;
- $tokenMap[\T_NAME_FULLY_QUALIFIED] = static::T_NAME_FULLY_QUALIFIED;
- $tokenMap[\T_NAME_RELATIVE] = static::T_NAME_RELATIVE;
- $tokenMap[\T_MATCH] = static::T_MATCH;
- $tokenMap[\T_NULLSAFE_OBJECT_OPERATOR] = static::T_NULLSAFE_OBJECT_OPERATOR;
- $tokenMap[\T_ATTRIBUTE] = static::T_ATTRIBUTE;
- $tokenMap[\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG] = static::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG;
- $tokenMap[\T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG] = static::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG;
- $tokenMap[\T_ENUM] = static::T_ENUM;
- $tokenMap[\T_READONLY] = static::T_READONLY;
-
-
- $fullTokenMap = [];
- foreach ($tokenMap as $phpToken => $extSymbol) {
- $intSymbol = $this->tokenToSymbol[$extSymbol];
- if ($intSymbol === $this->invalidSymbol) {
- continue;
- }
- $fullTokenMap[$phpToken] = $intSymbol;
- }
- return $fullTokenMap;
- }
- }
|