Skip to content

Commit

Permalink
Avoid negative indendation in formatting-preserving printer
Browse files Browse the repository at this point in the history
Fixes #1015.
  • Loading branch information
nikic committed Sep 29, 2024
1 parent e50c67b commit 961f158
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/PhpParser/PrettyPrinterAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,7 @@ protected function p(
$result .= $extraLeft;

$origIndentLevel = $this->indentLevel;
$this->setIndentLevel($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment);
$this->setIndentLevel(max($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment, 0));

// If it's the same node that was previously in this position, it certainly doesn't
// need fixup. It's important to check this here, because our fixup checks are more
Expand Down Expand Up @@ -839,7 +839,7 @@ protected function pArray(
\assert($itemStartPos >= 0 && $itemEndPos >= 0 && $itemStartPos >= $pos);

$origIndentLevel = $this->indentLevel;
$lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment;
$lastElemIndentLevel = max($this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment, 0);
$this->setIndentLevel($lastElemIndentLevel);

$comments = $arrItem->getComments();
Expand Down
33 changes: 33 additions & 0 deletions test/code/formatPreservation/indent.test
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,36 @@ if ($a) {
@@{"\t"}@@$x;
@@{"\t"}@@$y;
}
-----
<?php
array_merge(
[
$x,
$y,
]
);
-----
$call = $stmts[0]->expr;
$stmts[0]->expr = new Expr\StaticCall(new Node\Name\FullyQualified('Compat'), $call->name, $call->args);
-----
<?php
\Compat::array_merge([
$x,
$y,
]);
-----
<?php
if ($a) {
if (
$b
) {}
}
-----
$stmts[0] = new Stmt\While_($stmts[0]->cond, $stmts[0]->stmts);
-----
<?php
while ($a) {
if (
$b
) {}
}

0 comments on commit 961f158

Please sign in to comment.