Skip to content

Commit 33375c3

Browse files
gnutixclaude
andcommitted
Model TypeError throw points for illegal array key offsets
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QW8VaDtn3cMdQowPSh1xGG
1 parent 184d34e commit 33375c3

41 files changed

Lines changed: 1793 additions & 459 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/Analyser/ExprHandler/ArrayDimFetchHandler.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
use PHPStan\Analyser\ExpressionResultStorage;
1616
use PHPStan\Analyser\ExprHandler;
1717
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
18+
use PHPStan\Analyser\ExprHandler\Helper\IllegalOffsetTypeHelper;
1819
use PHPStan\Analyser\ExprHandler\Helper\MethodCallReturnTypeHelper;
1920
use PHPStan\Analyser\ExprHandler\Helper\MethodThrowPointHelper;
2021
use PHPStan\Analyser\Generics\TemplateArgumentFrame;
22+
use PHPStan\Analyser\InternalThrowPoint;
2123
use PHPStan\Analyser\IssetabilityDescriptor;
2224
use PHPStan\Analyser\MutatingScope;
2325
use PHPStan\Analyser\NodeScopeResolver;
@@ -29,13 +31,15 @@
2931
use PHPStan\Dependency\Dependencies;
3032
use PHPStan\DependencyInjection\AutowiredService;
3133
use PHPStan\Node\Expr\TypeExpr;
34+
use PHPStan\Php\PhpVersion;
3235
use PHPStan\Reflection\ParametersAcceptorSelector;
3336
use PHPStan\Turbo\ShadowedByTurboExtension;
3437
use PHPStan\Type\ErrorType;
3538
use PHPStan\Type\NeverType;
3639
use PHPStan\Type\ObjectType;
3740
use PHPStan\Type\Type;
3841
use PHPStan\Type\TypeCombinator;
42+
use TypeError;
3943
use function array_merge;
4044
use function is_string;
4145

@@ -52,6 +56,7 @@ public function __construct(
5256
private DefaultNarrowingHelper $defaultNarrowingHelper,
5357
private MethodThrowPointHelper $methodThrowPointHelper,
5458
private MethodCallReturnTypeHelper $methodCallReturnTypeHelper,
59+
private PhpVersion $phpVersion,
5560
)
5661
{
5762
}
@@ -130,6 +135,17 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, Stmt $stmt,
130135
$offsetGetCall = new MethodCall($expr->var, new Identifier('offsetGet'), [new Arg($expr->dim)], [TemplateArgumentFrame::SYNTHETIC_SITE_ATTRIBUTE => true]);
131136
}
132137

138+
if (
139+
$this->phpVersion->throwsTypeErrorForIllegalOffsets()
140+
// only array and string offset reads throw TypeError for illegal offsets,
141+
// reads on null and other scalars emit a warning, ArrayAccess objects go through offsetGet();
142+
// isset() and empty() of a string offset are false instead
143+
&& (!$varType->isArray()->no() || (!$context->isIssetTarget() && !$varType->isString()->no()))
144+
&& IllegalOffsetTypeHelper::mayOffsetThrowTypeError($dimResult->getType())
145+
) {
146+
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(TypeError::class), $expr, false);
147+
}
148+
133149
$result = $this->expressionResultFactory->create(
134150
$scope,
135151
beforeScope: $beforeScope,

‎src/Analyser/ExprHandler/ArrayHandler.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
use PHPStan\Analyser\ExpressionResultFactory;
1616
use PHPStan\Analyser\ExpressionResultStorage;
1717
use PHPStan\Analyser\ExprHandler;
18+
use PHPStan\Analyser\ExprHandler\Helper\IllegalOffsetTypeHelper;
1819
use PHPStan\Analyser\Generics\ClosureSignatureInference;
20+
use PHPStan\Analyser\InternalThrowPoint;
1921
use PHPStan\Analyser\MutatingScope;
2022
use PHPStan\Analyser\NodeScopeResolver;
2123
use PHPStan\Analyser\SpecifiedTypes;
@@ -27,6 +29,7 @@
2729
use PHPStan\Node\LiteralArrayItem;
2830
use PHPStan\Node\LiteralArrayNode;
2931
use PHPStan\Node\Variable\VariableWrite;
32+
use PHPStan\Php\PhpVersion;
3033
use PHPStan\Reflection\InitializerExprTypeResolver;
3134
use PHPStan\ShouldNotHappenException;
3235
use PHPStan\Turbo\ShadowedByTurboExtension;
@@ -35,8 +38,10 @@
3538
use PHPStan\Type\Constant\ConstantIntegerType;
3639
use PHPStan\Type\IntegerType;
3740
use PHPStan\Type\MixedType;
41+
use PHPStan\Type\ObjectType;
3842
use PHPStan\Type\Type;
3943
use PHPStan\Type\TypeCombinator;
44+
use TypeError;
4045
use function array_key_exists;
4146
use function array_map;
4247
use function array_merge;
@@ -57,6 +62,7 @@ final class ArrayHandler implements ExprHandler
5762
public function __construct(
5863
private InitializerExprTypeResolver $initializerExprTypeResolver,
5964
private ExpressionResultFactory $expressionResultFactory,
65+
private PhpVersion $phpVersion,
6066
)
6167
{
6268
}
@@ -144,6 +150,15 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
144150
$impurePoints = array_merge($impurePoints, $valueResult->getImpurePoints());
145151
$isAlwaysTerminating = $isAlwaysTerminating || $valueResult->isAlwaysTerminating();
146152
$scope = $valueResult->getScope();
153+
if (
154+
$keyResult !== null
155+
&& $this->phpVersion->throwsTypeErrorForIllegalOffsets()
156+
&& IllegalOffsetTypeHelper::mayOffsetThrowTypeError($keyResult->getType())
157+
) {
158+
// an array or an object key throws TypeError once the value was evaluated
159+
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(TypeError::class), $arrayItem->key, false);
160+
$variableFlows[] = VariableFlow::throwing(new ObjectType(TypeError::class), true);
161+
}
147162
// the item's callback fires after its key and value were processed,
148163
// with the item's entry scope - callback-side asks answer from the
149164
// storage instead of re-walking the yet-unstored sub-expressions

‎src/Analyser/ExprHandler/AssignHandler.php‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
use PHPStan\Analyser\ExprHandler;
3434
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
3535
use PHPStan\Analyser\ExprHandler\Helper\IdenticalNarrowingHelper;
36+
use PHPStan\Analyser\ExprHandler\Helper\IllegalOffsetTypeHelper;
3637
use PHPStan\Analyser\ExprHandler\Helper\MethodThrowPointHelper;
3738
use PHPStan\Analyser\ExprHandler\Helper\NonNullabilityHelper;
3839
use PHPStan\Analyser\ExprHandler\Helper\VirtualExprResultHelper;
@@ -286,6 +287,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
286287
VariableFlowBuilder::targetRead($expr->var, $storage, false),
287288
$assignedExprResult->getVariableFlow(),
288289
$valueFlowWrite !== null && $context->isValueConsumed() ? VariableFlow::inputs($valueFlowWrite->getId(), $context->getValueFlowTarget() !== null ? $context->getValueFlowTarget()->getId() : null) : null,
290+
// an illegal offset throws before the write
291+
count($target->getIllegalOffsetDimFetches()) > 0 ? VariableFlow::throwing(new ObjectType(TypeError::class), true) : null,
289292
VariableFlowBuilder::targetWrite($expr->var, VariableWrite::KIND_ASSIGN, $scope, $storage, $redundantType),
290293
);
291294
if ($expr instanceof Assign && $expr->expr instanceof Expr\Array_ && self::hasArrayReference($expr->expr)) {
@@ -852,6 +855,35 @@ private function doPrepareTarget(
852855
$nodeScopeResolver->callNodeCallback($nodeCallback, $dimFetch, $enterExpressionAssign ? $callbackScope->enterExpressionAssign($dimFetch) : $callbackScope, $storage);
853856
}
854857

858+
// the links whose offset may throw TypeError - PHP throws only after
859+
// evaluating the assigned value, so applyWrite() creates their throw points
860+
$illegalOffsetDimFetches = [];
861+
if ($this->phpVersion->throwsTypeErrorForIllegalOffsets()) {
862+
foreach ($offsetTypes as $i => [$offsetType, $offsetDimFetch]) {
863+
// $arr[] = ... never throws for the offset
864+
if ($offsetType === null) {
865+
continue;
866+
}
867+
if (!IllegalOffsetTypeHelper::mayOffsetThrowTypeError($offsetType)) {
868+
continue;
869+
}
870+
// writes to ArrayAccess objects go through offsetSet() whose throw points applyWrite() models;
871+
// the container is the previous chain link - the root for the first dimension
872+
$containerResult = $i === 0 ? $varResult : $deferredDimFetchResults[$i - 1][1];
873+
$containerType = $containerResult->getType();
874+
if ((new ObjectType(ArrayAccess::class))->isSuperTypeOf($containerType)->yes()) {
875+
continue;
876+
}
877+
// `$lvalue ??= ...` throws reading an array or a string container,
878+
// before the assigned value is evaluated
879+
if ($mode->issetSemanticsForRead() && ($containerType->isArray()->yes() || $containerType->isString()->yes())) {
880+
$throwPoints[] = InternalThrowPoint::createExplicit($scope, new ObjectType(TypeError::class), $offsetDimFetch, false);
881+
continue;
882+
}
883+
$illegalOffsetDimFetches[] = $offsetDimFetch;
884+
}
885+
}
886+
855887
if ($mode->issetSemanticsForRead()) {
856888
// `$lvalue ??= ...` reads the chain with isset() semantics. The root
857889
// and dimensions were just walked, so each chain link's read is
@@ -931,6 +963,7 @@ private function doPrepareTarget(
931963
targetReadResult: $targetReadResult,
932964
targetChainResults: $targetChainResults,
933965
dependencies: $targetDependencies,
966+
illegalOffsetDimFetches: $illegalOffsetDimFetches,
934967
);
935968
}
936969

@@ -1438,6 +1471,25 @@ public function applyWrite(
14381471
$varType = new ConstantArrayType([], []);
14391472
$varNativeType = new ConstantArrayType([], []);
14401473
}
1474+
1475+
// an illegal offset throws TypeError after the assigned value was
1476+
// evaluated and an undefined root was turned into an array
1477+
$illegalOffsetDimFetches = $target->getIllegalOffsetDimFetches();
1478+
if (count($illegalOffsetDimFetches) > 0) {
1479+
$throwPointScope = $scope;
1480+
if (!$isImplicitArrayCreation->no() && $var instanceof Variable && is_string($var->name)) {
1481+
$throwPointScope = $throwPointScope->assignVariable(
1482+
$var->name,
1483+
TypeCombinator::union($varType, new ConstantArrayType([], [])),
1484+
TypeCombinator::union($varNativeType, new ConstantArrayType([], [])),
1485+
TrinaryLogic::createYes(),
1486+
[],
1487+
);
1488+
}
1489+
foreach ($illegalOffsetDimFetches as $illegalOffsetDimFetch) {
1490+
$throwPoints[] = InternalThrowPoint::createExplicit($throwPointScope, new ObjectType(TypeError::class), $illegalOffsetDimFetch, false);
1491+
}
1492+
}
14411493
$offsetValueType = $varType;
14421494
$offsetNativeValueType = $varNativeType;
14431495

‎src/Analyser/ExprHandler/AssignOpHandler.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@
3535
use PHPStan\Type\ObjectType;
3636
use PHPStan\Type\StaticTypeFactory;
3737
use PHPStan\Type\Type;
38+
use TypeError;
3839
use function array_merge;
40+
use function count;
3941
use function get_class;
4042
use function is_string;
4143
use function sprintf;
@@ -296,6 +298,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
296298
$writeFlow = VariableFlow::sequence(
297299
$rhsResult->getVariableFlow(),
298300
$valueFlowWrite !== null && $context->isValueConsumed() ? VariableFlow::inputs($valueFlowWrite->getId(), $context->getValueFlowTarget() !== null ? $context->getValueFlowTarget()->getId() : null) : null,
301+
// an illegal offset throws before the write
302+
count($target->getIllegalOffsetDimFetches()) > 0 ? VariableFlow::throwing(new ObjectType(TypeError::class), true) : null,
299303
VariableFlowBuilder::targetWrite($expr->var, VariableWrite::KIND_READ_MODIFY_WRITE, $scope, $storage),
300304
);
301305
$variableFlow = VariableFlow::sequence(

‎src/Analyser/ExprHandler/EmptyHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
5151
$beforeScope = $scope;
5252
$nonNullabilityResult = $this->nonNullabilityHelper->ensureNonNullability($scope, $expr->expr);
5353
$scope = $nodeScopeResolver->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $expr->expr);
54-
$exprResult = $nodeScopeResolver->processExprNode($stmt, $expr->expr, $scope, $storage, $nodeCallback, $context->enterDeep());
54+
$exprResult = $nodeScopeResolver->processExprNode($stmt, $expr->expr, $scope, $storage, $nodeCallback, $context->enterDeep()->enterIssetTarget());
5555
$scope = $exprResult->getScope();
5656
$scope = $this->nonNullabilityHelper->revertNonNullability($scope, $nonNullabilityResult->getSpecifiedExpressions());
5757
$scope = $nodeScopeResolver->lookForUnsetAllowedUndefinedExpressions($scope, $expr->expr);
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser\ExprHandler\Helper;
4+
5+
use PHPStan\Turbo\ShadowedByTurboExtension;
6+
use PHPStan\Type\Type;
7+
8+
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../../turbo-ext/src/IllegalOffsetTypeHelper.cpp')]
9+
final class IllegalOffsetTypeHelper
10+
{
11+
12+
/**
13+
* On PHP 8.0+ using an array or an object as an array/string offset throws TypeError
14+
* (https://wiki.php.net/rfc/engine_warnings). Float, bool and null keys are coerced
15+
* with at most a deprecation, resource keys with a warning - no TypeError.
16+
*/
17+
public static function mayOffsetThrowTypeError(Type $offsetType): bool
18+
{
19+
return !$offsetType->isArray()->no() || !$offsetType->isObject()->no();
20+
}
21+
22+
}

‎src/Analyser/ExprHandler/IssetHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
7474
foreach ($expr->vars as $var) {
7575
$nonNullabilityResult = $this->nonNullabilityHelper->ensureNonNullability($scope, $var);
7676
$scope = $nodeScopeResolver->lookForSetAllowedUndefinedExpressions($nonNullabilityResult->getScope(), $var);
77-
$varResult = $nodeScopeResolver->processExprNode($stmt, $var, $scope, $storage, $nodeCallback, $context->enterDeep());
77+
$varResult = $nodeScopeResolver->processExprNode($stmt, $var, $scope, $storage, $nodeCallback, $context->enterDeep()->enterIssetTarget());
7878
$varResults[] = $varResult;
7979
$scope = $varResult->getScope();
8080
$hasYield = $hasYield || $varResult->hasYield();

‎src/Analyser/ExpressionContext.php‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ private function __construct(
2929
private ?bool $valueConsumed = null,
3030
private ?Type $passedToType = null,
3131
private ?Type $nativePassedToType = null,
32+
private bool $issetTarget = false,
3233
)
3334
{
3435
}
@@ -50,7 +51,7 @@ public static function createDeep(bool $resolveTemplateArguments = true): self
5051
*/
5152
public function enterDeep(): self
5253
{
53-
if ($this->isDeep && $this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
54+
if ($this->isDeep && $this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && !$this->issetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
5455
return $this;
5556
}
5657

@@ -78,7 +79,7 @@ public function enterDeepKeepingValueFlow(): self
7879
*/
7980
public function withoutValueFlow(): self
8081
{
81-
if ($this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
82+
if ($this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && !$this->issetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
8283
return $this;
8384
}
8485

@@ -136,7 +137,7 @@ public function withoutTemplateArgumentResolution(): self
136137
return $this;
137138
}
138139

139-
return new self($this->isDeep, $this->inAssignRightSideVariableName, $this->inAssignRightSideExpr, $this->inThrow, $this->inAssignRightSideType, $this->inAssignRightSideNativeType, false, $this->valueFlowTarget, $this->valueFlowDirect, $this->arrayDimFetchRoot, $this->unsetTarget, $this->valueConsumed);
140+
return new self($this->isDeep, $this->inAssignRightSideVariableName, $this->inAssignRightSideExpr, $this->inThrow, $this->inAssignRightSideType, $this->inAssignRightSideNativeType, false, $this->valueFlowTarget, $this->valueFlowDirect, $this->arrayDimFetchRoot, $this->unsetTarget, $this->valueConsumed, issetTarget: $this->issetTarget);
140141
}
141142

142143
public function enterThrow(): self
@@ -243,4 +244,18 @@ public function isUnsetTarget(): bool
243244
return $this->unsetTarget;
244245
}
245246

247+
/**
248+
* The expression is an isset() or empty() subject: an illegal offset of
249+
* a string container makes it false instead of throwing.
250+
*/
251+
public function enterIssetTarget(): self
252+
{
253+
return new self($this->isDeep, $this->inAssignRightSideVariableName, $this->inAssignRightSideExpr, $this->inThrow, $this->inAssignRightSideType, $this->inAssignRightSideNativeType, $this->resolveTemplateArguments, issetTarget: true);
254+
}
255+
256+
public function isIssetTarget(): bool
257+
{
258+
return $this->issetTarget;
259+
}
260+
246261
}

‎src/Analyser/PreparedAssignTarget.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ final class PreparedAssignTarget
4242
* @param non-empty-list<array{Type, ExistingArrayDimFetch}>|null $existingOffsetTypes
4343
* @param non-empty-list<array{Type, ExistingArrayDimFetch}>|null $existingOffsetNativeTypes
4444
* @param ExpressionResult[] $targetChainResults
45+
* @param list<ArrayDimFetch> $illegalOffsetDimFetches
4546
*/
4647
public function __construct(
4748
private string $kind,
@@ -71,6 +72,7 @@ public function __construct(
7172
private array $targetChainResults = [],
7273
private ?ExpressionResult $variableNameResult = null,
7374
private ?Dependencies $dependencies = null,
75+
private array $illegalOffsetDimFetches = [],
7476
)
7577
{
7678
}
@@ -302,4 +304,16 @@ public function getVariableNameResult(): ?ExpressionResult
302304
return $this->variableNameResult;
303305
}
304306

307+
/**
308+
* The links of an offset write whose offset may be an array or an object,
309+
* which throws TypeError on PHP 8+ - after the assigned value was evaluated
310+
* and an undefined root was turned into an array.
311+
*
312+
* @return list<ArrayDimFetch>
313+
*/
314+
public function getIllegalOffsetDimFetches(): array
315+
{
316+
return $this->illegalOffsetDimFetches;
317+
}
318+
305319
}

‎src/Php/PhpVersion.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,12 @@ public function throwsValueErrorForInternalFunctions(): bool
188188
return $this->versionId >= 80000;
189189
}
190190

191+
// see https://wiki.php.net/rfc/engine_warnings - "Illegal offset type" family
192+
public function throwsTypeErrorForIllegalOffsets(): bool
193+
{
194+
return $this->versionId >= 80000;
195+
}
196+
191197
public function supportsHhPrintfSpecifier(): bool
192198
{
193199
return $this->versionId >= 80000;

0 commit comments

Comments
 (0)