Skip to content

Commit

Permalink
[Parser] Fix key negative on BetterNodeFinder locate stmt on FileWith…
Browse files Browse the repository at this point in the history
…outNamespace lookup Declare_ (#3899)
  • Loading branch information
samsonasik committed May 19, 2023
1 parent a4d6d41 commit b5807b7
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/PhpParser/Node/BetterNodeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ private function resolveNeighborNextStmt(StmtsAwareInterface $stmtsAware, Stmt $
private function findFirstInlinedNext(Node $node, callable $filter, array $newStmts, ?Node $parentNode): ?Node
{
if (! $parentNode instanceof Node) {
$nextNode = $this->resolveNodeFromFile($newStmts, $node, false);
$nextNode = $this->resolveNextNodeFromFile($newStmts, $node);
} elseif ($node instanceof Stmt) {
if (! $parentNode instanceof StmtsAwareInterface) {
return null;
Expand Down Expand Up @@ -655,19 +655,38 @@ private function findFirstInTopLevelStmtsAware(StmtsAwareInterface $stmtsAware,
/**
* @param Stmt[] $newStmts
*/
private function resolveNodeFromFile(array $newStmts, Node $node, bool $isPrevious = true): ?Node
private function resolvePreviousNodeFromFile(array $newStmts, Node $node): ?Node
{
if (! $node instanceof Namespace_ && ! $node instanceof FileWithoutNamespace) {
return null;
}

$currentStmtKey = $node->getAttribute(AttributeKey::STMT_KEY);
$stmtKey = $isPrevious ? $currentStmtKey - 1 : $currentStmtKey + 1;
$stmtKey = $currentStmtKey - 1;

if ($isPrevious) {
return $newStmts[$stmtKey] ?? null;
if ($node instanceof FileWithoutNamespace) {
$stmtKey = $stmtKey === -1 ? 0 : $stmtKey;
}

if (isset($newStmts[$stmtKey]) && $newStmts[$stmtKey]->getStartTokenPos() === $node->getStartFilePos()) {
return null;
}

return $newStmts[$stmtKey] ?? null;
}

/**
* @param Stmt[] $newStmts
*/
private function resolveNextNodeFromFile(array $newStmts, Node $node): ?Node
{
if (! $node instanceof Namespace_ && ! $node instanceof FileWithoutNamespace) {
return null;
}

$currentStmtKey = $node->getAttribute(AttributeKey::STMT_KEY);
$stmtKey = $currentStmtKey + 1;

if (! isset($newStmts[$currentStmtKey - 1])) {
return $newStmts[$stmtKey] ?? null;
}
Expand Down Expand Up @@ -769,7 +788,7 @@ private function resolveNextNodeFromOtherNode(Node $node): ?Node
private function findFirstInlinedPrevious(Node $node, callable $filter, array $newStmts, ?Node $parentNode): ?Node
{
if (! $parentNode instanceof Node) {
$previousNode = $this->resolveNodeFromFile($newStmts, $node);
$previousNode = $this->resolvePreviousNodeFromFile($newStmts, $node);
} elseif ($node instanceof Stmt) {
if (! $parentNode instanceof StmtsAwareInterface) {
return null;
Expand Down

0 comments on commit b5807b7

Please sign in to comment.