Skip to content

Commit 66a13fd

Browse files
authored
Re-resolve ShortNameResolver short names on stmts change (#8697)
1 parent c63f963 commit 66a13fd

4 files changed

Lines changed: 226 additions & 9 deletions

File tree

‎bench/Source/ManyNamesSource.php‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Bench\Source;
6+
7+
use Countable;
8+
use DateTime;
9+
use DateTimeImmutable;
10+
11+
/**
12+
* Fixture parsed by short_name_resolver_bench.php. Deliberately name-heavy:
13+
* many fully-qualified references plus docblock types, so resolveFromFile() does real work.
14+
* References only real classes so it stays valid if any whole-repo check scans it.
15+
*/
16+
final class ManyNamesSource implements Countable
17+
{
18+
/**
19+
* @var \PhpParser\Node\Stmt\Class_[]
20+
*/
21+
private array $classes = [];
22+
23+
/**
24+
* @param \PhpParser\Node\Name $name
25+
* @return \PhpParser\Node\Expr\New_
26+
*/
27+
public function first(\PhpParser\Node\Name $name): \PhpParser\Node\Expr\New_
28+
{
29+
$a = new \PhpParser\Node\Scalar\String_('a');
30+
$b = new \PhpParser\Node\Identifier('b');
31+
$c = new DateTimeImmutable();
32+
33+
return new \PhpParser\Node\Expr\New_($name);
34+
}
35+
36+
/**
37+
* @param \PhpParser\Node\Stmt\Property $property
38+
* @return \PhpParser\Comment\Doc
39+
*/
40+
public function second(\PhpParser\Node\Stmt\Property $property): \PhpParser\Comment\Doc
41+
{
42+
$x = new \PhpParser\Node\Stmt\ClassMethod('x');
43+
$y = new \SplStack();
44+
$z = new \ArrayObject();
45+
46+
return new \PhpParser\Comment\Doc('/** */');
47+
}
48+
49+
/**
50+
* @param \PhpParser\Node\Arg $arg
51+
* @return \PhpParser\Node\Expr\MethodCall
52+
*/
53+
public function third(\PhpParser\Node\Arg $arg): \PhpParser\Node\Expr\MethodCall
54+
{
55+
$p = new \RuntimeException();
56+
$q = new \LogicException();
57+
$r = new DateTime();
58+
59+
return new \PhpParser\Node\Expr\MethodCall(new \PhpParser\Node\Expr\Variable('v'), 'm');
60+
}
61+
62+
/**
63+
* @param \PhpParser\Node\Stmt\Use_ $use
64+
* @return \PhpParser\Node\Stmt\Namespace_
65+
*/
66+
public function fourth(\PhpParser\Node\Stmt\Use_ $use): \PhpParser\Node\Stmt\Namespace_
67+
{
68+
$s = new \SplObjectStorage();
69+
$t = new \DateInterval('P1D');
70+
$u = new \PhpParser\Node\Scalar\Int_(1);
71+
72+
return new \PhpParser\Node\Stmt\Namespace_(new \PhpParser\Node\Name('N'));
73+
}
74+
75+
public function count(): int
76+
{
77+
return count($this->classes);
78+
}
79+
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Benchmark for ShortNameResolver::resolveFromFile() caching.
7+
*
8+
* Simulates the file-processing convergence loop: the same file is re-queried across
9+
* several passes, with its stmts version bumped between passes (as real rules do when
10+
* they change nodes). Two access patterns are measured:
11+
*
12+
* - single-version: one version, many per-node queries (isolates per-node caching)
13+
* - multi-version: version bumped each pass, many per-node queries per pass
14+
* (this is where the filePath-cached vs version-cached behavior differs)
15+
*
16+
* Run on both branches to compare:
17+
* php bench/short_name_resolver_bench.php
18+
*
19+
* Reports CPU time (user+sys) and wall time; CPU is the reliable metric, wall is noisy
20+
* under concurrent load.
21+
*/
22+
23+
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
24+
use Rector\CodingStyle\ClassNameImport\ShortNameResolver;
25+
use Rector\CodingStyle\NodeAnalyzer\UseImportNameMatcher;
26+
use Rector\DependencyInjection\LazyContainerFactory;
27+
use Rector\NodeNameResolver\NodeNameResolver;
28+
use Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser;
29+
use Rector\PhpParser\Node\BetterNodeFinder;
30+
use Rector\Testing\TestingParser\TestingParser;
31+
use Rector\ValueObject\Application\File;
32+
33+
require __DIR__ . '/../vendor/autoload.php';
34+
35+
const ITERATIONS = 8; // convergence passes (stmts version bumps)
36+
const NODES = 400; // resolveFromFile() calls per pass (one per FullyQualified node)
37+
const REPEAT = 25; // outer repeats, each with a fresh-cache resolver
38+
39+
$rectorConfig = (new LazyContainerFactory())->create();
40+
$rectorConfig->boot();
41+
42+
/** @var TestingParser $testingParser */
43+
$testingParser = $rectorConfig->make(TestingParser::class);
44+
45+
$sourceFilePath = __DIR__ . '/Source/ManyNamesSource.php';
46+
47+
// shared stateless dependencies; a fresh ShortNameResolver is built per repeat so its cache starts empty
48+
$simpleCallableNodeTraverser = $rectorConfig->make(SimpleCallableNodeTraverser::class);
49+
$nodeNameResolver = $rectorConfig->make(NodeNameResolver::class);
50+
$betterNodeFinder = $rectorConfig->make(BetterNodeFinder::class);
51+
$useImportNameMatcher = $rectorConfig->make(UseImportNameMatcher::class);
52+
$phpDocInfoFactory = $rectorConfig->make(PhpDocInfoFactory::class);
53+
54+
$makeResolver = static fn (): ShortNameResolver => new ShortNameResolver(
55+
$simpleCallableNodeTraverser,
56+
$nodeNameResolver,
57+
$betterNodeFinder,
58+
$useImportNameMatcher,
59+
$phpDocInfoFactory
60+
);
61+
62+
$cpuSeconds = static function (): float {
63+
$usage = getrusage();
64+
return $usage['ru_utime.tv_sec'] + $usage['ru_utime.tv_usec'] / 1_000_000
65+
+ $usage['ru_stime.tv_sec'] + $usage['ru_stime.tv_usec'] / 1_000_000;
66+
};
67+
68+
/**
69+
* @param callable(): ShortNameResolver $makeResolver
70+
*/
71+
$run = static function (bool $bumpVersionEachPass) use (
72+
$makeResolver,
73+
$testingParser,
74+
$sourceFilePath
75+
): void {
76+
$resolver = $makeResolver();
77+
$file = $testingParser->parseFilePathToFile($sourceFilePath);
78+
79+
for ($pass = 0; $pass < ITERATIONS; ++$pass) {
80+
if ($bumpVersionEachPass) {
81+
// mark the stmts as changed, exactly as a rule that edited the file does
82+
$file->changeNewStmts($file->getNewStmts());
83+
}
84+
85+
for ($node = 0; $node < NODES; ++$node) {
86+
$resolver->resolveFromFile($file);
87+
}
88+
}
89+
};
90+
91+
$measure = static function (bool $bumpVersionEachPass) use ($run, $cpuSeconds): array {
92+
// warm up autoloading / parser once, excluded from timing
93+
$run($bumpVersionEachPass);
94+
95+
$cpuStart = $cpuSeconds();
96+
$wallStart = hrtime(true);
97+
98+
for ($repeat = 0; $repeat < REPEAT; ++$repeat) {
99+
$run($bumpVersionEachPass);
100+
}
101+
102+
return [
103+
'cpu' => $cpuSeconds() - $cpuStart,
104+
'wall' => (hrtime(true) - $wallStart) / 1_000_000_000,
105+
];
106+
};
107+
108+
assert(class_exists(File::class));
109+
110+
$singleVersion = $measure(false);
111+
$multiVersion = $measure(true);
112+
113+
printf('ShortNameResolver::resolveFromFile benchmark%s', PHP_EOL);
114+
printf(' iterations=%d nodes=%d repeat=%d%s', ITERATIONS, NODES, REPEAT, PHP_EOL);
115+
printf('%s', PHP_EOL);
116+
printf(' single-version cpu=%.4fs wall=%.4fs%s', $singleVersion['cpu'], $singleVersion['wall'], PHP_EOL);
117+
printf(' multi-version cpu=%.4fs wall=%.4fs%s', $multiVersion['cpu'], $multiVersion['wall'], PHP_EOL);

‎rules-tests/CodingStyle/ClassNameImport/ShortNameResolver/ShortNameResolverTest.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ public function testResolveShortClassLikeNamesAgainAfterStmtsChange(): void
5454
$this->assertSame(['RenamedClass'], $this->shortNameResolver->resolveShortClassLikeNames($file));
5555
}
5656

57+
public function testResolveFromFileAgainAfterStmtsChange(): void
58+
{
59+
$file = $this->testingParser->parseFilePathToFile(__DIR__ . '/Fixture/various_imports.php.inc');
60+
$this->assertArrayHasKey('VariousImports', $this->shortNameResolver->resolveFromFile($file));
61+
62+
$class = new NodeFinder()
63+
->findFirstInstanceOf($file->getNewStmts(), Class_::class);
64+
$this->assertInstanceOf(Class_::class, $class);
65+
66+
$class->name = new Identifier('RenamedClass');
67+
$file->changeNewStmts($file->getNewStmts());
68+
69+
$shortNamesAfterChange = $this->shortNameResolver->resolveFromFile($file);
70+
$this->assertArrayNotHasKey('VariousImports', $shortNamesAfterChange);
71+
$this->assertArrayHasKey('RenamedClass', $shortNamesAfterChange);
72+
}
73+
5774
public function testResolveShortClassLikeNamesPerFile(): void
5875
{
5976
$firstFile = $this->testingParser->parseFilePathToFile(__DIR__ . '/Fixture/various_imports.php.inc');

‎rules/CodingStyle/ClassNameImport/ShortNameResolver.php‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,14 @@
2626
*/
2727
final class ShortNameResolver
2828
{
29+
private ?File $shortNamesFile = null;
30+
31+
private int $shortNamesVersion = 0;
32+
2933
/**
30-
* @var array<string, string[]>
34+
* @var array<string, string>
3135
*/
32-
private array $shortNamesByFilePath = [];
36+
private array $shortNamesToFullyQualifiedNames = [];
3337

3438
private ?File $shortClassLikeNamesFile = null;
3539

@@ -54,16 +58,16 @@ public function __construct(
5458
*/
5559
public function resolveFromFile(File $file): array
5660
{
57-
$filePath = $file->getFilePath();
58-
59-
if (isset($this->shortNamesByFilePath[$filePath])) {
60-
return $this->shortNamesByFilePath[$filePath];
61+
// re-resolve when the file stmts change, so later iterations don't read a stale map
62+
if ($file === $this->shortNamesFile && $file->getNewStmtsVersion() === $this->shortNamesVersion) {
63+
return $this->shortNamesToFullyQualifiedNames;
6164
}
6265

63-
$shortNamesToFullyQualifiedNames = $this->resolveForStmts($file->getNewStmts());
64-
$this->shortNamesByFilePath[$filePath] = $shortNamesToFullyQualifiedNames;
66+
$this->shortNamesFile = $file;
67+
$this->shortNamesVersion = $file->getNewStmtsVersion();
68+
$this->shortNamesToFullyQualifiedNames = $this->resolveForStmts($file->getNewStmts());
6569

66-
return $shortNamesToFullyQualifiedNames;
70+
return $this->shortNamesToFullyQualifiedNames;
6771
}
6872

6973
/**

0 commit comments

Comments
 (0)