Skip to content

Commit 4e317b2

Browse files
[printer] Keep blank lines between statements when a node list is emptied (#8886)
Co-authored-by: GitHub Action <actions@github.com>
1 parent 9a6fdb0 commit 4e317b2

2 files changed

Lines changed: 134 additions & 1 deletion

File tree

‎src/PhpParser/Printer/BetterStandardPrinter.php‎

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,11 @@
2929
use PhpParser\Node\InterpolatedStringPart;
3030
use PhpParser\Node\Scalar\InterpolatedString;
3131
use PhpParser\Node\Scalar\String_;
32+
use PhpParser\Node\Stmt\Class_;
3233
use PhpParser\Node\Stmt\Declare_;
34+
use PhpParser\Node\Stmt\Enum_;
3335
use PhpParser\Node\Stmt\InlineHTML;
36+
use PhpParser\Node\Stmt\Interface_;
3437
use PhpParser\Node\Stmt\Nop;
3538
use PhpParser\PrettyPrinter\Standard;
3639
use PhpParser\Token;
@@ -55,6 +58,19 @@ final class BetterStandardPrinter extends Standard
5558
*/
5659
private const string EXTRA_SPACE_BEFORE_NOP_REGEX = '#^[ \t]+$#m';
5760

61+
/**
62+
* php-parser cannot emptying a node list, it falls back to a full reprint of the parent node
63+
* and drops blank lines between its statements; these keyword tokens let us cut just the
64+
* emptied clause instead, e.g. the "implements" of a class that loses its last interface
65+
*
66+
* @var array<string, int>
67+
*/
68+
private const array EMPTIED_LIST_KEYWORD_TOKENS = [
69+
Class_::class . '->implements' => \T_IMPLEMENTS,
70+
Enum_::class . '->implements' => \T_IMPLEMENTS,
71+
Interface_::class . '->extends' => \T_EXTENDS,
72+
];
73+
5874
public function __construct(
5975
private readonly ExprAnalyzer $exprAnalyzer,
6076
private readonly PrivatesAccessor $privatesAccessor,
@@ -230,9 +246,20 @@ protected function pArray(
230246
string $subNodeName,
231247
?int $fixup
232248
): ?string {
249+
$startPos = $pos;
250+
233251
$content = parent::pArray($nodes, $origNodes, $pos, $indentAdjustment, $parentNodeClass, $subNodeName, $fixup);
234252
if ($content === null) {
235-
return $content;
253+
$cutToPos = $this->resolveEmptiedNodeListEndPos($nodes, $origNodes, $startPos, $parentNodeClass, $subNodeName);
254+
if ($cutToPos === null) {
255+
// restore the position possibly advanced by the parent before falling back
256+
$pos = $startPos;
257+
return null;
258+
}
259+
260+
// drop the whole clause: whitespace + keyword + type list
261+
$pos = $cutToPos;
262+
return '';
236263
}
237264

238265
if (! $this->containsNop($nodes)) {
@@ -242,6 +269,62 @@ protected function pArray(
242269
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX);
243270
}
244271

272+
/**
273+
* php-parser bails on emptying a node list, which forces the parent node to be fully reprinted
274+
* and loses blank lines between statements; when the whole list is removed we can instead cut
275+
* just the emptied clause (keyword + types) and keep the rest format-preserved
276+
*
277+
* Returns the token position right after the removed clause, or null when not handled.
278+
*
279+
* @param mixed[] $nodes
280+
* @param array<int, mixed> $origNodes
281+
*/
282+
private function resolveEmptiedNodeListEndPos(
283+
array $nodes,
284+
array $origNodes,
285+
int $startPos,
286+
string $parentNodeClass,
287+
string $subNodeName
288+
): ?int {
289+
// only the "whole list removed" case is handled here
290+
if ($nodes !== [] || $origNodes === []) {
291+
return null;
292+
}
293+
294+
if (! $this->origTokens instanceof TokenStream) {
295+
return null;
296+
}
297+
298+
$keywordToken = self::EMPTIED_LIST_KEYWORD_TOKENS[$parentNodeClass . '->' . $subNodeName] ?? null;
299+
if ($keywordToken === null) {
300+
return null;
301+
}
302+
303+
$firstOrigNode = $origNodes[0];
304+
$lastOrigNode = $origNodes[count($origNodes) - 1];
305+
if (! $firstOrigNode instanceof Node || ! $lastOrigNode instanceof Node) {
306+
return null;
307+
}
308+
309+
$firstStartPos = $firstOrigNode->getStartTokenPos();
310+
$lastEndPos = $lastOrigNode->getEndTokenPos();
311+
if ($firstStartPos < 0 || $lastEndPos < 0) {
312+
return null;
313+
}
314+
315+
// the keyword must sit between the previous sub-node and the removed list
316+
if (! $this->origTokens->haveTokenInRange($startPos, $firstStartPos, $keywordToken)) {
317+
return null;
318+
}
319+
320+
// bail on php tags in the removed range to avoid dropping them
321+
if ($this->origTokens->haveTagInRange($startPos, $lastEndPos + 1)) {
322+
return null;
323+
}
324+
325+
return $lastEndPos + 1;
326+
}
327+
245328
/**
246329
* Do not add "()" on Expressions
247330
* @see https://github.com/rectorphp/rector/pull/401#discussion_r181487199

‎tests/PhpParser/Printer/BetterStandardPrinterTest.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,16 @@
1111
use PhpParser\Node\Expr\Variable;
1212
use PhpParser\Node\Expr\Yield_;
1313
use PhpParser\Node\Scalar\String_;
14+
use PhpParser\Node\Stmt\Class_;
1415
use PhpParser\Node\Stmt\ClassMethod;
1516
use PhpParser\Node\Stmt\Expression;
17+
use PhpParser\NodeTraverser;
18+
use PhpParser\NodeVisitor\CloningVisitor;
1619
use PHPUnit\Framework\Attributes\DataProvider;
1720
use Rector\Configuration\Option;
1821
use Rector\Configuration\Parameter\SimpleParameterProvider;
1922
use Rector\NodeTypeResolver\Node\AttributeKey;
23+
use Rector\PhpParser\Parser\RectorParser;
2024
use Rector\PhpParser\Printer\BetterStandardPrinter;
2125
use Rector\Testing\PHPUnit\AbstractLazyTestCase;
2226

@@ -49,6 +53,32 @@ public function testAddingCommentOnSomeNodesFail(): void
4953
);
5054
}
5155

56+
public function testKeepBlankLinesBetweenMethodsWhenImplementsRemoved(): void
57+
{
58+
$fileContent = <<<'PHP'
59+
<?php
60+
61+
class SomeClass implements \SomeInterface
62+
{
63+
public function first()
64+
{
65+
}
66+
67+
public function second()
68+
{
69+
}
70+
}
71+
PHP;
72+
73+
$printed = $this->printWithRemovedImplements($fileContent);
74+
75+
// the interface is gone...
76+
$this->assertStringNotContainsString('implements', $printed);
77+
78+
// ...but the blank line between methods is kept
79+
$this->assertStringContainsString(" }\n\n public function second()", $printed);
80+
}
81+
5282
public function testStringWithAddedComment(): void
5383
{
5484
$string = new String_('hey');
@@ -105,6 +135,26 @@ public function testNoNewlineOnFluentCallWithoutAttribute(): void
105135
$this->assertSame('$foo->bar()->baz()', $printed);
106136
}
107137

138+
private function printWithRemovedImplements(string $fileContent): string
139+
{
140+
$rectorParser = $this->make(RectorParser::class);
141+
$stmtsAndTokens = $rectorParser->parseFileContentToStmtsAndTokens($fileContent);
142+
143+
$oldStmts = $stmtsAndTokens->getStmts();
144+
$tokens = $stmtsAndTokens->getTokens();
145+
146+
$nodeTraverser = new NodeTraverser(new CloningVisitor());
147+
$newStmts = $nodeTraverser->traverse($oldStmts);
148+
149+
foreach ($newStmts as $newStmt) {
150+
if ($newStmt instanceof Class_) {
151+
$newStmt->implements = [];
152+
}
153+
}
154+
155+
return $this->betterStandardPrinter->printFormatPreserving($newStmts, $oldStmts, $tokens);
156+
}
157+
108158
/**
109159
* @return Iterator<array<int, (Yield_|Expression|string)>>
110160
*/

0 commit comments

Comments
 (0)