Skip to content

Commit 2418876

Browse files
committed
Look up again only the missing symbols a changed file may declare
A class, function or constant a lookup did not find when the result cache was written is looked up again only when a new or changed analysed or scanned file declares that name, or when a Composer package or PHP extension version changed. Before, every missing name was looked up on every restore, which slowed down warm runs that changed nothing. The restore works out what may have been declared, and the ResultCache carries it to the finalizer, which checks the values a rule on collected data depends on before reusing its errors. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5c8-8d5b-7459-a22c-beb8e7ba8a3b
1 parent 603c305 commit 2418876

7 files changed

Lines changed: 168 additions & 5 deletions

File tree

‎src/Analyser/AnalyserResultFinalizer.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use PHPStan\AnalysedCodeException;
77
use PHPStan\Analyser\Ignore\LineIgnoreFixer;
88
use PHPStan\Analyser\Ignore\UnmatchedIgnoreFixer;
9+
use PHPStan\Analyser\ResultCache\AppearedSymbols;
910
use PHPStan\Analyser\ResultCache\LazyCollectedData;
1011
use PHPStan\Analyser\ResultCache\UnreadableCollectedDataException;
1112
use PHPStan\BetterReflection\NodeCompiler\Exception\UnableToCompileNode;
@@ -65,6 +66,8 @@ public function __construct(
6566
* previous run, from the result cache - a rule whose input did not change reuses its errors.
6667
* Only with the reuseCollectedDataRuleErrors feature toggle, otherwise every rule runs. A rule that
6768
* does not call get() on the node always runs.
69+
* @param AppearedSymbols|null $appearedSymbols what may have been declared since they were saved, see
70+
* ResultCache::getAppearedSymbols() - anything when null
6871
*/
6972
public function finalize(
7073
AnalyserResult $analyserResult,
@@ -73,8 +76,10 @@ public function finalize(
7376
?Closure $preRuleCallback = null,
7477
?Closure $postRuleCallback = null,
7578
array $previousCollectedDataRuleResults = [],
79+
?AppearedSymbols $appearedSymbols = null,
7680
): FinalizerResult
7781
{
82+
$appearedSymbols ??= AppearedSymbols::anything();
7883
if ($analyserResult->getLazyCollectedData()->isEmpty()) {
7984
return $this->processInlineIgnores($this->mergeFilteredPhpErrors($analyserResult), [], []);
8085
}
@@ -115,7 +120,7 @@ public function finalize(
115120
$ruleKey = sprintf('%s#%d', $ruleClass, $ruleCountsByClass[$ruleClass]);
116121

117122
$previousResult = $this->reuseCollectedDataRuleErrors ? $previousCollectedDataRuleResults[$ruleKey] ?? null : null;
118-
if ($previousResult !== null && $this->canReuse($previousResult, $onlyFiles, $hashCollector, $currentValues)) {
123+
if ($previousResult !== null && $this->canReuse($previousResult, $onlyFiles, $hashCollector, $appearedSymbols, $currentValues)) {
119124
$collectedDataRuleResults[$ruleKey] = $previousResult;
120125
$reusedRulesCount++;
121126
$collectedDataRuleSkipped = $collectedDataRuleSkipped || $previousResult->getOnlyFiles() === true;
@@ -291,7 +296,7 @@ private function createRuleResult(CollectedDataNodeReads $reads, bool $onlyFiles
291296
* @param Closure(string): string $hashCollector
292297
* @param array<string, string> $currentValues id => value, asked for once per run - every rule shares the values of the classes
293298
*/
294-
private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFiles, Closure $hashCollector, array &$currentValues): bool
299+
private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFiles, Closure $hashCollector, AppearedSymbols $appearedSymbols, array &$currentValues): bool
295300
{
296301
$previousOnlyFiles = $previousResult->getOnlyFiles();
297302
if ($previousOnlyFiles !== null && $previousOnlyFiles !== $onlyFiles) {
@@ -312,7 +317,10 @@ private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFil
312317
}
313318

314319
$id = ValueDependencyCollector::getId($extensionClass, $storedKey);
315-
$currentValues[$id] ??= $extension->getValue($extension->keyFromResultCache($storedKey));
320+
$key = $extension->keyFromResultCache($storedKey);
321+
$currentValues[$id] ??= $value === ValueDependencyCollector::MISSING && $appearedSymbols->isStillMissing($extensionClass, $key)
322+
? ValueDependencyCollector::MISSING
323+
: $extension->getValue($key);
316324
if ($currentValues[$id] !== $value) {
317325
return false;
318326
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser\ResultCache;
4+
5+
use function class_exists;
6+
use function defined;
7+
use function function_exists;
8+
use function interface_exists;
9+
use function ltrim;
10+
use function strtolower;
11+
use function trait_exists;
12+
13+
/**
14+
* Which classes, functions and constants may have been declared since the result cache was
15+
* written - a lookup that found nothing then is asked again only for those, see
16+
* ValueDependencyCollector::recordMissingSymbol(). Every other one is still missing.
17+
* ResultCacheManager::restore() creates it, and the restored ResultCache carries it to whatever
18+
* checks the values recorded in the result cache, like the reuse of the errors of a rule on
19+
* collected data.
20+
*
21+
* A name can only appear through:
22+
*
23+
* - an analysed or scanned file that is new or changed, or another file the analysed ones depend
24+
* on that changed - the names they declare, scanned the way the directory locators scan them.
25+
* The files of the project's Composer autoload entries (PSR-4, PSR-0, classmap and files) count
26+
* as scanned, see ResultCacheManager::getScannedFiles()
27+
* - a Composer package or a PHP extension of another version, the PHP version, PHPStan, a stub or a
28+
* bootstrap file - each changes the metadata, and anything is possible then
29+
* - a file a bootstrap file requires - what it declares exists at runtime, see isStillMissing()
30+
*/
31+
final class AppearedSymbols
32+
{
33+
34+
/**
35+
* @param array<string, true>|null $names lowercase names that may have been declared, null when anything may have
36+
*/
37+
private function __construct(private ?array $names)
38+
{
39+
}
40+
41+
/**
42+
* Anything may have been declared - every missing symbol is looked up again.
43+
*/
44+
public static function anything(): self
45+
{
46+
return new self(null);
47+
}
48+
49+
/**
50+
* @param list<string> $names declared by the files that are new or changed
51+
*/
52+
public static function fromNames(array $names): self
53+
{
54+
$lowercaseNames = [];
55+
foreach ($names as $name) {
56+
$lowercaseNames[strtolower($name)] = true;
57+
}
58+
59+
return new self($lowercaseNames);
60+
}
61+
62+
/**
63+
* Whether a value of the extension that was ValueDependencyCollector::MISSING is still that,
64+
* known without looking the symbol up.
65+
*/
66+
public function isStillMissing(string $extensionClass, string $key): bool
67+
{
68+
if ($this->names === null) {
69+
return false;
70+
}
71+
72+
$key = ltrim($key, '\\');
73+
if (isset($this->names[strtolower($key)])) {
74+
return false;
75+
}
76+
77+
// a bootstrap file, or a file it requires, declares symbols no tracked file shows - they
78+
// exist at runtime, without autoloading anything
79+
if ($extensionClass === ClassResultCacheValueExtension::class) {
80+
return !class_exists($key, false) && !interface_exists($key, false) && !trait_exists($key, false);
81+
}
82+
if ($extensionClass === FunctionResultCacheValueExtension::class) {
83+
return !function_exists($key);
84+
}
85+
if ($extensionClass === ConstantResultCacheValueExtension::class) {
86+
return !defined($key);
87+
}
88+
89+
return false;
90+
}
91+
92+
}

‎src/Analyser/ResultCache/ResultCache.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ public function __construct(
4848
private CachedExportedNodes $cachedExportedNodes,
4949
private array $projectExtensionFiles,
5050
private array $currentFileHashes,
51+
private AppearedSymbols $appearedSymbols,
5152
private array $collectedDataRuleResults = [],
5253
)
5354
{
@@ -189,6 +190,11 @@ public function getCurrentFileHashes(): array
189190
return $this->currentFileHashes;
190191
}
191192

193+
public function getAppearedSymbols(): AppearedSymbols
194+
{
195+
return $this->appearedSymbols;
196+
}
197+
192198
/**
193199
* @return array<string, CollectedDataRuleResult>
194200
*/

‎src/Analyser/ResultCache/ResultCacheManager.php‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
use PHPStan\Php\PhpVersion;
3535
use PHPStan\PhpDoc\StubFilesProvider;
3636
use PHPStan\Reflection\BetterReflection\SourceLocator\ComposerJsonAndInstalledJsonSourceLocatorMaker;
37+
use PHPStan\Reflection\BetterReflection\SourceLocator\SymbolFinderInFiles;
3738
use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider;
3839
use PHPStan\ShouldNotHappenException;
3940
use ReflectionClass;
@@ -264,6 +265,7 @@ public function __construct(
264265
private ComposerPhpVersionFactory $composerPhpVersionFactory,
265266
private FileStatSignatures $fileStatSignatures,
266267
private ValueDependencyCollector $valueDependencyCollector,
268+
private SymbolFinderInFiles $symbolFinderInFiles,
267269
private ComposerJsonAndInstalledJsonSourceLocatorMaker $composerSourceLocatorMaker,
268270
#[AutowiredParameter]
269271
private string $tmpDir,
@@ -325,6 +327,7 @@ private function fullAnalysis(
325327
cachedExportedNodes: CachedExportedNodes::createEmpty(),
326328
projectExtensionFiles: [],
327329
currentFileHashes: $currentFileHashes,
330+
appearedSymbols: AppearedSymbols::anything(),
328331
);
329332
}
330333

@@ -488,6 +491,9 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
488491
// make anything be re-analysed. A scanned file can change without any of its symbols changing,
489492
// and then nothing here has to happen at all.
490493
$scannedFilesWithChangedSymbols = [];
494+
// what may declare a symbol a lookup did not find last time - see AppearedSymbols
495+
$anySymbolMayHaveAppeared = false;
496+
$changedDeclaringFiles = [];
491497
$metaDifferent = $this->isMetaDifferent($data['meta'], $meta);
492498
if ($metaDifferent) {
493499
$diffs = $this->getMetaKeyDifferences($data['meta'], $meta);
@@ -540,6 +546,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
540546
);
541547
}
542548

549+
$changedDeclaringFiles[$changedScannedFile] = true;
543550
}
544551
}
545552

@@ -617,6 +624,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
617624
// The files depending on a changed package are seeded below. A symbol a package declares
618625
// now was looked up and not found by the files waiting for it, which recorded that as a
619626
// value dependency.
627+
$anySymbolMayHaveAppeared = true;
620628
$changedPackagesLookup = array_fill_keys(array_merge($changedPackages, $changedExtensionPackages), true);
621629
foreach ($packageDependencies as $packageDependentFile => $filePackages) {
622630
foreach ($filePackages as $filePackage) {
@@ -785,6 +793,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
785793
}
786794

787795
$changedAnalysedFiles[$analysedFile] = true;
796+
$changedDeclaringFiles[$analysedFile] = true;
788797
}
789798
foreach ($allAnalysedFiles as $analysedFile) {
790799
if (array_key_exists($analysedFile, $errors)) {
@@ -906,6 +915,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
906915

907916
if (is_file($notAnalysedFile) && $wasMissing) {
908917
$dependencyFilesChanged = true;
918+
$changedDeclaringFiles[$notAnalysedFile] = true;
909919
// It exists now. Whether it holds any symbol is beside the point - a file that was named
910920
// and was not there is now there, and that alone changes what the analysis says.
911921
$invertedDependenciesToReturn[$notAnalysedFile] = $dependentFiles;
@@ -936,6 +946,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
936946
?? ($cachedExportedNodes->has($notAnalysedFile) ? $decodeCachedExportedNodes($notAnalysedFile) : null);
937947

938948
$dependencyFilesChanged = true;
949+
$changedDeclaringFiles[$notAnalysedFile] = true;
939950
// Edited: the same rule as for an analysed file. Nothing the files depending on it can
940951
// see changed unless its exported nodes did, so a body-only edit re-analyses nothing -
941952
// except the classes using a trait declared here, whose body is analysed in their
@@ -997,10 +1008,22 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
9971008
$allAnalysedFilesSet = array_fill_keys($allAnalysedFiles, true);
9981009
$valueDependenciesToReturn = [];
9991010
$valueDependenciesChanged = false;
1011+
$appearedSymbols = $anySymbolMayHaveAppeared
1012+
? AppearedSymbols::anything()
1013+
: $this->getSymbolsDeclaredIn(array_keys($changedDeclaringFiles));
10001014
foreach ($cachedValueDependencies as $cachedValueDependency) {
10011015
$extension = $this->valueDependencyCollector->getExtension($cachedValueDependency['extensionClass']);
10021016
$key = $extension?->keyFromResultCache($cachedValueDependency['storedKey']);
1003-
$currentValue = $extension !== null && $key !== null ? $extension->getValue($key) : null;
1017+
if ($extension === null || $key === null) {
1018+
$currentValue = null;
1019+
} elseif (
1020+
$cachedValueDependency['value'] === ValueDependencyCollector::MISSING
1021+
&& $appearedSymbols->isStillMissing($cachedValueDependency['extensionClass'], $key)
1022+
) {
1023+
$currentValue = ValueDependencyCollector::MISSING;
1024+
} else {
1025+
$currentValue = $extension->getValue($key);
1026+
}
10041027
if ($currentValue !== $cachedValueDependency['value']) {
10051028
$valueDependenciesChanged = true;
10061029
foreach ($this->getValueDependentFilesToAnalyse($cachedValueDependency['analysis'], $cachedValueDependency['declarations'], $invertedDependencies, $allAnalysedFilesSet) as $valueDependentFile) {
@@ -1086,6 +1109,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
10861109
cachedExportedNodes: $cachedExportedNodes->only($keptCachedExportedNodes),
10871110
projectExtensionFiles: $data['projectExtensionFiles'],
10881111
currentFileHashes: $currentFileHashes,
1112+
appearedSymbols: $appearedSymbols,
10891113
collectedDataRuleResults: $collectedDataRuleResults,
10901114
);
10911115
}
@@ -3493,6 +3517,36 @@ private function getFileHash(string $path): string
34933517
return $hash;
34943518
}
34953519

3520+
/**
3521+
* The names a new or changed file declares, scanned the way the directory locators scan them -
3522+
* see AppearedSymbols.
3523+
*
3524+
* @param list<string> $changedFiles
3525+
*/
3526+
private function getSymbolsDeclaredIn(array $changedFiles): AppearedSymbols
3527+
{
3528+
$existingFiles = [];
3529+
foreach ($changedFiles as $changedFile) {
3530+
$changedFile = $this->fileReplacements[$changedFile] ?? $changedFile;
3531+
if (!is_file($changedFile)) {
3532+
continue;
3533+
}
3534+
3535+
$existingFiles[] = $changedFile;
3536+
}
3537+
3538+
$names = [];
3539+
foreach ($this->symbolFinderInFiles->findSymbols($existingFiles, $this->phpVersion->supportsEnums()) as $symbols) {
3540+
foreach ($symbols as $symbolsOfKind) {
3541+
foreach ($symbolsOfKind as $name) {
3542+
$names[] = $name;
3543+
}
3544+
}
3545+
}
3546+
3547+
return AppearedSymbols::fromNames($names);
3548+
}
3549+
34963550
/**
34973551
* The files the analysis reads symbols from without analysing them, other than the installed
34983552
* packages: scanFiles, scanDirectories, the files excluded from the analysis in an analysed

‎src/Command/AnalyseApplication.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ public function analyse(
147147
$postRuleCallback,
148148
// with -vvv the diagnose extensions print, and a rule can fill what they print only while it runs
149149
$errorOutput->isDebug() ? [] : $resultCache->getCollectedDataRuleResults(),
150+
$resultCache->getAppearedSymbols(),
150151
);
151152
if ($finalizerResult->getReusedRulesCount() > 0 && $errorOutput->isVeryVerbose()) {
152153
$errorOutput->writeLineFormatted(sprintf(

‎src/Command/FixerWorkerRunner.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ function (array $errors, array $locallyIgnoredErrors, array $analysedFiles) use
233233
false,
234234
true,
235235
);
236-
$finalizerResult = $this->analyserResultFinalizer->finalize($resultCacheResult->getAnalyserResult(), $isOnlyFiles, false, null, null, $resultCache->getCollectedDataRuleResults());
236+
$finalizerResult = $this->analyserResultFinalizer->finalize($resultCacheResult->getAnalyserResult(), $isOnlyFiles, false, null, null, $resultCache->getCollectedDataRuleResults(), $resultCache->getAppearedSymbols());
237237
$resultCacheResult->save($finalizerResult);
238238

239239
// FixerApplication's file monitor misses a file changed and changed back between two polls

‎tests/PHPStan/Analyser/ResultCache/ResultCacheManagerCollectedDataTest.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use PHPStan\Php\PhpVersion;
2222
use PHPStan\PhpDoc\StubFilesProvider;
2323
use PHPStan\Reflection\BetterReflection\SourceLocator\ComposerJsonAndInstalledJsonSourceLocatorMaker;
24+
use PHPStan\Reflection\BetterReflection\SourceLocator\SymbolFinderInFiles;
2425
use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider;
2526
use PHPStan\Rules\Comparison\ConstantConditionInTraitCollector;
2627
use PHPStan\Rules\DeadCode\MethodWithoutImpurePointsCollector;
@@ -519,6 +520,7 @@ private function createManager(): ResultCacheManager
519520
composerPhpVersionFactory: $container->getByType(ComposerPhpVersionFactory::class),
520521
fileStatSignatures: $container->getByType(FileStatSignatures::class),
521522
valueDependencyCollector: $container->getByType(ValueDependencyCollector::class),
523+
symbolFinderInFiles: $container->getByType(SymbolFinderInFiles::class),
522524
composerSourceLocatorMaker: $container->getByType(ComposerJsonAndInstalledJsonSourceLocatorMaker::class),
523525
tmpDir: $this->directory . '/tmp',
524526
);

0 commit comments

Comments
 (0)