From dee3fc43587e88c1d100adf40252660f949ec4b7 Mon Sep 17 00:00:00 2001 From: adrew Date: Mon, 6 Dec 2021 02:25:40 +0300 Subject: [PATCH] try to fix generic assertions for list and array --- .../Statements/Expression/CallAnalyzer.php | 3 +- src/Psalm/Storage/Assertion.php | 2 +- tests/Template/FunctionTemplateAssertTest.php | 92 +++++++++++++++++++ 3 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/CallAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/CallAnalyzer.php index ac6a2c5f21f..7d1fbfb25f7 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/CallAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/CallAnalyzer.php @@ -784,8 +784,9 @@ public static function applyAssertionsToContext( if ($replacement_atomic_type instanceof Type\Atomic\TArray || $replacement_atomic_type instanceof Type\Atomic\TKeyedArray + || $replacement_atomic_type instanceof Type\Atomic\TList ) { - $ored_type_assertions[] = $prefix . 'array'; + $ored_type_assertions[] = $prefix . $replacement_atomic_type->getId(); } elseif ($replacement_atomic_type instanceof Type\Atomic\TNamedObject) { $ored_type_assertions[] = $prefix . $replacement_atomic_type->value; } elseif ($replacement_atomic_type instanceof Type\Atomic\Scalar) { diff --git a/src/Psalm/Storage/Assertion.php b/src/Psalm/Storage/Assertion.php index c01cda7ca1e..8ab092786be 100644 --- a/src/Psalm/Storage/Assertion.php +++ b/src/Psalm/Storage/Assertion.php @@ -77,7 +77,7 @@ function (array $rules) use ($inferred_lower_bounds, $codebase): array { if ($first_type instanceof TTemplateParam) { $rule_token[0] = $first_type->param_name; } else { - $rule_token[0] = $first_type->getKey(); + $rule_token[0] = $first_type->getId(); } } } diff --git a/tests/Template/FunctionTemplateAssertTest.php b/tests/Template/FunctionTemplateAssertTest.php index 9a778f9cecc..548f5df9fe6 100644 --- a/tests/Template/FunctionTemplateAssertTest.php +++ b/tests/Template/FunctionTemplateAssertTest.php @@ -768,6 +768,98 @@ function validateUsername(string $username): void { } }' ], + 'ifTrueListAssertionFromGeneric' => [ + ' $_list + */ + function acceptsIntList(array $_list): void {} + + /** @var Type> $numbersT */ + $numbersT = new Type(); + + /** @var mixed $mixed */ + $mixed = null; + + if ($numbersT->is($mixed)) { + acceptsIntList($mixed); + }' + ], + 'assertListFromGeneric' => [ + ' $_list + */ + function acceptsIntList(array $_list): void {} + + /** @var Type> $numbersT */ + $numbersT = new Type(); + + /** @var mixed $mixed */ + $mixed = null; + + $numbersT->assert($mixed); + acceptsIntList($mixed);' + ], + 'assertArrayFromGeneric' => [ + ' $_list + */ + function acceptsArray(array $_list): void {} + + /** @var Type> $numbersT */ + $numbersT = new Type(); + + /** @var mixed $mixed */ + $mixed = null; + + $numbersT->assert($mixed); + acceptsArray($mixed);' + ], ]; }