Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try fixing assigning array offsets on possibly undefined nested array offsets #3865

Draft
wants to merge 4 commits into
base: 2.1.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 38 additions & 14 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -5384,12 +5384,12 @@ private function processAssignVar(
}

if ($dimExpr === null) {
$offsetTypes[] = null;
$offsetNativeTypes[] = null;
$offsetTypes[] = [null, TrinaryLogic::createYes()];
$offsetNativeTypes[] = [null, TrinaryLogic::createYes()];

} else {
$offsetTypes[] = $scope->getType($dimExpr);
$offsetNativeTypes[] = $scope->getNativeType($dimExpr);
$offsetTypes[] = [$scope->getType($dimExpr), $scope->getType($dimFetch->var)->hasOffsetValueType($scope->getType($dimExpr))->or($scope->hasExpressionType($dimFetch))];
$offsetNativeTypes[] = [$scope->getNativeType($dimExpr), $scope->getNativeType($dimFetch->var)->hasOffsetValueType($scope->getNativeType($dimExpr))->or($scope->hasExpressionType($dimFetch))];

if ($enterExpressionAssign) {
$scope->enterExpressionAssign($dimExpr);
Expand Down Expand Up @@ -5436,8 +5436,8 @@ private function processAssignVar(
$nativeValueToWrite = $this->produceArrayDimFetchAssignValueToWrite($offsetNativeTypes, $offsetNativeValueType, $nativeValueToWrite);
} else {
$rewritten = false;
foreach ($offsetTypes as $i => $offsetType) {
$offsetNativeType = $offsetNativeTypes[$i];
foreach ($offsetTypes as $i => [$offsetType]) {
[$offsetNativeType] = $offsetNativeTypes[$i];
if ($offsetType === null) {
if ($offsetNativeType !== null) {
throw new ShouldNotHappenException();
Expand Down Expand Up @@ -5489,6 +5489,26 @@ private function processAssignVar(
);
}
}

$arrayDimFetchVar = $originalVar;
while ($arrayDimFetchVar instanceof ArrayDimFetch) {
$dimExpr = $arrayDimFetchVar->dim;
if ($dimExpr === null) {
$arrayDimFetchVar = $arrayDimFetchVar->var;
continue;
}

$dimVar = $arrayDimFetchVar->var;
$dimVarType = $scope->getType($dimVar);
$dimDimType = $scope->getType($dimExpr);
if ($dimVarType->hasOffsetValueType($dimDimType)->yes()) {
$arrayDimFetchVar = $arrayDimFetchVar->var;
continue;
}

$scope = $scope->specifyExpressionType($arrayDimFetchVar, $scope->getType($arrayDimFetchVar), $scope->getNativeType($arrayDimFetchVar), TrinaryLogic::createYes());
$arrayDimFetchVar = $arrayDimFetchVar->var;
}
} else {
if ($var instanceof Variable) {
$nodeCallback(new VariableAssignNode($var, $assignedPropertyExpr, $isAssignOp), $scope);
Expand Down Expand Up @@ -5752,12 +5772,12 @@ static function (): void {
}

/**
* @param list<Type|null> $offsetTypes
* @param list<array{Type|null, TrinaryLogic}> $offsetTypes
*/
private function produceArrayDimFetchAssignValueToWrite(array $offsetTypes, Type $offsetValueType, Type $valueToWrite): Type
{
$offsetValueTypeStack = [$offsetValueType];
foreach (array_slice($offsetTypes, 0, -1) as $offsetType) {
$offsetValueTypeStack = [[$offsetValueType, TrinaryLogic::createYes()]];
foreach (array_slice($offsetTypes, 0, -1) as [$offsetType, $has]) {
if ($offsetType === null) {
$offsetValueType = new ConstantArrayType([], []);

Expand All @@ -5768,12 +5788,13 @@ private function produceArrayDimFetchAssignValueToWrite(array $offsetTypes, Type
}
}

$offsetValueTypeStack[] = $offsetValueType;
$offsetValueTypeStack[] = [$offsetValueType, $has];
}

foreach (array_reverse($offsetTypes) as $i => $offsetType) {
/** @var Type $offsetValueType */
$offsetValueType = array_pop($offsetValueTypeStack);
foreach (array_reverse($offsetTypes) as [$offsetType]) {
/** @var array{Type, TrinaryLogic} $stackItem */
$stackItem = array_pop($offsetValueTypeStack);
[$offsetValueType, $has] = $stackItem;
if (
!$offsetValueType instanceof MixedType
&& !$offsetValueType->isConstantArray()->yes()
Expand All @@ -5788,7 +5809,10 @@ private function produceArrayDimFetchAssignValueToWrite(array $offsetTypes, Type
}
$offsetValueType = TypeCombinator::intersect($offsetValueType, TypeCombinator::union(...$types));
}
$valueToWrite = $offsetValueType->setOffsetValueType($offsetType, $valueToWrite, $i === 0);
if (!$has->yes()) {
$offsetValueType = TypeCombinator::union($offsetValueType, new ConstantArrayType([], []));
}
$valueToWrite = $offsetValueType->setOffsetValueType($offsetType, $valueToWrite);
}

return $valueToWrite;
Expand Down
4 changes: 2 additions & 2 deletions tests/PHPStan/Analyser/data/bug-10922.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public function sayHello(array $array): void
foreach ($array as $key => $item) {
$array[$key]['bar'] = '';
}
assertType("array<string, array{foo: string, bar: ''}>", $array);
assertType("array<string, array{foo: string, bar?: ''}>", $array);
}

/** @param array<string, array{foo: string}> $array */
Expand All @@ -38,6 +38,6 @@ public function sayHello3(array $array): void
foreach ($array as $key => $item) {
$array[$key]['bar'] = '';
}
assertType("non-empty-array<string, array{foo: string, bar: ''}>", $array);
assertType("non-empty-array<string, array{foo: string, bar?: ''}>", $array);
}
}
25 changes: 25 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-10025.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types = 1);

namespace Bug10025;

use function PHPStan\Testing\assertType;

class MyClass {
public int $groupId;
}

/**
* @param list<MyClass> $foos
* @param list<MyClass> $bars
*/
function x(array $foos, array $bars): void {
$arr = [];
foreach ($foos as $foo) {
$arr[$foo->groupId]['foo'][] = $foo;
}
foreach ($bars as $bar) {
$arr[$bar->groupId]['bar'][] = $bar;
}

assertType('array<int, non-empty-array{foo?: non-empty-list<Bug10025\MyClass>, bar?: non-empty-list<Bug10025\MyClass>}>', $arr);
}
29 changes: 29 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-10089.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Bug10089;

use function PHPStan\Testing\assertType;

class Test
{

protected function create_matrix(int $size): array
{
$size = min(8, $size);
$matrix = [];
for ($i = 0; $i < $size; $i++) {
$matrix[] = array_fill(0, $size, 0);
}

assertType('list<non-empty-list<0>>', $matrix);

$matrix[$size - 1][8] = 3;

assertType('non-empty-array<int, non-empty-array<int<0, max>, 0|3>>', $matrix);

return $matrix;
}

}


16 changes: 16 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-10640.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Bug10640;

use function PHPStan\Testing\assertType;

function (array $a, array $b): void {
$changes = [];
foreach ($a as $add) {
$changes[$add['id']]['add'][] = 1;
}
foreach ($b as $del) {
$changes[$del['id']]['del'][] = 2;
}
assertType('array<non-empty-array{add?: non-empty-list<1>, del?: non-empty-list<2>}>', $changes);
};
44 changes: 44 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-12078.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php declare(strict_types = 1);

namespace Bug12078;

use function PHPStan\Testing\assertType;

/**
* @return array <string,string>
*/
function returnsData6M(): array
{
return ["A"=>'data A',"B"=>'Data B'];
}
/**
* @return array <string,string>
*/
function returnsData3M(): array
{
return ["A"=>'data A',"C"=>'Data C'];
}

function main(){
$arrDataByKey = [];

$arrData6M = returnsData6M();
if([] === $arrData6M){
echo "No data for 6M\n";
}else{
foreach($arrData6M as $key => $data){
$arrDataByKey[$key]['6M'][] = $data;
}
}

$arrData3M = returnsData3M();
if([] === $arrData3M){
echo "No data for 3M\n";
}else{
foreach($arrData3M as $key => $data){
$arrDataByKey[$key]['3M'][] = $data;
}
}

assertType('array<string, non-empty-array{6M?: non-empty-list<string>, 3M?: non-empty-list<string>}>', $arrDataByKey);
}
28 changes: 28 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-6173.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php declare(strict_types = 1);

namespace Bug6173;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @param int[] $ids1
* @param int[] $ids2
*/
public function sayHello(array $ids1, array $ids2): bool
{
$res = [];
foreach ($ids1 as $id) {
$res[$id]['foo'] = $id;
}

foreach ($ids2 as $id) {
$res[$id]['bar'] = $id;
}

assertType('array<int, non-empty-array{foo?: int, bar?: int}>', $res);

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -829,4 +829,10 @@ public function testArrayDimFetchAfterArraySearch(): void
]);
}

public function testBug11679(): void
{
$this->reportPossiblyNonexistentGeneralArrayOffset = true;
$this->analyse([__DIR__ . '/data/bug-11679.php'], []);
}

}
31 changes: 31 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/bug-11679.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Bug11679;

class WorkingExample
{
/** @var array{foo?: bool} */
private array $arr = [];

public function sayHello(): bool
{
if (!isset($this->arr['foo'])) {
$this->arr['foo'] = true;
}
return $this->arr['foo'];
}
}

class NonworkingExample
{
/** @var array<int, array{foo?: bool}> */
private array $arr = [];

public function sayHello(int $index): bool
{
if (!isset($this->arr[$index]['foo'])) {
$this->arr[$index]['foo'] = true;
}
return $this->arr[$index]['foo'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,11 @@ public function testBug6356b(): void
26,
"Offset 'age' (int) does not accept type int|string.",
],
[
'Property Bug6356b\HelloWorld2::$nestedDetails (array<array{name: string, age: int}>) does not accept non-empty-array<array{age: \'Eleventy-one\'|\'Five\'|\'Twelve\'|int, name: string}>.',
29,
'Offset \'age\' (int) does not accept type int|string.',
],
]);
}

Expand Down