Skip to content

Commit 2ef5ee0

Browse files
committed
Single-pass inside-out Expr processing
2 parents 1bfa8dd + 00f2b74 commit 2ef5ee0

246 files changed

Lines changed: 15574 additions & 7376 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Build;
4+
5+
use PhpParser\Node;
6+
use PhpParser\Node\Expr\MethodCall;
7+
use PHPStan\Analyser\Scope;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleErrorBuilder;
10+
use function array_key_exists;
11+
use function in_array;
12+
use function sprintf;
13+
use function str_starts_with;
14+
15+
/**
16+
* The single-pass engine must not price expressions through Scope::getType()
17+
* and friends - every walked node's type lives in its ExpressionResult
18+
* (threaded via ArgsResult, storage, or gathered statement scopes). A scope
19+
* read in engine code either re-walks a node on demand or silently diverges
20+
* from the stored result. The allowlist below names the documented seams
21+
* (rule-facing bridge asks and ask-ahead-of-walk reads).
22+
*
23+
* @implements Rule<MethodCall>
24+
*/
25+
final class NoScopeTypeReadInEngineRule implements Rule
26+
{
27+
28+
private const ENGINE_NAMESPACES = [
29+
'PHPStan\\Analyser\\NodeScopeResolver',
30+
'PHPStan\\Analyser\\StmtHandler\\',
31+
'PHPStan\\Analyser\\ExprHandler\\',
32+
];
33+
34+
private const BANNED_METHODS = ['getType', 'getNativeType', 'getKeepVoidType'];
35+
36+
private const ALLOWED_SEAMS = [
37+
// rule-facing bridge asks: the scope carries no storage
38+
'PHPStan\\Analyser\\ExprHandler\\Helper\\ClosureTypeResolver' => ['readExprType', 'resolveArrowFunctionReturnType'],
39+
'PHPStan\\Analyser\\ExprHandler\\Helper\\CountNarrowingHelper' => ['isNormalCountCall'],
40+
// immediately invoked closures: the invocation args are walked after the closure
41+
'PHPStan\\Analyser\\ExprHandler\\Helper\\ClosureTypeResolver#buildParametersAndAcceptors' => [],
42+
];
43+
44+
public function getNodeType(): string
45+
{
46+
return MethodCall::class;
47+
}
48+
49+
public function processNode(Node $node, Scope $scope): array
50+
{
51+
if (!$node->name instanceof Node\Identifier) {
52+
return [];
53+
}
54+
$methodName = $node->name->toString();
55+
if (!in_array($methodName, self::BANNED_METHODS, true)) {
56+
return [];
57+
}
58+
59+
$currentClassReflection = $scope->getClassReflection();
60+
if ($currentClassReflection === null) {
61+
return [];
62+
}
63+
$namespace = $currentClassReflection->getName();
64+
$inEngine = false;
65+
foreach (self::ENGINE_NAMESPACES as $prefix) {
66+
if ($namespace === $prefix || str_starts_with($namespace, $prefix)) {
67+
$inEngine = true;
68+
break;
69+
}
70+
}
71+
if (!$inEngine) {
72+
return [];
73+
}
74+
75+
$calledOnType = $scope->getType($node->var);
76+
if ($calledOnType->getObjectClassNames() === []) {
77+
return [];
78+
}
79+
$isScope = false;
80+
foreach ($calledOnType->getObjectClassReflections() as $classReflection) {
81+
if ($classReflection->is(Scope::class)) {
82+
$isScope = true;
83+
break;
84+
}
85+
}
86+
if (!$isScope) {
87+
return [];
88+
}
89+
90+
$function = $scope->getFunction();
91+
$functionName = $function !== null ? $function->getName() : null;
92+
if (
93+
array_key_exists($namespace, self::ALLOWED_SEAMS)
94+
&& $functionName !== null
95+
&& in_array($functionName, self::ALLOWED_SEAMS[$namespace], true)
96+
) {
97+
return [];
98+
}
99+
if ($functionName !== null && array_key_exists($namespace . '#' . $functionName, self::ALLOWED_SEAMS)) {
100+
return [];
101+
}
102+
103+
return [
104+
RuleErrorBuilder::message(sprintf(
105+
'Engine code must not price expressions via Scope::%s() - read the expression\'s stored ExpressionResult (ArgsResult, storage, gathered scopes) instead.',
106+
$methodName,
107+
))->identifier('phpstanBuild.scopeTypeReadInEngine')->build(),
108+
];
109+
}
110+
111+
}

‎build/phpstan.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ parameters:
188188

189189
rules:
190190
- PHPStan\Build\FinalClassRule
191+
- PHPStan\Build\NoScopeTypeReadInEngineRule
191192
- PHPStan\Build\AttributeNamedArgumentsRule
192193
- PHPStan\Build\NamedArgumentsRule
193194
- PHPStan\Build\OverrideAttributeThirdPartyMethodRule

‎phpstan-baseline.neon‎

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -37,39 +37,27 @@ parameters:
3737
path: src/Analyser/ExprHandler/BinaryOpHandler.php
3838

3939
-
40-
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantBooleanType is error-prone and deprecated. Use Type::isTrue() or Type::isFalse() instead.'
41-
identifier: phpstanApi.instanceofType
42-
count: 1
43-
path: src/Analyser/ExprHandler/BooleanNotHandler.php
44-
45-
-
46-
rawMessage: 'Doing instanceof PHPStan\Type\ConstantScalarType is error-prone and deprecated. Use Type::isConstantScalarValue() or Type::getConstantScalarTypes() or Type::getConstantScalarValues() instead.'
47-
identifier: phpstanApi.instanceofType
48-
count: 2
49-
path: src/Analyser/ExprHandler/Helper/EqualityTypeSpecifyingHelper.php
50-
51-
-
52-
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantBooleanType is error-prone and deprecated. Use Type::isTrue() or Type::isFalse() instead.'
53-
identifier: phpstanApi.instanceofType
40+
rawMessage: Casting to string something that's already string.
41+
identifier: cast.useless
5442
count: 3
55-
path: src/Analyser/ExprHandler/Helper/EqualityTypeSpecifyingHelper.php
43+
path: src/Analyser/ExprHandler/Helper/ConditionalExpressionHolderHelper.php
5644

5745
-
5846
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantStringType is error-prone and deprecated. Use Type::getConstantStrings() instead.'
5947
identifier: phpstanApi.instanceofType
6048
count: 2
61-
path: src/Analyser/ExprHandler/IssetHandler.php
49+
path: src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php
6250

6351
-
6452
rawMessage: 'Only numeric types are allowed in pre-increment, float|int|string|null given.'
6553
identifier: preInc.nonNumeric
6654
count: 1
67-
path: src/Analyser/ExprHandler/PreIncHandler.php
55+
path: src/Analyser/ExprHandler/Helper/IncDecTypeHelper.php
6856

6957
-
7058
rawMessage: Casting to string something that's already string.
7159
identifier: cast.useless
72-
count: 1
60+
count: 4
7361
path: src/Analyser/MutatingScope.php
7462

7563
-
@@ -108,24 +96,12 @@ parameters:
10896
count: 1
10997
path: src/Analyser/RuleErrorTransformer.php
11098

111-
-
112-
rawMessage: Casting to string something that's already string.
113-
identifier: cast.useless
114-
count: 2
115-
path: src/Analyser/ScopeOps.php
116-
11799
-
118100
rawMessage: 'Parameter #2 $node of method PHPStan\BetterReflection\SourceLocator\Ast\Strategy\NodeToReflection::__invoke() expects PhpParser\Node\Expr\ArrowFunction|PhpParser\Node\Expr\Closure|PhpParser\Node\Expr\FuncCall|PhpParser\Node\Stmt\Class_|PhpParser\Node\Stmt\Const_|PhpParser\Node\Stmt\Enum_|PhpParser\Node\Stmt\Function_|PhpParser\Node\Stmt\Interface_|PhpParser\Node\Stmt\Trait_, PhpParser\Node\Stmt\ClassLike given.'
119101
identifier: argument.type
120102
count: 1
121103
path: src/Analyser/StmtHandler/ClassLikeHandler.php
122104

123-
-
124-
rawMessage: 'Doing instanceof PHPStan\Type\Constant\ConstantBooleanType is error-prone and deprecated. Use Type::isTrue() or Type::isFalse() instead.'
125-
identifier: phpstanApi.instanceofType
126-
count: 2
127-
path: src/Analyser/TypeSpecifier.php
128-
129105
-
130106
rawMessage: 'Template type TNodeType is declared as covariant, but occurs in contravariant position in parameter node of method PHPStan\Collectors\Collector::processNode().'
131107
identifier: generics.variance

‎src/Analyser/ArgsResult.php‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,76 @@
22

33
namespace PHPStan\Analyser;
44

5+
use PhpParser\Node\Expr;
56
use PHPStan\Reflection\ParametersAcceptor;
7+
use PHPStan\ShouldNotHappenException;
8+
use function get_class;
9+
use function spl_object_id;
10+
use function sprintf;
611

712
/**
813
* Result of NodeScopeResolver::processArgs(): the scope/throw/impure state after
914
* processing all arguments (wrapped ExpressionResult) plus the ParametersAcceptor
1015
* resolved from the arg types gathered on the arg-to-arg evolving scope. The
1116
* resolved acceptor is type-driven (selectFromTypes) so its generics are resolved
12-
* against the actual argument types - callers wire it into the call's return
13-
* type. Null when the call had no variants (dynamic callee).
17+
* against the actual argument types - callers wire it into the call expression's
18+
* stored return type. Null when the call had no variants (dynamic callee).
1419
*/
1520
final class ArgsResult
1621
{
1722

23+
/**
24+
* @param array<int, ExpressionResult> $argResults keyed by spl_object_id of each argument's value expression
25+
*/
1826
public function __construct(
1927
private ExpressionResult $expressionResult,
2028
private ?ParametersAcceptor $resolvedParametersAcceptor,
29+
private array $argResults,
2130
)
2231
{
2332
}
2433

34+
/**
35+
* Membership query: the ExpressionResult of the given expression if it is one of
36+
* the call's processed arguments. Null means the expression is not such an
37+
* argument - either it is a different expression altogether (the callee name, a
38+
* synthetic node, a narrowed subexpression), or it is a default-value argument
39+
* ArgumentsNormalizer synthesized for an omitted optional parameter, which has no
40+
* source code behind it and so was never processed. Call sites holding an actual
41+
* argument of the call use requireArgResult() instead.
42+
*/
43+
public function findArgResult(Expr $argValue): ?ExpressionResult
44+
{
45+
return $this->argResults[spl_object_id($argValue)] ?? null;
46+
}
47+
48+
/**
49+
* @return array<int, ExpressionResult> keyed by spl_object_id of each argument's value expression
50+
*/
51+
public function getArgResults(): array
52+
{
53+
return $this->argResults;
54+
}
55+
56+
/**
57+
* The stored ExpressionResult of a call argument's value expression; the
58+
* argument must have been processed by processArgs() - engine code reads
59+
* argument types through this instead of re-asking the scope.
60+
*/
61+
public function requireArgResult(Expr $argValue): ExpressionResult
62+
{
63+
$result = $this->argResults[spl_object_id($argValue)] ?? null;
64+
if ($result === null) {
65+
throw new ShouldNotHappenException(sprintf(
66+
'No stored ExpressionResult for a %s argument on line %d.',
67+
get_class($argValue),
68+
$argValue->getStartLine(),
69+
));
70+
}
71+
72+
return $result;
73+
}
74+
2575
public function getScope(): MutatingScope
2676
{
2777
return $this->expressionResult->getScope();
@@ -53,6 +103,19 @@ public function getImpurePoints(): array
53103
return $this->expressionResult->getImpurePoints();
54104
}
55105

106+
/**
107+
* The same processed arguments under another acceptor: an immediately
108+
* invoked closure's arguments are walked on its declared signature, the
109+
* acceptor the call resolves from is the walked closure's.
110+
*/
111+
public function withResolvedParametersAcceptor(?ParametersAcceptor $resolvedParametersAcceptor): self
112+
{
113+
$clone = clone $this;
114+
$clone->resolvedParametersAcceptor = $resolvedParametersAcceptor;
115+
116+
return $clone;
117+
}
118+
56119
public function getResolvedParametersAcceptor(): ?ParametersAcceptor
57120
{
58121
return $this->resolvedParametersAcceptor;

‎src/Analyser/CalledMethodProcessor.php‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ public function processCalledMethod(NodeScopeResolver $nodeScopeResolver, Method
8787
if ($returnStatement !== null) {
8888
foreach ($returnStatement->getExecutionEnds() as $executionEnd) {
8989
$statementResult = $executionEnd->getStatementResult();
90-
$endNode = $executionEnd->getNode();
91-
if ($endNode instanceof Node\Stmt\Expression) {
92-
$exprType = $statementResult->getScope()->getType($endNode->expr);
90+
$endExprResult = $executionEnd->getExprResult();
91+
if ($endExprResult !== null) {
92+
$walkScope = $statementResult->getScope()->toWalkScope();
93+
$exprType = $endExprResult->getTypeOnScope($walkScope, $walkScope->nativeTypesPromoted);
9394
if ($exprType instanceof NeverType && $exprType->isExplicit()) {
9495
continue;
9596
}

‎src/Analyser/ConditionalExpressionHolderRecipe.php‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ final class ConditionalExpressionHolderRecipe
2222
{
2323

2424
/**
25-
* @param list<array{string, Expr, bool, Type}> $conditionEntries [exprString, expr, fromSureTypes, type]
25+
* @param list<array{string, Expr, bool, Type, ?ExpressionResult}> $conditionEntries [exprString, expr, fromSureTypes, type, the operand walk's result for the expr]
2626
* @param list<array{string, Expr, Type, ?Type}> $holderEntries [exprString, expr, type, target type pinned at compose time (null = read the applying scope)]
2727
*/
2828
public function __construct(
@@ -43,8 +43,15 @@ public function evaluate(MutatingScope $scope): array
4343
// the unnarrowed type of each condition expression, for the
4444
// dropped-self-condition complement below
4545
$conditionOriginalTypes = [];
46-
foreach ($this->conditionEntries as [$exprString, $expr, $fromSureTypes, $type]) {
47-
$scopeType = $scope->getType($expr);
46+
foreach ($this->conditionEntries as [$exprString, $expr, $fromSureTypes, $type, $conditionResult]) {
47+
// through the expression's own result, which answers from the applying
48+
// scope's state where that scope owns the expression - a narrowing
49+
// subject no walk produced (an extension is free to specify a type for
50+
// an expression the source never evaluated on its own) has no result
51+
// and is read from the scope state directly
52+
$scopeType = $conditionResult !== null
53+
? $conditionResult->getTypeOnScope($scope, $scope->nativeTypesPromoted)
54+
: $scope->getStateType($expr);
4855
$conditionType = $fromSureTypes
4956
? TypeCombinator::remove($scopeType, $type)
5057
: TypeCombinator::intersect($scopeType, $type);
@@ -81,7 +88,7 @@ public function evaluate(MutatingScope $scope): array
8188
continue;
8289
}
8390

84-
$targetType = $pinnedTargetType ?? $scope->getType($expr);
91+
$targetType = $pinnedTargetType ?? $scope->getStateType($expr);
8592
$holderType = $this->holdersFromSureTypes
8693
? TypeCombinator::intersect($targetType, $type)
8794
: TypeCombinator::remove($targetType, $type);

0 commit comments

Comments
 (0)