diff --git a/build/collision-detector.json b/build/collision-detector.json index e90fbd033b9..7ac9a60bd96 100644 --- a/build/collision-detector.json +++ b/build/collision-detector.json @@ -9,6 +9,7 @@ "../tests/PHPStan/Parser/data/cleaning-property-hooks-after.php", "../tests/PHPStan/Rules/Functions/data/duplicate-function.php", "../tests/PHPStan/Rules/Classes/data/duplicate-class.php", + "../tests/PHPStan/Reflection/BetterReflection/SourceLocator/data/group/second", "../tests/PHPStan/Rules/Names/data/multiple-namespaces.php", "../tests/PHPStan/Rules/Names/data/repeated-namespaces.php", "../tests/PHPStan/Rules/Names/data/repeated-braced-namespaces.php", diff --git a/e2e/ext-ds-version/ext-ds-version_test.sh b/e2e/ext-ds-version/ext-ds-version_test.sh index 04487d65a71..ed6072acc8b 100644 --- a/e2e/ext-ds-version/ext-ds-version_test.sh +++ b/e2e/ext-ds-version/ext-ds-version_test.sh @@ -27,7 +27,7 @@ function test_changed_ext_ds_version_reanalyses_dependent_files() { OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" - assert_contains 'PHP extension versions changed (ext-ds); re-analysing the files depending on them and the files with errors.' "$OUTPUT" + assert_contains 'PHP extension versions changed (ext-ds); re-analysing the files depending on them.' "$OUTPUT" assert_contains 'Foo.php:11:Instantiated class Ds\Vector not found.' "$OUTPUT" assert_contains 'Bar.php:15:Call to an undefined method Ds\Pair::copy().' "$OUTPUT" assert_not_contains 'Ds\Seq' "$OUTPUT" @@ -39,7 +39,7 @@ function test_changed_ext_ds_version_reanalyses_dependent_files() { OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" - assert_contains 'PHP extension versions changed (ext-ds); re-analysing the files depending on them and the files with errors.' "$OUTPUT" + assert_contains 'PHP extension versions changed (ext-ds); re-analysing the files depending on them.' "$OUTPUT" assert_contains 'Foo.php:12:Instantiated class Ds\Seq not found.' "$OUTPUT" assert_not_contains 'Ds\Vector' "$OUTPUT" assert_not_contains 'Bar.php' "$OUTPUT" diff --git a/e2e/result-cache-autoload-entries/.gitignore b/e2e/result-cache-autoload-entries/.gitignore new file mode 100644 index 00000000000..de4a392c331 --- /dev/null +++ b/e2e/result-cache-autoload-entries/.gitignore @@ -0,0 +1,2 @@ +/vendor +/composer.lock diff --git a/e2e/result-cache-autoload-entries/classmap/.gitkeep b/e2e/result-cache-autoload-entries/classmap/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/e2e/result-cache-autoload-entries/composer.json b/e2e/result-cache-autoload-entries/composer.json new file mode 100644 index 00000000000..ec8049134c2 --- /dev/null +++ b/e2e/result-cache-autoload-entries/composer.json @@ -0,0 +1,29 @@ +{ + "name": "phpstan/result-cache-autoload-entries-e2e", + "repositories": [ + { + "type": "path", + "url": "./path-lib" + } + ], + "require": { + "test/path-lib": "*" + }, + "autoload": { + "psr-4": { + "AutoloadEntries\\": "src/", + "AutoloadEntries\\Lib\\": "lib/", + "AutoloadEntries\\Root\\": "" + }, + "psr-0": { + "AutoloadEntries_Legacy_": "legacy/" + }, + "classmap": ["classmap/"], + "files": ["helpers.php"] + }, + "autoload-dev": { + "psr-4": { + "AutoloadEntries\\Tests\\": "tests/" + } + } +} diff --git a/e2e/result-cache-autoload-entries/helpers.php b/e2e/result-cache-autoload-entries/helpers.php new file mode 100644 index 00000000000..f7b77f3f0af --- /dev/null +++ b/e2e/result-cache-autoload-entries/helpers.php @@ -0,0 +1,3 @@ + +function write_php() { + mkdir -p "$(dirname "$1")" + if [ -n "$2" ]; then + printf ' "$1" + else + printf ' "$1" + fi +} + +function assert_files_to_analyse() { + INFO=$(../../bin/phpstan result-cache-info --json) + echo "$INFO" + assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" + assert_equals "$1" "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" +} + +function assert_same_as_cold_run() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + rm -rf tmp/resultCache.php + COLD_OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && COLD_CODE=0 || COLD_CODE=$? + echo "$COLD_OUTPUT" + assert_same "$COLD_CODE" "$CODE" + assert_same "$COLD_OUTPUT" "$OUTPUT" +} + +function analyse() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" +} + +# src/Consumer.php uses the class, src/Unrelated.php does not: write_class_consumer +function write_class_consumer() { + write_php src/Consumer.php AutoloadEntries "function consume(): int +{ + return (new \\$1())->value(); +}" + write_php src/Unrelated.php AutoloadEntries 'function unrelated(): int +{ + return 1; +}' + analyse + assert_same '1' "$CODE" + assert_contains 'Consumer.php:7:Instantiated class' "$OUTPUT" +} + +# the class appears, then its method body changes, then its signature does +function assert_class_appears() { + write_php "$1" "$2" "class $3 +{ + + public function value(): int + { + return 1; + } + +}" + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" + + sed -i 's/return 1;/return 2;/' "$1" + assert_files_to_analyse 0 + assert_same_as_cold_run + + sed -i 's/): int/): string/; s/return 2;/return "x";/' "$1" + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'Consumer.php:7:Function AutoloadEntries\consume() should return int but returns string.' "$OUTPUT" + + rm "$1" + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'Consumer.php:7:Instantiated class' "$OUTPUT" +} + +function test_class_appears_in_a_psr4_directory() { + write_class_consumer 'AutoloadEntries\Lib\Thing' + assert_class_appears lib/Thing.php 'AutoloadEntries\Lib' Thing +} + +function test_class_appears_in_a_psr0_directory() { + write_class_consumer 'AutoloadEntries_Legacy_Thing' + assert_class_appears legacy/AutoloadEntries/Legacy/Thing.php '' AutoloadEntries_Legacy_Thing +} + +function test_class_appears_in_a_classmap_directory() { + write_class_consumer 'AutoloadEntries\Mapped\Thing' + # a classmap file is found by what it declares, not by its name + assert_class_appears classmap/whatever.php 'AutoloadEntries\Mapped' Thing +} + +function test_class_appears_in_an_autoload_dev_directory() { + write_class_consumer 'AutoloadEntries\Tests\Thing' + assert_class_appears tests/Thing.php 'AutoloadEntries\Tests' Thing +} + +function test_class_appears_in_a_path_package() { + write_class_consumer 'PathLib\Thing' + assert_class_appears path-lib/src/Thing.php PathLib Thing +} + +function test_class_appears_under_a_psr4_namespace_mapped_to_the_project_root() { + write_class_consumer 'AutoloadEntries\Root\Thing' + # the tmpDir is under the project root too, but PHPStan's own files there are not scanned files + OUTPUT=$(../../bin/phpstan analyse -vv 2>&1) || true + assert_contains 'Result cache was not rewritten because it is unchanged.' "$OUTPUT" + assert_class_appears Thing.php 'AutoloadEntries\Root' Thing +} + +function test_class_appears_in_an_existing_psr4_file_of_another_name() { + write_php lib/Existing.php 'AutoloadEntries\Lib' 'class Existing +{ + +}' + write_class_consumer 'AutoloadEntries\Lib\Thing' + # the edited file is read for what it declares, and Thing is looked up again - but no PSR-4 path + # leads to it, so a cold run does not find it either + printf '\nclass Thing\n{\n\n\tpublic function value(): int\n\t{\n\t\treturn 1;\n\t}\n\n}\n' >> lib/Existing.php + assert_files_to_analyse 0 + assert_same_as_cold_run + assert_contains 'Consumer.php:7:Instantiated class' "$OUTPUT" +} + +# src/Consumer.php calls the function, src/Unrelated.php does not: write_function_consumer +function write_function_consumer() { + write_php src/Consumer.php AutoloadEntries "function consume(): int +{ + return \\$1(); +}" + write_php src/Unrelated.php AutoloadEntries 'function unrelated(): int +{ + return 1; +}' + analyse + assert_same '1' "$CODE" + assert_contains 'Consumer.php:7:Function' "$OUTPUT" +} + +# the function appears in an existing file, then its body changes, then its signature does +function assert_function_appears() { + printf '\nfunction %s(): int\n{\n\treturn 1;\n}\n' "$2" >> "$1" + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" + + sed -i 's/return 1;/return 2;/' "$1" + assert_files_to_analyse 0 + assert_same_as_cold_run + + sed -i 's/): int/): string/; s/return 2;/return "x";/' "$1" + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'Consumer.php:7:Function AutoloadEntries\consume() should return int but returns string.' "$OUTPUT" +} + +function test_function_appears_in_a_files_entry() { + write_function_consumer 'AutoloadEntries\helper' + assert_function_appears helpers.php helper +} + +function test_function_appears_in_a_files_entry_of_a_path_package() { + write_function_consumer 'PathLib\helper' + assert_function_appears path-lib/functions.php helper +} + +function test_class_appears_in_a_classmap_file_excluded_from_scanning() { + # excludePaths keeps the file out of the scanned files, and out of what PHPStan's classmap + # locator finds too - the class stays unknown, and nothing has to be analysed again + printf 'parameters:\n\tlevel: 8\n\ttmpDir: tmp\n\tpaths:\n\t\t- src\n\texcludePaths:\n\t\t- classmap/excluded/*\n' > phpstan.neon + write_class_consumer 'AutoloadEntries\Mapped\Thing' + write_php classmap/excluded/Thing.php 'AutoloadEntries\Mapped' 'class Thing +{ + + public function value(): int + { + return 1; + } + +}' + assert_files_to_analyse 0 + assert_same_as_cold_run + assert_contains 'Consumer.php:7:Instantiated class' "$OUTPUT" +} diff --git a/e2e/result-cache-autoload-entries/src/.gitkeep b/e2e/result-cache-autoload-entries/src/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/e2e/result-cache-autoload-entries/tests/.gitkeep b/e2e/result-cache-autoload-entries/tests/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/e2e/result-cache-autoload-entries/tmp/.gitignore b/e2e/result-cache-autoload-entries/tmp/.gitignore new file mode 100644 index 00000000000..125e34294bf --- /dev/null +++ b/e2e/result-cache-autoload-entries/tmp/.gitignore @@ -0,0 +1,2 @@ +* +!.* diff --git a/e2e/result-cache-collector-sweep/result-cache-collector-sweep_test.sh b/e2e/result-cache-collector-sweep/result-cache-collector-sweep_test.sh index fe35e4f6415..5dbf39e5c0b 100644 --- a/e2e/result-cache-collector-sweep/result-cache-collector-sweep_test.sh +++ b/e2e/result-cache-collector-sweep/result-cache-collector-sweep_test.sh @@ -16,8 +16,9 @@ function test_result_cache_collector_sweep() { echo "$OUTPUT" assert_contains 'PlainCaller.php:8:Method ResultCacheE2ECollectorSweep\PlainCaller::doPlainCaller() has invalid return type ResultCacheE2ECollectorSweep\Missing.' "$OUTPUT" assert_contains 'Caller.php:7:Call to function resultCacheE2ECollectorHelper() on a separate line has no effect.' "$OUTPUT" - # One new file defines both missing symbols. The files with errors are re-analysed - including - # the file holding the error of the collector-backed rule, which is not in the cached error map. + # One new file defines both missing symbols. Both lookups were recorded as missing, so the + # files making them are re-analysed - including the file holding the error of the + # collector-backed rule, which is not in the cached error map. cp appears/nsfns.php src/nsfns.php OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "0" "$CODE" diff --git a/e2e/result-cache-empty-file-gains-symbol/result-cache-empty-file-gains-symbol_test.sh b/e2e/result-cache-empty-file-gains-symbol/result-cache-empty-file-gains-symbol_test.sh index 18850f3e6f4..b5960fa582a 100644 --- a/e2e/result-cache-empty-file-gains-symbol/result-cache-empty-file-gains-symbol_test.sh +++ b/e2e/result-cache-empty-file-gains-symbol/result-cache-empty-file-gains-symbol_test.sh @@ -16,9 +16,8 @@ function test_result_cache_empty_file_gains_symbol() { assert_same "1" "$CODE" echo "$OUTPUT" assert_contains 'user.php:7:Instantiated class ResultCacheE2EEmptyFileGainsSymbol\Thing not found.' "$OUTPUT" - # That file now declares a class. A root symbol appeared, so the files with errors have to - # be re-analysed, the same way a brand new file makes them re-analysed - the missing - # exported nodes entry must not be read as "nothing changed". + # That file now declares a class. src/user.php recorded it as missing, so it is re-analysed + # no matter whether the file declaring it was known to the cache before. mv gains/script.php src/script.php OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "0" "$CODE" diff --git a/e2e/result-cache-file-dependency/result-cache-file-dependency_test.sh b/e2e/result-cache-file-dependency/result-cache-file-dependency_test.sh index d822837d67a..5e883dcf3b2 100644 --- a/e2e/result-cache-file-dependency/result-cache-file-dependency_test.sh +++ b/e2e/result-cache-file-dependency/result-cache-file-dependency_test.sh @@ -132,8 +132,8 @@ function test_result_cache_file_dependency() { assert_not_contains 'Holder.php:17:Method ResultCacheE2EFileDependency\Holder::get() should return int but returns string.' "$OUTPUT" assert_not_contains 'UsesHolder.php:9:Function ResultCacheE2EFileDependency\usesHolder() should return int but returns string.' "$OUTPUT" # And for a declared file that is analysed itself: deleted, it is no longer analysed, and the files - # of the rule's nodes are re-analysed; created again, all three are - and as with any new file, so - # are the three files with errors. + # of the rule's nodes are re-analysed; created again, all three are - but not the three files with + # errors, the file declares no symbol they could be waiting for. rm src/Config.php INFO=$(../../bin/phpstan result-cache-info --json) echo "$INFO" @@ -145,7 +145,7 @@ function test_result_cache_file_dependency() { printf " src/Config.php INFO=$(../../bin/phpstan result-cache-info --json) echo "$INFO" - assert_equals '6' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" + assert_equals '3' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" diff --git a/e2e/result-cache-missing-classes/.gitignore b/e2e/result-cache-missing-classes/.gitignore new file mode 100644 index 00000000000..de4a392c331 --- /dev/null +++ b/e2e/result-cache-missing-classes/.gitignore @@ -0,0 +1,2 @@ +/vendor +/composer.lock diff --git a/e2e/result-cache-missing-classes/composer.json b/e2e/result-cache-missing-classes/composer.json new file mode 100644 index 00000000000..606b3b33d72 --- /dev/null +++ b/e2e/result-cache-missing-classes/composer.json @@ -0,0 +1,10 @@ +{ + "name": "phpstan/result-cache-missing-classes-e2e", + "autoload": { + "psr-4": { + "ResultCacheE2EMissingClasses\\": "src/", + "ResultCacheE2EMissingClasses\\Lib\\": "lib/", + "ResultCacheE2EMissingClassesRules\\": "rules/" + } + } +} diff --git a/e2e/result-cache-missing-classes/lib/.gitkeep b/e2e/result-cache-missing-classes/lib/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/e2e/result-cache-missing-classes/phpstan.neon b/e2e/result-cache-missing-classes/phpstan.neon new file mode 100644 index 00000000000..876c71b814c --- /dev/null +++ b/e2e/result-cache-missing-classes/phpstan.neon @@ -0,0 +1,8 @@ +parameters: + level: 8 + tmpDir: tmp + paths: + - src + +rules: + - ResultCacheE2EMissingClassesRules\ReplacementRule diff --git a/e2e/result-cache-missing-classes/result-cache-missing-classes_test.sh b/e2e/result-cache-missing-classes/result-cache-missing-classes_test.sh new file mode 100644 index 00000000000..853291cb7f8 --- /dev/null +++ b/e2e/result-cache-missing-classes/result-cache-missing-classes_test.sh @@ -0,0 +1,393 @@ +#!/usr/bin/env bash +# @tags result-cache + +# A class looked up and not found is a dependency of whatever asked for it. These files have no +# error while the class is missing, so declaring it re-analyses them only because they asked. + +function set_up() { + e2e::set_up + composer install --quiet +} + +function tear_down() { + e2e::tear_down +} + +# writes a file in the namespace of the project: write_php +function write_php() { + printf ' "$1" +} + +function assert_files_to_analyse() { + INFO=$(../../bin/phpstan result-cache-info --json) + echo "$INFO" + assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" + assert_equals "$1" "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" +} + +function assert_same_as_cold_run() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + rm -rf tmp/resultCache.php + COLD_OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && COLD_CODE=0 || COLD_CODE=$? + echo "$COLD_OUTPUT" + assert_same "$COLD_CODE" "$CODE" + assert_same "$COLD_OUTPUT" "$OUTPUT" +} + +function analyse_without_errors() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same '0' "$CODE" +} + +function test_narrowed_by_class_exists() { + write_php src/User.php 'function doUser(): int +{ + if (class_exists(Thing::class)) { + return (new Thing())->count(); + } + + return 0; +}' + analyse_without_errors + write_php src/Thing.php 'class Thing +{ + +}' + # src/Thing.php is new, src/User.php asked for the class + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:8:Call to an undefined method ResultCacheE2EMissingClasses\Thing::count().' "$OUTPUT" +} + +function test_class_name_in_a_string() { + write_php src/User.php 'function doUser(Other $other): bool +{ + return get_class($other) === '"'"'ResultCacheE2EMissingClasses\Thing'"'"'; +}' + analyse_without_errors + write_php src/Thing.php 'class Thing +{ + +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Strict comparison using === between' "$OUTPUT" +} + +function test_rule_asking_for_a_class() { + write_php src/legacy.php 'function legacyCall(): void +{ +}' + write_php src/User.php 'function doUser(): void +{ + legacyCall(); +}' + analyse_without_errors + write_php src/Replacement.php 'class Replacement +{ + +}' + # src/legacy.php declares nothing the rule asked about + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Use Replacement instead of legacyCall().' "$OUTPUT" +} + +function test_missing_parent_of_a_used_class() { + # src/Child.php reports its missing parent, src/User.php only uses Child + write_php src/Child.php 'class Child extends Base +{ + +}' + write_php src/User.php 'function doUser(): Child +{ + return new Child(); +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Base.php 'class Base +{ + + public function __construct(int $value) + { + } + +}' + # src/Base.php is new, src/Child.php named it, src/User.php used what Child declares + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'User.php:7:Class ResultCacheE2EMissingClasses\Child constructor invoked with 0 parameters, 1 required.' "$OUTPUT" +} + +function test_missing_trait_of_a_used_class() { + write_php src/Child.php 'class Child +{ + + use Base; + +}' + write_php src/User.php 'function doUser(): Child +{ + return new Child(); +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Base.php 'trait Base +{ + + public function __construct(int $value) + { + } + +}' + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'User.php:7:Class ResultCacheE2EMissingClasses\Child constructor invoked with 0 parameters, 1 required.' "$OUTPUT" +} + +function test_phpdoc_type_becomes_a_class() { + # "scalar" is a PHPDoc type until a class of the name exists in the namespace + write_php src/scalar.php '/** + * @param scalar $value + */ +function takeScalar(mixed $value): void +{ +}' + write_php src/User.php 'function doUser(): void +{ + takeScalar(1); +}' + analyse_without_errors + write_php src/Scalar.php 'class Scalar +{ + +}' + # src/scalar.php resolved its PHPDoc, src/User.php called the function + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'User.php:7:Parameter #1 $value of function ResultCacheE2EMissingClasses\takeScalar expects ResultCacheE2EMissingClasses\Scalar, int given.' "$OUTPUT" +} + +function test_class_appears_in_an_autoloaded_directory() { + # lib/ is neither analysed nor scanned, its classes come from the Composer autoloader + write_php src/User.php 'function doUser(): object +{ + return new Lib\Thing(); +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + printf ' lib/Thing.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_not_contains 'not found' "$OUTPUT" +} + +function test_unrelated_error_is_not_analysed_again() { + # src/Broken.php has an error, but it never asked for the class + write_php src/Broken.php 'function broken(): int +{ + return "x"; +}' + write_php src/User.php 'function doUser(): object +{ + return new Thing(); +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Thing.php 'class Thing +{ + +}' + # src/Thing.php is new, src/User.php asked for the class + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'Broken.php:7:Function ResultCacheE2EMissingClasses\broken() should return int but returns string.' "$OUTPUT" +} + +function test_same_lookup_in_several_files() { + # only the first file to ask finds out, the others get the remembered answer + for name in First Second Third; do + write_php "src/$name.php" "function do$name(Other \$other): bool +{ + return get_class(\$other) === 'ResultCacheE2EMissingClasses\\Thing'; +}" + done + analyse_without_errors + write_php src/Thing.php 'class Thing +{ + +}' + assert_files_to_analyse 4 + assert_same_as_cold_run + assert_contains 'First.php:7:Strict comparison using === between' "$OUTPUT" + assert_contains 'Third.php:7:Strict comparison using === between' "$OUTPUT" +} + +function test_missing_mixin() { + write_php src/Child.php '/** + * @mixin Helper + */ +class Child +{ + +}' + write_php src/User.php 'function doUser(Child $child): void +{ + $child->help(); +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Helper.php 'class Helper +{ + + public function help(int $value): void + { + } + +}' + # src/Helper.php is new, src/Child.php named it, src/User.php called a method it adds + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'User.php:7:Method ResultCacheE2EMissingClasses\Helper::help() invoked with 0 parameters, 1 required.' "$OUTPUT" +} + +function test_class_constant_initializer() { + write_php src/Config.php 'class Config +{ + + const LIMIT = Limits::MAX; + +}' + write_php src/User.php 'function doUser(): int +{ + return Config::LIMIT; +}' + # the type of the constant is remembered, only the first of the two files resolves it + write_php src/UserToo.php 'function doUserToo(): int +{ + return Config::LIMIT; +}' + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Limits.php 'class Limits +{ + + const MAX = "many"; + +}' + # src/Limits.php is new, src/Config.php named it, src/User.php and src/UserToo.php read the constant + assert_files_to_analyse 4 + assert_same_as_cold_run + assert_contains "User.php:7:Function ResultCacheE2EMissingClasses\\doUser() should return int but returns string." "$OUTPUT" + assert_contains "UserToo.php:7:Function ResultCacheE2EMissingClasses\\doUserToo() should return int but returns string." "$OUTPUT" +} + +function test_class_name_in_a_shared_constant() { + # the type of the constant is resolved once, both files compare against it + write_php src/Names.php 'class Names +{ + + const THING = '"'"'ResultCacheE2EMissingClasses\Thing'"'"'; + +}' + for name in First Second; do + write_php "src/$name.php" "function do$name(Other \$other): bool +{ + return get_class(\$other) === Names::THING; +}" + done + analyse_without_errors + write_php src/Thing.php 'class Thing +{ + +}' + # src/Thing.php is new, src/First.php and src/Second.php asked for the class + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'Second.php:7:Strict comparison using === between' "$OUTPUT" +} + +function test_enum_case_value() { + write_php src/Suit.php 'enum Suit: string +{ + + case Hearts = Values::HEARTS; + +}' + for name in First Second; do + write_php "src/$name.php" "function do$name(): int +{ + return strlen(Suit::Hearts->value); +}" + done + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Values.php 'class Values +{ + + const HEARTS = "h"; + +}' + # src/Values.php is new, src/Suit.php named it, src/First.php and src/Second.php read the case + assert_files_to_analyse 4 + assert_same_as_cold_run +} + +function test_parameter_default_value() { + write_php src/pick.php '/** + * @return ($flag is true ? int : string) + */ +function pick(bool $flag = Flags::ON): int|string +{ + return $flag ? 1 : "a"; +}' + for name in First Second; do + write_php "src/$name.php" "function do$name(): int +{ + return pick(); +}" + done + ../../bin/phpstan analyse > /dev/null 2>&1 || true + write_php src/Flags.php 'class Flags +{ + + const ON = false; + +}' + # src/Flags.php is new, src/pick.php named it, src/First.php and src/Second.php called pick() + assert_files_to_analyse 4 + assert_same_as_cold_run + assert_contains 'Second.php:7:Function ResultCacheE2EMissingClasses\doSecond() should return int but returns string.' "$OUTPUT" +} + +function test_global_type_alias_to_a_missing_class() { + # the global type alias is resolved once for the whole analysis + for name in First Second; do + write_php "src/$name.php" "/** + * @return Amount + */ +function make$name(): mixed +{ + return 1; +}" + write_php "src/Use$name.php" "function use$name(): int +{ + return make$name()->value; +}" + done + ../../bin/phpstan analyse -c type-aliases.neon > /dev/null 2>&1 || true + write_php src/Money.php 'class Money +{ + + public string $value = ""; + +}' + INFO=$(../../bin/phpstan result-cache-info --json -c type-aliases.neon) + echo "$INFO" + assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" + # src/Money.php is new, the two files with the PHPDoc and the two using the functions + assert_equals '5' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" + OUTPUT=$(../../bin/phpstan analyse -c type-aliases.neon --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + rm -rf tmp/resultCache.php + COLD_OUTPUT=$(../../bin/phpstan analyse -c type-aliases.neon --error-format raw 2>&1) && COLD_CODE=0 || COLD_CODE=$? + echo "$COLD_OUTPUT" + assert_same "$COLD_CODE" "$CODE" + assert_same "$COLD_OUTPUT" "$OUTPUT" + assert_contains 'UseSecond.php:7:Function ResultCacheE2EMissingClasses\useSecond() should return int but returns string.' "$OUTPUT" +} diff --git a/e2e/result-cache-missing-classes/rules/ReplacementRule.php b/e2e/result-cache-missing-classes/rules/ReplacementRule.php new file mode 100644 index 00000000000..ffbaff5b311 --- /dev/null +++ b/e2e/result-cache-missing-classes/rules/ReplacementRule.php @@ -0,0 +1,43 @@ + + */ +final class ReplacementRule implements Rule +{ + + public function __construct(private ReflectionProvider $reflectionProvider) + { + } + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Name || $node->name->toLowerString() !== 'legacycall') { + return []; + } + + if (!$this->reflectionProvider->hasClass('ResultCacheE2EMissingClasses\Replacement')) { + return []; + } + + return [RuleErrorBuilder::message('Use Replacement instead of legacyCall().')->identifier('e2e.replacement')->build()]; + } + +} diff --git a/e2e/result-cache-missing-classes/src/Other.php b/e2e/result-cache-missing-classes/src/Other.php new file mode 100644 index 00000000000..7a1d373e6e5 --- /dev/null +++ b/e2e/result-cache-missing-classes/src/Other.php @@ -0,0 +1,8 @@ +&1) && CODE=0 || CODE=$? assert_same "0" "$CODE" echo "$OUTPUT" - assert_contains 'Composer packages changed (test/logger); re-analysing the files depending on them and the files with errors.' "$OUTPUT" + assert_contains 'Composer packages changed (test/logger); re-analysing the files depending on them.' "$OUTPUT" } diff --git a/e2e/result-cache-path-repository/result-cache-path-repository_test.sh b/e2e/result-cache-path-repository/result-cache-path-repository_test.sh index a58b97d6da7..62f3108a360 100644 --- a/e2e/result-cache-path-repository/result-cache-path-repository_test.sh +++ b/e2e/result-cache-path-repository/result-cache-path-repository_test.sh @@ -22,7 +22,7 @@ function test_result_cache_path_repository() { OUTPUT=$(../../bin/phpstan analyse -vv 2>&1) && CODE=0 || CODE=$? assert_same "0" "$CODE" echo "$OUTPUT" - assert_contains 'Composer packages changed (psr/log); re-analysing the files depending on them and the files with errors.' "$OUTPUT" + assert_contains 'Composer packages changed (psr/log); re-analysing the files depending on them.' "$OUTPUT" # Editing a file of an installed package is not a valid thing to do - the next Composer # command overwrites it - so PHPStan does not track it and keeps the cached results, even # though this edit takes away a method the analysed code calls. diff --git a/e2e/result-cache-scanned-2/result-cache-scanned-2_test.sh b/e2e/result-cache-scanned-2/result-cache-scanned-2_test.sh index 3200a5c8737..542e3da2800 100644 --- a/e2e/result-cache-scanned-2/result-cache-scanned-2_test.sh +++ b/e2e/result-cache-scanned-2/result-cache-scanned-2_test.sh @@ -41,13 +41,13 @@ function test_result_cache_scanned_2() { assert_same "1" "$CODE" echo "$OUTPUT" assert_contains 'UsesExtra.php:10:Method ResultCacheE2EScanned2\UsesExtra::doUsesExtra() should return int but returns string.' "$OUTPUT" - # Deleting a scanned file re-analyses the files depending on it, and because it declared a - # symbol, the files with errors too: src/Foo.php and src/UsesExtra.php. + # Deleting a scanned file re-analyses the files depending on it: src/Foo.php, not + # src/UsesExtra.php with its unrelated error. rm scanned/Dep.php INFO=$(../../bin/phpstan result-cache-info --json) echo "$INFO" assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" - assert_equals '2' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" + assert_equals '1' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" diff --git a/e2e/result-cache-scanned-exported-nodes/result-cache-scanned-exported-nodes_test.sh b/e2e/result-cache-scanned-exported-nodes/result-cache-scanned-exported-nodes_test.sh index 894500640fa..6ce05ebe0a6 100644 --- a/e2e/result-cache-scanned-exported-nodes/result-cache-scanned-exported-nodes_test.sh +++ b/e2e/result-cache-scanned-exported-nodes/result-cache-scanned-exported-nodes_test.sh @@ -64,13 +64,13 @@ function test_result_cache_scanned_exported_nodes() { assert_same "1" "$CODE" echo "$OUTPUT" assert_contains 'Bar.php:10:Instantiated class ResultCacheE2EScannedExportedNodes\NewDep not found.' "$OUTPUT" - # A file declaring a class may define a symbol reported as unknown, so the files with - # errors are re-analysed - both of them - and the error about the class is gone. + # A file declaring the missing class re-analyses the file that looked it up, src/Bar.php, + # and not src/Foo.php with its unrelated error. The error about the class is gone. mv new-file/NewDep.php scanned/NewDep.php INFO=$(../../bin/phpstan result-cache-info --json) echo "$INFO" assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" - assert_equals '2' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" + assert_equals '1' "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" diff --git a/e2e/result-cache-scanned-new-file/result-cache-scanned-new-file_test.sh b/e2e/result-cache-scanned-new-file/result-cache-scanned-new-file_test.sh index 1d280227928..fa93d1377af 100644 --- a/e2e/result-cache-scanned-new-file/result-cache-scanned-new-file_test.sh +++ b/e2e/result-cache-scanned-new-file/result-cache-scanned-new-file_test.sh @@ -14,9 +14,8 @@ function test_result_cache_scanned_new_file() { assert_same "1" "$CODE" echo "$OUTPUT" assert_contains 'UsesNew.php:10:Instantiated class ResultCacheE2EScannedNewFile\NewlyScanned not found.' "$OUTPUT" - # A file that newly appears in a scanDirectories directory may define a symbol that was - # reported as unknown somewhere, so the files with errors are re-analysed too - the same - # way a new analysed file makes them re-analysed. src/Foo.php is still left alone. + # A file that newly appears in a scanDirectories directory defines a class src/UsesNew.php + # recorded as missing, so that file is re-analysed. src/Foo.php is left alone. mv new-file/NewlyScanned.php scanned/NewlyScanned.php INFO=$(../../bin/phpstan result-cache-info --json) echo "$INFO" @@ -25,7 +24,6 @@ function test_result_cache_scanned_new_file() { OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" - assert_contains 'Scanned files with changed symbols (1); re-analysing the files affected by them.' "$OUTPUT" assert_not_contains 'Instantiated class ResultCacheE2EScannedNewFile\NewlyScanned not found.' "$OUTPUT" assert_contains 'UsesNew.php:10:Method ResultCacheE2EScannedNewFile\UsesNew::doUsesNew() should return int but returns string.' "$OUTPUT" } diff --git a/e2e/result-cache-scanned-vendor/result-cache-scanned-vendor_test.sh b/e2e/result-cache-scanned-vendor/result-cache-scanned-vendor_test.sh index cfc14a41e9a..f7fbf40159a 100644 --- a/e2e/result-cache-scanned-vendor/result-cache-scanned-vendor_test.sh +++ b/e2e/result-cache-scanned-vendor/result-cache-scanned-vendor_test.sh @@ -11,6 +11,9 @@ function tear_down() { function test_result_cache_scanned_vendor() { composer install + # A package from a path repository is the project's own code and is tracked file by file; + # record the fixture package as downloaded, like one from Packagist + php -r '$f = "vendor/composer/installed.json"; $j = json_decode(file_get_contents($f), true); foreach ($j["packages"] as &$p) { $p["dist"]["type"] = "zip"; } file_put_contents($f, json_encode($j, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));' ../../bin/phpstan analyse # A scanned file that belongs to an installed Composer package is not tracked as a file # dependency - packages are tracked at package granularity - so editing it still has to diff --git a/e2e/result-cache-stub-files-errors/result-cache-stub-files-errors_test.sh b/e2e/result-cache-stub-files-errors/result-cache-stub-files-errors_test.sh index 294a7ed5f7f..9fb711a2829 100644 --- a/e2e/result-cache-stub-files-errors/result-cache-stub-files-errors_test.sh +++ b/e2e/result-cache-stub-files-errors/result-cache-stub-files-errors_test.sh @@ -16,8 +16,9 @@ function test_result_cache_stub_files_errors() { echo "$OUTPUT" assert_contains 'test.stub:8:Method StubFilesResultCache\Foo::doFoo() has parameter $a with no type specified.' "$OUTPUT" assert_not_contains 'return statement is missing' "$OUTPUT" - # A new file makes the files with errors re-analysed. The stub file is not one of them, - # otherwise the rules for analysed files would report that doFoo() does not return. + # A new file is analysed while the cached results are restored. The stub file must not be + # analysed with it, otherwise the rules for analysed files would report that doFoo() does + # not return. echo ' src/Baz.php OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" diff --git a/e2e/result-cache-symbol-lookups/.gitignore b/e2e/result-cache-symbol-lookups/.gitignore new file mode 100644 index 00000000000..de4a392c331 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/.gitignore @@ -0,0 +1,2 @@ +/vendor +/composer.lock diff --git a/e2e/result-cache-symbol-lookups/composer.json b/e2e/result-cache-symbol-lookups/composer.json new file mode 100644 index 00000000000..3306e6183a5 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/composer.json @@ -0,0 +1,10 @@ +{ + "name": "phpstan/result-cache-symbol-lookups-e2e", + "autoload": { + "psr-4": { + "ResultCacheE2ESymbolLookups\\": "src/", + "ResultCacheE2ESymbolLookups\\Lib\\": "lib/", + "ResultCacheE2ESymbolLookupsRules\\": "rules/" + } + } +} diff --git a/e2e/result-cache-symbol-lookups/phpstan.neon b/e2e/result-cache-symbol-lookups/phpstan.neon new file mode 100644 index 00000000000..9bd0a6e8e85 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/phpstan.neon @@ -0,0 +1,20 @@ +includes: + - ../../conf/bleedingEdge.neon + +parameters: + level: 8 + tmpDir: tmp + paths: + - src + scanDirectories: + - scanned + +rules: + - ResultCacheE2ESymbolLookupsRules\ReplacementRule + - ResultCacheE2ESymbolLookupsRules\CollectedReplacementRule + +services: + - + class: ResultCacheE2ESymbolLookupsRules\LegacyCallCollector + tags: + - phpstan.collector diff --git a/e2e/result-cache-symbol-lookups/result-cache-symbol-lookups_test.sh b/e2e/result-cache-symbol-lookups/result-cache-symbol-lookups_test.sh new file mode 100644 index 00000000000..144369d8161 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/result-cache-symbol-lookups_test.sh @@ -0,0 +1,614 @@ +#!/usr/bin/env bash +# @tags result-cache + +# Every class, function and constant looked up is recorded, found or not: whatever asked is +# re-analysed when it appears or goes away, and nothing else is. + +function set_up() { + e2e::set_up + composer install --quiet +} + +function tear_down() { + e2e::tear_down +} + +# writes a file in the namespace of the project: write_php +function write_php() { + printf ' "$1" +} + +function assert_files_to_analyse() { + INFO=$(../../bin/phpstan result-cache-info --json) + echo "$INFO" + assert_equals 'true' "$(echo "$INFO" | jq --raw-output '.resultCacheUsed')" + assert_equals "$1" "$(echo "$INFO" | jq --raw-output '.filesToAnalyseCount')" +} + +function assert_same_as_cold_run() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + rm -rf tmp/resultCache.php + COLD_OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && COLD_CODE=0 || COLD_CODE=$? + echo "$COLD_OUTPUT" + assert_same "$COLD_CODE" "$CODE" + assert_same "$COLD_OUTPUT" "$OUTPUT" +} + +function analyse() { + OUTPUT=$(../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" +} + +# lib/ is neither analysed nor scanned, its classes come from the Composer autoloader +function write_lib_collected_replacement() { + mkdir -p lib + printf ' lib/CollectedReplacement.php +} + +function write_strlen_users() { + for name in First Second; do + write_php "src/$name.php" "function do$name(string \$value): int +{ + return strlen(\$value); +}" + done +} + +STRLEN='function strlen(string $value): string +{ + return $value; +}' + +# {{{ appearing + +function test_function_shadows_a_global_function() { + # https://github.com/phpstan/phpstan/issues/15453 + write_strlen_users + analyse + assert_same '0' "$CODE" + write_php src/strlen.php "$STRLEN" + # src/strlen.php is new, the two files calling strlen() asked for the function in the namespace + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_contains 'Second.php:7:Function ResultCacheE2ESymbolLookups\doSecond() should return int but returns string.' "$OUTPUT" +} + +function test_function_appears_in_a_scanned_file() { + write_strlen_users + analyse + assert_same '0' "$CODE" + write_php scanned/strlen.php "$STRLEN" + # scanned/ is not analysed + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'First.php:7:Function ResultCacheE2ESymbolLookups\doFirst() should return int but returns string.' "$OUTPUT" +} + +function test_constant_shadows_a_global_constant() { + write_php src/User.php 'function doUser(): string +{ + return PHP_EOL; +}' + analyse + assert_same '0' "$CODE" + write_php src/constants.php 'const PHP_EOL = 1;' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return string but returns int.' "$OUTPUT" +} + +function test_narrowed_by_function_exists() { + write_php src/User.php 'function doUser(): mixed +{ + if (function_exists('"'"'ResultCacheE2ESymbolLookups\helper'"'"')) { + return \ResultCacheE2ESymbolLookups\helper(1, 2); + } + + return 0; +}' + analyse + assert_same '0' "$CODE" + write_php src/helper.php 'function helper(): string +{ + return ""; +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:8:Function ResultCacheE2ESymbolLookups\helper invoked with 2 parameters, 0 required.' "$OUTPUT" +} + +function test_narrowed_by_defined() { + write_php src/User.php 'function doUser(): bool +{ + if (defined('"'"'ResultCacheE2ESymbolLookups\LIMIT'"'"')) { + return \ResultCacheE2ESymbolLookups\LIMIT === "x"; + } + + return false; +}' + analyse + assert_same '0' "$CODE" + write_php src/constants.php 'const LIMIT = 1;' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:8:Strict comparison using === between 1 and' "$OUTPUT" +} + +function test_function_named_in_a_string() { + write_php src/User.php 'function doUser(): ?\ReflectionFunction +{ + try { + return new \ReflectionFunction('"'"'ResultCacheE2ESymbolLookups\helper'"'"'); + } catch (\ReflectionException $e) { + return null; + } +}' + analyse + assert_same '0' "$CODE" + write_php src/helper.php 'function helper(): void +{ +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:9:Dead catch - ReflectionException is never thrown in the try block.' "$OUTPUT" +} + +function test_rule_on_collected_data_asking_for_a_class() { + write_php src/legacy.php 'function collectedLegacyCall(): void +{ +}' + write_php src/User.php 'function doUser(): void +{ + collectedLegacyCall(); +}' + analyse + assert_same '0' "$CODE" + write_lib_collected_replacement + # nothing to re-analyse - the rule runs again + assert_files_to_analyse 0 + assert_same_as_cold_run + assert_contains 'User.php:7:Use CollectedReplacement instead of collectedLegacyCall().' "$OUTPUT" +} + +function test_missing_class_returned_from_another_file() { + write_php src/make.php '/** + * @return Thing + */ +function makeThing(): mixed +{ + return null; +}' + for name in First Second; do + write_php "src/$name.php" "function do$name(): \\Countable +{ + return makeThing(); +}" + done + analyse + write_php src/Thing.php 'class Thing implements \Countable +{ + + public function count(): int + { + return 0; + } + +}' + # src/Thing.php is new, src/make.php named it, src/First.php and src/Second.php returned it + assert_files_to_analyse 4 + assert_same_as_cold_run +} + +# }}} + +# {{{ going away + +function test_removed_class_named_in_a_string() { + write_php src/Thing.php 'class Thing +{ + +}' + write_php src/User.php 'function doUser(Other $other): bool +{ + return get_class($other) === '"'"'ResultCacheE2ESymbolLookups\Thing'"'"'; +}' + analyse + assert_contains 'User.php:7:Strict comparison using === between' "$OUTPUT" + rm src/Thing.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_class_removed_from_an_existing_file() { + printf '\nclass Thing\n{\n\n}\n' >> src/Other.php + write_php src/User.php 'function doUser(Other $other): bool +{ + return get_class($other) === '"'"'ResultCacheE2ESymbolLookups\Thing'"'"'; +}' + analyse + assert_contains 'User.php:7:Strict comparison using === between' "$OUTPUT" + write_php src/Other.php 'class Other +{ + +}' + # src/Other.php changed, src/User.php found the class in it + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_class_named_in_a_shared_constant() { + write_php src/Thing.php 'class Thing +{ + +}' + write_php src/Names.php 'class Names +{ + + const THING = '"'"'ResultCacheE2ESymbolLookups\Thing'"'"'; + +}' + for name in First Second; do + write_php "src/$name.php" "function do$name(Other \$other): bool +{ + return get_class(\$other) === Names::THING; +}" + done + analyse + assert_contains 'Second.php:7:Strict comparison using === between' "$OUTPUT" + rm src/Thing.php + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_rule_asking_for_a_removed_class() { + write_php src/Replacement.php 'class Replacement +{ + +}' + write_php src/legacy.php 'function legacyCall(): void +{ +}' + write_php src/User.php 'function doUser(): void +{ + legacyCall(); +}' + analyse + assert_contains 'User.php:7:Use Replacement instead of legacyCall().' "$OUTPUT" + rm src/Replacement.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_rule_on_collected_data_asking_for_a_removed_class() { + write_lib_collected_replacement + write_php src/legacy.php 'function collectedLegacyCall(): void +{ +}' + write_php src/User.php 'function doUser(): void +{ + collectedLegacyCall(); +}' + analyse + assert_contains 'User.php:7:Use CollectedReplacement instead of collectedLegacyCall().' "$OUTPUT" + rm lib/CollectedReplacement.php + # nothing to re-analyse - the rule runs again + assert_files_to_analyse 0 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_class_in_a_phpdoc_of_another_file() { + write_php src/Scalar.php 'class Scalar +{ + +}' + # "scalar" is the class while it exists + write_php src/scalar.php '/** + * @param scalar $value + */ +function takeScalar(mixed $value): void +{ +}' + # the second caller reuses the PHPDoc the first one resolved + for name in First Second; do + write_php "src/$name.php" "function do$name(): void +{ + takeScalar(1); +}" + done + analyse + assert_contains 'Second.php:7:Parameter #1 $value of function ResultCacheE2ESymbolLookups\takeScalar expects ResultCacheE2ESymbolLookups\Scalar, int given.' "$OUTPUT" + rm src/Scalar.php + # src/scalar.php resolved its PHPDoc to the class, src/First.php and src/Second.php called the function + assert_files_to_analyse 3 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_class_in_a_phpdoc_of_a_function_not_called() { + write_php src/Scalar.php 'class Scalar +{ + +}' + write_php src/functions.php '/** + * @param scalar $value + */ +function takeScalar(mixed $value): void +{ +} + +function other(): void +{ +}' + write_php src/First.php 'function doFirst(): void +{ + takeScalar(1); +}' + # src/Second.php is analysed after the PHPDoc of takeScalar() was resolved, but does not call it + write_php src/Second.php 'function doSecond(): void +{ + other(); +}' + analyse + assert_contains 'First.php:7:Parameter #1 $value of function ResultCacheE2ESymbolLookups\takeScalar expects ResultCacheE2ESymbolLookups\Scalar, int given.' "$OUTPUT" + rm src/Scalar.php + # src/functions.php resolved its PHPDoc to the class, src/First.php called the function + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_function_named_in_a_string() { + write_php src/helper.php 'function helper(): void +{ +}' + write_php src/User.php 'function doUser(): ?\ReflectionFunction +{ + try { + return new \ReflectionFunction('"'"'ResultCacheE2ESymbolLookups\helper'"'"'); + } catch (\ReflectionException $e) { + return null; + } +}' + analyse + assert_contains 'Dead catch' "$OUTPUT" + rm src/helper.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_shadowing_function() { + write_php src/strlen.php "$STRLEN" + write_strlen_users + analyse + assert_contains 'First.php:7:Function ResultCacheE2ESymbolLookups\doFirst() should return int but returns string.' "$OUTPUT" + rm src/strlen.php + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_shadowing_function_in_a_scanned_file() { + write_php scanned/strlen.php "$STRLEN" + write_strlen_users + analyse + assert_contains 'First.php:7:Function ResultCacheE2ESymbolLookups\doFirst() should return int but returns string.' "$OUTPUT" + rm scanned/strlen.php + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +function test_removed_constant_narrowed_by_defined() { + write_php src/constants.php 'const LIMIT = 1;' + write_php src/User.php 'function doUser(): bool +{ + if (defined('"'"'ResultCacheE2ESymbolLookups\LIMIT'"'"')) { + return \ResultCacheE2ESymbolLookups\LIMIT === "x"; + } + + return false; +}' + analyse + assert_contains 'User.php:8:Strict comparison using === between 1 and' "$OUTPUT" + rm src/constants.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_same '0' "$CODE" +} + +# }}} + +# {{{ suspected gaps + +function test_function_called_in_another_case() { + # function names are case-insensitive: the lookup of Helper() must be found by helper() + write_php src/User.php 'function doUser(): int +{ + return \ResultCacheE2ESymbolLookups\Helper(); +}' + analyse + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\Helper not found.' "$OUTPUT" + write_php src/helper.php 'function helper(): string +{ + return ""; +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return int but returns string.' "$OUTPUT" +} + +function test_constant_namespace_in_another_case() { + # the namespace of a constant is case-insensitive, its name is not + write_php src/User.php 'function doUser(): string +{ + return \resultcachee2esymbollookups\LIMIT; +}' + analyse + assert_contains 'User.php:7:Constant resultcachee2esymbollookups\LIMIT not found.' "$OUTPUT" + write_php src/constants.php 'const LIMIT = 1;' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return string but returns int.' "$OUTPUT" +} + +function test_constant_name_in_another_case() { + write_php src/User.php 'function doUser(): string +{ + return \ResultCacheE2ESymbolLookups\Limit; +}' + analyse + assert_contains 'User.php:7:Constant ResultCacheE2ESymbolLookups\Limit not found.' "$OUTPUT" + write_php src/constants.php 'const LIMIT = 1;' + # Limit is still missing, only the new file is analysed + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'User.php:7:Constant ResultCacheE2ESymbolLookups\Limit not found.' "$OUTPUT" +} + +function test_ignored_error_about_a_missing_function() { + write_php src/User.php 'function doUser(): void +{ + \ResultCacheE2ESymbolLookups\helper(); // @phpstan-ignore function.notFound +}' + analyse + assert_same '0' "$CODE" + write_php src/helper.php 'function helper(): void +{ +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:No error with identifier function.notFound is reported on line 7.' "$OUTPUT" +} + +function test_function_appears_in_an_existing_scanned_file() { + # no analysed file depends on scanned/helpers.php before the function appears in it + write_php scanned/helpers.php 'function otherHelper(): void +{ +}' + write_php src/User.php 'function doUser(): int +{ + return \ResultCacheE2ESymbolLookups\helper(); +}' + analyse + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\helper not found.' "$OUTPUT" + write_php scanned/helpers.php 'function otherHelper(): void +{ +} + +function helper(): string +{ + return ""; +}' + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return int but returns string.' "$OUTPUT" +} + +function test_removed_trait() { + write_php src/Greets.php 'trait Greets +{ + + public function greet(): string + { + return "hello"; + } + +}' + write_php src/Greeter.php 'class Greeter +{ + + use Greets; + +}' + write_php src/User.php 'function doUser(): string +{ + return (new Greeter())->greet(); +}' + analyse + assert_same '0' "$CODE" + rm src/Greets.php + # src/Greeter.php used the trait, src/User.php called its method + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'Greeter.php:8:Class ResultCacheE2ESymbolLookups\Greeter uses unknown trait ResultCacheE2ESymbolLookups\Greets.' "$OUTPUT" +} + +function test_class_moved_to_another_file() { + THING='class Thing +{ + + public function size(): int + { + return 1; + } + +}' + write_php src/Thing.php "$THING" + write_php src/User.php 'function doUser(): int +{ + return (new Thing())->size(); +}' + analyse + assert_same '0' "$CODE" + rm src/Thing.php + write_php src/Things.php "$THING" + # src/Things.php is new, src/User.php found the class in the deleted file + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_same '0' "$CODE" + # the class is found in its new file now + write_php src/Things.php "${THING/int/string}" + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return int but returns string.' "$OUTPUT" +} + +function test_constant_declared_by_define() { + write_php src/User.php 'function doUser(): string +{ + return \ResultCacheE2ESymbolLookups\LIMIT; +}' + analyse + assert_contains 'User.php:7:Constant ResultCacheE2ESymbolLookups\LIMIT not found.' "$OUTPUT" + write_php src/constants.php 'define('"'"'ResultCacheE2ESymbolLookups\LIMIT'"'"', 1);' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return string but returns int.' "$OUTPUT" + rm src/constants.php + assert_files_to_analyse 1 + assert_same_as_cold_run + assert_contains 'User.php:7:Constant ResultCacheE2ESymbolLookups\LIMIT not found.' "$OUTPUT" +} + +function test_function_declared_conditionally() { + write_php src/User.php 'function doUser(): int +{ + return \ResultCacheE2ESymbolLookups\helper(); +}' + analyse + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\helper not found.' "$OUTPUT" + write_php src/helper.php 'if (!function_exists('"'"'ResultCacheE2ESymbolLookups\helper'"'"')) { + function helper(): string + { + return ""; + } +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\doUser() should return int but returns string.' "$OUTPUT" + write_php src/helper.php 'function other(): void +{ +}' + assert_files_to_analyse 2 + assert_same_as_cold_run + assert_contains 'User.php:7:Function ResultCacheE2ESymbolLookups\helper not found.' "$OUTPUT" +} + +# }}} diff --git a/e2e/result-cache-symbol-lookups/rules/CollectedReplacementRule.php b/e2e/result-cache-symbol-lookups/rules/CollectedReplacementRule.php new file mode 100644 index 00000000000..1d3ca380555 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/rules/CollectedReplacementRule.php @@ -0,0 +1,49 @@ + + */ +final class CollectedReplacementRule implements Rule +{ + + public function __construct(private ReflectionProvider $reflectionProvider) + { + } + + public function getNodeType(): string + { + return CollectedDataNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$this->reflectionProvider->hasClass('ResultCacheE2ESymbolLookups\Lib\CollectedReplacement')) { + return []; + } + + $errors = []; + foreach ($node->get(LegacyCallCollector::class) as $file => $lines) { + foreach ($lines as $line) { + $errors[] = RuleErrorBuilder::message('Use CollectedReplacement instead of collectedLegacyCall().') + ->identifier('e2e.collectedReplacement') + ->file($file) + ->line($line) + ->build(); + } + } + + return $errors; + } + +} diff --git a/e2e/result-cache-symbol-lookups/rules/LegacyCallCollector.php b/e2e/result-cache-symbol-lookups/rules/LegacyCallCollector.php new file mode 100644 index 00000000000..9362b98fd44 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/rules/LegacyCallCollector.php @@ -0,0 +1,31 @@ + + */ +final class LegacyCallCollector implements Collector +{ + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): ?int + { + if (!$node->name instanceof Name || $node->name->toLowerString() !== 'collectedlegacycall') { + return null; + } + + return $node->getStartLine(); + } + +} diff --git a/e2e/result-cache-symbol-lookups/rules/ReplacementRule.php b/e2e/result-cache-symbol-lookups/rules/ReplacementRule.php new file mode 100644 index 00000000000..c5e52fe99a9 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/rules/ReplacementRule.php @@ -0,0 +1,43 @@ + + */ +final class ReplacementRule implements Rule +{ + + public function __construct(private ReflectionProvider $reflectionProvider) + { + } + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Name || $node->name->toLowerString() !== 'legacycall') { + return []; + } + + if (!$this->reflectionProvider->hasClass('ResultCacheE2ESymbolLookups\Replacement')) { + return []; + } + + return [RuleErrorBuilder::message('Use Replacement instead of legacyCall().')->identifier('e2e.replacement')->build()]; + } + +} diff --git a/e2e/result-cache-symbol-lookups/scanned/.gitkeep b/e2e/result-cache-symbol-lookups/scanned/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/e2e/result-cache-symbol-lookups/src/Other.php b/e2e/result-cache-symbol-lookups/src/Other.php new file mode 100644 index 00000000000..12f4c7557e8 --- /dev/null +++ b/e2e/result-cache-symbol-lookups/src/Other.php @@ -0,0 +1,8 @@ +&1) && CODE=0 || CODE=$? assert_same "1" "$CODE" echo "$OUTPUT" assert_contains 'Foo.php:10:Parameter $logger of method ResultCacheE2EVendorClassAppears\Foo::doFoo() has invalid type Psr\Log\PluginProvidedLogger.' "$OUTPUT" # Composer updates the package, and a plugin writes the class into it on the way - which is # what phpstan/phpstan#15164 is about. Nothing the cache knows about points at that file, - # so the files with errors have to be re-analysed on a package change; otherwise the error - # stands while a run from a cleared cache reports nothing. + # but the class is no longer missing, so the file that looked it up is re-analysed; + # otherwise the error stands while a run from a cleared cache reports nothing. patch -p0 < updatePsrLog.patch composer update psr/log --no-cache cp plugin-writes/PluginProvidedLogger.php vendor/psr/log/src/PluginProvidedLogger.php OUTPUT=$(../../bin/phpstan analyse -vv --error-format raw 2>&1) && CODE=0 || CODE=$? assert_same "0" "$CODE" echo "$OUTPUT" - assert_contains 'Composer packages changed (psr/log); re-analysing the files depending on them and the files with errors.' "$OUTPUT" + assert_contains 'Composer packages changed (psr/log); re-analysing the files depending on them.' "$OUTPUT" assert_not_contains 'has invalid type Psr\Log\PluginProvidedLogger' "$OUTPUT" } diff --git a/src/Analyser/AnalysedDeclarationDependencyCollector.php b/src/Analyser/AnalysedDeclarationDependencyCollector.php index b02844a7ae8..fea52c1ea0c 100644 --- a/src/Analyser/AnalysedDeclarationDependencyCollector.php +++ b/src/Analyser/AnalysedDeclarationDependencyCollector.php @@ -13,6 +13,9 @@ * UnmatchedIgnoredErrorJudge follows it from the files reached through AnalysedFileDependencyCollector data. * It is not registered as a collector, the data is emitted with CollectedDataEmitter. * + * The result cache makes the same split for the values and symbols a file depends on: the "analysis" and + * "declarations" dependents of ValueDependencyCollector. + * * @implements CollectorWithPaths */ final class AnalysedDeclarationDependencyCollector implements CollectorWithPaths diff --git a/src/Analyser/AnalysedFileDependencyCollector.php b/src/Analyser/AnalysedFileDependencyCollector.php index 969b52a2c7b..c4a0eb007e0 100644 --- a/src/Analyser/AnalysedFileDependencyCollector.php +++ b/src/Analyser/AnalysedFileDependencyCollector.php @@ -13,6 +13,9 @@ * of the declarations in a file depends on is AnalysedDeclarationDependencyCollector data. It is not registered as a collector, * the data is emitted with CollectedDataEmitter. * + * The result cache makes the same split for the values and symbols a file depends on: the "analysis" and + * "declarations" dependents of ValueDependencyCollector. + * * @implements CollectorWithPaths */ final class AnalysedFileDependencyCollector implements CollectorWithPaths diff --git a/src/Analyser/AnalyserResultFinalizer.php b/src/Analyser/AnalyserResultFinalizer.php index b9a479ac1e7..399d6f44f7c 100644 --- a/src/Analyser/AnalyserResultFinalizer.php +++ b/src/Analyser/AnalyserResultFinalizer.php @@ -6,6 +6,7 @@ use PHPStan\AnalysedCodeException; use PHPStan\Analyser\Ignore\LineIgnoreFixer; use PHPStan\Analyser\Ignore\UnmatchedIgnoreFixer; +use PHPStan\Analyser\ResultCache\AppearedSymbols; use PHPStan\Analyser\ResultCache\LazyCollectedData; use PHPStan\Analyser\ResultCache\UnreadableCollectedDataException; use PHPStan\BetterReflection\NodeCompiler\Exception\UnableToCompileNode; @@ -65,6 +66,8 @@ public function __construct( * previous run, from the result cache - a rule whose input did not change reuses its errors. * Only with the reuseCollectedDataRuleErrors feature toggle, otherwise every rule runs. A rule that * does not call get() on the node always runs. + * @param AppearedSymbols|null $appearedSymbols what may have been declared since they were saved, see + * ResultCache::getAppearedSymbols() - anything when null */ public function finalize( AnalyserResult $analyserResult, @@ -73,8 +76,10 @@ public function finalize( ?Closure $preRuleCallback = null, ?Closure $postRuleCallback = null, array $previousCollectedDataRuleResults = [], + ?AppearedSymbols $appearedSymbols = null, ): FinalizerResult { + $appearedSymbols ??= AppearedSymbols::anything(); if ($analyserResult->getLazyCollectedData()->isEmpty()) { return $this->processInlineIgnores($this->mergeFilteredPhpErrors($analyserResult), [], []); } @@ -115,7 +120,7 @@ public function finalize( $ruleKey = sprintf('%s#%d', $ruleClass, $ruleCountsByClass[$ruleClass]); $previousResult = $this->reuseCollectedDataRuleErrors ? $previousCollectedDataRuleResults[$ruleKey] ?? null : null; - if ($previousResult !== null && $this->canReuse($previousResult, $onlyFiles, $hashCollector, $currentValues)) { + if ($previousResult !== null && $this->canReuse($previousResult, $onlyFiles, $hashCollector, $appearedSymbols, $currentValues)) { $collectedDataRuleResults[$ruleKey] = $previousResult; $reusedRulesCount++; $collectedDataRuleSkipped = $collectedDataRuleSkipped || $previousResult->getOnlyFiles() === true; @@ -133,7 +138,10 @@ public function finalize( } try { $ruleErrors = $rule->processNode($ruleNode, $scope); - $ruleValueDependencies = $this->valueDependencyCollector->getCollectedDataRuleValues(); + // a rule that never asked for collected data works with something else, so it runs + // every time - its result is not kept, and neither are the values it depends on + $isReusable = $this->reuseCollectedDataRuleErrors && $reads->getCollectorTypes() !== []; + $ruleValueDependencies = $isReusable ? $this->valueDependencyCollector->getCollectedDataRuleValues() : []; // the rule may have caught the read error and reported errors from partial data $unreadableException = $collectedData->getUnreadableException(); if ($unreadableException !== null) { @@ -192,8 +200,7 @@ public function finalize( $errors[] = $this->ruleErrorTransformer->transform($ruleError, $scope, [], $ruleNode); } - // a rule that never asked for collected data works with something else, so it runs every time - if ($this->reuseCollectedDataRuleErrors && $reads->getCollectorTypes() !== []) { + if ($isReusable) { $collectedDataRuleResults[$ruleKey] = $this->createRuleResult($reads, $onlyFiles, $hashCollector, $errors, $ruleValueDependencies); } @@ -289,7 +296,7 @@ private function createRuleResult(CollectedDataNodeReads $reads, bool $onlyFiles * @param Closure(string): string $hashCollector * @param array $currentValues id => value, asked for once per run - every rule shares the values of the classes */ - private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFiles, Closure $hashCollector, array &$currentValues): bool + private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFiles, Closure $hashCollector, AppearedSymbols $appearedSymbols, array &$currentValues): bool { $previousOnlyFiles = $previousResult->getOnlyFiles(); if ($previousOnlyFiles !== null && $previousOnlyFiles !== $onlyFiles) { @@ -310,7 +317,10 @@ private function canReuse(CollectedDataRuleResult $previousResult, bool $onlyFil } $id = ValueDependencyCollector::getId($extensionClass, $storedKey); - $currentValues[$id] ??= $extension->getValue($extension->keyFromResultCache($storedKey)); + $key = $extension->keyFromResultCache($storedKey); + $currentValues[$id] ??= $value === ValueDependencyCollector::MISSING && $appearedSymbols->isStillMissing($extensionClass, $key) + ? ValueDependencyCollector::MISSING + : $extension->getValue($key); if ($currentValues[$id] !== $value) { return false; } diff --git a/src/Analyser/FileAnalyser.php b/src/Analyser/FileAnalyser.php index bcb0a7dca0e..682db029517 100644 --- a/src/Analyser/FileAnalyser.php +++ b/src/Analyser/FileAnalyser.php @@ -9,7 +9,10 @@ use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound; use PHPStan\Collectors\CollectedData; use PHPStan\Collectors\Registry as CollectorRegistry; +use PHPStan\Dependency\Dependencies; use PHPStan\Dependency\DependencyResolver; +use PHPStan\Dependency\ResolvedDependencies; +use PHPStan\Dependency\RootExportedNode; use PHPStan\DependencyInjection\AutowiredExtensions; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; @@ -18,6 +21,9 @@ use PHPStan\Parser\Parser; use PHPStan\Parser\ParserErrorsException; use PHPStan\Rules\Registry as RuleRegistry; +use function array_fill_keys; +use function array_keys; +use function array_merge; use function array_unique; use function array_values; use function count; @@ -73,6 +79,93 @@ public function __construct( { } + /** + * The files declaring what the code references, and what the reflection layer found by name - + * from a string, a PHPDoc, a rule asking - during the analysis of the file, or while resolving + * the declarations it depends on: those of the symbols it depends on, and every one of its own. + * Those are remembered for the rest of the process and reused without asking again, so what they + * found is what every file depending on them depends on - also through the declarations of what + * they found. + * + * @param list $exportedNodes what the analysed file declares + * @param array $analysedFiles + */ + private function resolveDependenciesWithFoundSymbols(string $file, ?Dependencies $dependencies, array $exportedNodes, array $analysedFiles): ResolvedDependencies + { + $resolvedDependencies = $this->dependencyResolver->resolveFileDependencies($dependencies, $analysedFiles); + $fileDependencies = array_fill_keys($resolvedDependencies->getFileDependencies(), true); + $usedTraitFileDependencies = $resolvedDependencies->getUsedTraitFileDependencies(); + $packageDependencies = $resolvedDependencies->getPackageDependencies(); + $classReflections = $resolvedDependencies->getClassReflections(); + + // the declarations depended on - every one of the analysed file, and those of the symbols + // depended on; what was found while resolving them is depended on too + $declarationKeys = $this->valueDependencyCollector->getDeclarationKeysOfFile($file); + foreach ($exportedNodes as $exportedNode) { + if ($exportedNode->getType() === RootExportedNode::TYPE_FUNCTION) { + $declarationKeys[] = ValueDependencyCollector::getFunctionDeclarationKey($exportedNode->getName()); + } elseif ($exportedNode->getType() !== RootExportedNode::TYPE_CONSTANT) { + $declarationKeys[] = ValueDependencyCollector::getClassDeclarationKey($exportedNode->getName()); + } + } + $keysToFollow = []; + $followedKeys = []; + $addDeclarationKeys = static function (ResolvedDependencies $resolved, array $newFiles, array $keys) use (&$keysToFollow, &$followedKeys): void { + foreach ($newFiles as $newFile) { + $keys[] = ValueDependencyCollector::getFileDeclarationKey($newFile); + } + foreach ($resolved->getClassReflections() as $classReflection) { + $keys[] = ValueDependencyCollector::getClassDeclarationKey($classReflection->getName()); + } + foreach ($resolved->getFunctionNames() as $functionName) { + $keys[] = ValueDependencyCollector::getFunctionDeclarationKey($functionName); + } + foreach ($keys as $key) { + if (isset($followedKeys[$key])) { + continue; + } + + $followedKeys[$key] = true; + $keysToFollow[] = $key; + } + }; + $addDeclarationKeys($resolvedDependencies, [$file, ...array_keys($fileDependencies)], $declarationKeys); + + $includeAnalysis = true; + while ($keysToFollow !== [] || $includeAnalysis) { + $foundDependencies = $this->dependencyResolver->createFoundSymbolDependencies( + $file, + $this->valueDependencyCollector->getFoundSymbols($keysToFollow, $includeAnalysis), + ); + $includeAnalysis = false; + $keysToFollow = []; + if ($foundDependencies === null) { + break; + } + + $resolvedFoundDependencies = $this->dependencyResolver->resolveFileDependencies($foundDependencies, $analysedFiles); + $newFiles = []; + foreach ($resolvedFoundDependencies->getFileDependencies() as $foundFile) { + if (isset($fileDependencies[$foundFile])) { + continue; + } + + $fileDependencies[$foundFile] = true; + $newFiles[] = $foundFile; + } + $addDeclarationKeys($resolvedFoundDependencies, $newFiles, []); + $packageDependencies = array_merge($packageDependencies, $resolvedFoundDependencies->getPackageDependencies()); + $classReflections = array_merge($classReflections, $resolvedFoundDependencies->getClassReflections()); + } + + return new ResolvedDependencies( + array_keys($fileDependencies), + $usedTraitFileDependencies, + array_values(array_unique($packageDependencies)), + $classReflections, + ); + } + /** * @param array $analysedFiles * @param callable(Node $node, Scope $scope): void|null $outerNodeCallback @@ -132,7 +225,8 @@ public function analyseFile( ); $fileErrors = $nodeCallback->getFileErrors(); $fileCollectedData = $nodeCallback->getFileCollectedData(); - $resolvedDependencies = $this->dependencyResolver->resolveFileDependencies($dependencies, $analysedFiles); + $exportedNodes = $nodeCallback->getExportedNodes(); + $resolvedDependencies = $this->resolveDependenciesWithFoundSymbols($file, $dependencies, $exportedNodes, $analysedFiles); $fileDependencies = $resolvedDependencies->getFileDependencies(); $usedTraitFileDependencies = $resolvedDependencies->getUsedTraitFileDependencies(); $filePackageDependencies = $resolvedDependencies->getPackageDependencies(); @@ -140,7 +234,6 @@ public function analyseFile( // what an extension described the class with may depend on something - see DeclarationDependencyTracker $this->valueDependencyCollector->noteClassDependency($classReflection); } - $exportedNodes = $nodeCallback->getExportedNodes(); $linesToIgnore = $nodeCallback->getLinesToIgnore(); $unmatchedLineIgnores = $nodeCallback->getUnmatchedLineIgnores(); $temporaryFileErrors = $nodeCallback->getTemporaryFileErrors(); diff --git a/src/Analyser/NameScope.php b/src/Analyser/NameScope.php index 685927eb279..874008314e6 100644 --- a/src/Analyser/NameScope.php +++ b/src/Analyser/NameScope.php @@ -44,11 +44,20 @@ public function __construct( private bool $bypassTypeAliases = false, private array $constUses = [], private ?string $typeAliasClassName = null, + private ?string $fileName = null, ) { $this->templateTypeMap = $templateTypeMap ?? TemplateTypeMap::createEmpty(); } + /** + * The file the PHPDoc resolved in this scope is in, if it is in one. + */ + public function getFileName(): ?string + { + return $this->fileName; + } + public function getNamespace(): ?string { return $this->namespace; @@ -80,6 +89,11 @@ public function getClassName(): ?string return $this->className; } + public function getFunctionName(): ?string + { + return $this->functionName; + } + public function getClassNameForTypeAlias(): ?string { return $this->typeAliasClassName ?? $this->className; @@ -196,6 +210,7 @@ public function withTemplateTypeMap(TemplateTypeMap $map, array $templateTags): $this->typeAliasesMap, $this->bypassTypeAliases, $this->constUses, + fileName: $this->fileName, ); } @@ -211,6 +226,7 @@ public function withoutNamespaceAndUses(): self $this->typeAliasesMap, $this->bypassTypeAliases, $this->constUses, + fileName: $this->fileName, ); } @@ -226,6 +242,7 @@ public function withClassName(string $className): self $this->typeAliasesMap, $this->bypassTypeAliases, $this->constUses, + fileName: $this->fileName, ); } @@ -246,12 +263,13 @@ public function unsetTemplateType(string $name): self $this->typeAliasesMap, $this->bypassTypeAliases, $this->constUses, + fileName: $this->fileName, ); } public function bypassTypeAliases(): self { - return new self($this->namespace, $this->uses, $this->className, $this->functionName, $this->templateTypeMap, $this->templateTags, $this->typeAliasesMap, true, $this->constUses); + return new self($this->namespace, $this->uses, $this->className, $this->functionName, $this->templateTypeMap, $this->templateTags, $this->typeAliasesMap, true, $this->constUses, fileName: $this->fileName); } public function shouldBypassTypeAliases(): bool diff --git a/src/Analyser/ResultCache/AppearedSymbols.php b/src/Analyser/ResultCache/AppearedSymbols.php new file mode 100644 index 00000000000..9ba59aa8867 --- /dev/null +++ b/src/Analyser/ResultCache/AppearedSymbols.php @@ -0,0 +1,92 @@ +|null $names lowercase names that may have been declared, null when anything may have + */ + private function __construct(private ?array $names) + { + } + + /** + * Anything may have been declared - every missing symbol is looked up again. + */ + public static function anything(): self + { + return new self(null); + } + + /** + * @param list $names declared by the files that are new or changed + */ + public static function fromNames(array $names): self + { + $lowercaseNames = []; + foreach ($names as $name) { + $lowercaseNames[strtolower($name)] = true; + } + + return new self($lowercaseNames); + } + + /** + * Whether a value of the extension that was ValueDependencyCollector::MISSING is still that, + * known without looking the symbol up. + */ + public function isStillMissing(string $extensionClass, string $key): bool + { + if ($this->names === null) { + return false; + } + + $key = ltrim($key, '\\'); + if (isset($this->names[strtolower($key)])) { + return false; + } + + // a bootstrap file, or a file it requires, declares symbols no tracked file shows - they + // exist at runtime, without autoloading anything + if ($extensionClass === ClassResultCacheValueExtension::class) { + return !class_exists($key, false) && !interface_exists($key, false) && !trait_exists($key, false); + } + if ($extensionClass === FunctionResultCacheValueExtension::class) { + return !function_exists($key); + } + if ($extensionClass === ConstantResultCacheValueExtension::class) { + return !defined($key); + } + + return false; + } + +} diff --git a/src/Analyser/ResultCache/ClassResultCacheValueExtension.php b/src/Analyser/ResultCache/ClassResultCacheValueExtension.php index 5ae12d75a8f..a7c639b8f4f 100644 --- a/src/Analyser/ResultCache/ClassResultCacheValueExtension.php +++ b/src/Analyser/ResultCache/ClassResultCacheValueExtension.php @@ -2,6 +2,7 @@ namespace PHPStan\Analyser\ResultCache; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\Dependency\ExportedNodeFetcher; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\File\FileContentHasher; @@ -29,8 +30,6 @@ final class ClassResultCacheValueExtension implements ResultCacheValueExtension { - private const MISSING_CLASS = 'missing'; - /** @var array}> file => [content hash, lowercase name => exported node JSON] */ private array $exportedNodesByFile = []; @@ -50,13 +49,15 @@ public static function createKey(string $className): string public function getValue(string $key): string { if (!$this->reflectionProvider->hasClass($key)) { - return self::MISSING_CLASS; + return ValueDependencyCollector::MISSING; } $classReflection = $this->reflectionProvider->getClass($key); $declarations = []; foreach ([$classReflection->getName() => $classReflection] + $classReflection->getAncestors() as $name => $declaringClass) { - $fileName = $declaringClass->getFileName(); + // a built-in class is read from a stub, which one depends on the source locator that + // reflected it first; it changes only with PHP, its extensions or PHPStan itself + $fileName = $declaringClass->isBuiltin() ? null : $declaringClass->getFileName(); $declarations[strtolower($name)] = $fileName === null ? 'built-in' : sprintf('%s %s', $fileName, $this->getExportedNode($fileName, $name)); diff --git a/src/Analyser/ResultCache/ConstantResultCacheValueExtension.php b/src/Analyser/ResultCache/ConstantResultCacheValueExtension.php new file mode 100644 index 00000000000..2e7557e14be --- /dev/null +++ b/src/Analyser/ResultCache/ConstantResultCacheValueExtension.php @@ -0,0 +1,64 @@ +reflectionProvider->hasConstant(new FullyQualified($key), null) + ? self::FOUND + : ValueDependencyCollector::MISSING; + } + + public function keyToResultCache(string $key): string + { + return $key; + } + + public function keyFromResultCache(string $storedKey): string + { + return $storedKey; + } + +} diff --git a/src/Analyser/ResultCache/FunctionResultCacheValueExtension.php b/src/Analyser/ResultCache/FunctionResultCacheValueExtension.php new file mode 100644 index 00000000000..c5af7a7e5dc --- /dev/null +++ b/src/Analyser/ResultCache/FunctionResultCacheValueExtension.php @@ -0,0 +1,55 @@ +reflectionProvider->hasFunction(new FullyQualified($key), null) + ? self::FOUND + : ValueDependencyCollector::MISSING; + } + + public function keyToResultCache(string $key): string + { + return $key; + } + + public function keyFromResultCache(string $storedKey): string + { + return $storedKey; + } + +} diff --git a/src/Analyser/ResultCache/ResultCache.php b/src/Analyser/ResultCache/ResultCache.php index 67ed2712887..c5ed9b838a3 100644 --- a/src/Analyser/ResultCache/ResultCache.php +++ b/src/Analyser/ResultCache/ResultCache.php @@ -28,7 +28,6 @@ final class ResultCache * @param array $projectExtensionFiles * @param array $currentFileHashes * @param array $collectedDataRuleResults - * @param list $filesWithCollectedDataRuleErrors the files with errors of the rules on CollectedDataNode */ public function __construct( private array $filesToAnalyse, @@ -49,8 +48,8 @@ public function __construct( private CachedExportedNodes $cachedExportedNodes, private array $projectExtensionFiles, private array $currentFileHashes, + private AppearedSymbols $appearedSymbols, private array $collectedDataRuleResults = [], - private array $filesWithCollectedDataRuleErrors = [], ) { } @@ -191,20 +190,17 @@ public function getCurrentFileHashes(): array return $this->currentFileHashes; } - /** - * @return array - */ - public function getCollectedDataRuleResults(): array + public function getAppearedSymbols(): AppearedSymbols { - return $this->collectedDataRuleResults; + return $this->appearedSymbols; } /** - * @return list + * @return array */ - public function getFilesWithCollectedDataRuleErrors(): array + public function getCollectedDataRuleResults(): array { - return $this->filesWithCollectedDataRuleErrors; + return $this->collectedDataRuleResults; } } diff --git a/src/Analyser/ResultCache/ResultCacheManager.php b/src/Analyser/ResultCache/ResultCacheManager.php index 38e4551cbe7..eb287e27b91 100644 --- a/src/Analyser/ResultCache/ResultCacheManager.php +++ b/src/Analyser/ResultCache/ResultCacheManager.php @@ -33,6 +33,8 @@ use PHPStan\Php\ComposerPhpVersionFactory; use PHPStan\Php\PhpVersion; use PHPStan\PhpDoc\StubFilesProvider; +use PHPStan\Reflection\BetterReflection\SourceLocator\ComposerJsonAndInstalledJsonSourceLocatorMaker; +use PHPStan\Reflection\BetterReflection\SourceLocator\SymbolFinderInFiles; use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider; use PHPStan\ShouldNotHappenException; use ReflectionClass; @@ -47,7 +49,6 @@ use function array_is_list; use function array_key_exists; use function array_keys; -use function array_map; use function array_merge; use function array_unique; use function array_values; @@ -94,6 +95,7 @@ use function uniqid; use function unlink; use function unserialize; +use const DIRECTORY_SEPARATOR; use const PHP_VERSION_ID; use const SEEK_CUR; @@ -116,7 +118,7 @@ final class ResultCacheManager */ private const EXTENSIONS_NOT_INVALIDATING_CACHE = ['xdebug', 'blackfire', 'phpstan_turbo']; - private const CACHE_VERSION = 'v27-exportedNodesSignatureDetails'; + private const CACHE_VERSION = 'v28-symbolLookups'; /** * The recorded hash of a dependency that does not exist. A rule can depend on a path rather than on @@ -132,18 +134,15 @@ final class ResultCacheManager */ private const REANALYSE_FILE_HASH_PREFIX = 'reanalyse:'; - private const SCANNED_FILE_APPEARED = 'appeared'; - private const SCANNED_FILE_EDITED = 'edited'; - private const SCANNED_FILE_GONE = 'gone'; - /** * Metadata keys whose change does not invalidate the whole result cache: the analysed files they * affect can be pinpointed and re-analysed on their own. See restore(). * - * The scannedFiles entry covers scanFiles, scanDirectories and the files excluded from the - * analysis but living in an analysed directory - see getScannedFiles(). The bootstrapFiles are - * deliberately not here: they are executed, not just read, so a change in one of them can affect - * anything about the analysis. They stay in the fully invalidating executedFilesHashes entry. + * The scannedFiles entry covers scanFiles, scanDirectories, the files excluded from the + * analysis but living in an analysed directory, and the files of the project's Composer autoload + * entries - see getScannedFiles(). The bootstrapFiles are deliberately not here: they are + * executed, not just read, so a change in one of them can affect anything about the analysis. + * They stay in the fully invalidating executedFilesHashes entry. */ private const PARTIALLY_INVALIDATING_META_KEYS = ['composerLocks', 'composerInstalled', 'extensionVersions', 'scannedFiles']; @@ -266,6 +265,10 @@ public function __construct( private ComposerPhpVersionFactory $composerPhpVersionFactory, private FileStatSignatures $fileStatSignatures, private ValueDependencyCollector $valueDependencyCollector, + private SymbolFinderInFiles $symbolFinderInFiles, + private ComposerJsonAndInstalledJsonSourceLocatorMaker $composerSourceLocatorMaker, + #[AutowiredParameter] + private string $tmpDir, ) { } @@ -324,6 +327,7 @@ private function fullAnalysis( cachedExportedNodes: CachedExportedNodes::createEmpty(), projectExtensionFiles: [], currentFileHashes: $currentFileHashes, + appearedSymbols: AppearedSymbols::anything(), ); } @@ -483,11 +487,13 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? // absolutized above, so it is always present here $packageDependencies = $data['packageDependencies']; $packageSeededFiles = []; - $notAnalysedFileSymbolsChanged = false; // Scanned files whose exported nodes differ from the ones the cache holds - the only ones that // make anything be re-analysed. A scanned file can change without any of its symbols changing, // and then nothing here has to happen at all. $scannedFilesWithChangedSymbols = []; + // what may declare a symbol a lookup did not find last time - see AppearedSymbols + $anySymbolMayHaveAppeared = false; + $changedDeclaringFiles = []; $metaDifferent = $this->isMetaDifferent($data['meta'], $meta); if ($metaDifferent) { $diffs = $this->getMetaKeyDifferences($data['meta'], $meta); @@ -514,20 +520,20 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? // treats an analysed file: the files depending on it are re-analysed only when its // exported nodes changed, and it is that loop which counts it as changed. What is left // for the metadata to notice is a file the dependency graph does not know: one that - // appeared, or an edited one nothing depends on. Either may define a symbol that was - // reported as unknown somewhere - if it declares any symbol at all - so the files with - // errors are re-analysed the same way a new analysed file makes them re-analysed. The - // previous nodes of a file nothing depends on are not kept, so for it "declares a symbol" - // stands in for "declares a new symbol". - $changedScannedFiles = $this->getChangedScannedFiles($data['meta'], $meta); - foreach ($changedScannedFiles as $changedScannedFile => $change) { + // appeared, or an edited one nothing depends on. A symbol it declares now was looked up + // and not found by the files waiting for it, which recorded that as a value dependency. + foreach ($this->getChangedScannedFiles($data['meta'], $meta) as $changedScannedFile) { // The scanned files getFileAndPackageDependencies() leaves out: nothing would - // re-analyse the files depending on them, so the whole cache has to go. + // re-analyse the files depending on them, so the whole cache has to go. A package from a + // path repository is the project's own code and is tracked file by file. $notTrackedReason = null; if (str_starts_with($changedScannedFile, 'phar://')) { $notTrackedReason = 'is inside a PHAR'; - } elseif ($this->packageDependencyResolver->resolvePackage($changedScannedFile) !== null) { - $notTrackedReason = 'belongs to a Composer package'; + } else { + $package = $this->packageDependencyResolver->resolvePackage($changedScannedFile); + if ($package !== null && !$this->packageDependencyResolver->isPathPackage($package)) { + $notTrackedReason = 'belongs to a Composer package'; + } } if ($notTrackedReason !== null) { @@ -540,20 +546,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? ); } - if ($change === self::SCANNED_FILE_GONE) { - continue; - } - - if ($change === self::SCANNED_FILE_EDITED && array_key_exists($changedScannedFile, $data['dependencies'])) { - continue; - } - - if ($this->exportedNodeFetcher->fetchNodes($changedScannedFile) === []) { - continue; - } - - $scannedFilesWithChangedSymbols[$changedScannedFile] = true; - $notAnalysedFileSymbolsChanged = true; + $changedDeclaringFiles[$changedScannedFile] = true; } } @@ -614,7 +607,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? if ($output->isVeryVerbose()) { $output->writeLineFormatted(sprintf( - 'Composer packages changed (%s); re-analysing the files depending on them and the files with errors.', + 'Composer packages changed (%s); re-analysing the files depending on them.', implode(', ', $changedPackages), )); } @@ -622,20 +615,16 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? if ($changedExtensionPackages !== [] && $output->isVeryVerbose()) { $output->writeLineFormatted(sprintf( - 'PHP extension versions changed (%s); re-analysing the files depending on them and the files with errors.', + 'PHP extension versions changed (%s); re-analysing the files depending on them.', implode(', ', $changedExtensionPackages), )); } if ($changedPackages !== [] || $changedExtensionPackages !== []) { - // The files depending on a changed package are seeded below, but a file whose error is - // that a class does not exist depends on nothing: there was no file to record an edge to. - // An installed package is exactly where such a class tends to arrive from - Composer - // unpacking a new version, or a plugin writing into vendor/ while it does - and so is a - // newly selected extension version, so the files with errors are re-analysed too, the - // same way a new analysed file makes them. - $notAnalysedFileSymbolsChanged = true; - + // The files depending on a changed package are seeded below. A symbol a package declares + // now was looked up and not found by the files waiting for it, which recorded that as a + // value dependency. + $anySymbolMayHaveAppeared = true; $changedPackagesLookup = array_fill_keys(array_merge($changedPackages, $changedExtensionPackages), true); foreach ($packageDependencies as $packageDependentFile => $filePackages) { foreach ($filePackages as $filePackage) { @@ -747,18 +736,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? } } $collectedDataRuleResults = $transformer->absolutizeCollectedDataRuleResults($collectedDataRuleResults); - $storedFilesWithCollectedDataRuleErrors = $data['filesWithCollectedDataRuleErrors'] ?? []; - if (!is_array($storedFilesWithCollectedDataRuleErrors)) { - throw new RuntimeException('The cached files with errors of the rules on collected data are not an array.'); - } - $filesWithCollectedDataRuleErrors = []; - foreach ($storedFilesWithCollectedDataRuleErrors as $fileWithCollectedDataRuleError) { - if (!is_string($fileWithCollectedDataRuleError)) { - throw new RuntimeException('A cached file with errors of the rules on collected data is not a string.'); - } - - $filesWithCollectedDataRuleErrors[] = $transformer->absolutizePath($fileWithCollectedDataRuleError); - } } catch (Throwable $e) { @unlink($cacheFilePath); @@ -778,7 +755,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? $filteredExportedNodes = []; // the analysed and scanned files whose exported nodes stay in the old cache file until save() $keptCachedExportedNodes = []; - $newFileAppeared = false; $dependencyFilesChanged = false; $cachedExportedNodesError = null; $decodeCachedExportedNodes = static function (string $file) use ($cachedExportedNodes, &$cachedExportedNodesError): array { @@ -800,8 +776,8 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? } // Whether a changed file's exported nodes changed decides what else has to be re-analysed with - // it: its dependents, the classes using a trait it declares, and - when a symbol appeared or - // disappeared - the files with errors. Finding out means parsing the file, serially here in + // it: its dependents and the classes using a trait it declares. Finding out means parsing the + // file, serially here in // the main process. When all of those files are re-analysed anyway, because they changed // themselves, the answer cannot add anything and the file is not parsed. After a branch switch // or a formatting run that touched most of the project, that is most of the changed files - @@ -817,39 +793,12 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? } $changedAnalysedFiles[$analysedFile] = true; + $changedDeclaringFiles[$analysedFile] = true; } - // The errors of the rules on CollectedDataNode are not in $errors: those rules run on the merged - // collected data on every run, a cached copy would be reported twice. But such an error waits - // for a symbol to appear just like any other, and re-analysing its file renews the file's share - // of the collected data. - $cachedFilesWithCollectedDataRuleErrors = array_fill_keys($filesWithCollectedDataRuleErrors, true); - $filteredFilesWithCollectedDataRuleErrors = []; - - // only the stub files with errors so far, which are never analysed - $filesWithErrorsAllChanged = $filteredErrors === []; - foreach ($allAnalysedFiles as $analysedFile) { - if ( - ( - !array_key_exists($analysedFile, $errors) - && !array_key_exists($analysedFile, $locallyIgnoredErrors) - && !array_key_exists($analysedFile, $cachedFilesWithCollectedDataRuleErrors) - ) - || array_key_exists($analysedFile, $changedAnalysedFiles) - ) { - continue; - } - - $filesWithErrorsAllChanged = false; - break; - } - foreach ($allAnalysedFiles as $analysedFile) { if (array_key_exists($analysedFile, $errors)) { $filteredErrors[$analysedFile] = $errors[$analysedFile]; } - if (array_key_exists($analysedFile, $cachedFilesWithCollectedDataRuleErrors)) { - $filteredFilesWithCollectedDataRuleErrors[] = $analysedFile; - } if (array_key_exists($analysedFile, $locallyIgnoredErrors)) { $filteredLocallyIgnoredErrors[$analysedFile] = $locallyIgnoredErrors[$analysedFile]; } @@ -870,7 +819,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? if (!array_key_exists($analysedFile, $invertedDependencies)) { // new file $filesToAnalyse[] = $analysedFile; - $newFileAppeared = true; continue; } @@ -892,25 +840,21 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? $filesToAnalyse[] = $analysedFile; if ( - ($filesWithErrorsAllChanged || $newFileAppeared) - && $this->areAllChanged($dependentFiles, $changedAnalysedFiles) + $this->areAllChanged($dependentFiles, $changedAnalysedFiles) && $this->areAllChanged($usedTraitDependentFiles, $changedAnalysedFiles) ) { continue; } // A file that declared nothing has no entry at all - save() only writes one for a file with - // at least one exported node - and a missing entry is not the same as nothing to propagate: - // the file may have gained its first symbol, which is exactly what the files with errors are - // waiting for. Comparing against an empty list says so, and says nothing changed when the + // at least one exported node. Comparing against an empty list says nothing changed when the // file still declares nothing. $fileExportedNodes = $this->exportedNodeFetcher->fetchNodesIfParsable($this->fileReplacements[$analysedFile] ?? $analysedFile); if ($fileExportedNodes === null) { // A parse error, typically code saved half typed. The file is re-analysed and reports it, // but its symbols count as unchanged: the files using them keep their results until it is - // fixed, instead of being analysed against a file that declares nothing, and so do the - // files with errors. process() keeps the symbols it had, which the fixed file is compared - // with. + // fixed, instead of being analysed against a file that declares nothing. process() keeps + // the symbols it had, which the fixed file is compared with. continue; } $cachedFileExportedNodes = $filteredExportedNodes[$analysedFile] @@ -938,10 +882,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? continue; } - if ($exportedNodesChanged) { - $newFileAppeared = true; - } - foreach ($dependentFiles as $dependentFile) { if (!is_file($dependentFile)) { continue; @@ -950,9 +890,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? } } - // in the order process() compares them in - sort($filteredFilesWithCollectedDataRuleErrors); - // the freshly computed metadata, so a file that stopped being scanned is not counted $scannedFiles = is_array($meta['scannedFiles'] ?? null) ? $meta['scannedFiles'] : []; foreach (array_keys($notAnalysedFiles) as $notAnalysedFile) { @@ -978,6 +915,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? if (is_file($notAnalysedFile) && $wasMissing) { $dependencyFilesChanged = true; + $changedDeclaringFiles[$notAnalysedFile] = true; // It exists now. Whether it holds any symbol is beside the point - a file that was named // and was not there is now there, and that alone changes what the analysis says. $invertedDependenciesToReturn[$notAnalysedFile] = $dependentFiles; @@ -1008,6 +946,7 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? ?? ($cachedExportedNodes->has($notAnalysedFile) ? $decodeCachedExportedNodes($notAnalysedFile) : null); $dependencyFilesChanged = true; + $changedDeclaringFiles[$notAnalysedFile] = true; // Edited: the same rule as for an analysed file. Nothing the files depending on it can // see changed unless its exported nodes did, so a body-only edit re-analyses nothing - // except the classes using a trait declared here, whose body is analysed in their @@ -1036,25 +975,11 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? $scannedFilesWithChangedSymbols[$notAnalysedFile] = true; } - if ($exportedNodesChanged) { - // A symbol appeared or disappeared. The dependents are not enough then: a file that - // reported the symbol as unknown - or referenced this file while it had a syntax error - // and no symbols at all - recorded no edge to it, so only the files with errors can - // bring it back, the same way a new analysed file makes them re-analysed. - $notAnalysedFileSymbolsChanged = true; - } - $dependentFiles = array_merge($dependentFiles, $usedTraitDependentFiles); } else { + // Deleted. The files that found its symbols depend on it, by name too - see + // ValueDependencyCollector::recordFoundSymbol(). $dependencyFilesChanged = true; - // Deleted. The files using its symbols depend on it and are re-analysed, but a file can - // also have an error because a symbol exists - a dead catch of ReflectionException, a - // comparison with a class name that is always false - without depending on its file. - $deletedFileExportedNodes = $exportedNodes[$notAnalysedFile] - ?? ($cachedExportedNodes->has($notAnalysedFile) ? $decodeCachedExportedNodes($notAnalysedFile) : []); - if (count($deletedFileExportedNodes) > 0) { - $notAnalysedFileSymbolsChanged = true; - } } foreach ($dependentFiles as $dependentFile) { @@ -1083,10 +1008,22 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? $allAnalysedFilesSet = array_fill_keys($allAnalysedFiles, true); $valueDependenciesToReturn = []; $valueDependenciesChanged = false; + $appearedSymbols = $anySymbolMayHaveAppeared + ? AppearedSymbols::anything() + : $this->getSymbolsDeclaredIn(array_keys($changedDeclaringFiles)); foreach ($cachedValueDependencies as $cachedValueDependency) { $extension = $this->valueDependencyCollector->getExtension($cachedValueDependency['extensionClass']); $key = $extension?->keyFromResultCache($cachedValueDependency['storedKey']); - $currentValue = $extension !== null && $key !== null ? $extension->getValue($key) : null; + if ($extension === null || $key === null) { + $currentValue = null; + } elseif ( + $cachedValueDependency['value'] === ValueDependencyCollector::MISSING + && $appearedSymbols->isStillMissing($cachedValueDependency['extensionClass'], $key) + ) { + $currentValue = ValueDependencyCollector::MISSING; + } else { + $currentValue = $extension->getValue($key); + } if ($currentValue !== $cachedValueDependency['value']) { $valueDependenciesChanged = true; foreach ($this->getValueDependentFilesToAnalyse($cachedValueDependency['analysis'], $cachedValueDependency['declarations'], $invertedDependencies, $allAnalysedFilesSet) as $valueDependentFile) { @@ -1106,26 +1043,6 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? ]; } - if ($newFileAppeared || $notAnalysedFileSymbolsChanged) { - foreach (array_keys($filteredErrors) as $fileWithError) { - // A stub file has errors from the stub validation, which runs on the full analysis only. - // It is not an analysed file, so analysing it would report the errors of all rules in it. - if (array_key_exists($fileWithError, $cachedStubFiles)) { - continue; - } - - $filesToAnalyse[] = $fileWithError; - } - // An error ignored by a comment on its line waits for the symbol all the same, and when it - // goes away, the comment no longer matches anything, which is reported. - foreach (array_keys($filteredLocallyIgnoredErrors) as $fileWithError) { - $filesToAnalyse[] = $fileWithError; - } - foreach ($filteredFilesWithCollectedDataRuleErrors as $fileWithError) { - $filesToAnalyse[] = $fileWithError; - } - } - foreach ($packageSeededFiles as $packageSeededFile) { if (!is_file($packageSeededFile)) { continue; @@ -1192,8 +1109,8 @@ public function restore(array $allAnalysedFiles, bool $debug, bool $onlyFiles, ? cachedExportedNodes: $cachedExportedNodes->only($keptCachedExportedNodes), projectExtensionFiles: $data['projectExtensionFiles'], currentFileHashes: $currentFileHashes, + appearedSymbols: $appearedSymbols, collectedDataRuleResults: $collectedDataRuleResults, - filesWithCollectedDataRuleErrors: $filteredFilesWithCollectedDataRuleErrors, ); } @@ -1450,13 +1367,6 @@ public function process(AnalyserResult $analyserResult, ResultCache $resultCache $collectedDataRuleResults = $finalizerResult->getCollectedDataRuleResults(); ksort($collectedDataRuleResults); - $filesWithCollectedDataRuleErrors = []; - foreach ($finalizerResult->getCollectorErrors() as $collectorError) { - $filesWithCollectedDataRuleErrors[$collectorError->getFilePath()] = true; - } - ksort($filesWithCollectedDataRuleErrors); - $filesWithCollectedDataRuleErrors = array_keys($filesWithCollectedDataRuleErrors); - $stubFiles = $this->getStubFiles(); if ( !$resultCache->isFullAnalysis() @@ -1470,7 +1380,6 @@ public function process(AnalyserResult $analyserResult, ResultCache $resultCache && $collectedData->getFresh() === [] && $collectedData->getCachedIndex() === $resultCache->getCollectedData()->getCachedIndex() && $collectedDataRuleResults === $resultCache->getCollectedDataRuleResults() - && $filesWithCollectedDataRuleErrors === $resultCache->getFilesWithCollectedDataRuleErrors() && $packageDependencies === $resultCache->getPackageDependencies() && $exportedNodes === $resultCache->getExportedNodes() && $cachedExportedNodes->getFiles() === $resultCache->getCachedExportedNodes()->getFiles() @@ -1490,7 +1399,7 @@ public function process(AnalyserResult $analyserResult, ResultCache $resultCache } try { - $savedCollectedData = $this->save($resultCache->getLastFullAnalysisTime(), $errorsByFile, $locallyIgnoredErrorsByFile, $linesToIgnore, $unmatchedLineIgnores, $collectedData, $dependencies, $usedTraitDependencies, $valueDependencies, $packageDependencies, $exportedNodes, $cachedExportedNodes, $projectExtensionFiles, $currentFileHashes, $meta, $stubFiles, $collectedDataRuleResults, $filesWithCollectedDataRuleErrors); + $savedCollectedData = $this->save($resultCache->getLastFullAnalysisTime(), $errorsByFile, $locallyIgnoredErrorsByFile, $linesToIgnore, $unmatchedLineIgnores, $collectedData, $dependencies, $usedTraitDependencies, $valueDependencies, $packageDependencies, $exportedNodes, $cachedExportedNodes, $projectExtensionFiles, $currentFileHashes, $meta, $stubFiles, $collectedDataRuleResults); } catch (RuntimeException $e) { // Only the copy of the cached collected data throws this: the file it was restored from // no longer holds the entries where the index says, so another run sharing the tmpDir @@ -2044,7 +1953,6 @@ private function mergeUnmatchedLineIgnores(ResultCache $resultCache, array $fres * @param mixed[] $meta * @param array $stubFiles * @param array $collectedDataRuleResults - * @param list $filesWithCollectedDataRuleErrors * @return LazyCollectedData The same collected data, with the cached entries indexed in the saved file */ private function save( @@ -2065,7 +1973,6 @@ private function save( array $meta, array $stubFiles, array $collectedDataRuleResults, - array $filesWithCollectedDataRuleErrors, ): LazyCollectedData { $invertedDependencies = []; @@ -2146,7 +2053,6 @@ private function save( $packageDependencies = $transformer->relativizeFileKeyed($packageDependencies); $projectExtensionFiles = $transformer->relativizeFileKeyed($projectExtensionFiles); $collectedDataRuleResults = $transformer->relativizeCollectedDataRuleResults($collectedDataRuleResults); - $filesWithCollectedDataRuleErrors = array_map(static fn (string $path): string => $transformer->relativizePath($path), $filesWithCollectedDataRuleErrors); $file = $this->cacheFilePath; @@ -2184,7 +2090,6 @@ private function save( $this->writeArrayFrame($handle, $file, 'unmatchedLineIgnores', $unmatchedLineIgnores); $savedCollectedDataIndex = $this->writeCollectedDataFrame($handle, $file, $collectedData); $this->writeValueFrame($handle, $file, 'collectedDataRuleResults', $collectedDataRuleResults); - $this->writeValueFrame($handle, $file, 'filesWithCollectedDataRuleErrors', $filesWithCollectedDataRuleErrors); // An older PHPStan reading this file absolutizes the dependencies before it gets to the // cacheVersion check that makes it discard the file, and fails on a missing section. $this->writeArrayFrame($handle, $file, 'dependencies', []); @@ -3254,11 +3159,11 @@ private function getAllDependencies(string $fileName, array $dependencies): arra } /** - * Scanned files that differ between two metadata snapshots, each mapped to what happened to it. + * Scanned files that differ between two metadata snapshots: appeared, edited or gone. * * @param mixed[] $cachedMeta * @param mixed[] $currentMeta - * @return array + * @return list */ private function getChangedScannedFiles(array $cachedMeta, array $currentMeta): array { @@ -3267,23 +3172,18 @@ private function getChangedScannedFiles(array $cachedMeta, array $currentMeta): $changed = []; foreach ($current as $file => $hash) { - if (!array_key_exists($file, $cached)) { - $changed[$file] = self::SCANNED_FILE_APPEARED; - continue; - } - - if ($cached[$file] === $hash) { + if (array_key_exists($file, $cached) && $cached[$file] === $hash) { continue; } - $changed[$file] = self::SCANNED_FILE_EDITED; + $changed[] = (string) $file; } foreach (array_keys($cached) as $file) { if (array_key_exists($file, $current)) { continue; } - $changed[$file] = self::SCANNED_FILE_GONE; + $changed[] = (string) $file; } return $changed; @@ -3618,6 +3518,41 @@ private function getFileHash(string $path): string } /** + * The names a new or changed file declares, scanned the way the directory locators scan them - + * see AppearedSymbols. + * + * @param list $changedFiles + */ + private function getSymbolsDeclaredIn(array $changedFiles): AppearedSymbols + { + $existingFiles = []; + foreach ($changedFiles as $changedFile) { + $changedFile = $this->fileReplacements[$changedFile] ?? $changedFile; + if (!is_file($changedFile)) { + continue; + } + + $existingFiles[] = $changedFile; + } + + $names = []; + foreach ($this->symbolFinderInFiles->findSymbols($existingFiles, $this->phpVersion->supportsEnums()) as $symbols) { + foreach ($symbols as $symbolsOfKind) { + foreach ($symbolsOfKind as $name) { + $names[] = $name; + } + } + } + + return AppearedSymbols::fromNames($names); + } + + /** + * The files the analysis reads symbols from without analysing them, other than the installed + * packages: scanFiles, scanDirectories, the files excluded from the analysis in an analysed + * directory, and the project's own Composer autoload entries - a class, function or constant can + * appear in any of them without anything else changing. + * * @param string[] $allAnalysedFiles * @return array */ @@ -3637,13 +3572,27 @@ private function getScannedFiles(array $allAnalysedFiles): array $analysedDirectories[] = $analysedPath; } - $directories = array_unique(array_merge($analysedDirectories, $this->scanDirectories)); + $autoloadPaths = []; + $pathPackages = $this->packageDependencyResolver->getPathPackages(); + foreach ($this->composerAutoloaderProjectPaths as $projectPath) { + $autoloadPaths[] = $this->composerSourceLocatorMaker->getAutoloadPaths($projectPath, $pathPackages); + } + + $directories = array_unique(array_merge($analysedDirectories, $this->scanDirectories, ...$autoloadPaths)); foreach ($this->scanFileFinder->findFilesCached($directories)->getFiles() as $file) { $scannedFiles[] = $file; } + // PHPStan's own files - the result cache, the container - change on every run, and a + // directory holding the tmpDir, like a PSR-4 namespace mapped to the project root, would + // make them look like changed scanned files + $tmpDir = rtrim($this->tmpDir, '/\\') . DIRECTORY_SEPARATOR; $hashes = []; foreach (array_diff($scannedFiles, $allAnalysedFiles) as $file) { + if (str_starts_with($file, $tmpDir)) { + continue; + } + $hashes[$file] = $this->getFileHash($file); } diff --git a/src/Analyser/ValueDependencyCollector.php b/src/Analyser/ValueDependencyCollector.php index 9394281606d..d73762ee487 100644 --- a/src/Analyser/ValueDependencyCollector.php +++ b/src/Analyser/ValueDependencyCollector.php @@ -3,23 +3,35 @@ namespace PHPStan\Analyser; use PHPStan\Analyser\ResultCache\ClassResultCacheValueExtension; +use PHPStan\Analyser\ResultCache\ConstantResultCacheValueExtension; use PHPStan\Analyser\ResultCache\DirectoryResultCacheValueExtension; use PHPStan\Analyser\ResultCache\FileResultCacheValueExtension; +use PHPStan\Analyser\ResultCache\FunctionResultCacheValueExtension; use PHPStan\Analyser\ResultCache\ResultCacheValueExtension; use PHPStan\DependencyInjection\AutowiredExtensions; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\DependencyInjection\ExtensionsCollection; use PHPStan\File\FileHelper; +use PHPStan\Reflection\ClassNameHelper; use PHPStan\Reflection\ClassReflection; use PHPStan\ShouldNotHappenException; +use PHPStan\Turbo\ReferencedByTurboExtension; use function array_key_exists; use function array_keys; +use function array_map; use function array_merge; +use function array_pop; use function array_unique; use function array_values; +use function count; +use function in_array; +use function ltrim; use function rtrim; use function sprintf; +use function str_starts_with; +use function strrpos; use function strtolower; +use function substr; /** * Collects the values declared through DependencyTracker::trackValueDependency() while a file is being @@ -29,9 +41,9 @@ * or another one, or by another file, is the same dependency, recorded once. Two kinds of * dependents are recorded for it: * - * - "analysis": the file being analysed. Its analysis read the value, so a change of it has to - * re-analyse this file. - * - "declarations": the file of the scope, when the dependency is declared outside the walk of + * - "analysis": what is reported in the file being analysed. Its analysis read the value, so a + * change of it has to re-analyse this file. + * - "declarations": what a file declares - the file of the scope, when the dependency is declared outside the walk of * the analysed file, on a scope without a node callback. PHPStan steps outside of it to infer * what a file declares - the type of a private property without a type is inferred from the * constructor of its class, on a scope of the class's file, whenever the property is first @@ -39,6 +51,9 @@ * by the files analysed after it, so it is what the scope's file declares that depends on the * value: a change of it re-analyses the scope's file and every file depending on it. * + * AnalysedFileDependencyCollector and AnalysedDeclarationDependencyCollector make the same split for + * the files an analysis of only some files has to include to report unmatched ignoreErrors entries. + * * A rule for CollectedDataNode runs outside the analysis of a file. What it declares is collected * for the rule itself, between startCollectedDataRule() and finishCollectedDataRule(), and stored * with its errors: the next run reuses them only while every value is still the same. Outside of @@ -52,18 +67,51 @@ * A rule for CollectedDataNode gets those of every class, because it is not known which classes * it read. * + * Every class, function and constant the reflection layer is asked about is recorded too, found or + * not - the result of whatever asked would be different once it appears or goes away, and the + * analysed code does not always name it, it can come from a string: + * + * - not found, see recordMissingSymbol(): a value dependency, "missing" until it is declared + * - found, see recordFoundSymbol(): a dependency on the file declaring it, like on the files + * declaring the symbols the analysed code references, see getFoundSymbols() + * + * Both are split like the values are: looked up during the analysis of the file, what is reported in + * it depends on them; looked up while resolving a declaration, see enterDeclaration(), what the + * declaration declares depends on them, and so does every file depending on the declaration. + * + * The lookups are recorded per context - the analysed file and the declarations being resolved, + * see enterDeclaration() - and getContext() changes with it: the reflection layer remembers its + * answers, and asks to record a remembered one again only in a context it has not recorded it in + * yet. + * * @phpstan-type ValueDependencies = array{ * values: array, * dependents: array, declarations: list}>, * } */ #[AutowiredService] +#[ReferencedByTurboExtension(key: 'valueDependencyCollector')] final class ValueDependencyCollector { + public const KIND_CLASS = 'class'; + + public const KIND_FUNCTION = 'function'; + + public const KIND_CONSTANT = 'constant'; + + /** the value of a class, a function or a constant that does not exist */ + public const MISSING = 'missing'; + private ?string $analysedFile = null; - /** @var array|null id => [extension class, key, value], while a rule for CollectedDataNode runs */ + /** + * While a rule for CollectedDataNode runs. A value is null until getCollectedDataRuleValues() asks + * for it: most of them are never needed, as the result of a rule reading no collected data is not + * kept, and the value of a class found means parsing the files declaring it and its ancestors. + * + * @var array|null id => [extension class, key, value] + */ private ?array $collectedDataRuleValues = null; /** @var array id => [extension class, key, value] */ @@ -78,6 +126,21 @@ final class ValueDependencyCollector /** @var array lowercase class names the analysed file depends on, with their ancestors */ private array $dependedOnClasses = []; + /** @var list the files and the keys of the declarations being resolved, see enterDeclaration() */ + private array $declarations = []; + + /** @var array> file => keys of the declarations resolved in it, for the whole process */ + private array $fileDeclarationKeys = []; + + /** @var array> kind => lowercase name => name, found during the analysis of the file */ + private array $analysisFoundSymbols = []; + + /** @var array>> declaration key => kind => lowercase name => name, found while resolving the declaration, for the whole process */ + private array $declarationFoundSymbols = []; + + /** see getContext() */ + private static int $context = 0; + /** * @param ExtensionsCollection $valueExtensions */ @@ -89,6 +152,16 @@ public function __construct( { } + /** + * Changes whenever what a lookup is recorded for does: another file is analysed, or the + * declarations of another file are being resolved. A cache of lookups remembers it with each + * answer and asks to record the answer again only when it is different. + */ + public static function getContext(): int + { + return self::$context; + } + public static function getId(string $extensionClass, string $key): string { return $extensionClass . "\0" . $key; @@ -100,6 +173,8 @@ public function startFile(string $analysedFile): void $this->values = []; $this->dependents = [$analysedFile => ['analysis' => [], 'declarations' => []]]; $this->dependedOnClasses = []; + $this->analysisFoundSymbols = []; + self::$context++; } /** @@ -108,8 +183,7 @@ public function startFile(string $analysedFile): void public function record(string $extensionClass, string $key, Scope $scope, bool $insideWalk): void { if ($this->collectedDataRuleValues !== null) { - $id = self::getId($extensionClass, $key); - $this->collectedDataRuleValues[$id] ??= [$extensionClass, $key, $this->getRegisteredExtension($extensionClass)->getValue($key)]; + $this->collectedDataRuleValues[self::getId($extensionClass, $key)] ??= [$extensionClass, $key, null]; return; } @@ -170,6 +244,7 @@ public function recordClass(string $className, Scope $scope, bool $insideWalk): public function startCollectedDataRule(): void { $this->collectedDataRuleValues = []; + self::$context++; } /** @@ -184,6 +259,20 @@ public function getCollectedDataRuleValues(): array return []; } + // getting a value can look up more symbols, which are recorded for the rule too + do { + $computed = false; + foreach ($this->collectedDataRuleValues as $id => [$extensionClass, $key, $value]) { + if ($value !== null) { + continue; + } + + $this->collectedDataRuleValues[$id][2] = $this->getRegisteredExtension($extensionClass)->getValue($key); + $computed = true; + } + } while ($computed); + + /** @var array $values */ $values = $this->collectedDataRuleValues; foreach ($this->classDeclarations as $classValues) { $values += $classValues; @@ -195,6 +284,7 @@ public function getCollectedDataRuleValues(): array public function finishCollectedDataRule(): void { $this->collectedDataRuleValues = null; + self::$context++; } public function getFileKey(string $file): string @@ -224,6 +314,225 @@ public function recordForClass(string $className, string $extensionClass, string $this->classDeclarations[$className][$id] = [$extensionClass, $key, $this->getRegisteredExtension($extensionClass)->getValue($key)]; } + /** + * A lookup of a class, a function or a constant found nothing. The analysed file - or the rule + * for CollectedDataNode running - depends on it not existing, and so does what the files passed + * to enterDeclaration() declare: the answer is remembered with their reflection, and a file + * asking the same later gets it without the lookup. + * + * Called from the reflection layer, which has no Scope. The value is known without asking the + * extension, which would look the symbol up again. + * + * @param self::KIND_* $kind + */ + public function recordMissingSymbol(string $kind, string $name): void + { + if (!self::isValidSymbolName($kind, $name)) { + // can never be declared + return; + } + + [$extensionClass, $key] = self::getExtensionAndKey($kind, $name); + $id = self::getId($extensionClass, $key); + $value = [$extensionClass, $key, self::MISSING]; + if ($this->collectedDataRuleValues !== null) { + $this->collectedDataRuleValues[$id] ??= $value; + return; + } + + if ($this->analysedFile === null) { + return; + } + + $this->values[$id] ??= $value; + $this->dependents[$this->analysedFile]['analysis'][$id] = true; + foreach ($this->declarations as [$declaringFile]) { + if ($declaringFile === null) { + // a built-in symbol, nothing to re-analyse + continue; + } + if (!array_key_exists($declaringFile, $this->dependents)) { + $this->dependents[$declaringFile] = ['analysis' => [], 'declarations' => []]; + } + $this->dependents[$declaringFile]['declarations'][$id] = true; + } + } + + /** + * A lookup of a class, a function or a constant found it. The analysed file depends on the file + * declaring it, and so do the files depending on the declarations passed to enterDeclaration(), + * see getFoundSymbols(): when it goes away, they are re-analysed. + * + * A rule for CollectedDataNode, whose result is reused while the collected data it read stay the + * same, depends on the value of the symbol instead: the symbol can go away without them + * changing. + * + * @param self::KIND_* $kind + * @param string $name the name it was found by, without a leading backslash + */ + public function recordFoundSymbol(string $kind, string $name): void + { + if ($this->collectedDataRuleValues !== null) { + [$extensionClass, $key] = self::getExtensionAndKey($kind, $name); + $this->collectedDataRuleValues[self::getId($extensionClass, $key)] ??= [$extensionClass, $key, null]; + return; + } + + if ($this->analysedFile === null) { + return; + } + + $lowerName = strtolower($name); + $this->analysisFoundSymbols[$kind][$lowerName] = $name; + foreach ($this->declarations as [, $declarationKey]) { + if ($declarationKey === null) { + continue; + } + $this->declarationFoundSymbols[$declarationKey][$kind][$lowerName] = $name; + } + } + + /** + * The symbols found during the analysis of the file - with $includeAnalysis - and while + * resolving the declarations it depends on, by kind - the files declaring them are what the + * analysed file depends on too. + * $declarationKeys are the keys of the declarations the analysed file depends on so far - see + * getClassDeclarationKey(), getFunctionDeclarationKey(), getFileDeclarationKey() and + * getDeclarationKeysOfFile(); those of what is returned are to be passed again, until nothing + * new is returned. + * + * @param list $declarationKeys + * @return array> + */ + public function getFoundSymbols(array $declarationKeys, bool $includeAnalysis): array + { + $symbols = $includeAnalysis ? $this->analysisFoundSymbols : []; + foreach ($declarationKeys as $declarationKey) { + foreach ($this->declarationFoundSymbols[$declarationKey] ?? [] as $kind => $names) { + $symbols[$kind] = ($symbols[$kind] ?? []) + $names; + } + } + + return array_map(static fn (array $names): array => array_values($names), $symbols); + } + + /** + * What a class declares, with what PHPDocs of its members declare - a file depending on the class + * or on a class extending it depends on it. + */ + public static function getClassDeclarationKey(string $className): string + { + return 'class ' . strtolower(ltrim($className, '\\')); + } + + public static function getFunctionDeclarationKey(string $functionName): string + { + return 'function ' . strtolower(ltrim($functionName, '\\')); + } + + /** + * What a file declares besides its classes and functions, and what its anonymous classes do - a + * file depending on any symbol of the file depends on it. + * + * @param string $file normalized, see getFileKey() + */ + public static function getFileDeclarationKey(string $file): string + { + return 'file ' . $file; + } + + /** + * The keys of every declaration resolved in $file so far - the analysed file depends on all of + * them, they can be declared in a function body, or by a class declared elsewhere using a trait + * of the file. + * + * @return list + */ + public function getDeclarationKeysOfFile(string $file): array + { + return array_keys($this->fileDeclarationKeys[$file] ?? []); + } + + /** + * Until leaveDeclaration(), what is looked up is recorded for the declaration of $className - + * or of $functionName outside a class, or of $file outside both - too: while resolving something + * its reflection remembers for the rest of the process, its ancestors, the types in its PHPDocs, + * the initializers of its constants. Files depending on the declaration depend on what is found + * for it, see getFoundSymbols(), and files depending on $file on what is missing. + * + * @param string|null $className the class declaring it - the class using the trait for a trait member + */ + public function enterDeclaration(?string $file, ?string $className = null, ?string $functionName = null): void + { + $declarationKey = null; + if ($file !== null) { + $file = $this->getFileKey($file); + if ($className !== null) { + // the name of an anonymous class is not the same everywhere + $declarationKey = str_starts_with($className, 'AnonymousClass') + ? self::getFileDeclarationKey($file) + : self::getClassDeclarationKey($className); + } elseif ($functionName !== null) { + $declarationKey = self::getFunctionDeclarationKey($functionName); + } else { + $declarationKey = self::getFileDeclarationKey($file); + } + $this->fileDeclarationKeys[$file][$declarationKey] = true; + } + + $declaration = [$file, $declarationKey]; + if ($this->declarations === [] || $this->declarations[count($this->declarations) - 1] !== $declaration) { + self::$context++; + } + $this->declarations[] = $declaration; + } + + public function leaveDeclaration(): void + { + $declaration = array_pop($this->declarations); + if ($this->declarations !== [] && $this->declarations[count($this->declarations) - 1] === $declaration) { + return; + } + + self::$context++; + } + + /** + * @param self::KIND_* $kind + * @return array{class-string, string} + */ + private static function getExtensionAndKey(string $kind, string $name): array + { + switch ($kind) { + case self::KIND_CLASS: + return [ClassResultCacheValueExtension::class, ClassResultCacheValueExtension::createKey($name)]; + case self::KIND_FUNCTION: + return [FunctionResultCacheValueExtension::class, FunctionResultCacheValueExtension::createKey($name)]; + default: + return [ConstantResultCacheValueExtension::class, ConstantResultCacheValueExtension::createKey($name)]; + } + } + + /** + * @param self::KIND_* $kind + */ + private static function isValidSymbolName(string $kind, string $name): bool + { + if (!ClassNameHelper::isValidClassName($name)) { + return false; + } + + if ($kind !== self::KIND_CONSTANT) { + return true; + } + + // resolved by the parser, never declared + $lastBackslash = strrpos($name, '\\'); + $shortName = strtolower($lastBackslash === false ? $name : substr($name, $lastBackslash + 1)); + + return !in_array($shortName, ['true', 'false', 'null'], true); + } + /** * The analysed file depends on the class - it gets what the class and its ancestors declare * depends on, see recordForClass(). @@ -267,6 +576,8 @@ public function finishFile(): array $this->values = []; $this->dependents = []; $this->dependedOnClasses = []; + $this->analysisFoundSymbols = []; + self::$context++; return ['values' => $values, 'dependents' => $dependents]; } diff --git a/src/Command/AnalyseApplication.php b/src/Command/AnalyseApplication.php index 35b12d2c85d..b97dcd49ca3 100644 --- a/src/Command/AnalyseApplication.php +++ b/src/Command/AnalyseApplication.php @@ -147,6 +147,7 @@ public function analyse( $postRuleCallback, // with -vvv the diagnose extensions print, and a rule can fill what they print only while it runs $errorOutput->isDebug() ? [] : $resultCache->getCollectedDataRuleResults(), + $resultCache->getAppearedSymbols(), ); if ($finalizerResult->getReusedRulesCount() > 0 && $errorOutput->isVeryVerbose()) { $errorOutput->writeLineFormatted(sprintf( diff --git a/src/Command/FixerWorkerRunner.php b/src/Command/FixerWorkerRunner.php index 163efa9bff0..2603b74aefe 100644 --- a/src/Command/FixerWorkerRunner.php +++ b/src/Command/FixerWorkerRunner.php @@ -233,7 +233,7 @@ function (array $errors, array $locallyIgnoredErrors, array $analysedFiles) use false, true, ); - $finalizerResult = $this->analyserResultFinalizer->finalize($resultCacheResult->getAnalyserResult(), $isOnlyFiles, false, null, null, $resultCache->getCollectedDataRuleResults()); + $finalizerResult = $this->analyserResultFinalizer->finalize($resultCacheResult->getAnalyserResult(), $isOnlyFiles, false, null, null, $resultCache->getCollectedDataRuleResults(), $resultCache->getAppearedSymbols()); $resultCacheResult->save($finalizerResult); // FixerApplication's file monitor misses a file changed and changed back between two polls diff --git a/src/Dependency/DependencyResolver.php b/src/Dependency/DependencyResolver.php index 6d22e2d6143..e4ee58b46ea 100644 --- a/src/Dependency/DependencyResolver.php +++ b/src/Dependency/DependencyResolver.php @@ -3,8 +3,10 @@ namespace PHPStan\Dependency; use PhpParser\Node; +use PhpParser\Node\Name\FullyQualified; use PHPStan\Analyser\NamespaceUsesTracker; use PHPStan\Analyser\Scope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\Broker\ClassNotFoundException; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\File\FileHelper; @@ -172,8 +174,13 @@ public function resolveFileDependencies(?Dependencies $dependencies, array $anal $packages = []; $classReflections = []; + $functionNames = []; foreach ($reflectionsByFile as $file => $reflections) { foreach ($reflections as $id => $reflection) { + if ($reflection instanceof FunctionReflection) { + $functionNames[$reflection->getName()] = $reflection->getName(); + continue; + } if (!$reflection instanceof ClassReflection) { continue; } @@ -193,9 +200,47 @@ public function resolveFileDependencies(?Dependencies $dependencies, array $anal array_values($usedTraitFileDependencies), array_values($packages), array_values($classReflections), + array_values($functionNames), ); } + /** + * What the reflection layer found by name, see ValueDependencyCollector::getFoundSymbols(), as + * dependencies of $file to resolve. + * + * @param array> $foundSymbols + */ + public function createFoundSymbolDependencies(string $file, array $foundSymbols): ?Dependencies + { + $reflections = []; + foreach ($foundSymbols[ValueDependencyCollector::KIND_FUNCTION] ?? [] as $functionName) { + if ($functionName === '') { + continue; + } + + $nameNode = new FullyQualified($functionName); + if (!$this->reflectionProvider->hasFunction($nameNode, null)) { + continue; + } + + $reflections[] = $this->reflectionProvider->getFunction($nameNode, null); + } + foreach ($foundSymbols[ValueDependencyCollector::KIND_CONSTANT] ?? [] as $constantName) { + if ($constantName === '') { + continue; + } + + $nameNode = new FullyQualified($constantName); + if (!$this->reflectionProvider->hasConstant($nameNode, null)) { + continue; + } + + $reflections[] = $this->reflectionProvider->getConstant($nameNode, null); + } + + return Dependencies::create($file, [], $foundSymbols[ValueDependencyCollector::KIND_CLASS] ?? [], $reflections); + } + /** * @return array */ diff --git a/src/Dependency/PackageDependencyResolver.php b/src/Dependency/PackageDependencyResolver.php index b7074040651..e14c319170c 100644 --- a/src/Dependency/PackageDependencyResolver.php +++ b/src/Dependency/PackageDependencyResolver.php @@ -308,8 +308,8 @@ private function getInstallPathToPackage(): array return $this->installPathToPackage; } - /** @return array */ - private function getPathPackages(): array + /** @return array names of the installed packages that came from a path repository */ + public function getPathPackages(): array { $this->resolveInstalledPackages(); diff --git a/src/Dependency/ResolvedDependencies.php b/src/Dependency/ResolvedDependencies.php index efcec9e7789..54031c559d7 100644 --- a/src/Dependency/ResolvedDependencies.php +++ b/src/Dependency/ResolvedDependencies.php @@ -15,12 +15,14 @@ final class ResolvedDependencies * @param list $usedTraitFileDependencies * @param list $packageDependencies * @param list $classReflections every class depended on, with its ancestors + * @param list $functionNames every function depended on */ public function __construct( private array $fileDependencies, private array $usedTraitFileDependencies, private array $packageDependencies, private array $classReflections, + private array $functionNames = [], ) { } @@ -57,4 +59,12 @@ public function getClassReflections(): array return $this->classReflections; } + /** + * @return list + */ + public function getFunctionNames(): array + { + return $this->functionNames; + } + } diff --git a/src/DependencyInjection/ValidateIgnoredErrorsExtension.php b/src/DependencyInjection/ValidateIgnoredErrorsExtension.php index 4cfdb396799..5ee8d0b295a 100644 --- a/src/DependencyInjection/ValidateIgnoredErrorsExtension.php +++ b/src/DependencyInjection/ValidateIgnoredErrorsExtension.php @@ -8,8 +8,10 @@ use Override; use PHPStan\Analyser\ConstantResolver; use PHPStan\Analyser\NameScope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\Command\IgnoredRegexValidator; use PHPStan\File\FileExcluder; +use PHPStan\File\FileHelper; use PHPStan\Php\ComposerPhpVersionFactory; use PHPStan\Php\ConfiguredPhpVersionRangeHelper; use PHPStan\Php\PhpVersion; @@ -89,6 +91,8 @@ public function loadConfiguration(): void try { $composerPhpVersionFactory = new ComposerPhpVersionFactory([]); $constantResolver = new ConstantResolver($reflectionProviderProvider, [], new ConfiguredPhpVersionRangeHelper(null, $composerPhpVersionFactory), container: null); + // nothing is analysed while the configuration is validated, nothing is recorded + $valueDependencyCollector = new ValueDependencyCollector(new DirectExtensionsCollection([]), new FileHelper($builder->parameters['currentWorkingDirectory'])); $phpDocParserConfig = new ParserConfig([]); $ignoredRegexValidator = new IgnoredRegexValidator( @@ -122,8 +126,9 @@ public function resolveTypeAlias(string $aliasName, NameScope $nameScope): ?Type }), $constantResolver, - new InitializerExprTypeResolver($constantResolver, $reflectionProviderProvider, new PhpVersion(PHP_VERSION_ID), new OperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new UnaryOperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new OversizedArrayBuilder(), true), + new InitializerExprTypeResolver($constantResolver, $reflectionProviderProvider, new PhpVersion(PHP_VERSION_ID), new OperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new UnaryOperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new OversizedArrayBuilder(), true, $valueDependencyCollector), reportUnsafeArrayStringKeyCasting: null, + valueDependencyCollector: $valueDependencyCollector, ), ), ); diff --git a/src/PhpDoc/TypeNodeResolver.php b/src/PhpDoc/TypeNodeResolver.php index 7a9db84a9e3..409afced88f 100644 --- a/src/PhpDoc/TypeNodeResolver.php +++ b/src/PhpDoc/TypeNodeResolver.php @@ -10,6 +10,7 @@ use PhpParser\Node\Name; use PHPStan\Analyser\ConstantResolver; use PHPStan\Analyser\NameScope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\DependencyInjection\ReportUnsafeArrayStringKeyCastingToggle; @@ -161,12 +162,25 @@ public function __construct( private InitializerExprTypeResolver $initializerExprTypeResolver, #[AutowiredParameter] private ?string $reportUnsafeArrayStringKeyCasting, + private ValueDependencyCollector $valueDependencyCollector, ) { } /** @api */ public function resolve(TypeNode $typeNode, NameScope $nameScope): Type + { + // The resolved type is remembered with the reflection of what the PHPDoc describes, so a name + // in it that is not a class yet is what it declares depends on. + $this->valueDependencyCollector->enterDeclaration($nameScope->getFileName(), $nameScope->getClassName(), $nameScope->getFunctionName()); + try { + return $this->resolveType($typeNode, $nameScope); + } finally { + $this->valueDependencyCollector->leaveDeclaration(); + } + } + + private function resolveType(TypeNode $typeNode, NameScope $nameScope): Type { foreach ($this->extensionRegistryProvider->getRegistry()->getExtensions() as $extension) { $type = $extension->resolve($typeNode, $nameScope); diff --git a/src/Reflection/BetterReflection/BetterReflectionProvider.php b/src/Reflection/BetterReflection/BetterReflectionProvider.php index 056a17b258a..6ba7dac0446 100644 --- a/src/Reflection/BetterReflection/BetterReflectionProvider.php +++ b/src/Reflection/BetterReflection/BetterReflectionProvider.php @@ -6,6 +6,7 @@ use Nette\Utils\Strings; use PhpParser\Node; use PHPStan\Analyser\Scope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\BetterReflection\Identifier\Exception\InvalidIdentifierName; use PHPStan\BetterReflection\NodeCompiler\Exception\UnableToCompileNode; use PHPStan\BetterReflection\Reflection\Adapter\ReflectionAttributeFactory; @@ -13,6 +14,7 @@ use PHPStan\BetterReflection\Reflection\Adapter\ReflectionFunction; use PHPStan\BetterReflection\Reflection\Adapter\ReflectionParameter; use PHPStan\BetterReflection\Reflection\ReflectionAttribute as BetterReflectionAttribute; +use PHPStan\BetterReflection\Reflection\ReflectionClass as BetterReflectionClass; use PHPStan\BetterReflection\Reflection\ReflectionEnum; use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound; use PHPStan\BetterReflection\Reflector\Reflector; @@ -113,6 +115,7 @@ public function __construct( private AttributeReflectionFactory $attributeReflectionFactory, #[AutowiredParameter(ref: '%universalObjectCratesClasses%')] private array $universalObjectCratesClasses, + private ValueDependencyCollector $valueDependencyCollector, ) { } @@ -155,6 +158,8 @@ public function getClass(string $className): ClassReflection return $this->classReflections[$reflectionClassName]; } + $this->recordMissingAncestors($reflectionClass); + if ($reflectionClass instanceof ReflectionEnum && PHP_VERSION_ID >= 80000) { $adaptedClass = new \PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum($reflectionClass); } else { @@ -170,6 +175,33 @@ public function getClass(string $className): ClassReflection ); } + /** + * A parent, interface or trait that does not exist is left out of the class reflection, which + * is remembered for the rest of the process: every file depending on the class depends on it + * not existing. + */ + private function recordMissingAncestors(BetterReflectionClass $reflectionClass): void + { + $ancestorNames = [...$reflectionClass->getInterfaceClassNames(), ...$reflectionClass->getTraitClassNames()]; + $parentClassName = $reflectionClass->getParentClassName(); + if ($parentClassName !== null) { + $ancestorNames[] = $parentClassName; + } + + $this->valueDependencyCollector->enterDeclaration($reflectionClass->getFileName(), $reflectionClass->getName()); + try { + foreach ($ancestorNames as $ancestorName) { + if ($this->hasClass($ancestorName)) { + continue; + } + + $this->valueDependencyCollector->recordMissingSymbol(ValueDependencyCollector::KIND_CLASS, $ancestorName); + } + } finally { + $this->valueDependencyCollector->leaveDeclaration(); + } + } + public function getClassName(string $className): string { if (!$this->hasClass($className)) { @@ -526,11 +558,14 @@ public function resolveConstantName(Node\Name $nameNode, ?NamespaceAnswerer $nam return $resolved; } + /** + * A fully qualified name is marked apart from the name: new Name('\\strval'), the name of a + * callable string, keeps the backslash and resolves differently than new FullyQualified('strval'). + */ private function nameResolutionCacheKey(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): string { return ($namespaceAnswerer !== null ? ($namespaceAnswerer->getNamespace() ?? '') : '') - . '::' - . ($nameNode->isFullyQualified() ? '\\' : '') + . ($nameNode->isFullyQualified() ? ':fq:' : '::') . (string) $nameNode; } diff --git a/src/Reflection/BetterReflection/BetterReflectionSourceLocatorFactory.php b/src/Reflection/BetterReflection/BetterReflectionSourceLocatorFactory.php index d4a0fb8c61e..dc2420446a8 100644 --- a/src/Reflection/BetterReflection/BetterReflectionSourceLocatorFactory.php +++ b/src/Reflection/BetterReflection/BetterReflectionSourceLocatorFactory.php @@ -25,6 +25,7 @@ use PHPStan\Reflection\BetterReflection\SourceLocator\FileNodesFetcher; use PHPStan\Reflection\BetterReflection\SourceLocator\LazySourceLocator; use PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedDirectorySourceLocatorFactory; +use PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedDirectorySourceLocatorGroup; use PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedDirectorySourceLocatorRepository; use PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedPsrAutoloaderLocatorFactory; use PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedSingleFileSourceLocatorRepository; @@ -143,8 +144,12 @@ public function create(): SourceLocator $batch = $this->optimizedDirectorySourceLocatorFactory->createBatch(); try { $directories = array_unique(array_merge($analysedDirectories, $this->scanDirectories)); + $directoryLocators = []; foreach ($directories as $directory) { - $fileLocators[] = $this->optimizedDirectorySourceLocatorRepository->getOrCreate($directory, $batch); + $directoryLocators[] = $this->optimizedDirectorySourceLocatorRepository->getOrCreate($directory, $batch); + } + if ($directoryLocators !== []) { + $fileLocators[] = OptimizedDirectorySourceLocatorGroup::create($directoryLocators); } $composerLocators = []; diff --git a/src/Reflection/BetterReflection/SourceLocator/CachedPhpInternalSourceLocator.php b/src/Reflection/BetterReflection/SourceLocator/CachedPhpInternalSourceLocator.php index 974b68fdf09..e5a0fa8b99d 100644 --- a/src/Reflection/BetterReflection/SourceLocator/CachedPhpInternalSourceLocator.php +++ b/src/Reflection/BetterReflection/SourceLocator/CachedPhpInternalSourceLocator.php @@ -2,6 +2,7 @@ namespace PHPStan\Reflection\BetterReflection\SourceLocator; +use JetBrains\PHPStormStub\PhpStormStubsMap; use Override; use PHPStan\BetterReflection\Identifier\Identifier; use PHPStan\BetterReflection\Identifier\IdentifierType; @@ -17,6 +18,7 @@ use PHPStan\Internal\ComposerHelper; use PHPStan\Php\PhpVersion; use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider; +use function array_change_key_case; use function array_key_exists; use function is_array; use function is_file; @@ -53,6 +55,9 @@ final class CachedPhpInternalSourceLocator implements SourceLocator private const RELATIVE_FILENAME_PREFIX = 'phpstorm-stubs:'; + /** @var array|null lowercase name => stub file, of every function in the stubs of any extension version */ + private static ?array $stubFunctions = null; + private ?string $variableCacheKey = null; private ?string $stubsRootDir = null; @@ -75,16 +80,21 @@ public function locateIdentifier(Reflector $reflector, Identifier $identifier): $name = strtolower($name); } - // Almost everything that reaches this locator is a userland class name - // that every earlier locator failed to resolve, and a name the stubs do - // not have can never have been cached - the stubber is the only source - // the wrapped locator reads from. Ruling those out against the stubs map - // is an array lookup, where asking the cache means hashing the key and - // stat()ing a file that will never exist. The wrapped locator is still - // asked: it resolves class aliases before consulting the stubber, so it - // can answer for a name the map does not list - such an answer just does - // not get cached, under a key that would be the alias anyway. - if ($identifier->isClass() && !$this->stubber->hasClass($name)) { + // Almost everything that reaches this locator is a userland class or + // function name that every earlier locator failed to resolve - also every + // namespaced name an unqualified function call is looked up by first - + // and a name the stubs do not have can never have been cached - the + // stubber is the only source the wrapped locator reads from. Ruling those + // out against the stubs map is an array lookup, where asking the cache + // means hashing the key and stat()ing a file that will never exist. The + // wrapped locator is still asked: it resolves class aliases before + // consulting the stubber, so it can answer for a name the map does not + // list - such an answer just does not get cached, under a key that would + // be the alias anyway. + if ( + ($identifier->isClass() && !$this->stubber->hasClass($name)) + || ($identifier->isFunction() && !self::isStubFunction($name)) + ) { return $this->inner->locateIdentifier($reflector, $identifier); } @@ -171,6 +181,26 @@ private function resolveStubFilename(array $cached): ?array /** * @return list */ + /** + * Whether the stubber could have a function: the stubber has no cheap way to tell, its own + * answer parses the stub file. The functions of the extension versions it selects are added + * to the default ones, so they are all included. + */ + private static function isStubFunction(string $lowercaseName): bool + { + if (self::$stubFunctions === null) { + $functions = array_change_key_case(PhpStormStubsMap::FUNCTIONS); + foreach (PhpStormStubsMap::EXTENSION_VERSIONS as $versionMaps) { + foreach ($versionMaps as $versionMap) { + $functions += array_change_key_case($versionMap['functions']); + } + } + self::$stubFunctions = $functions; + } + + return array_key_exists($lowercaseName, self::$stubFunctions); + } + #[Override] public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array { diff --git a/src/Reflection/BetterReflection/SourceLocator/ComposerJsonAndInstalledJsonSourceLocatorMaker.php b/src/Reflection/BetterReflection/SourceLocator/ComposerJsonAndInstalledJsonSourceLocatorMaker.php index 5e202ddbf65..dd73cddd2a8 100644 --- a/src/Reflection/BetterReflection/SourceLocator/ComposerJsonAndInstalledJsonSourceLocatorMaker.php +++ b/src/Reflection/BetterReflection/SourceLocator/ComposerJsonAndInstalledJsonSourceLocatorMaker.php @@ -18,6 +18,7 @@ use function array_merge; use function array_merge_recursive; use function array_reverse; +use function array_values; use function count; use function dirname; use function glob; @@ -25,7 +26,13 @@ use function is_dir; use function is_file; use function is_string; +use function realpath; +use function rtrim; +use function scandir; use function str_contains; +use function str_ends_with; +use function str_starts_with; +use const DIRECTORY_SEPARATOR; use const GLOB_ONLYDIR; #[AutowiredService] @@ -47,30 +54,12 @@ public function __construct( */ public function create(string $projectInstallationPath, ?OptimizedDirectorySourceLocatorBatch $batch = null): ?SourceLocator { - $composer = ComposerHelper::getComposerConfig($projectInstallationPath); - - if ($composer === null) { - return null; - } - - $vendorDirectory = ComposerHelper::getVendorDirFromComposerConfig($projectInstallationPath, $composer); - - $installedJsonPath = $vendorDirectory . '/composer/installed.json'; - if (!is_file($installedJsonPath)) { + $project = $this->readProject($projectInstallationPath); + if ($project === null) { return null; } - $installedJsonDirectoryPath = dirname($installedJsonPath); - - try { - $installedJsonContents = FileReader::read($installedJsonPath); - $installedJson = Json::decode($installedJsonContents, Json::FORCE_ARRAY); - } catch (CouldNotReadFileException | JsonException) { - return null; - } - - $installed = $installedJson['packages'] ?? $installedJson; - $dev = (bool) ($installedJson['dev'] ?? true); + [$composer, $vendorDirectory, $installedJsonDirectoryPath, $installed, $dev] = $project; $classMapPaths = array_merge( $this->prefixPaths($this->packageToClassMapPaths($composer), $projectInstallationPath . '/'), @@ -117,9 +106,10 @@ public function create(string $projectInstallationPath, ?OptimizedDirectorySourc ); $files = []; + $directoryLocators = []; foreach ($classMapPaths as $classMapPath) { if (is_dir($classMapPath)) { - $locators[] = $this->optimizedDirectorySourceLocatorRepository->getOrCreate($classMapPath, $batch); + $directoryLocators[] = $this->optimizedDirectorySourceLocatorRepository->getOrCreate($classMapPath, $batch); continue; } if (!is_file($classMapPath)) { @@ -135,10 +125,13 @@ public function create(string $projectInstallationPath, ?OptimizedDirectorySourc } if (count($files) > 0) { - $locators[] = $batch !== null + $directoryLocators[] = $batch !== null ? $batch->createByFiles($files, 'odsl-installed-files') : $this->optimizedDirectorySourceLocatorFactory->createByFiles($files, 'odsl-installed-files'); } + if ($directoryLocators !== []) { + $locators[] = OptimizedDirectorySourceLocatorGroup::create($directoryLocators); + } $binDir = ComposerHelper::getBinDirFromComposerConfig($projectInstallationPath, $composer); $phpunitBridgeDir = $binDir . '/.phpunit'; @@ -176,6 +169,149 @@ public function create(string $projectInstallationPath, ?OptimizedDirectorySourc return new AggregateSourceLocator($locators); } + /** + * The existing directories and files of the PSR-4, PSR-0, classmap and files entries of the + * project and of the packages in $packageNames - where the project's own code that create() + * finds lives. An entry containing the vendor directory, like a PSR-4 namespace mapped to the + * project root, is left out: it would bring all the installed packages with it. + * + * @param array $packageNames + * @return list + */ + public function getAutoloadPaths(string $projectInstallationPath, array $packageNames): array + { + $project = $this->readProject($projectInstallationPath); + if ($project === null) { + return []; + } + + [$composer, $vendorDirectory, $installedJsonDirectoryPath, $installed, $dev] = $project; + + // the project's own entries can point into the vendor directory too, like a files entry + // requiring a file of an installed package - that one changes only through Composer, and is + // tracked with its package + $packages = [[$composer, $projectInstallationPath . '/', $dev ? ['autoload', 'autoload-dev'] : ['autoload'], true]]; + foreach ($installed as $package) { + if (!isset($packageNames[$package['name'] ?? ''])) { + continue; + } + + $packages[] = [$package, $this->packagePrefixPath($installedJsonDirectoryPath, $package, $vendorDirectory), ['autoload'], false]; + } + + $realVendorDirectory = realpath($vendorDirectory); + $paths = []; + foreach ($packages as [$package, $prefix, $sections, $skipVendorPaths]) { + foreach ($sections as $section) { + $sectionPaths = $this->prefixPaths(array_merge( + $this->packageToClassMapPaths($package, $section), + $this->packageToFilePaths($package, $section), + ...array_values($this->packageToPsr4AutoloadNamespaces($package, $section)), + ...array_values($this->packageToPsr0AutoloadNamespaces($package, $section)), + ), $prefix); + foreach ($sectionPaths as $path) { + $realPath = realpath($path); + if ( + $skipVendorPaths + && $realPath !== false + && $realVendorDirectory !== false + && str_starts_with($realPath, $realVendorDirectory . DIRECTORY_SEPARATOR) + ) { + continue; + } + + foreach ($this->withoutVendorDirectory($path, $realVendorDirectory) as $pathWithoutVendor) { + $paths[] = $pathWithoutVendor; + } + } + } + } + + return $paths; + } + + /** + * The path itself, or when it is a directory containing the vendor directory, like a PSR-4 + * namespace mapped to the project root, its entries other than the vendor directory and the + * hidden ones. The files are named the way the source locators name them - through the vendor + * directory for a package from a path repository, not where its symlink points. + * + * @return list + */ + private function withoutVendorDirectory(string $path, string|false $realVendorDirectory): array + { + $realPath = realpath($path); + if ($realPath === false) { + return []; + } + + $realPath = rtrim($realPath, '/\\'); + if ($realVendorDirectory === false || !str_starts_with($realVendorDirectory . DIRECTORY_SEPARATOR, $realPath . DIRECTORY_SEPARATOR)) { + return [$path]; + } + + $entries = scandir($realPath); + if ($entries === false) { + return []; + } + + $paths = []; + foreach ($entries as $entry) { + if (str_starts_with($entry, '.')) { + continue; + } + + $entryPath = $realPath . DIRECTORY_SEPARATOR . $entry; + if ($entryPath === $realVendorDirectory) { + continue; + } + // a file given by itself is taken whatever its extension, unlike one found in a directory + if (!is_dir($entryPath) && !str_ends_with($entry, '.php')) { + continue; + } + + foreach ($this->withoutVendorDirectory($entryPath, $realVendorDirectory) as $entryPathWithoutVendor) { + $paths[] = $entryPathWithoutVendor; + } + } + + return $paths; + } + + /** + * @return array{mixed[], string, string, list, bool}|null composer.json, the vendor directory, the directory of installed.json, the installed packages, whether the dev ones are + */ + private function readProject(string $projectInstallationPath): ?array + { + $composer = ComposerHelper::getComposerConfig($projectInstallationPath); + + if ($composer === null) { + return null; + } + + $vendorDirectory = ComposerHelper::getVendorDirFromComposerConfig($projectInstallationPath, $composer); + + $installedJsonPath = $vendorDirectory . '/composer/installed.json'; + if (!is_file($installedJsonPath)) { + return null; + } + + try { + $installedJsonContents = FileReader::read($installedJsonPath); + $installedJson = Json::decode($installedJsonContents, Json::FORCE_ARRAY); + } catch (CouldNotReadFileException | JsonException) { + return null; + } + + return [ + $composer, + $vendorDirectory, + dirname($installedJsonPath), + $installedJson['packages'] ?? $installedJson, + (bool) ($installedJson['dev'] ?? true), + ]; + } + /** * @param mixed[] $package * diff --git a/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocator.php b/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocator.php index 643e8948e2e..a7ad252f288 100644 --- a/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocator.php +++ b/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocator.php @@ -21,9 +21,12 @@ use PHPStan\Php\PhpVersion; use PHPStan\Reflection\ConstantNameHelper; use PHPStan\ShouldNotHappenException; +use function array_fill_keys; use function array_key_exists; +use function array_keys; use function array_values; use function current; +use function is_array; use function sprintf; use function strtolower; @@ -73,6 +76,21 @@ public function fillScanned(array $classToFile, array $functionToFiles, array $c $this->awaitingScan = false; } + /** + * The lowercase class names, the lowercase function names and the normalized constant names + * it declares - see OptimizedDirectorySourceLocatorGroup. + * + * @return array{list, list, list} + */ + public function getDeclaredSymbolNames(): array + { + if ($this->awaitingScan) { + throw new ShouldNotHappenException('Symbols were looked up in a directory whose batch has not been scanned yet.'); + } + + return [array_keys($this->classToFile), array_keys($this->functionToFiles), array_keys($this->constantToFile)]; + } + /** * @return array{non-empty-string, string} */ @@ -165,6 +183,10 @@ public function locateIdentifier(Reflector $reflector, Identifier $identifier): $fetchedFunctionNode = null; $fetchedFile = null; foreach ($files as $file) { + if (!$this->declares($file, $identifier, $identifierName)) { + continue; + } + $fetchedFunctionNodes = $this->fileNodesFetcher->fetchNodes($file)->getFunctionNodes(); if (!array_key_exists($identifierName, $fetchedFunctionNodes)) { @@ -191,6 +213,10 @@ public function locateIdentifier(Reflector $reflector, Identifier $identifier): } elseif ($identifier->isConstant()) { $fetchedConstantNode = null; foreach ($files as $file) { + if (!$this->declares($file, $identifier, $identifierName)) { + return null; + } + $fetchedConstantNodes = $this->fileNodesFetcher->fetchNodes($file)->getConstantNodes(); if (!array_key_exists($identifierName, $fetchedConstantNodes)) { @@ -234,6 +260,31 @@ private function nodeToReflection(Reflector $reflector, FetchedNode $fetchedNode ); } + /** + * Whether the file declares the function or the constant, remembered for its contents. + * + * The symbol scan lists more files than declare them - a method looks like a function to it, + * and define() may be called anywhere - so a function or a constant that does not exist would + * otherwise parse those files on each lookup, such as when the result cache checks on every + * run that it is still missing. + */ + private function declares(string $file, Identifier $identifier, string $identifierName): bool + { + [, $variableCacheKey] = $this->getCacheKeys($file, $identifier); + $cacheKey = sprintf('odsl-declared-%s', $file); + $declared = $this->cache->load($cacheKey, $variableCacheKey); + if (!is_array($declared)) { + $fetchedNodes = $this->fileNodesFetcher->fetchNodes($file); + $declared = [ + 'functions' => array_fill_keys(array_keys($fetchedNodes->getFunctionNodes()), true), + 'constants' => array_fill_keys(array_keys($fetchedNodes->getConstantNodes()), true), + ]; + $this->cache->save($cacheKey, $variableCacheKey, $declared); + } + + return isset($declared[$identifier->isFunction() ? 'functions' : 'constants'][$identifierName]); + } + private function findFileByClass(string $className): ?string { return $this->classToFile[$className] ?? null; diff --git a/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorGroup.php b/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorGroup.php new file mode 100644 index 00000000000..6702410fb93 --- /dev/null +++ b/src/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorGroup.php @@ -0,0 +1,117 @@ +>, array>, array>}|null class, function and constant name => the locators declaring it */ + private ?array $declaringLocators = null; + + /** + * @param list $locators + */ + public function __construct(private array $locators) + { + } + + /** + * @param list $locators + */ + public static function create(array $locators): SourceLocator + { + if (count($locators) === 1) { + return $locators[0]; + } + + return new self($locators); + } + + #[Override] + public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection + { + if ($identifier->isClass()) { + $kind = 0; + $name = strtolower($identifier->getName()); + } elseif ($identifier->isFunction()) { + $kind = 1; + $name = strtolower($identifier->getName()); + } elseif ($identifier->isConstant()) { + $kind = 2; + $name = ConstantNameHelper::normalize($identifier->getName()); + } else { + return null; + } + + $this->declaringLocators ??= $this->buildDeclaringLocators(); + $indexes = $this->declaringLocators[$kind][$name] ?? null; + if ($indexes === null) { + return null; + } + + foreach (is_int($indexes) ? [$indexes] : $indexes as $index) { + $reflection = $this->locators[$index]->locateIdentifier($reflector, $identifier); + if ($reflection !== null) { + return $reflection; + } + } + + return null; + } + + /** + * @return array{array>, array>, array>} + */ + private function buildDeclaringLocators(): array + { + $declaringLocators = [[], [], []]; + foreach ($this->locators as $index => $locator) { + foreach ($locator->getDeclaredSymbolNames() as $kind => $names) { + foreach ($names as $name) { + $declaring = $declaringLocators[$kind][$name] ?? null; + if ($declaring === null) { + $declaringLocators[$kind][$name] = $index; + continue; + } + + $declaring = is_int($declaring) ? [$declaring] : $declaring; + $declaring[] = $index; + $declaringLocators[$kind][$name] = $declaring; + } + } + } + + return $declaringLocators; + } + + #[Override] + public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array + { + $reflections = []; + foreach ($this->locators as $locator) { + $reflections[] = $locator->locateIdentifiersByType($reflector, $identifierType); + } + + return array_merge([], ...$reflections); + } + +} diff --git a/src/Reflection/InitializerExprTypeResolver.php b/src/Reflection/InitializerExprTypeResolver.php index b92613242d1..be6369d447d 100644 --- a/src/Reflection/InitializerExprTypeResolver.php +++ b/src/Reflection/InitializerExprTypeResolver.php @@ -29,6 +29,7 @@ use PhpParser\Node\Scalar\String_; use PHPStan\Analyser\ConstantResolver; use PHPStan\Analyser\OutOfClassScope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\Node\Expr\TypeExpr; @@ -131,6 +132,7 @@ public function __construct( private OversizedArrayBuilder $oversizedArrayBuilder, #[AutowiredParameter] private bool $usePathConstantsAsConstantString, + private ValueDependencyCollector $valueDependencyCollector, ) { } @@ -1496,7 +1498,14 @@ public function getClassConstFetchTypeByReflection(Name|Expr $class, string $con continue; } $reflectionConstantDeclaringClass = $reflectionConstant->getDeclaringClass(); - $constantType = $this->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($reflectionConstantDeclaringClass->getName(), $reflectionConstantDeclaringClass->getFileName() ?: null)); + // the resolved type is cached: a class it names that does not exist is what the + // declaring class declares depends on + $this->valueDependencyCollector->enterDeclaration($reflectionConstantDeclaringClass->getFileName() ?: null, $reflectionConstantDeclaringClass->getName()); + try { + $constantType = $this->getType($reflectionConstant->getValueExpression(), InitializerExprContext::fromClass($reflectionConstantDeclaringClass->getName(), $reflectionConstantDeclaringClass->getFileName() ?: null)); + } finally { + $this->valueDependencyCollector->leaveDeclaration(); + } $nativeType = null; if ($reflectionConstant->getType() !== null) { $nativeType = TypehintHelper::decideTypeFromReflection($reflectionConstant->getType(), selfClass: $constantClassReflection); diff --git a/src/Reflection/ReflectionProvider/MemoizingReflectionProvider.php b/src/Reflection/ReflectionProvider/MemoizingReflectionProvider.php index 8e3e3741608..3cd4bc862dc 100644 --- a/src/Reflection/ReflectionProvider/MemoizingReflectionProvider.php +++ b/src/Reflection/ReflectionProvider/MemoizingReflectionProvider.php @@ -4,22 +4,29 @@ use PhpParser\Node; use PHPStan\Analyser\Scope; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\ConstantReflection; use PHPStan\Reflection\FunctionReflection; use PHPStan\Reflection\NamespaceAnswerer; use PHPStan\Reflection\ReflectionProvider; use PHPStan\Turbo\ReferencedByTurboExtension; +use function sprintf; use function strtolower; +/** + * Remembers the answers about classes, and records every lookup with ValueDependencyCollector - + * a remembered answer too, once in each of its contexts: the values of $knownClasses, + * $unknownClasses and $nameLookups are the context it was recorded in last. + */ #[ReferencedByTurboExtension(key: 'memoizingReflectionProvider')] final class MemoizingReflectionProvider implements ReflectionProvider { - /** @var array */ + /** @var array */ private array $knownClasses = []; - /** @var array */ + /** @var array */ private array $unknownClasses = []; /** @var array */ @@ -28,27 +35,44 @@ final class MemoizingReflectionProvider implements ReflectionProvider /** @var array */ private array $classNames = []; - public function __construct(private ReflectionProvider $provider) + /** @var array kind, namespace and name as written => context */ + private array $nameLookups = []; + + public function __construct( + private ReflectionProvider $provider, + private ValueDependencyCollector $valueDependencyCollector, + ) { } public function hasClass(string $className): bool { $lowerClassName = strtolower($className); + $context = ValueDependencyCollector::getContext(); if (isset($this->knownClasses[$lowerClassName])) { + if ($this->knownClasses[$lowerClassName] !== $context) { + $this->knownClasses[$lowerClassName] = $context; + $this->valueDependencyCollector->recordFoundSymbol(ValueDependencyCollector::KIND_CLASS, $className); + } return true; } if (isset($this->unknownClasses[$className])) { + if ($this->unknownClasses[$className] !== $context) { + $this->unknownClasses[$className] = $context; + $this->valueDependencyCollector->recordMissingSymbol(ValueDependencyCollector::KIND_CLASS, $className); + } return false; } $result = $this->provider->hasClass($className); if ($result) { - $this->knownClasses[$lowerClassName] = true; + $this->knownClasses[$lowerClassName] = $context; + $this->valueDependencyCollector->recordFoundSymbol(ValueDependencyCollector::KIND_CLASS, $className); } else { - $this->unknownClasses[$className] = true; + $this->unknownClasses[$className] = $context; + $this->valueDependencyCollector->recordMissingSymbol(ValueDependencyCollector::KIND_CLASS, $className); } return $result; @@ -56,12 +80,35 @@ public function hasClass(string $className): bool public function getClass(string $className): ClassReflection { - return $this->classes[strtolower($className)] ??= $this->provider->getClass($className); + $lowerClassName = strtolower($className); + $classReflection = $this->classes[$lowerClassName] ??= $this->provider->getClass($className); + $this->recordFoundClass($className, $lowerClassName); + + return $classReflection; } public function getClassName(string $className): string { - return $this->classNames[strtolower($className)] ??= $this->provider->getClassName($className); + $lowerClassName = strtolower($className); + $name = $this->classNames[$lowerClassName] ??= $this->provider->getClassName($className); + $this->recordFoundClass($className, $lowerClassName); + + return $name; + } + + /** + * @param lowercase-string $lowerClassName + */ + private function recordFoundClass(string $className, string $lowerClassName): void + { + // read after the class was found: building its reflection resolves declarations in other contexts + $context = ValueDependencyCollector::getContext(); + if (($this->knownClasses[$lowerClassName] ?? null) === $context) { + return; + } + + $this->knownClasses[$lowerClassName] = $context; + $this->valueDependencyCollector->recordFoundSymbol(ValueDependencyCollector::KIND_CLASS, $className); } public function getAnonymousClassReflection(Node\Stmt\Class_ $classNode, Scope $scope): ClassReflection @@ -76,32 +123,83 @@ public function getUniversalObjectCratesClasses(): array public function hasFunction(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): bool { - return $this->provider->hasFunction($nameNode, $namespaceAnswerer); + return $this->resolveFunctionName($nameNode, $namespaceAnswerer) !== null; } public function getFunction(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): FunctionReflection { - return $this->provider->getFunction($nameNode, $namespaceAnswerer); + $function = $this->provider->getFunction($nameNode, $namespaceAnswerer); + $this->recordNameLookup(ValueDependencyCollector::KIND_FUNCTION, $nameNode, $namespaceAnswerer, fn (): ?string => $this->provider->resolveFunctionName($nameNode, $namespaceAnswerer)); + + return $function; } public function resolveFunctionName(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): ?string { - return $this->provider->resolveFunctionName($nameNode, $namespaceAnswerer); + $resolved = $this->provider->resolveFunctionName($nameNode, $namespaceAnswerer); + $this->recordNameLookup(ValueDependencyCollector::KIND_FUNCTION, $nameNode, $namespaceAnswerer, static fn (): ?string => $resolved); + + return $resolved; } public function hasConstant(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): bool { - return $this->provider->hasConstant($nameNode, $namespaceAnswerer); + return $this->resolveConstantName($nameNode, $namespaceAnswerer) !== null; } public function getConstant(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): ConstantReflection { - return $this->provider->getConstant($nameNode, $namespaceAnswerer); + $constant = $this->provider->getConstant($nameNode, $namespaceAnswerer); + $this->recordNameLookup(ValueDependencyCollector::KIND_CONSTANT, $nameNode, $namespaceAnswerer, fn (): ?string => $this->provider->resolveConstantName($nameNode, $namespaceAnswerer)); + + return $constant; } public function resolveConstantName(Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer): ?string { - return $this->provider->resolveConstantName($nameNode, $namespaceAnswerer); + $resolved = $this->provider->resolveConstantName($nameNode, $namespaceAnswerer); + $this->recordNameLookup(ValueDependencyCollector::KIND_CONSTANT, $nameNode, $namespaceAnswerer, static fn (): ?string => $resolved); + + return $resolved; + } + + /** + * An unqualified name in a namespace is looked for in the namespace first, then globally: + * strlen() in namespace App calls App\strlen() once it is declared. Both are recorded - the + * one in the namespace not found, unless it was. + * + * @param ValueDependencyCollector::KIND_FUNCTION|ValueDependencyCollector::KIND_CONSTANT $kind + * @param callable(): ?string $resolve the name it resolved to + */ + private function recordNameLookup(string $kind, Node\Name $nameNode, ?NamespaceAnswerer $namespaceAnswerer, callable $resolve): void + { + $namespace = $namespaceAnswerer?->getNamespace(); + $name = (string) $nameNode; + $fallback = $namespace !== null && !$nameNode->isFullyQualified(); + $lookupKey = $kind . ':' . ($fallback ? $namespace . '\\' : '\\') . $name; + $context = ValueDependencyCollector::getContext(); + if (($this->nameLookups[$lookupKey] ?? null) === $context) { + return; + } + + $this->nameLookups[$lookupKey] = $context; + $resolved = $resolve(); + if ($fallback) { + $namespacedName = sprintf('%s\\%s', $namespace, $name); + if ($resolved === $namespacedName) { + $this->valueDependencyCollector->recordFoundSymbol($kind, $resolved); + return; + } + + $this->valueDependencyCollector->recordMissingSymbol($kind, $namespacedName); + } + + if ($resolved === null) { + $this->valueDependencyCollector->recordMissingSymbol($kind, $name); + return; + } + + $this->valueDependencyCollector->recordFoundSymbol($kind, $resolved); } } diff --git a/src/Reflection/ReflectionProvider/ReflectionProviderFactory.php b/src/Reflection/ReflectionProvider/ReflectionProviderFactory.php index 9f2e6424fdb..4cd2489d804 100644 --- a/src/Reflection/ReflectionProvider/ReflectionProviderFactory.php +++ b/src/Reflection/ReflectionProvider/ReflectionProviderFactory.php @@ -2,6 +2,7 @@ namespace PHPStan\Reflection\ReflectionProvider; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\Reflection\ReflectionProvider; @@ -13,13 +14,14 @@ final class ReflectionProviderFactory public function __construct( #[AutowiredParameter(ref: '@betterReflectionProvider')] private ReflectionProvider $staticReflectionProvider, + private ValueDependencyCollector $valueDependencyCollector, ) { } public function create(): ReflectionProvider { - return new MemoizingReflectionProvider($this->staticReflectionProvider); + return new MemoizingReflectionProvider($this->staticReflectionProvider, $this->valueDependencyCollector); } } diff --git a/src/Testing/PHPStanTestCase.php b/src/Testing/PHPStanTestCase.php index f7947ba02f4..ec8f1cb06aa 100644 --- a/src/Testing/PHPStanTestCase.php +++ b/src/Testing/PHPStanTestCase.php @@ -8,6 +8,7 @@ use PHPStan\Analyser\Error; use PHPStan\Analyser\ScopeFactory; use PHPStan\Analyser\TypeSpecifier; +use PHPStan\Analyser\ValueDependencyCollector; use PHPStan\BetterReflection\Reflector\Reflector; use PHPStan\DependencyInjection\Reflection\ClassReflectionExtensionRegistryProvider; use PHPStan\Node\Printer\ExprPrinter; @@ -114,6 +115,7 @@ public static function createScopeFactory(ReflectionProvider $reflectionProvider $container->getByType(UnaryOperatorTypeSpecifyingExtensionRegistry::class), new OversizedArrayBuilder(), $container->getParameter('usePathConstantsAsConstantString'), + $container->getByType(ValueDependencyCollector::class), ); return new ScopeFactory( diff --git a/src/Type/FileTypeMapper.php b/src/Type/FileTypeMapper.php index 13fa366d6fe..b928944736a 100644 --- a/src/Type/FileTypeMapper.php +++ b/src/Type/FileTypeMapper.php @@ -281,6 +281,7 @@ public function getNameScope( $parent->shouldBypassTypeAliases(), $parent->getConstUses(), $parent->getClassNameForTypeAlias(), + $fileName, ); if ($parent->getTraitData() !== null) { [$traitFileName, $traitClassName, $traitName, $lookForTraitName, $traitDocComment] = $parent->getTraitData(); @@ -364,6 +365,7 @@ public function getNameScope( $intermediaryNameScope->shouldBypassTypeAliases(), $intermediaryNameScope->getConstUses(), $intermediaryNameScope->getClassNameForTypeAlias(), + $fileName, ); } finally { unset($this->inProcess[$nameScopeKey]); diff --git a/tests/PHPStan/Analyser/ResultCache/ResultCacheManagerCollectedDataTest.php b/tests/PHPStan/Analyser/ResultCache/ResultCacheManagerCollectedDataTest.php index 42e741345d6..291e9ded834 100644 --- a/tests/PHPStan/Analyser/ResultCache/ResultCacheManagerCollectedDataTest.php +++ b/tests/PHPStan/Analyser/ResultCache/ResultCacheManagerCollectedDataTest.php @@ -20,6 +20,8 @@ use PHPStan\Php\ComposerPhpVersionFactory; use PHPStan\Php\PhpVersion; use PHPStan\PhpDoc\StubFilesProvider; +use PHPStan\Reflection\BetterReflection\SourceLocator\ComposerJsonAndInstalledJsonSourceLocatorMaker; +use PHPStan\Reflection\BetterReflection\SourceLocator\SymbolFinderInFiles; use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider; use PHPStan\Rules\Comparison\ConstantConditionInTraitCollector; use PHPStan\Rules\DeadCode\MethodWithoutImpurePointsCollector; @@ -518,6 +520,9 @@ private function createManager(): ResultCacheManager composerPhpVersionFactory: $container->getByType(ComposerPhpVersionFactory::class), fileStatSignatures: $container->getByType(FileStatSignatures::class), valueDependencyCollector: $container->getByType(ValueDependencyCollector::class), + symbolFinderInFiles: $container->getByType(SymbolFinderInFiles::class), + composerSourceLocatorMaker: $container->getByType(ComposerJsonAndInstalledJsonSourceLocatorMaker::class), + tmpDir: $this->directory . '/tmp', ); } diff --git a/tests/PHPStan/Reflection/BetterReflection/BetterReflectionProviderTest.php b/tests/PHPStan/Reflection/BetterReflection/BetterReflectionProviderTest.php index 961cfee9c50..a1bba9dd075 100644 --- a/tests/PHPStan/Reflection/BetterReflection/BetterReflectionProviderTest.php +++ b/tests/PHPStan/Reflection/BetterReflection/BetterReflectionProviderTest.php @@ -3,10 +3,13 @@ namespace PHPStan\Reflection\BetterReflection; use PhpParser\Node; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Stmt\Class_; use PhpParser\NodeFinder; use PHPStan\Analyser\ScopeContext; use PHPStan\Analyser\ScopeFactory; +use PHPStan\Reflection\ReflectionProvider; use PHPStan\Testing\PHPStanTestCase; use function array_shift; use function file_put_contents; @@ -24,6 +27,15 @@ class BetterReflectionProviderTest extends PHPStanTestCase private const ANONYMOUS_CLASS_COUNT_LIMIT = 10; + public function testFullyQualifiedNameDoesNotAnswerNameWithLeadingBackslash(): void + { + $reflectionProvider = self::getContainer()->getByType(ReflectionProvider::class); + + // the name of a callable string keeps its backslash, a fully qualified name does not + $this->assertSame('strval', $reflectionProvider->resolveFunctionName(new FullyQualified('strval'), null)); + $this->assertSame('\\strval', $reflectionProvider->resolveFunctionName(new Name('\\strval'), null)); + } + public function testAnonymousClassesOfOneFileShareItsContents(): void { $fileName = sys_get_temp_dir() . '/phpstan-anonymous-classes-' . uniqid() . '.php'; diff --git a/tests/PHPStan/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorTest.php b/tests/PHPStan/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorTest.php index 3e72877eef6..6032ea1d313 100644 --- a/tests/PHPStan/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorTest.php +++ b/tests/PHPStan/Reflection/BetterReflection/SourceLocator/OptimizedDirectorySourceLocatorTest.php @@ -305,6 +305,24 @@ public function testFunctionDoesNotExist(string $functionName): void $reflector->reflectFunction($functionName); } + public function testGroupAnswersLikeTheLocatorsInTurn(): void + { + $factory = self::getContainer()->getByType(OptimizedDirectorySourceLocatorFactory::class); + $first = $factory->createByDirectory(__DIR__ . '/data/group/first'); + $second = $factory->createByDirectory(__DIR__ . '/data/group/second'); + + $reflector = new DefaultReflector(OptimizedDirectorySourceLocatorGroup::create([$first, $second])); + $this->assertStringEndsWith('/first/Duplicate.php', (string) $reflector->reflectClass('OptimizedDirectoryGroup\\duplicate')->getFileName()); + $this->assertSame('OptimizedDirectoryGroup\\onlyInSecond', $reflector->reflectFunction('optimizeddirectorygroup\\onlyinsecond')->getName()); + $this->assertSame('OptimizedDirectoryGroup\\ONLY_IN_SECOND', $reflector->reflectConstant('OptimizedDirectoryGroup\\ONLY_IN_SECOND')->getName()); + + $reflector = new DefaultReflector(OptimizedDirectorySourceLocatorGroup::create([$second, $first])); + $this->assertStringEndsWith('/second/Duplicate.php', (string) $reflector->reflectClass('OptimizedDirectoryGroup\\Duplicate')->getFileName()); + + $this->expectException(IdentifierNotFound::class); + $reflector->reflectClass('OptimizedDirectoryGroup\\Missing'); + } + public function testBug5525(): void { $factory = self::getContainer()->getByType(OptimizedDirectorySourceLocatorFactory::class); diff --git a/tests/PHPStan/Reflection/BetterReflection/SourceLocator/data/group/first/Duplicate.php b/tests/PHPStan/Reflection/BetterReflection/SourceLocator/data/group/first/Duplicate.php new file mode 100644 index 00000000000..1e665e6f36a --- /dev/null +++ b/tests/PHPStan/Reflection/BetterReflection/SourceLocator/data/group/first/Duplicate.php @@ -0,0 +1,8 @@ +nameLookups['function:' . $lookupName] ?? null) === + * ValueDependencyCollector::getContext() of exactly a + * MemoizingReflectionProvider - the lookup was recorded in the current + * context already, see MemoizingReflectionProvider::recordNameLookup(); the + * lookup name is the namespace and the name for an unqualified name in a + * namespace, the name with a leading backslash otherwise. false also when + * the reader cannot tell (the caller then calls the method, which records + * it); error = pending exception */ +bool functionLookupRecorded(zval *provider, zval *nameNode, zval *namespaceAnswerer, bool &error) +{ + error = false; + zend_long context; + if (!pt_value_dependency_context(context)) return false; + const ClassSlots *memoizing = slotsOf(pt_fra_memoizing_reflection_provider, PT_CLASS_MEMOIZING_REFLECTION_PROVIDER, Z_OBJ_P(provider), pt_fra_memoizing_names, 2); + if (memoizing == NULL) return false; + zval *lookups = initializedSlot(provider, memoizing, 1); + if (lookups == NULL || Z_TYPE_P(lookups) != IS_ARRAY) return false; + bool fullyQualified; + zend_string *name = plainName(nameNode, fullyQualified); + if (name == NULL) return false; + zv::Val ns = zv::Val::null(); + if (namespaceAnswerer != NULL && Z_TYPE_P(namespaceAnswerer) != IS_NULL) { + if (Z_TYPE_P(namespaceAnswerer) != IS_OBJECT) return false; + ns = pt_mutating_scope_get_namespace(Z_OBJ_P(namespaceAnswerer)); + if (UNEXPECTED(ns.isUndef())) { + error = true; + return false; + } + if (UNEXPECTED(!ns.isNull() && !ns.ref().isString())) return false; + } + zend_string *nsString = !ns.isNull() && !fullyQualified ? Z_STR_P(ns.raw()) : ZSTR_EMPTY_ALLOC(); + size_t length = sizeof("function:") - 1 + ZSTR_LEN(nsString) + 1 + ZSTR_LEN(name); + zend_string *key = zend_string_alloc(length, 0); + char *cursor = ZSTR_VAL(key); + memcpy(cursor, "function:", sizeof("function:") - 1); + cursor += sizeof("function:") - 1; + memcpy(cursor, ZSTR_VAL(nsString), ZSTR_LEN(nsString)); + cursor += ZSTR_LEN(nsString); + *cursor++ = '\\'; + memcpy(cursor, ZSTR_VAL(name), ZSTR_LEN(name)); + cursor += ZSTR_LEN(name); + *cursor = '\0'; + zval *found = zend_symtable_find(Z_ARRVAL_P(lookups), key); + zend_string_release(key); + if (found == NULL) return false; + ZVAL_DEREF(found); + return Z_TYPE_P(found) == IS_LONG && Z_LVAL_P(found) == context; +} + /* $provider->method($nameNode, $namespaceAnswerer) through the engine */ zv::Val callProvider(zval *provider, const char *lcname, size_t len, const char *name, zval *nameNode, zval *namespaceAnswerer) { @@ -334,7 +391,8 @@ bool pt_reflection_provider_has_function(zval *provider, zval *nameNode, zval *n { const ClassSlots *slots = NULL; zval *better = betterReflectionProviderOf(provider, slots); - if (EXPECTED(better != NULL)) { + bool lookupError = false; + if (EXPECTED(better != NULL) && functionLookupRecorded(provider, nameNode, namespaceAnswerer, lookupError)) { MemoAnswer answer; zend_string *resolved = NULL; zv::Str hold; @@ -345,6 +403,7 @@ bool pt_reflection_provider_has_function(zval *provider, zval *nameNode, zval *n return true; } } + if (UNEXPECTED(lookupError)) return false; zv::Val value = callProvider(provider, PT_LC("hasfunction"), "hasFunction", nameNode, namespaceAnswerer); if (UNEXPECTED(value.isUndef())) return false; out = zend_is_true(value.raw()); @@ -355,7 +414,8 @@ zv::Val pt_reflection_provider_get_function(zval *provider, zval *nameNode, zval { const ClassSlots *slots = NULL; zval *better = betterReflectionProviderOf(provider, slots); - if (EXPECTED(better != NULL)) { + bool lookupError = false; + if (EXPECTED(better != NULL) && functionLookupRecorded(provider, nameNode, namespaceAnswerer, lookupError)) { MemoAnswer answer; zend_string *resolved = NULL; zv::Str hold; @@ -372,6 +432,7 @@ zv::Val pt_reflection_provider_get_function(zval *provider, zval *nameNode, zval } } } + if (UNEXPECTED(lookupError)) return zv::Val(); return callProvider(provider, PT_LC("getfunction"), "getFunction", nameNode, namespaceAnswerer); } diff --git a/turbo-ext/src/InitializerExprTypeResolver.cpp b/turbo-ext/src/InitializerExprTypeResolver.cpp index 4e8cc02485c..b97bd81ba40 100644 --- a/turbo-ext/src/InitializerExprTypeResolver.cpp +++ b/turbo-ext/src/InitializerExprTypeResolver.cpp @@ -2776,7 +2776,21 @@ class InitializerExprTypeResolver IETR_VAL(declaringFileNameHold, callOn(reflectionConstantDeclaringClass.raw(), mGetFileName)); zv::Val declaringFileName = zend_is_true(declaringFileNameHold.raw()) ? std::move(declaringFileNameHold) : zv::Val::null(); IETR_VAL(constantContext, contextFromClass(declaringClassName.raw(), declaringFileName.raw())); + /* the resolved type is cached: a class it names that does not + * exist is what the declaring class declares depends on — + * ValueDependencyCollector::enterDeclaration(), as in the twin. + * With an exception pending (an internal error already) the + * declaration is not left: what is missed later counts for the + * class too, more is re-analysed, nothing goes stale. */ + zval *valueDependencyCollector = prop(slots::valueDependencyCollector); + zv::Args enterDeclarationArgs{declaringFileName.raw(), declaringClassName.raw()}; + if (UNEXPECTED(pt_type_call(Z_OBJ_P(valueDependencyCollector), PT_LC("enterdeclaration"), 2, enterDeclarationArgs).isUndef())) { + return zv::Val(); + } IETR_VAL(constantType, getTypeRecursive(valueExpression.raw(), constantContext.raw())); + if (UNEXPECTED(pt_type_call(Z_OBJ_P(valueDependencyCollector), PT_LC("leavedeclaration"), 0, NULL).isUndef())) { + return zv::Val(); + } zv::Val nativeType = zv::Val::null(); { IETR_VAL(reflectionType, callOn(reflectionConstant.raw(), mGetType)); @@ -3596,9 +3610,9 @@ PT_MINIT_REGISTRATION(pt_register_initializer_expr_type_resolver) /* the real parameter class names: the DI container autowires the * service by reflecting the constructor */ cls.method(sigs::__construct, [](INTERNAL_FUNCTION_PARAMETERS) { - zval *constantResolver, *reflectionProviderProvider, *phpVersion, *operatorTypeSpecifyingExtensionRegistry, *unaryOperatorTypeSpecifyingExtensionRegistry, *oversizedArrayBuilder; + zval *constantResolver, *reflectionProviderProvider, *phpVersion, *operatorTypeSpecifyingExtensionRegistry, *unaryOperatorTypeSpecifyingExtensionRegistry, *oversizedArrayBuilder, *valueDependencyCollector; bool usePathConstantsAsConstantString; - ZEND_PARSE_PARAMETERS_START(7, 7) + ZEND_PARSE_PARAMETERS_START(8, 8) Z_PARAM_OBJECT(constantResolver) Z_PARAM_OBJECT(reflectionProviderProvider) Z_PARAM_OBJECT(phpVersion) @@ -3606,6 +3620,7 @@ PT_MINIT_REGISTRATION(pt_register_initializer_expr_type_resolver) Z_PARAM_OBJECT(unaryOperatorTypeSpecifyingExtensionRegistry) Z_PARAM_OBJECT(oversizedArrayBuilder) Z_PARAM_BOOL(usePathConstantsAsConstantString) + Z_PARAM_OBJECT(valueDependencyCollector) ZEND_PARSE_PARAMETERS_END(); zend_object *self = Z_OBJ_P(ZEND_THIS); pt_write_slot(self, slots::constantResolver, constantResolver); @@ -3617,6 +3632,7 @@ PT_MINIT_REGISTRATION(pt_register_initializer_expr_type_resolver) zval flag = {}; ZVAL_BOOL(&flag, usePathConstantsAsConstantString); pt_write_slot(self, slots::usePathConstantsAsConstantString, &flag); + pt_write_slot(self, slots::valueDependencyCollector, valueDependencyCollector); }); cls.method(sigs::getType, [](INTERNAL_FUNCTION_PARAMETERS) { diff --git a/turbo-ext/src/ReflectionAccess.cpp b/turbo-ext/src/ReflectionAccess.cpp index 04e8ce871f1..a2ba57295f7 100644 --- a/turbo-ext/src/ReflectionAccess.cpp +++ b/turbo-ext/src/ReflectionAccess.cpp @@ -7,8 +7,11 @@ * provider from the twin's `private static ?ReflectionProvider * $instance` (the method, which throws, while it is null); * - MemoizingReflectionProvider::hasClass() / getClass(): the memoized - * answer from $knownClasses / $unknownClasses / $classes (the method, - * which asks the decorated provider and memoizes, on a miss); + * answer from $knownClasses / $unknownClasses / $classes while it is + * recorded in the current context - the value in $knownClasses / + * $unknownClasses is ValueDependencyCollector::$context (the method, + * which asks the decorated provider, memoizes and records the lookup, + * otherwise); * - LazyClassReflectionExtensionRegistryProvider::getRegistry() followed by * one ClassReflectionExtensionRegistry getter: the built registry from the * provider's $registry memo and the extension from the registry's own @@ -49,6 +52,8 @@ struct StaticSlot MemoizingProviderSlots pt_mrp_slots = { NULL, 0, 0, 0 }; StaticSlot pt_rpsa_slot = { NULL, NULL }; +/* ValueDependencyCollector's `private static int $context` */ +StaticSlot pt_vdc_context_slot = { NULL, NULL }; /* the $registry memo slot of the lazy registry provider's class entry */ struct RegistryProviderSlots @@ -132,6 +137,40 @@ const MemoizingProviderSlots *memoizingProviderSlots(zend_object *provider, bool return &pt_mrp_slots; } +} // namespace + +/* ValueDependencyCollector::getContext(); false while it cannot be read - + * the class not loaded or its statics not initialized yet, and then + * nothing is answered from the memo */ +bool pt_value_dependency_context(zend_long &context) +{ + if (UNEXPECTED(pt_vdc_context_slot.slot == NULL)) { + zend_class_entry *ce = pt_class_loaded(PT_CLASS_VALUE_DEPENDENCY_COLLECTOR); + if (ce == NULL) return false; + zval *slot = staticSlot(ce, PT_LC("context")); + if (slot == NULL) return false; + pt_vdc_context_slot = { ce, slot }; + } + zval *value = pt_vdc_context_slot.slot; + ZVAL_DEREF(value); + if (UNEXPECTED(Z_TYPE_P(value) != IS_LONG)) return false; + context = Z_LVAL_P(value); + return true; +} + +namespace { + +/* $memo[$key] === $context: the memoized answer was recorded in the current + * context */ +bool recordedInContext(zval *memo, zend_string *key, zend_long context) +{ + if (Z_TYPE_P(memo) != IS_ARRAY) return false; + zval *found = zend_symtable_find(Z_ARRVAL_P(memo), key); + if (found == NULL) return false; + ZVAL_DEREF(found); + return Z_TYPE_P(found) == IS_LONG && Z_LVAL_P(found) == context; +} + /* $object->method(...$args) through the object's own class entry, coerced * to bool; false = pending exception */ [[nodiscard]] bool callBool(zend_object *object, const char *lcname, size_t len, uint32_t argc, zval *argv, bool &out) @@ -142,23 +181,13 @@ const MemoizingProviderSlots *memoizingProviderSlots(zend_object *provider, bool return true; } -/* isset($array[$key]) for a string offset: the symtable lookup (a numeric - * string is an integer key), an entry holding null is not set */ -bool issetStringOffset(zval *array, zend_string *key) -{ - if (Z_TYPE_P(array) != IS_ARRAY) return false; - zval *found = zend_symtable_find(Z_ARRVAL_P(array), key); - if (found == NULL) return false; - ZVAL_DEREF(found); - return Z_TYPE_P(found) != IS_NULL; -} - } // namespace void pt_reflection_access_rinit() { pt_mrp_slots.ce = NULL; pt_rpsa_slot = { NULL, NULL }; + pt_vdc_context_slot = { NULL, NULL }; pt_registry_provider_slots.ce = NULL; pt_registry_slots.ce = NULL; pt_lazy_extensions_collection_slots.ce = NULL; @@ -195,23 +224,26 @@ zv::Val pt_reflection_provider_instance() /* {{{ MemoizingReflectionProvider */ -/* $lower = strtolower($className); if (isset($this->knownClasses[$lower])) - * return true; if (isset($this->unknownClasses[$className])) return false; - * — the memoized answer; the method asks the decorated provider otherwise. +/* $lower = strtolower($className); $context = ValueDependencyCollector::getContext(); + * if (($this->knownClasses[$lower] ?? null) === $context) return true; + * if (($this->unknownClasses[$className] ?? null) === $context) return false; + * — the memoized answer, recorded in this context already; the method asks + * the decorated provider, or records the remembered answer, otherwise. * strtolower() is ASCII-only since PHP 8.2, as zend_string_tolower() is. */ bool pt_reflection_provider_has_class(zend_object *provider, zval *className, bool &out) { bool error; const MemoizingProviderSlots *slots = memoizingProviderSlots(provider, error); - if (slots != NULL && Z_TYPE_P(className) == IS_STRING) { + zend_long context; + if (slots != NULL && Z_TYPE_P(className) == IS_STRING && pt_value_dependency_context(context)) { zend_string *lower = zend_string_tolower(Z_STR_P(className)); - bool known = issetStringOffset(OBJ_PROP(provider, slots->knownClasses), lower); + bool known = recordedInContext(OBJ_PROP(provider, slots->knownClasses), lower, context); zend_string_release(lower); if (known) { out = true; return true; } - if (issetStringOffset(OBJ_PROP(provider, slots->unknownClasses), Z_STR_P(className))) { + if (recordedInContext(OBJ_PROP(provider, slots->unknownClasses), Z_STR_P(className), context)) { out = false; return true; } @@ -230,16 +262,21 @@ zv::Val pt_reflection_provider_has_class_zv(zend_object *provider, zval *classNa } /* return $this->classes[strtolower($className)] ??= $this->provider->getClass($className); - * — the memoized reflection; the method resolves and memoizes otherwise */ + * — the memoized reflection while it is recorded in the current context + * (see pt_reflection_provider_has_class()); the method resolves, memoizes + * and records otherwise */ zv::Val pt_reflection_provider_get_class(zend_object *provider, zval *className) { bool error; const MemoizingProviderSlots *slots = memoizingProviderSlots(provider, error); - if (slots != NULL && Z_TYPE_P(className) == IS_STRING) { + zend_long context; + if (slots != NULL && Z_TYPE_P(className) == IS_STRING && pt_value_dependency_context(context)) { zval *classes = OBJ_PROP(provider, slots->classes); if (EXPECTED(Z_TYPE_P(classes) == IS_ARRAY)) { zend_string *lower = zend_string_tolower(Z_STR_P(className)); - zval *found = zend_symtable_find(Z_ARRVAL_P(classes), lower); + zval *found = recordedInContext(OBJ_PROP(provider, slots->knownClasses), lower, context) + ? zend_symtable_find(Z_ARRVAL_P(classes), lower) + : NULL; zend_string_release(lower); if (found != NULL) { ZVAL_DEREF(found); diff --git a/turbo-ext/src/generated/InitializerExprTypeResolver.h b/turbo-ext/src/generated/InitializerExprTypeResolver.h index da105b41cb8..6c25986814d 100644 --- a/turbo-ext/src/generated/InitializerExprTypeResolver.h +++ b/turbo-ext/src/generated/InitializerExprTypeResolver.h @@ -19,6 +19,7 @@ inline constexpr uint32_t operatorTypeSpecifyingExtensionRegistry = 5; inline constexpr uint32_t unaryOperatorTypeSpecifyingExtensionRegistry = 6; inline constexpr uint32_t oversizedArrayBuilder = 7; inline constexpr uint32_t usePathConstantsAsConstantString = 8; +inline constexpr uint32_t valueDependencyCollector = 9; } // namespace slot inline void declareClass(reg::Class &cls) @@ -38,6 +39,7 @@ inline void declareProperties(reg::Class &cls) cls.property("unaryOperatorTypeSpecifyingExtensionRegistry", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\Type\\UnaryOperatorTypeSpecifyingExtensionRegistry"); cls.property("oversizedArrayBuilder", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\Type\\Constant\\OversizedArrayBuilder"); cls.property("usePathConstantsAsConstantString", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_BOOL); + cls.property("valueDependencyCollector", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\Analyser\\ValueDependencyCollector"); } /* the string and parameter tables the signatures below index into (see reg::Sig) */ @@ -56,96 +58,98 @@ inline constexpr char strings[] = "oversizedArrayBuilder\0" /* 373 */ "PHPStan\\Type\\Constant\\OversizedArrayBuilder\0" /* 395 */ "usePathConstantsAsConstantString\0" /* 439 */ - "__construct\0" /* 472 */ - "expr\0" /* 484 */ - "PhpParser\\Node\\Expr\0" /* 489 */ - "context\0" /* 509 */ - "PHPStan\\Reflection\\InitializerExprContext\0" /* 517 */ - "\0" /* 559 */ - "PHPStan\\Type\\Type\0" /* 560 */ - "getType\0" /* 578 */ - "className\0" /* 586 */ - "caseName\0" /* 596 */ - "valueExpr\0" /* 605 */ - "getEnumCaseValueType\0" /* 615 */ - "left\0" /* 636 */ - "right\0" /* 641 */ - "getTypeCallback\0" /* 647 */ - "getConcatType\0" /* 663 */ - "resolveConcatType\0" /* 677 */ - "PhpParser\\Node\\Expr\\Array_\0" /* 695 */ - "phpVersions\0" /* 722 */ - "PHPStan\\Php\\PhpVersions\0" /* 734 */ - "null\0" /* 758 */ - "getArrayType\0" /* 763 */ - "PhpParser\\Node\\Expr\\Cast\0" /* 776 */ - "getCastType\0" /* 801 */ - "exprType\0" /* 813 */ - "getCastObjectType\0" /* 822 */ - "type\0" /* 840 */ - "isNullable\0" /* 845 */ - "isVariadic\0" /* 856 */ - "getFunctionType\0" /* 867 */ - "parameter\0" /* 883 */ - "PhpParser\\Node\\Param\0" /* 893 */ - "isParameterValueNullable\0" /* 914 */ - "PhpParser\\Node\\Expr\\CallLike\0" /* 939 */ - "nativeTypesPromoted\0" /* 968 */ - "getFirstClassCallableType\0" /* 988 */ - "function\0" /* 1014 */ - "PHPStan\\Reflection\\FunctionReflection|PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 1023 */ - "variants\0" /* 1105 */ - "createFirstClassCallable\0" /* 1114 */ - "parameters\0" /* 1139 */ - "names\0" /* 1150 */ - "renameParameters\0" /* 1156 */ - "getBitwiseAndType\0" /* 1173 */ - "getBitwiseOrType\0" /* 1191 */ - "getBitwiseXorType\0" /* 1208 */ - "getSpaceshipType\0" /* 1226 */ - "getDivType\0" /* 1243 */ - "getModType\0" /* 1254 */ - "getPlusType\0" /* 1265 */ - "getMinusType\0" /* 1277 */ - "getMulType\0" /* 1290 */ - "getPowType\0" /* 1301 */ - "getShiftLeftType\0" /* 1312 */ - "getShiftRightType\0" /* 1329 */ - "leftType\0" /* 1347 */ - "rightType\0" /* 1356 */ - "PHPStan\\Type\\TypeResult\0" /* 1366 */ - "resolveIdenticalType\0" /* 1390 */ - "resolveEqualType\0" /* 1411 */ - "isNonNumericString\0" /* 1428 */ - "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 1447 */ - "valueComparisonCallback\0" /* 1487 */ - "resolveConstantArrayTypeComparison\0" /* 1511 */ - "class\0" /* 1546 */ - "PhpParser\\Node\\Name|PhpParser\\Node\\Expr\0" /* 1552 */ - "constantName\0" /* 1592 */ - "classReflection\0" /* 1605 */ - "PHPStan\\Reflection\\ClassReflection\0" /* 1621 */ - "false\0" /* 1656 */ - "getClassConstFetchTypeByReflection\0" /* 1662 */ - "fetchedOnType\0" /* 1697 */ - "transformStaticType\0" /* 1711 */ - "getClassConstFetchType\0" /* 1731 */ - "getUnaryPlusType\0" /* 1754 */ - "getUnaryMinusType\0" /* 1771 */ - "getBitwiseNotType\0" /* 1789 */ - "getBitwiseNotTypeFromType\0" /* 1807 */ - "name\0" /* 1833 */ - "PhpParser\\Node\\Name\0" /* 1838 */ - "resolveName\0" /* 1858 */ - "PHPStan\\Type\\TypeWithClassName\0" /* 1870 */ - "resolveTypeByName\0" /* 1901 */ - "classType\0" /* 1919 */ - "methodReflectionCandidate\0" /* 1929 */ - "PHPStan\\Reflection\\MethodReflection\0" /* 1955 */ - "resolveTypeByNameWithLateStaticBinding\0" /* 1991 */ - "PHPStan\\Reflection\\ReflectionProvider\0" /* 2030 */ - "getReflectionProvider\0" /* 2068 */ - "getNeverType"; /* 2090 */ + "valueDependencyCollector\0" /* 472 */ + "PHPStan\\Analyser\\ValueDependencyCollector\0" /* 497 */ + "__construct\0" /* 539 */ + "expr\0" /* 551 */ + "PhpParser\\Node\\Expr\0" /* 556 */ + "context\0" /* 576 */ + "PHPStan\\Reflection\\InitializerExprContext\0" /* 584 */ + "\0" /* 626 */ + "PHPStan\\Type\\Type\0" /* 627 */ + "getType\0" /* 645 */ + "className\0" /* 653 */ + "caseName\0" /* 663 */ + "valueExpr\0" /* 672 */ + "getEnumCaseValueType\0" /* 682 */ + "left\0" /* 703 */ + "right\0" /* 708 */ + "getTypeCallback\0" /* 714 */ + "getConcatType\0" /* 730 */ + "resolveConcatType\0" /* 744 */ + "PhpParser\\Node\\Expr\\Array_\0" /* 762 */ + "phpVersions\0" /* 789 */ + "PHPStan\\Php\\PhpVersions\0" /* 801 */ + "null\0" /* 825 */ + "getArrayType\0" /* 830 */ + "PhpParser\\Node\\Expr\\Cast\0" /* 843 */ + "getCastType\0" /* 868 */ + "exprType\0" /* 880 */ + "getCastObjectType\0" /* 889 */ + "type\0" /* 907 */ + "isNullable\0" /* 912 */ + "isVariadic\0" /* 923 */ + "getFunctionType\0" /* 934 */ + "parameter\0" /* 950 */ + "PhpParser\\Node\\Param\0" /* 960 */ + "isParameterValueNullable\0" /* 981 */ + "PhpParser\\Node\\Expr\\CallLike\0" /* 1006 */ + "nativeTypesPromoted\0" /* 1035 */ + "getFirstClassCallableType\0" /* 1055 */ + "function\0" /* 1081 */ + "PHPStan\\Reflection\\FunctionReflection|PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 1090 */ + "variants\0" /* 1172 */ + "createFirstClassCallable\0" /* 1181 */ + "parameters\0" /* 1206 */ + "names\0" /* 1217 */ + "renameParameters\0" /* 1223 */ + "getBitwiseAndType\0" /* 1240 */ + "getBitwiseOrType\0" /* 1258 */ + "getBitwiseXorType\0" /* 1275 */ + "getSpaceshipType\0" /* 1293 */ + "getDivType\0" /* 1310 */ + "getModType\0" /* 1321 */ + "getPlusType\0" /* 1332 */ + "getMinusType\0" /* 1344 */ + "getMulType\0" /* 1357 */ + "getPowType\0" /* 1368 */ + "getShiftLeftType\0" /* 1379 */ + "getShiftRightType\0" /* 1396 */ + "leftType\0" /* 1414 */ + "rightType\0" /* 1423 */ + "PHPStan\\Type\\TypeResult\0" /* 1433 */ + "resolveIdenticalType\0" /* 1457 */ + "resolveEqualType\0" /* 1478 */ + "isNonNumericString\0" /* 1495 */ + "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 1514 */ + "valueComparisonCallback\0" /* 1554 */ + "resolveConstantArrayTypeComparison\0" /* 1578 */ + "class\0" /* 1613 */ + "PhpParser\\Node\\Name|PhpParser\\Node\\Expr\0" /* 1619 */ + "constantName\0" /* 1659 */ + "classReflection\0" /* 1672 */ + "PHPStan\\Reflection\\ClassReflection\0" /* 1688 */ + "false\0" /* 1723 */ + "getClassConstFetchTypeByReflection\0" /* 1729 */ + "fetchedOnType\0" /* 1764 */ + "transformStaticType\0" /* 1778 */ + "getClassConstFetchType\0" /* 1798 */ + "getUnaryPlusType\0" /* 1821 */ + "getUnaryMinusType\0" /* 1838 */ + "getBitwiseNotType\0" /* 1856 */ + "getBitwiseNotTypeFromType\0" /* 1874 */ + "name\0" /* 1900 */ + "PhpParser\\Node\\Name\0" /* 1905 */ + "resolveName\0" /* 1925 */ + "PHPStan\\Type\\TypeWithClassName\0" /* 1937 */ + "resolveTypeByName\0" /* 1968 */ + "classType\0" /* 1986 */ + "methodReflectionCandidate\0" /* 1996 */ + "PHPStan\\Reflection\\MethodReflection\0" /* 2022 */ + "resolveTypeByNameWithLateStaticBinding\0" /* 2058 */ + "PHPStan\\Reflection\\ReflectionProvider\0" /* 2097 */ + "getReflectionProvider\0" /* 2135 */ + "getNeverType"; /* 2157 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 17), /* __construct $constantResolver */ reg::packed(51, 0, 78), /* __construct $reflectionProviderProvider */ @@ -154,196 +158,197 @@ inline constexpr reg::PackedArg args[] = { reg::packed(270, 0, 315), /* __construct $unaryOperatorTypeSpecifyingExtensionRegistry */ reg::packed(373, 0, 395), /* __construct $oversizedArrayBuilder */ reg::packed(439, MAY_BE_BOOL), /* __construct $usePathConstantsAsConstantString */ - reg::packed(484, 0, 489), /* getType $expr */ - reg::packed(509, 0, 517), /* getType $context */ - reg::packed(559, 0, 560), /* getType return */ - reg::packed(586, MAY_BE_STRING), /* getEnumCaseValueType $className */ - reg::packed(596, MAY_BE_STRING), /* getEnumCaseValueType $caseName */ - reg::packed(605, 0, 489), /* getEnumCaseValueType $valueExpr */ - reg::packed(509, 0, 517), /* getEnumCaseValueType $context */ - reg::packed(559, 0, 560), /* getEnumCaseValueType return */ - reg::packed(636, 0, 489), /* getConcatType $left */ - reg::packed(641, 0, 489), /* getConcatType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getConcatType $getTypeCallback */ - reg::packed(559, 0, 560), /* getConcatType return */ - reg::packed(636, 0, 560), /* resolveConcatType $left */ - reg::packed(641, 0, 560), /* resolveConcatType $right */ - reg::packed(559, 0, 560), /* resolveConcatType return */ - reg::packed(484, 0, 695), /* getArrayType $expr */ - reg::packed(647, MAY_BE_CALLABLE), /* getArrayType $getTypeCallback */ - reg::packed(722, MAY_BE_NULL, 734, false, false, 758), /* getArrayType $phpVersions */ - reg::packed(559, 0, 560), /* getArrayType return */ - reg::packed(484, 0, 776), /* getCastType $expr */ - reg::packed(647, MAY_BE_CALLABLE), /* getCastType $getTypeCallback */ - reg::packed(559, 0, 560), /* getCastType return */ - reg::packed(813, 0, 560), /* getCastObjectType $exprType */ - reg::packed(559, 0, 560), /* getCastObjectType return */ - reg::packed(840, 0), /* getFunctionType $type */ - reg::packed(845, MAY_BE_BOOL), /* getFunctionType $isNullable */ - reg::packed(856, MAY_BE_BOOL), /* getFunctionType $isVariadic */ - reg::packed(509, 0, 517), /* getFunctionType $context */ - reg::packed(559, 0, 560), /* getFunctionType return */ - reg::packed(883, 0, 893), /* isParameterValueNullable $parameter */ - reg::packed(559, MAY_BE_BOOL), /* isParameterValueNullable return */ - reg::packed(484, 0, 939), /* getFirstClassCallableType $expr */ - reg::packed(509, 0, 517), /* getFirstClassCallableType $context */ - reg::packed(968, MAY_BE_BOOL), /* getFirstClassCallableType $nativeTypesPromoted */ - reg::packed(559, 0, 560), /* getFirstClassCallableType return */ - reg::packed(1014, MAY_BE_NULL, 1023), /* createFirstClassCallable $function */ - reg::packed(1105, MAY_BE_ARRAY), /* createFirstClassCallable $variants */ - reg::packed(968, MAY_BE_BOOL), /* createFirstClassCallable $nativeTypesPromoted */ - reg::packed(559, 0, 560), /* createFirstClassCallable return */ - reg::packed(1139, MAY_BE_ARRAY), /* renameParameters $parameters */ - reg::packed(1150, MAY_BE_ARRAY), /* renameParameters $names */ - reg::packed(559, MAY_BE_ARRAY), /* renameParameters return */ - reg::packed(636, 0, 489), /* getBitwiseAndType $left */ - reg::packed(641, 0, 489), /* getBitwiseAndType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getBitwiseAndType $getTypeCallback */ - reg::packed(559, 0, 560), /* getBitwiseAndType return */ - reg::packed(636, 0, 489), /* getBitwiseOrType $left */ - reg::packed(641, 0, 489), /* getBitwiseOrType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getBitwiseOrType $getTypeCallback */ - reg::packed(559, 0, 560), /* getBitwiseOrType return */ - reg::packed(636, 0, 489), /* getBitwiseXorType $left */ - reg::packed(641, 0, 489), /* getBitwiseXorType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getBitwiseXorType $getTypeCallback */ - reg::packed(559, 0, 560), /* getBitwiseXorType return */ - reg::packed(636, 0, 489), /* getSpaceshipType $left */ - reg::packed(641, 0, 489), /* getSpaceshipType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getSpaceshipType $getTypeCallback */ - reg::packed(559, 0, 560), /* getSpaceshipType return */ - reg::packed(636, 0, 489), /* getDivType $left */ - reg::packed(641, 0, 489), /* getDivType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getDivType $getTypeCallback */ - reg::packed(559, 0, 560), /* getDivType return */ - reg::packed(636, 0, 489), /* getModType $left */ - reg::packed(641, 0, 489), /* getModType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getModType $getTypeCallback */ - reg::packed(559, 0, 560), /* getModType return */ - reg::packed(636, 0, 489), /* getPlusType $left */ - reg::packed(641, 0, 489), /* getPlusType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getPlusType $getTypeCallback */ - reg::packed(559, 0, 560), /* getPlusType return */ - reg::packed(636, 0, 489), /* getMinusType $left */ - reg::packed(641, 0, 489), /* getMinusType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getMinusType $getTypeCallback */ - reg::packed(559, 0, 560), /* getMinusType return */ - reg::packed(636, 0, 489), /* getMulType $left */ - reg::packed(641, 0, 489), /* getMulType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getMulType $getTypeCallback */ - reg::packed(559, 0, 560), /* getMulType return */ - reg::packed(636, 0, 489), /* getPowType $left */ - reg::packed(641, 0, 489), /* getPowType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getPowType $getTypeCallback */ - reg::packed(559, 0, 560), /* getPowType return */ - reg::packed(636, 0, 489), /* getShiftLeftType $left */ - reg::packed(641, 0, 489), /* getShiftLeftType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getShiftLeftType $getTypeCallback */ - reg::packed(559, 0, 560), /* getShiftLeftType return */ - reg::packed(636, 0, 489), /* getShiftRightType $left */ - reg::packed(641, 0, 489), /* getShiftRightType $right */ - reg::packed(647, MAY_BE_CALLABLE), /* getShiftRightType $getTypeCallback */ - reg::packed(559, 0, 560), /* getShiftRightType return */ - reg::packed(1347, 0, 560), /* resolveIdenticalType $leftType */ - reg::packed(1356, 0, 560), /* resolveIdenticalType $rightType */ - reg::packed(559, 0, 1366), /* resolveIdenticalType return */ - reg::packed(1347, 0, 560), /* resolveEqualType $leftType */ - reg::packed(1356, 0, 560), /* resolveEqualType $rightType */ - reg::packed(722, MAY_BE_NULL, 734, false, false, 758), /* resolveEqualType $phpVersions */ - reg::packed(559, 0, 1366), /* resolveEqualType return */ - reg::packed(840, 0, 560), /* isNonNumericString $type */ - reg::packed(722, MAY_BE_ARRAY), /* isNonNumericString $phpVersions */ - reg::packed(559, MAY_BE_BOOL), /* isNonNumericString return */ - reg::packed(1347, 0, 1447), /* resolveConstantArrayTypeComparison $leftType */ - reg::packed(1356, 0, 1447), /* resolveConstantArrayTypeComparison $rightType */ - reg::packed(1487, MAY_BE_CALLABLE), /* resolveConstantArrayTypeComparison $valueComparisonCallback */ - reg::packed(559, 0, 1366), /* resolveConstantArrayTypeComparison return */ - reg::packed(1546, 0, 1552), /* getClassConstFetchTypeByReflection $class */ - reg::packed(1592, MAY_BE_STRING), /* getClassConstFetchTypeByReflection $constantName */ - reg::packed(1605, MAY_BE_NULL, 1621), /* getClassConstFetchTypeByReflection $classReflection */ - reg::packed(647, MAY_BE_CALLABLE), /* getClassConstFetchTypeByReflection $getTypeCallback */ - reg::packed(968, MAY_BE_BOOL, reg::NoString, false, false, 1656), /* getClassConstFetchTypeByReflection $nativeTypesPromoted */ - reg::packed(559, 0, 560), /* getClassConstFetchTypeByReflection return */ - reg::packed(840, 0, 560), /* transformStaticType $type */ - reg::packed(1697, 0, 560), /* transformStaticType $fetchedOnType */ - reg::packed(559, 0, 560), /* transformStaticType return */ - reg::packed(1546, 0, 1552), /* getClassConstFetchType $class */ - reg::packed(1592, MAY_BE_STRING), /* getClassConstFetchType $constantName */ - reg::packed(586, MAY_BE_NULL | MAY_BE_STRING), /* getClassConstFetchType $className */ - reg::packed(647, MAY_BE_CALLABLE), /* getClassConstFetchType $getTypeCallback */ - reg::packed(559, 0, 560), /* getClassConstFetchType return */ - reg::packed(484, 0, 489), /* getUnaryPlusType $expr */ - reg::packed(647, MAY_BE_CALLABLE), /* getUnaryPlusType $getTypeCallback */ - reg::packed(559, 0, 560), /* getUnaryPlusType return */ - reg::packed(484, 0, 489), /* getUnaryMinusType $expr */ - reg::packed(647, MAY_BE_CALLABLE), /* getUnaryMinusType $getTypeCallback */ - reg::packed(559, 0, 560), /* getUnaryMinusType return */ - reg::packed(484, 0, 489), /* getBitwiseNotType $expr */ - reg::packed(647, MAY_BE_CALLABLE), /* getBitwiseNotType $getTypeCallback */ - reg::packed(559, 0, 560), /* getBitwiseNotType return */ - reg::packed(813, 0, 560), /* getBitwiseNotTypeFromType $exprType */ - reg::packed(559, 0, 560), /* getBitwiseNotTypeFromType return */ - reg::packed(1833, 0, 1838), /* resolveName $name */ - reg::packed(1605, MAY_BE_NULL, 1621), /* resolveName $classReflection */ - reg::packed(559, MAY_BE_STRING), /* resolveName return */ - reg::packed(1833, 0, 1838), /* resolveTypeByName $name */ - reg::packed(1605, MAY_BE_NULL, 1621), /* resolveTypeByName $classReflection */ - reg::packed(559, 0, 1870), /* resolveTypeByName return */ - reg::packed(1546, 0, 1838), /* resolveTypeByNameWithLateStaticBinding $class */ - reg::packed(1919, 0, 560), /* resolveTypeByNameWithLateStaticBinding $classType */ - reg::packed(1929, 0, 1955), /* resolveTypeByNameWithLateStaticBinding $methodReflectionCandidate */ - reg::packed(559, 0, 560), /* resolveTypeByNameWithLateStaticBinding return */ - reg::packed(559, 0, 2030), /* getReflectionProvider return */ - reg::packed(1347, 0, 560), /* getNeverType $leftType */ - reg::packed(1356, 0, 560), /* getNeverType $rightType */ - reg::packed(559, 0, 560), /* getNeverType return */ + reg::packed(472, 0, 497), /* __construct $valueDependencyCollector */ + reg::packed(551, 0, 556), /* getType $expr */ + reg::packed(576, 0, 584), /* getType $context */ + reg::packed(626, 0, 627), /* getType return */ + reg::packed(653, MAY_BE_STRING), /* getEnumCaseValueType $className */ + reg::packed(663, MAY_BE_STRING), /* getEnumCaseValueType $caseName */ + reg::packed(672, 0, 556), /* getEnumCaseValueType $valueExpr */ + reg::packed(576, 0, 584), /* getEnumCaseValueType $context */ + reg::packed(626, 0, 627), /* getEnumCaseValueType return */ + reg::packed(703, 0, 556), /* getConcatType $left */ + reg::packed(708, 0, 556), /* getConcatType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getConcatType $getTypeCallback */ + reg::packed(626, 0, 627), /* getConcatType return */ + reg::packed(703, 0, 627), /* resolveConcatType $left */ + reg::packed(708, 0, 627), /* resolveConcatType $right */ + reg::packed(626, 0, 627), /* resolveConcatType return */ + reg::packed(551, 0, 762), /* getArrayType $expr */ + reg::packed(714, MAY_BE_CALLABLE), /* getArrayType $getTypeCallback */ + reg::packed(789, MAY_BE_NULL, 801, false, false, 825), /* getArrayType $phpVersions */ + reg::packed(626, 0, 627), /* getArrayType return */ + reg::packed(551, 0, 843), /* getCastType $expr */ + reg::packed(714, MAY_BE_CALLABLE), /* getCastType $getTypeCallback */ + reg::packed(626, 0, 627), /* getCastType return */ + reg::packed(880, 0, 627), /* getCastObjectType $exprType */ + reg::packed(626, 0, 627), /* getCastObjectType return */ + reg::packed(907, 0), /* getFunctionType $type */ + reg::packed(912, MAY_BE_BOOL), /* getFunctionType $isNullable */ + reg::packed(923, MAY_BE_BOOL), /* getFunctionType $isVariadic */ + reg::packed(576, 0, 584), /* getFunctionType $context */ + reg::packed(626, 0, 627), /* getFunctionType return */ + reg::packed(950, 0, 960), /* isParameterValueNullable $parameter */ + reg::packed(626, MAY_BE_BOOL), /* isParameterValueNullable return */ + reg::packed(551, 0, 1006), /* getFirstClassCallableType $expr */ + reg::packed(576, 0, 584), /* getFirstClassCallableType $context */ + reg::packed(1035, MAY_BE_BOOL), /* getFirstClassCallableType $nativeTypesPromoted */ + reg::packed(626, 0, 627), /* getFirstClassCallableType return */ + reg::packed(1081, MAY_BE_NULL, 1090), /* createFirstClassCallable $function */ + reg::packed(1172, MAY_BE_ARRAY), /* createFirstClassCallable $variants */ + reg::packed(1035, MAY_BE_BOOL), /* createFirstClassCallable $nativeTypesPromoted */ + reg::packed(626, 0, 627), /* createFirstClassCallable return */ + reg::packed(1206, MAY_BE_ARRAY), /* renameParameters $parameters */ + reg::packed(1217, MAY_BE_ARRAY), /* renameParameters $names */ + reg::packed(626, MAY_BE_ARRAY), /* renameParameters return */ + reg::packed(703, 0, 556), /* getBitwiseAndType $left */ + reg::packed(708, 0, 556), /* getBitwiseAndType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getBitwiseAndType $getTypeCallback */ + reg::packed(626, 0, 627), /* getBitwiseAndType return */ + reg::packed(703, 0, 556), /* getBitwiseOrType $left */ + reg::packed(708, 0, 556), /* getBitwiseOrType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getBitwiseOrType $getTypeCallback */ + reg::packed(626, 0, 627), /* getBitwiseOrType return */ + reg::packed(703, 0, 556), /* getBitwiseXorType $left */ + reg::packed(708, 0, 556), /* getBitwiseXorType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getBitwiseXorType $getTypeCallback */ + reg::packed(626, 0, 627), /* getBitwiseXorType return */ + reg::packed(703, 0, 556), /* getSpaceshipType $left */ + reg::packed(708, 0, 556), /* getSpaceshipType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getSpaceshipType $getTypeCallback */ + reg::packed(626, 0, 627), /* getSpaceshipType return */ + reg::packed(703, 0, 556), /* getDivType $left */ + reg::packed(708, 0, 556), /* getDivType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getDivType $getTypeCallback */ + reg::packed(626, 0, 627), /* getDivType return */ + reg::packed(703, 0, 556), /* getModType $left */ + reg::packed(708, 0, 556), /* getModType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getModType $getTypeCallback */ + reg::packed(626, 0, 627), /* getModType return */ + reg::packed(703, 0, 556), /* getPlusType $left */ + reg::packed(708, 0, 556), /* getPlusType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getPlusType $getTypeCallback */ + reg::packed(626, 0, 627), /* getPlusType return */ + reg::packed(703, 0, 556), /* getMinusType $left */ + reg::packed(708, 0, 556), /* getMinusType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getMinusType $getTypeCallback */ + reg::packed(626, 0, 627), /* getMinusType return */ + reg::packed(703, 0, 556), /* getMulType $left */ + reg::packed(708, 0, 556), /* getMulType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getMulType $getTypeCallback */ + reg::packed(626, 0, 627), /* getMulType return */ + reg::packed(703, 0, 556), /* getPowType $left */ + reg::packed(708, 0, 556), /* getPowType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getPowType $getTypeCallback */ + reg::packed(626, 0, 627), /* getPowType return */ + reg::packed(703, 0, 556), /* getShiftLeftType $left */ + reg::packed(708, 0, 556), /* getShiftLeftType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getShiftLeftType $getTypeCallback */ + reg::packed(626, 0, 627), /* getShiftLeftType return */ + reg::packed(703, 0, 556), /* getShiftRightType $left */ + reg::packed(708, 0, 556), /* getShiftRightType $right */ + reg::packed(714, MAY_BE_CALLABLE), /* getShiftRightType $getTypeCallback */ + reg::packed(626, 0, 627), /* getShiftRightType return */ + reg::packed(1414, 0, 627), /* resolveIdenticalType $leftType */ + reg::packed(1423, 0, 627), /* resolveIdenticalType $rightType */ + reg::packed(626, 0, 1433), /* resolveIdenticalType return */ + reg::packed(1414, 0, 627), /* resolveEqualType $leftType */ + reg::packed(1423, 0, 627), /* resolveEqualType $rightType */ + reg::packed(789, MAY_BE_NULL, 801, false, false, 825), /* resolveEqualType $phpVersions */ + reg::packed(626, 0, 1433), /* resolveEqualType return */ + reg::packed(907, 0, 627), /* isNonNumericString $type */ + reg::packed(789, MAY_BE_ARRAY), /* isNonNumericString $phpVersions */ + reg::packed(626, MAY_BE_BOOL), /* isNonNumericString return */ + reg::packed(1414, 0, 1514), /* resolveConstantArrayTypeComparison $leftType */ + reg::packed(1423, 0, 1514), /* resolveConstantArrayTypeComparison $rightType */ + reg::packed(1554, MAY_BE_CALLABLE), /* resolveConstantArrayTypeComparison $valueComparisonCallback */ + reg::packed(626, 0, 1433), /* resolveConstantArrayTypeComparison return */ + reg::packed(1613, 0, 1619), /* getClassConstFetchTypeByReflection $class */ + reg::packed(1659, MAY_BE_STRING), /* getClassConstFetchTypeByReflection $constantName */ + reg::packed(1672, MAY_BE_NULL, 1688), /* getClassConstFetchTypeByReflection $classReflection */ + reg::packed(714, MAY_BE_CALLABLE), /* getClassConstFetchTypeByReflection $getTypeCallback */ + reg::packed(1035, MAY_BE_BOOL, reg::NoString, false, false, 1723), /* getClassConstFetchTypeByReflection $nativeTypesPromoted */ + reg::packed(626, 0, 627), /* getClassConstFetchTypeByReflection return */ + reg::packed(907, 0, 627), /* transformStaticType $type */ + reg::packed(1764, 0, 627), /* transformStaticType $fetchedOnType */ + reg::packed(626, 0, 627), /* transformStaticType return */ + reg::packed(1613, 0, 1619), /* getClassConstFetchType $class */ + reg::packed(1659, MAY_BE_STRING), /* getClassConstFetchType $constantName */ + reg::packed(653, MAY_BE_NULL | MAY_BE_STRING), /* getClassConstFetchType $className */ + reg::packed(714, MAY_BE_CALLABLE), /* getClassConstFetchType $getTypeCallback */ + reg::packed(626, 0, 627), /* getClassConstFetchType return */ + reg::packed(551, 0, 556), /* getUnaryPlusType $expr */ + reg::packed(714, MAY_BE_CALLABLE), /* getUnaryPlusType $getTypeCallback */ + reg::packed(626, 0, 627), /* getUnaryPlusType return */ + reg::packed(551, 0, 556), /* getUnaryMinusType $expr */ + reg::packed(714, MAY_BE_CALLABLE), /* getUnaryMinusType $getTypeCallback */ + reg::packed(626, 0, 627), /* getUnaryMinusType return */ + reg::packed(551, 0, 556), /* getBitwiseNotType $expr */ + reg::packed(714, MAY_BE_CALLABLE), /* getBitwiseNotType $getTypeCallback */ + reg::packed(626, 0, 627), /* getBitwiseNotType return */ + reg::packed(880, 0, 627), /* getBitwiseNotTypeFromType $exprType */ + reg::packed(626, 0, 627), /* getBitwiseNotTypeFromType return */ + reg::packed(1900, 0, 1905), /* resolveName $name */ + reg::packed(1672, MAY_BE_NULL, 1688), /* resolveName $classReflection */ + reg::packed(626, MAY_BE_STRING), /* resolveName return */ + reg::packed(1900, 0, 1905), /* resolveTypeByName $name */ + reg::packed(1672, MAY_BE_NULL, 1688), /* resolveTypeByName $classReflection */ + reg::packed(626, 0, 1937), /* resolveTypeByName return */ + reg::packed(1613, 0, 1905), /* resolveTypeByNameWithLateStaticBinding $class */ + reg::packed(1986, 0, 627), /* resolveTypeByNameWithLateStaticBinding $classType */ + reg::packed(1996, 0, 2022), /* resolveTypeByNameWithLateStaticBinding $methodReflectionCandidate */ + reg::packed(626, 0, 627), /* resolveTypeByNameWithLateStaticBinding return */ + reg::packed(626, 0, 2097), /* getReflectionProvider return */ + reg::packed(1414, 0, 627), /* getNeverType $leftType */ + reg::packed(1423, 0, 627), /* getNeverType $rightType */ + reg::packed(626, 0, 627), /* getNeverType return */ }; using Sig = reg::Sig; } // namespace sigtab /* the signatures of the methods the class declares itself (a used trait's are in the trait's header) */ namespace sig { -inline constexpr sigtab::Sig __construct = { { 472 /* __construct */, 7, 0, 7, reg::NoArg, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getType = { { 578 /* getType */, 2, 7, 2, 9, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getEnumCaseValueType = { { 615 /* getEnumCaseValueType */, 4, 10, 4, 14, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getConcatType = { { 663 /* getConcatType */, 3, 15, 3, 18, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig resolveConcatType = { { 677 /* resolveConcatType */, 2, 19, 2, 21, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getArrayType = { { 763 /* getArrayType */, 2, 22, 3, 25, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getCastType = { { 801 /* getCastType */, 2, 26, 2, 28, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getCastObjectType = { { 822 /* getCastObjectType */, 1, 29, 1, 30, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getFunctionType = { { 867 /* getFunctionType */, 4, 31, 4, 35, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isParameterValueNullable = { { 914 /* isParameterValueNullable */, 1, 36, 1, 37, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getFirstClassCallableType = { { 988 /* getFirstClassCallableType */, 3, 38, 3, 41, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig createFirstClassCallable = { { 1114 /* createFirstClassCallable */, 3, 42, 3, 45, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig renameParameters = { { 1156 /* renameParameters */, 2, 46, 2, 48, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig getBitwiseAndType = { { 1173 /* getBitwiseAndType */, 3, 49, 3, 52, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getBitwiseOrType = { { 1191 /* getBitwiseOrType */, 3, 53, 3, 56, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getBitwiseXorType = { { 1208 /* getBitwiseXorType */, 3, 57, 3, 60, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getSpaceshipType = { { 1226 /* getSpaceshipType */, 3, 61, 3, 64, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getDivType = { { 1243 /* getDivType */, 3, 65, 3, 68, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getModType = { { 1254 /* getModType */, 3, 69, 3, 72, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getPlusType = { { 1265 /* getPlusType */, 3, 73, 3, 76, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getMinusType = { { 1277 /* getMinusType */, 3, 77, 3, 80, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getMulType = { { 1290 /* getMulType */, 3, 81, 3, 84, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getPowType = { { 1301 /* getPowType */, 3, 85, 3, 88, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getShiftLeftType = { { 1312 /* getShiftLeftType */, 3, 89, 3, 92, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getShiftRightType = { { 1329 /* getShiftRightType */, 3, 93, 3, 96, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig resolveIdenticalType = { { 1390 /* resolveIdenticalType */, 2, 97, 2, 99, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig resolveEqualType = { { 1411 /* resolveEqualType */, 2, 100, 3, 103, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isNonNumericString = { { 1428 /* isNonNumericString */, 2, 104, 2, 106, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig resolveConstantArrayTypeComparison = { { 1511 /* resolveConstantArrayTypeComparison */, 3, 107, 3, 110, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getClassConstFetchTypeByReflection = { { 1662 /* getClassConstFetchTypeByReflection */, 4, 111, 5, 116, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig transformStaticType = { { 1711 /* transformStaticType */, 2, 117, 2, 119, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getClassConstFetchType = { { 1731 /* getClassConstFetchType */, 4, 120, 4, 124, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnaryPlusType = { { 1754 /* getUnaryPlusType */, 2, 125, 2, 127, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnaryMinusType = { { 1771 /* getUnaryMinusType */, 2, 128, 2, 130, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getBitwiseNotType = { { 1789 /* getBitwiseNotType */, 2, 131, 2, 133, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getBitwiseNotTypeFromType = { { 1807 /* getBitwiseNotTypeFromType */, 1, 134, 1, 135, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig resolveName = { { 1858 /* resolveName */, 2, 136, 2, 138, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig resolveTypeByName = { { 1901 /* resolveTypeByName */, 2, 139, 2, 141, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig resolveTypeByNameWithLateStaticBinding = { { 1991 /* resolveTypeByNameWithLateStaticBinding */, 3, 142, 3, 145, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getReflectionProvider = { { 2068 /* getReflectionProvider */, 0, 146, 0, 146, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getNeverType = { { 2090 /* getNeverType */, 2, 147, 2, 149, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig __construct = { { 539 /* __construct */, 8, 0, 8, reg::NoArg, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getType = { { 645 /* getType */, 2, 8, 2, 10, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getEnumCaseValueType = { { 682 /* getEnumCaseValueType */, 4, 11, 4, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getConcatType = { { 730 /* getConcatType */, 3, 16, 3, 19, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig resolveConcatType = { { 744 /* resolveConcatType */, 2, 20, 2, 22, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getArrayType = { { 830 /* getArrayType */, 2, 23, 3, 26, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getCastType = { { 868 /* getCastType */, 2, 27, 2, 29, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getCastObjectType = { { 889 /* getCastObjectType */, 1, 30, 1, 31, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getFunctionType = { { 934 /* getFunctionType */, 4, 32, 4, 36, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isParameterValueNullable = { { 981 /* isParameterValueNullable */, 1, 37, 1, 38, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getFirstClassCallableType = { { 1055 /* getFirstClassCallableType */, 3, 39, 3, 42, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig createFirstClassCallable = { { 1181 /* createFirstClassCallable */, 3, 43, 3, 46, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig renameParameters = { { 1223 /* renameParameters */, 2, 47, 2, 49, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig getBitwiseAndType = { { 1240 /* getBitwiseAndType */, 3, 50, 3, 53, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getBitwiseOrType = { { 1258 /* getBitwiseOrType */, 3, 54, 3, 57, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getBitwiseXorType = { { 1275 /* getBitwiseXorType */, 3, 58, 3, 61, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getSpaceshipType = { { 1293 /* getSpaceshipType */, 3, 62, 3, 65, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getDivType = { { 1310 /* getDivType */, 3, 66, 3, 69, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getModType = { { 1321 /* getModType */, 3, 70, 3, 73, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getPlusType = { { 1332 /* getPlusType */, 3, 74, 3, 77, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getMinusType = { { 1344 /* getMinusType */, 3, 78, 3, 81, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getMulType = { { 1357 /* getMulType */, 3, 82, 3, 85, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getPowType = { { 1368 /* getPowType */, 3, 86, 3, 89, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getShiftLeftType = { { 1379 /* getShiftLeftType */, 3, 90, 3, 93, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getShiftRightType = { { 1396 /* getShiftRightType */, 3, 94, 3, 97, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig resolveIdenticalType = { { 1457 /* resolveIdenticalType */, 2, 98, 2, 100, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig resolveEqualType = { { 1478 /* resolveEqualType */, 2, 101, 3, 104, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isNonNumericString = { { 1495 /* isNonNumericString */, 2, 105, 2, 107, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig resolveConstantArrayTypeComparison = { { 1578 /* resolveConstantArrayTypeComparison */, 3, 108, 3, 111, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getClassConstFetchTypeByReflection = { { 1729 /* getClassConstFetchTypeByReflection */, 4, 112, 5, 117, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig transformStaticType = { { 1778 /* transformStaticType */, 2, 118, 2, 120, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getClassConstFetchType = { { 1798 /* getClassConstFetchType */, 4, 121, 4, 125, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnaryPlusType = { { 1821 /* getUnaryPlusType */, 2, 126, 2, 128, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnaryMinusType = { { 1838 /* getUnaryMinusType */, 2, 129, 2, 131, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getBitwiseNotType = { { 1856 /* getBitwiseNotType */, 2, 132, 2, 134, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getBitwiseNotTypeFromType = { { 1874 /* getBitwiseNotTypeFromType */, 1, 135, 1, 136, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig resolveName = { { 1925 /* resolveName */, 2, 137, 2, 139, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig resolveTypeByName = { { 1968 /* resolveTypeByName */, 2, 140, 2, 142, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig resolveTypeByNameWithLateStaticBinding = { { 2058 /* resolveTypeByNameWithLateStaticBinding */, 3, 143, 3, 146, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getReflectionProvider = { { 2135 /* getReflectionProvider */, 0, 147, 0, 147, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getNeverType = { { 2157 /* getNeverType */, 2, 148, 2, 150, ZEND_ACC_PRIVATE } }; } // namespace sig } // namespace ptdecl::InitializerExprTypeResolver diff --git a/turbo-ext/src/support.cpp b/turbo-ext/src/support.cpp index eece49a5ae3..9818e91b6ee 100644 --- a/turbo-ext/src/support.cpp +++ b/turbo-ext/src/support.cpp @@ -416,6 +416,7 @@ static const pt_class_template pt_class_templates[PT_CLASS_COUNT] = { /* PT_CLASS_FULLY_QUALIFIED_NAME_NODE */ {"fullyQualifiedNameNode", "PHPStan\\PhpDocParser\\Ast\\Type\\FullyQualifiedNameNode"}, /* PT_CLASS_TYPE_NODE_DESCRIBER */ {"typeNodeDescriber", "PHPStan\\Type\\TypeNodeDescriber"}, /* PT_CLASS_ARRAY_MAP_CALLBACK_PARAMETER_TYPES */ {"arrayMapCallbackParameterTypes", "PHPStan\\Reflection\\ArrayMapCallbackParameterTypes"}, + /* PT_CLASS_VALUE_DEPENDENCY_COLLECTOR */ {"valueDependencyCollector", "PHPStan\\Analyser\\ValueDependencyCollector"}, }; zend_class_entry *pt_class(int idx) diff --git a/turbo-ext/src/support.h b/turbo-ext/src/support.h index baefe30df0d..c5a651d5ecf 100644 --- a/turbo-ext/src/support.h +++ b/turbo-ext/src/support.h @@ -521,6 +521,8 @@ enum { PT_CLASS_TYPE_NODE_DESCRIBER, /* the null array_map() passes for the shorter arrays */ PT_CLASS_ARRAY_MAP_CALLBACK_PARAMETER_TYPES, + /* the result cache's record of what a declaration's resolution looked up */ + PT_CLASS_VALUE_DEPENDENCY_COLLECTOR, PT_CLASS_COUNT }; @@ -2970,6 +2972,11 @@ zv::Val pt_args_result_with_resolved_parameters_acceptor(zval *argsResult, zval zv::Val pt_arguments_normalizer_reorder_call_user_func_arguments(zval *callUserFuncCall, zval *scope); zv::Val pt_arguments_normalizer_reorder_call_user_func_array_arguments(zval *callUserFuncArrayCall, zval *scope); +/* ReflectionAccess.cpp — ValueDependencyCollector::getContext(), the + * context lookups are recorded in: a memoized answer is given natively only + * when it was recorded in it already; false while it cannot be read */ +[[nodiscard]] bool pt_value_dependency_context(zend_long &context); + /* FunctionReflectionAccess.cpp — $reflectionProvider->hasFunction($nameNode, * $namespaceAnswerer) / ->getFunction(...): the memoized answer of a * MemoizingReflectionProvider over a BetterReflectionProvider diff --git a/turbo-ext/tests/initializer-escape.php b/turbo-ext/tests/initializer-escape.php index 0fd44a7e845..f986f7ce710 100644 --- a/turbo-ext/tests/initializer-escape.php +++ b/turbo-ext/tests/initializer-escape.php @@ -197,6 +197,7 @@ public function callUnaryOperatorTypeSpecifyingExtensions(string $operatorSigil, $ieNoOperatorExtensions, $ieBuilder, false, + $ieContainer->getByType(\PHPStan\Analyser\ValueDependencyCollector::class), ); $ieOversized = new \PhpParser\Node\Expr\Array_(array_map(static fn (int $i) => new \PhpParser\Node\ArrayItem(new \PhpParser\Node\Scalar\Int_($i)), range(0, 300))); $ieContext = \PHPStan\Reflection\InitializerExprContext::fromClass(\PHPStan\TrinaryLogic::class, null);