6060use PHPStan \Node \Expr \ExistingArrayDimFetch ;
6161use PHPStan \Node \Expr \IntertwinedVariableByReferenceWithExpr ;
6262use PHPStan \Node \Expr \NativeTypeExpr ;
63+ use PHPStan \Node \Expr \OffsetWriteBaseExpr ;
6364use PHPStan \Node \Expr \SetExistingOffsetValueTypeExpr ;
6465use PHPStan \Node \Expr \SetOffsetValueTypeExpr ;
6566use PHPStan \Node \Expr \TypeExpr ;
@@ -1467,10 +1468,10 @@ public function applyWrite(
14671468 $ offsetValueType = $ varType ;
14681469 $ offsetNativeValueType = $ varNativeType ;
14691470
1470- [$ valueToWrite , $ additionalExpressions ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetTypes , $ offsetValueType , $ valueToWrite , $ scope , $ storage );
1471+ [$ valueToWrite , $ additionalExpressions ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetTypes , $ offsetValueType , $ valueToWrite , $ scope , $ storage, $ scope );
14711472
14721473 if (!$ offsetValueType ->equals ($ offsetNativeValueType ) || !$ valueToWrite ->equals ($ nativeValueToWrite )) {
1473- [$ nativeValueToWrite , $ additionalNativeExpressions ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetNativeTypes , $ offsetNativeValueType , $ nativeValueToWrite , $ scope , $ storage );
1474+ [$ nativeValueToWrite , $ additionalNativeExpressions ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetNativeTypes , $ offsetNativeValueType , $ nativeValueToWrite , $ scope , $ storage, $ scope -> doNotTreatPhpDocTypesAsCertain () );
14741475 } else {
14751476 $ rewritten = false ;
14761477 foreach ($ offsetTypes as $ i => [$ offsetType ]) {
@@ -1489,7 +1490,7 @@ public function applyWrite(
14891490 continue ;
14901491 }
14911492
1492- [$ nativeValueToWrite ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetNativeTypes , $ offsetNativeValueType , $ nativeValueToWrite , $ scope , $ storage );
1493+ [$ nativeValueToWrite ] = $ this ->produceArrayDimFetchAssignValueToWrite ($ nodeScopeResolver , $ dimFetchStack , $ offsetNativeTypes , $ offsetNativeValueType , $ nativeValueToWrite , $ scope , $ storage, $ scope -> doNotTreatPhpDocTypesAsCertain () );
14931494 $ rewritten = true ;
14941495 break ;
14951496 }
@@ -2877,20 +2878,20 @@ private function advanceImplicitIndex(int $index): ?int
28772878 * @param non-empty-list<ArrayDimFetch> $dimFetchStack
28782879 * @param non-empty-list<array{Type|null, ArrayDimFetch}> $offsetTypes
28792880 *
2881+ * @param MutatingScope $writeBaseScope the scope to read the remembered containers from (see OffsetWriteBaseExpr)
2882+ *
28802883 * @return array{Type, list<array{Expr, Type}>}
28812884 */
2882- private function produceArrayDimFetchAssignValueToWrite (NodeScopeResolver $ nodeScopeResolver , array $ dimFetchStack , array $ offsetTypes , Type $ offsetValueType , Type $ valueToWrite , MutatingScope $ scope , ExpressionResultStorage $ storage ): array
2885+ private function produceArrayDimFetchAssignValueToWrite (NodeScopeResolver $ nodeScopeResolver , array $ dimFetchStack , array $ offsetTypes , Type $ offsetValueType , Type $ valueToWrite , MutatingScope $ scope , ExpressionResultStorage $ storage, MutatingScope $ writeBaseScope ): array
28832886 {
28842887 $ originalValueToWrite = $ valueToWrite ;
28852888
28862889 $ offsetValueTypeStack = [$ offsetValueType ];
2887- $ generalizeOnWrite = $ offsetTypes [array_key_last ($ offsetTypes )][0 ] !== null ;
28882890 $ dimDepth = 0 ;
28892891 foreach (array_slice ($ offsetTypes , 0 , -1 ) as [$ offsetType , $ dimFetch ]) {
28902892 $ dimDepth ++;
28912893 if ($ offsetType === null ) {
28922894 $ offsetValueType = new ConstantArrayType ([], []);
2893- $ generalizeOnWrite = false ;
28942895 } else {
28952896 if ($ dimDepth > self ::ARRAY_DIM_FETCH_WRITE_DEPTH_LIMIT && $ offsetValueType ->isOversizedArray ()->yes ()) {
28962897 $ offsetValueType = new MixedType ();
@@ -2904,13 +2905,11 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
29042905 }
29052906 } elseif ($ has ->maybe ()) {
29062907 if ($ scope ->hasExpressionType ($ dimFetch )->yes ()) {
2907- $ generalizeOnWrite = false ;
29082908 $ offsetValueType = $ scope ->getStateType ($ dimFetch );
29092909 } else {
29102910 $ offsetValueType = TypeCombinator ::union ($ offsetValueType ->getOffsetValueType ($ offsetType ), new ConstantArrayType ([], []));
29112911 }
29122912 } else {
2913- $ generalizeOnWrite = false ;
29142913 $ offsetValueType = new ConstantArrayType ([], []);
29152914 }
29162915 }
@@ -2921,6 +2920,7 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
29212920
29222921 $ lastDimKey = array_key_last ($ dimFetchStack );
29232922 $ computedContainerValues = [];
2923+ $ writeBases = [];
29242924 foreach (array_reverse ($ offsetTypes ) as $ i => [$ offsetType , $ writtenDimFetch ]) {
29252925 /** @var Type $offsetValueType */
29262926 $ offsetValueType = array_pop ($ offsetValueTypeStack );
@@ -2935,6 +2935,18 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
29352935 }
29362936 }
29372937
2938+ // the container as it was before this offset was first written - writing
2939+ // into it instead of into the current container drops the value the
2940+ // offset held after the previous write to it
2941+ $ writeBase = null ;
2942+ if ($ offsetType !== null && $ this ->denotesSameOffsetEveryTime ($ writtenDimFetch )) {
2943+ $ writeBaseExpr = new OffsetWriteBaseExpr ($ writtenDimFetch );
2944+ if ($ writeBaseScope ->hasExpressionType ($ writeBaseExpr )->yes ()) {
2945+ $ writeBase = $ writeBaseScope ->getStateType ($ writeBaseExpr );
2946+ }
2947+ $ writeBases [] = [$ writeBaseExpr , $ writeBase ?? $ offsetValueType ];
2948+ }
2949+
29382950 // the link of the chain that is looked up in the scope: the written
29392951 // dim fetch itself for a one-dimensional write, another link of the
29402952 // same chain for a nested one
@@ -2953,7 +2965,13 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
29532965 if ($ offsetType instanceof ConstantStringType || $ offsetType instanceof ConstantIntegerType) {
29542966 $ hasOffsetType = new HasOffsetValueType ($ offsetType , $ valueToWrite );
29552967 }
2956- $ valueToWrite = $ offsetValueType ->setExistingOffsetValueType ($ offsetType , $ valueToWrite );
2968+ if ($ writeBase === null ) {
2969+ $ valueToWrite = $ offsetValueType ->setExistingOffsetValueType ($ offsetType , $ valueToWrite );
2970+ } elseif ($ writeBase ->hasOffsetValueType ($ offsetType )->yes ()) {
2971+ $ valueToWrite = $ writeBase ->setExistingOffsetValueType ($ offsetType , $ valueToWrite );
2972+ } else {
2973+ $ valueToWrite = $ writeBase ->setOffsetValueType ($ offsetType , $ valueToWrite );
2974+ }
29572975
29582976 if ($ valueToWrite ->isArray ()->yes ()) {
29592977 if ($ hasOffsetType !== null ) {
@@ -2970,24 +2988,7 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
29702988 }
29712989
29722990 } else {
2973- // when $unionValues=false the array item-type will be replaced with $valueToWrite
2974- // when $unionValues=true the existing array item-type will be union'ed with $valueToWrite -> type gets wider
2975- $ unionValues = false ;
2976- if ($ i === 0 ) {
2977- $ unionValues = true ;
2978- } elseif (
2979- $ generalizeOnWrite
2980- && $ i === count ($ offsetTypes ) - 1
2981- &&
2982- (
2983- $ originalValueToWrite ->isConstantScalarValue ()->yes ()
2984- || !$ offsetValueType ->getIterableValueType ()->isSuperTypeOf ($ valueToWrite )->yes ()
2985- )
2986- ) {
2987- $ unionValues = true ;
2988- }
2989-
2990- $ valueToWrite = $ offsetValueType ->setOffsetValueType ($ offsetType , $ valueToWrite , $ unionValues );
2991+ $ valueToWrite = ($ writeBase ?? $ offsetValueType )->setOffsetValueType ($ offsetType , $ valueToWrite );
29912992 }
29922993
29932994 if ($ offsetValueType ->isList ()->yes () && $ this ->shouldKeepList ($ nodeScopeResolver , $ writtenDimFetch , $ scope , $ storage , $ offsetValueType , $ offsetType )) {
@@ -3024,7 +3025,7 @@ private function produceArrayDimFetchAssignValueToWrite(NodeScopeResolver $nodeS
30243025 $ additionalExpressions [] = [$ dimFetch , $ additionalValueType ];
30253026 }
30263027
3027- return [$ valueToWrite , $ additionalExpressions ];
3028+ return [$ valueToWrite , array_merge ( $ additionalExpressions, $ writeBases ) ];
30283029 }
30293030
30303031 private function shouldKeepList (NodeScopeResolver $ nodeScopeResolver , ArrayDimFetch $ arrayDimFetch , MutatingScope $ scope , ExpressionResultStorage $ storage , Type $ offsetValueType , ?Type $ offsetType ): bool
@@ -3083,6 +3084,59 @@ private function shouldKeepList(NodeScopeResolver $nodeScopeResolver, ArrayDimFe
30833084 && $ scope ->hasExpressionType ($ arrayDimFetch )->yes ();
30843085 }
30853086
3087+ /**
3088+ * Whether evaluating the expression again yields the same value as long as nothing
3089+ * it consists of is reassigned - which invalidates what the scope remembers about it.
3090+ * `$a[rand()]` or `$a[]` denote a new offset every time.
3091+ */
3092+ private function denotesSameOffsetEveryTime (Expr $ expr ): bool
3093+ {
3094+ if ($ expr instanceof Variable) {
3095+ return is_string ($ expr ->name );
3096+ }
3097+ if ($ expr instanceof ArrayDimFetch) {
3098+ return $ expr ->dim !== null && $ this ->denotesSameOffsetEveryTime ($ expr ->var ) && $ this ->denotesSameOffsetEveryTime ($ expr ->dim );
3099+ }
3100+ if ($ expr instanceof PropertyFetch || $ expr instanceof Expr \NullsafePropertyFetch) {
3101+ return $ expr ->name instanceof Node \Identifier && $ this ->denotesSameOffsetEveryTime ($ expr ->var );
3102+ }
3103+ if ($ expr instanceof StaticPropertyFetch) {
3104+ return $ expr ->class instanceof Name && $ expr ->name instanceof Node \VarLikeIdentifier;
3105+ }
3106+ if ($ expr instanceof Expr \ClassConstFetch) {
3107+ return $ expr ->class instanceof Name && $ expr ->name instanceof Node \Identifier;
3108+ }
3109+ if ($ expr instanceof Expr \ConstFetch) {
3110+ return true ;
3111+ }
3112+ if ($ expr instanceof Node \Scalar \InterpolatedString) {
3113+ foreach ($ expr ->parts as $ part ) {
3114+ if (!$ part instanceof Node \InterpolatedStringPart && !$ this ->denotesSameOffsetEveryTime ($ part )) {
3115+ return false ;
3116+ }
3117+ }
3118+
3119+ return true ;
3120+ }
3121+ if ($ expr instanceof Node \Scalar) {
3122+ return true ;
3123+ }
3124+ if ($ expr instanceof Expr \BinaryOp) {
3125+ return $ this ->denotesSameOffsetEveryTime ($ expr ->left ) && $ this ->denotesSameOffsetEveryTime ($ expr ->right );
3126+ }
3127+ if (
3128+ $ expr instanceof Expr \UnaryMinus
3129+ || $ expr instanceof Expr \UnaryPlus
3130+ || $ expr instanceof Expr \BitwiseNot
3131+ || $ expr instanceof Expr \BooleanNot
3132+ || $ expr instanceof Expr \Cast
3133+ ) {
3134+ return $ this ->denotesSameOffsetEveryTime ($ expr ->expr );
3135+ }
3136+
3137+ return false ;
3138+ }
3139+
30863140 /**
30873141 * A link of the chain other than the written one being tracked does not
30883142 * prove the written offset is there. It is the usual evidence when the
0 commit comments