Skip to content

Commit c7683f3

Browse files
committed
Keep the symbols of a file with a parse error in the result cache
Code saved half typed declared nothing, so the result cache re-analysed the files using it and all files with errors when it broke, and again when it was fixed. In PHPStan Pro's watch mode, a syntax error in a class with 600 subclasses re-analysed them twice and showed 5,400 errors about the unknown class. A changed file with a parse error now counts as unchanged: only it is re-analysed, and it keeps the symbols it had before, so fixing it re-analyses only it too when they are the same. The other files keep their results while it is broken. The symbols are kept only while no other file is analysed, because that file sees them missing, and its result has to be renewed when they come back. Refs phpstan/phpstan#10110 Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5c8-8d5b-7459-a22c-beb8e7ba8a3b
1 parent f29b0e3 commit c7683f3

3 files changed

Lines changed: 94 additions & 16 deletions

File tree

‎e2e/result-cache-parse-error/result-cache-parse-error_test.sh‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,57 @@ function test_result_cache_parse_error() {
3434
echo "$OUTPUT"
3535
assert_not_contains 'not found' "$OUTPUT"
3636
}
37+
38+
function test_result_cache_parse_error_keeps_symbols() {
39+
# A warm result cache without the parse error, and src/Other.php with an error, which makes
40+
# it one of the files that are re-analysed when a symbol appears or disappears.
41+
cp src/Thing.php "$TMPDIR/BrokenThing.php"
42+
cp fixed/Thing.php src/Thing.php
43+
printf '<?php declare(strict_types = 1);\n\nnamespace ResultCacheE2EParseError;\n\nfunction doOther(): int\n{\n\treturn "other";\n}\n' > src/Other.php
44+
../../bin/phpstan analyse --error-format raw > /dev/null 2>&1 || true
45+
# Breaking src/Thing.php re-analyses only it: src/User.php keeps its result.
46+
cp "$TMPDIR/BrokenThing.php" src/Thing.php
47+
OUTPUT=$(../../bin/phpstan analyse -vvv --error-format raw 2>&1) && CODE=0 || CODE=$?
48+
assert_same "1" "$CODE"
49+
echo "$OUTPUT"
50+
assert_contains 'Result cache restored. 1 file will be reanalysed.' "$OUTPUT"
51+
assert_contains 'Thing.php:12:Syntax error, unexpected EOF on line 12' "$OUTPUT"
52+
# The first run had nothing to save, so the next one records the file stat of src/Thing.php,
53+
# and the cache is not rewritten after that.
54+
../../bin/phpstan analyse --error-format raw > /dev/null 2>&1 || true
55+
OUTPUT=$(../../bin/phpstan analyse -vvv --error-format raw 2>&1) && CODE=0 || CODE=$?
56+
assert_same "1" "$CODE"
57+
echo "$OUTPUT"
58+
assert_contains 'Result cache restored. 1 file will be reanalysed.' "$OUTPUT"
59+
assert_contains 'Result cache was not rewritten because it is unchanged.' "$OUTPUT"
60+
# Fixing it declares the same symbols as before, so nothing else is re-analysed either.
61+
cp fixed/Thing.php src/Thing.php
62+
OUTPUT=$(../../bin/phpstan analyse -vvv --error-format raw 2>&1) && CODE=0 || CODE=$?
63+
assert_same "1" "$CODE"
64+
echo "$OUTPUT"
65+
assert_contains 'Result cache restored. 1 file will be reanalysed.' "$OUTPUT"
66+
assert_not_contains 'Syntax error' "$OUTPUT"
67+
assert_contains 'Other.php:7:Function ResultCacheE2EParseError\doOther() should return int but returns string.' "$OUTPUT"
68+
}
69+
70+
function test_result_cache_parse_error_file_analysed_meanwhile() {
71+
cp src/Thing.php "$TMPDIR/BrokenThing.php"
72+
cp fixed/Thing.php src/Thing.php
73+
../../bin/phpstan analyse --error-format raw > /dev/null 2>&1 || true
74+
cp "$TMPDIR/BrokenThing.php" src/Thing.php
75+
../../bin/phpstan analyse --error-format raw > /dev/null 2>&1 || true
76+
# src/NewUser.php is analysed while src/Thing.php declares nothing, so it finds Thing missing,
77+
# and it has to be analysed again once src/Thing.php is fixed, even though its symbols are the
78+
# same as before it broke.
79+
printf '<?php declare(strict_types = 1);\n\nnamespace ResultCacheE2EParseError;\n\nfunction doNewUser(): string\n{\n\treturn (new Thing())->doThing();\n}\n' > src/NewUser.php
80+
../../bin/phpstan analyse --error-format raw > /dev/null 2>&1 || true
81+
cp fixed/Thing.php src/Thing.php
82+
OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$?
83+
echo "$OUTPUT"
84+
rm -rf tmp/resultCache.php
85+
COLD_OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && COLD_CODE=0 || COLD_CODE=$?
86+
echo "$COLD_OUTPUT"
87+
assert_same "$COLD_CODE" "$CODE"
88+
assert_same "$COLD_OUTPUT" "$OUTPUT"
89+
assert_contains 'NewUser.php:7:Function ResultCacheE2EParseError\doNewUser() should return string but returns int.' "$OUTPUT"
90+
}

‎src/Analyser/ResultCache/ResultCacheManager.php‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
use RuntimeException;
4141
use Throwable;
4242
use function array_diff;
43+
use function array_diff_key;
4344
use function array_fill_keys;
4445
use function array_filter;
4546
use function array_intersect;
@@ -899,9 +900,18 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ?
899900
// the file may have gained its first symbol, which is exactly what the files with errors are
900901
// waiting for. Comparing against an empty list says so, and says nothing changed when the
901902
// file still declares nothing.
903+
$fileExportedNodes = $this->exportedNodeFetcher->fetchNodesIfParsable($this->fileReplacements[$analysedFile] ?? $analysedFile);
904+
if ($fileExportedNodes === null) {
905+
// A parse error, typically code saved half typed. The file is re-analysed and reports it,
906+
// but its symbols count as unchanged: the files using them keep their results until it is
907+
// fixed, instead of being analysed against a file that declares nothing, and so do the
908+
// files with errors. process() keeps the symbols it had, which the fixed file is compared
909+
// with.
910+
continue;
911+
}
902912
$cachedFileExportedNodes = $filteredExportedNodes[$analysedFile]
903913
?? ($cachedExportedNodes->has($analysedFile) ? $decodeCachedExportedNodes($analysedFile) : []);
904-
$exportedNodesChanged = $this->exportedNodesChanged($analysedFile, $cachedFileExportedNodes);
914+
$exportedNodesChanged = $this->compareExportedNodes($cachedFileExportedNodes, $fileExportedNodes);
905915
if ($exportedNodesChanged === null) {
906916
if (count($cachedFileExportedNodes) === 0) {
907917
continue;
@@ -1244,19 +1254,6 @@ private function areAllChanged(array $files, array $changedFiles): bool
12441254
return true;
12451255
}
12461256

1247-
/**
1248-
* @param array<int, RootExportedNode> $cachedFileExportedNodes
1249-
* @return bool|null null means nothing changed, true means new root symbol appeared, false means nested node changed
1250-
*/
1251-
private function exportedNodesChanged(string $analysedFile, array $cachedFileExportedNodes): ?bool
1252-
{
1253-
if (array_key_exists($analysedFile, $this->fileReplacements)) {
1254-
$analysedFile = $this->fileReplacements[$analysedFile];
1255-
}
1256-
1257-
return $this->compareExportedNodes($cachedFileExportedNodes, $this->exportedNodeFetcher->fetchNodes($analysedFile));
1258-
}
1259-
12601257
/**
12611258
* @param array<int, RootExportedNode> $cachedFileExportedNodes
12621259
* @param array<int, RootExportedNode> $fileExportedNodes
@@ -1521,8 +1518,27 @@ public function process(AnalyserResult $analyserResult, ResultCache $resultCache
15211518
$usedTraitDependencies = $this->mergeDependencies($resultCache->getUsedTraitDependencies(), $resultCache->getFilesToAnalyse(), $analyserResult->getUsedTraitDependencies());
15221519
$valueDependencies = $this->mergeValueDependencies($resultCache->getValueDependencies(), $resultCache->getFilesToAnalyse(), $analyserResult->getValueDependencies());
15231520
$packageDependencies = $this->mergePackageDependencies($resultCache->getPackageDependencies(), $resultCache->getFilesToAnalyse(), $analyserResult->getPackageDependencies());
1521+
// A re-analysed file with a parse error keeps the symbols it had before, see restore(), so that
1522+
// fixing it re-analyses nothing else when they are the same. But only while no other file is
1523+
// analysed: that file sees the broken file's symbols missing, and its result has to be renewed
1524+
// when they come back, which comparing the fixed file with no symbols does.
1525+
$filesToReplaceExportedNodes = array_fill_keys($resultCache->getFilesToAnalyse(), true);
1526+
$filesWithParseError = [];
1527+
foreach ($freshErrorsByFile as $file => $errors) {
1528+
foreach ($errors as $error) {
1529+
if ($error->getIdentifier() !== 'phpstan.parse' || !$error->hasNonIgnorableException()) {
1530+
continue;
1531+
}
1532+
1533+
$filesWithParseError[$file] = true;
1534+
}
1535+
}
1536+
if (array_diff_key($filesToReplaceExportedNodes, $filesWithParseError) === []) {
1537+
$filesToReplaceExportedNodes = [];
1538+
}
1539+
15241540
// the re-analysed files take their fresh nodes, what is left of the cached ones stays undecoded
1525-
$cachedExportedNodes = $resultCache->getCachedExportedNodes()->without(array_fill_keys($resultCache->getFilesToAnalyse(), true));
1541+
$cachedExportedNodes = $resultCache->getCachedExportedNodes()->without($filesToReplaceExportedNodes);
15261542
$exportedNodes = $this->addNonAnalysedExportedNodes($this->mergeExportedNodes($resultCache, $analyserResult->getExportedNodes()), $dependencies, $usedTraitDependencies, $cachedExportedNodes);
15271543
$linesToIgnore = $this->mergeLinesToIgnore($resultCache, $analyserResult->getLinesToIgnore());
15281544
$unmatchedLineIgnores = $this->mergeUnmatchedLineIgnores($resultCache, $analyserResult->getUnmatchedLineIgnores());

‎src/Dependency/ExportedNodeFetcher.php‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,22 @@ public function __construct(
2424
* @return RootExportedNode[]
2525
*/
2626
public function fetchNodes(string $fileName): array
27+
{
28+
return $this->fetchNodesIfParsable($fileName) ?? [];
29+
}
30+
31+
/**
32+
* @return RootExportedNode[]|null null when the file has a parse error
33+
*/
34+
public function fetchNodesIfParsable(string $fileName): ?array
2735
{
2836
$nodeTraverser = new NodeTraverser();
2937
$nodeTraverser->addVisitor($this->visitor);
3038

3139
try {
3240
$ast = $this->parser->parseFile($fileName);
3341
} catch (ParserErrorsException) {
34-
return [];
42+
return null;
3543
}
3644
$this->visitor->reset($fileName);
3745
$nodeTraverser->traverse($ast);

0 commit comments

Comments
 (0)