Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 18 additions & 39 deletions src/Reporting/NeededSkipVerifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Rector\ValueObject\ProcessResult;

/**
* Re-runs each rule-scoped skip on its exact file with skipping off. A skip whose rule still does
* Re-runs each rule-scoped skip on its exact file with only that skip lifted. A skip whose rule still does
* not change the file never prevented anything and can be removed. The re-processing is forced to a
* dry run, so it never writes, no matter the mode of the real run.
*
Expand Down Expand Up @@ -43,19 +43,14 @@ public function verify(ProcessResult $processResult): array
return [];
}

$changedRulesByFilePath = $this->resolveChangedRulesByFilePath($skippedFilePathsByRule);
// force a dry run, so re-processing detects the change but never writes the skipped file
$dryRunConfiguration = new Configuration(isDryRun: true);

$unnecessarySkips = [];
foreach ($skippedFilePathsByRule as $rectorClass => $filePaths) {
$unnecessaryRelativePaths = [];
foreach ($filePaths as $filePath) {
// file could not be re-processed (e.g. parse error), keep the skip to stay safe
if (! array_key_exists($filePath, $changedRulesByFilePath)) {
continue;
}

// the rule changed the file, so the skip really prevents a change - keep it
if (in_array($rectorClass, $changedRulesByFilePath[$filePath], true)) {
if ($this->isSkipNeeded($rectorClass, $filePath, $dryRunConfiguration)) {
continue;
}

Expand All @@ -74,43 +69,27 @@ public function verify(ProcessResult $processResult): array
}

/**
* @param array<string, string[]> $skippedFilePathsByRule
* @return array<string, string[]> real file path => rule classes that changed it
* Lifts only this one skip, so other skipped rules cannot make the same change first
*/
private function resolveChangedRulesByFilePath(array $skippedFilePathsByRule): array
private function isSkipNeeded(string $rectorClass, string $filePath, Configuration $configuration): bool
{
$uniqueFilePaths = [];
foreach ($skippedFilePathsByRule as $filePaths) {
foreach ($filePaths as $filePath) {
$uniqueFilePaths[$filePath] = true;
}
}
$this->skipper->startVerifyingSkip($rectorClass);

// force a dry run, so re-processing detects the change but never writes the skipped file
$dryRunConfiguration = new Configuration(isDryRun: true);

$this->skipper->startVerifyingSkips();

$changedRulesByFilePath = [];
try {
foreach (array_keys($uniqueFilePaths) as $filePath) {
$file = new File($filePath, FileSystem::read($filePath));
$this->currentFileProvider->setFile($file);

$fileProcessResult = $this->fileProcessor->processFile($file, $dryRunConfiguration);
$file = new File($filePath, FileSystem::read($filePath));
$this->currentFileProvider->setFile($file);

// a broken file is not verifiable, leave it out so its skips are kept
if ($fileProcessResult->getSystemErrors() !== []) {
continue;
}

$fileDiff = $fileProcessResult->getFileDiff();
$changedRulesByFilePath[$filePath] = $fileDiff?->getRectorClasses() ?? [];
}
$fileProcessResult = $this->fileProcessor->processFile($file, $configuration);
} finally {
$this->skipper->stopVerifyingSkips();
$this->skipper->stopVerifyingSkip();
}

// a broken file is not verifiable, keep the skip to stay safe
if ($fileProcessResult->getSystemErrors() !== []) {
return true;
}

return $changedRulesByFilePath;
$fileDiff = $fileProcessResult->getFileDiff();
return in_array($rectorClass, $fileDiff?->getRectorClasses() ?? [], true);
}
}
23 changes: 14 additions & 9 deletions src/Skipper/Skipper/Skipper.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ final class Skipper
*/
private array $skippedFilePathsByRule = [];

// flipped on while the needed-skip verification re-runs rules with skipping off
private bool $isVerifyingSkips = false;
/**
* Rule whose skip is lifted while the needed-skip verification re-runs a file
*/
private ?string $verifiedRectorClass = null;

public function __construct(
private readonly PathSkipper $pathSkipper,
Expand All @@ -62,9 +64,12 @@ public function shouldSkipFilePath(string $filePath): bool

public function shouldSkipRectorAndFile(object $rector, string $filePath): bool
{
// verification re-runs every rule with skipping off, to learn which skips really matter
if ($this->isVerifyingSkips) {
return false;
// verification lifts only the verified rule's skip, other skips keep applying
if ($this->verifiedRectorClass !== null) {
return $rector::class !== $this->verifiedRectorClass && $this->matchSkip(
$rector,
$filePath
) instanceof SkipMatch;
}

$skipMatch = $this->matchSkip($rector, $filePath);
Expand All @@ -86,14 +91,14 @@ public function shouldSkipRectorAndFile(object $rector, string $filePath): bool
return true;
}

public function startVerifyingSkips(): void
public function startVerifyingSkip(string $rectorClass): void
{
$this->isVerifyingSkips = true;
$this->verifiedRectorClass = $rectorClass;
}

public function stopVerifyingSkips(): void
public function stopVerifyingSkip(): void
{
$this->isVerifyingSkips = false;
$this->verifiedRectorClass = null;
}

/**
Expand Down
36 changes: 36 additions & 0 deletions tests/Reporting/NeededSkipVerifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
use Rector\Config\RectorConfig;
use Rector\Configuration\Option;
use Rector\Configuration\Parameter\SimpleParameterProvider;
use Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector;
use Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector;
use Rector\DependencyInjection\LazyContainerFactory;
use Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider;
use Rector\Reporting\NeededSkipVerifier;
use Rector\Skipper\Skipper\Skipper;
use Rector\Testing\PHPUnit\AbstractLazyTestCase;
Expand Down Expand Up @@ -97,6 +100,39 @@ public function testReportsSkipCollectedByWorkers(): void
$this->assertStringContainsString('unnecessary_skip.php', $unnecessarySkips[0]);
}

/**
* @see https://github.com/rectorphp/rector/issues/9979
*/
public function testKeepsBothSkipsWhenTwoRulesWouldMakeTheSameChange(): void
{
$filePath = $this->tempDirectory . '/shape.php';
FileSystem::write($filePath, FileSystem::read(__DIR__ . '/Source/sealed_shape.php'), null);

SimpleParameterProvider::setParameter(Option::REPORT_UNUSED_SKIPS, true);
SimpleParameterProvider::setParameter(Option::SKIP, [
RemoveAlwaysTrueIfConditionRector::class => [$filePath],
RemoveDeadInstanceOfRector::class => [$filePath],
]);

$rectorConfig = new LazyContainerFactory()->create();
$rectorConfig->rules([RemoveDeadInstanceOfRector::class, RemoveAlwaysTrueIfConditionRector::class]);
$rectorConfig->boot();

// the real run registers processed files, so the sealed hierarchy is reflectable
$dynamicSourceLocatorProvider = $rectorConfig->make(DynamicSourceLocatorProvider::class);
$dynamicSourceLocatorProvider->addFiles([$filePath]);

$processResult = new ProcessResult([], [], 0, [], [
RemoveAlwaysTrueIfConditionRector::class => [$filePath],
RemoveDeadInstanceOfRector::class => [$filePath],
]);

$neededSkipVerifier = $rectorConfig->make(NeededSkipVerifier::class);

// each rule alone changes the file, so neither skip is unnecessary
$this->assertSame([], $neededSkipVerifier->verify($processResult));
}

public function testReportsNothingWithoutCapturedSkips(): void
{
$rectorConfig = $this->createContainerWithRule();
Expand Down
36 changes: 36 additions & 0 deletions tests/Reporting/Source/sealed_shape.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Reporting\Source\SealedShape;

/**
* @phpstan-sealed Circle|Square
*/
abstract class Shape
{
}

final class Circle extends Shape
{
}

final class Square extends Shape
{
}

final class ShapeChecker
{
public function isRound(Shape $shape): bool
{
if ($shape instanceof Circle) {
return true;
}

if ($shape instanceof Square) {
return false;
}

throw new \LogicException('Unknown shape');
}
}
Loading