Skip to content

Commit bcfd1ce

Browse files
authored
Massive Performance Optimization and bug fixes (#137)
* Introduce targeted optimization for bottlenecks found via profiler * Optimized ArrayShapeValidator * Enhance RuntimeTypeChecker and ParamChecker with new configuration options and optimizations * Add /benchmark/ directory to .gitignore * Enhance type evaluation by adding trusted variable types to evaluators and static type checks to elimanate return type checking * Add fast-path handling for common scalar identifiers in ParamChecker to improve performance * Enhance RuntimeTypeChecker with additional parameter check constants and optimize validation logic * Refactor MemberAssignChecker and RuntimeTypeChecker for improved type validation and caching - Introduced new caching mechanisms in MemberAssignChecker for property mutation plans and substituted element contracts. - Enhanced type validation logic in MemberAssignChecker to utilize RuntimeTypeChecker for inline properties and array validation. - Updated RuntimeTypeChecker to support fast-path checks for generic return types and improved handling of inline properties. - Refactored TemplateManager to include compiled binding plan caches for generic types, optimizing template binding processes. - Added support for object generics in GenericValidator, ensuring proper validation of object types. - Enhanced TypeValidatorRegistry to streamline type validation logic for identifiers. - Added tests for handling PHP 8.1+ first-class callable syntax and parameter overwriting scenarios in ParameterTypeTrackingEliminationTest. * Enhance MemberAssignChecker with improved contract validation and generics performance * Refactor type substitution and resolution in TemplateSubstitutor and SpecialTypeResolver - Improved type substitution logic to avoid unnecessary object creation when types remain unchanged in TemplateSubstitutor. - Enhanced the resolveWithContext method in SpecialTypeResolver to streamline type resolution with context, reducing redundancy. - Introduced caching mechanisms in CallableWrapper to optimize callable parameter type resolution and reduce repeated parsing. - Simplified the execution of simple scope plans in RuntimeTypeChecker for better performance and readability. - Added reset functionality for CallableWrapper to clear caches effectively. * Enhance type checking and caching mechanisms in ConditionalChecker, GeneratorChecker, MemberAssignChecker, TemplateManager, RuntimeTypeChecker, and IterableWrapper for improved performance and reliability * Massively improve performance in Various internal components * Enhance type annotations across various components for improved type safety and clarity * Enhance TemplateManager with additional caching mechanisms for generic type bindings and improve property binding propagation * Enhance ContractVisitor and EliminationSafetyPolicy to support traits, improve FunctionContractInjector with elimination checks, and add property dimension assignment checks in RuntimeTypeChecker * Enhance ParamChecker and TemplateManager with improved type handling and caching mechanisms, and add ClosureParameterTemplateOverwritingTest to ensure template preservation in closures * Enhance ParamChecker, ReturnChecker, TemplateManager, RuntimeTypeChecker, and GenericValidator with improved caching mechanisms, refined template handling, and optimized validation logic for better performance and type safety * Refactor type validation logic and enhance class-string handling - Changed the visibility of `validClassStringCache` in ClassNameValidator to public for better accessibility. - Updated CollectionElementValidator to utilize RuntimeTypeChecker for hybrid validation checks instead of Config. - Added support for new types in CollectionElementValidator: 'object', 'array-key', and 'class-string' with appropriate validation logic. - Enhanced GenericValidator to include detailed array plan handling and improved validation for key-value type arrays. - Updated UnionValidator to streamline type checks and added support for mixed types, arrays, and iterables. - Improved type validation logic in TypeValidatorRegistry to include class-string checks. - Fixed test case to correctly reference TypeError class. * Enhance ContractVisitor and NodeBuilder to support class constant checks for protected and private constants, and add tests for validation and transformation of constant visibility * Refactor ParamChecker and TemplateManager by improving template binding logic and removing unused methods for cleaner code * Add tests for cross-namespace imported type alias resolution and related edge cases * Refactor CRLF line-drift test to update parameter type from non-empty-string to string for consistency * Enhance SpecialTypeResolver to support autoload parameter in type resolution methods and update CRLF line-drift test for improved readability * Refactor CollectionElementValidator and GenericValidator to streamline type validation logic and remove unused SpecialTypeResolver references * Refactor RuntimeTypeChecker to enhance type validation logic and improve cache management
1 parent 72e4979 commit bcfd1ce

48 files changed

Lines changed: 9144 additions & 1239 deletions

Some content is hidden

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

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ benchmark.php
88
.php-cs-fixer.cache
99
/app
1010
/coverage-report
11-
/coverage
11+
/coverage
12+
/benchmark/

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ final class ContractVisitor extends NodeVisitorAbstract
6464
private string $currentNamespace = '';
6565

6666
/**
67-
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool}>
67+
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool}>
6868
*/
6969
private array $classStack = [];
7070

@@ -368,14 +368,19 @@ private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, stri
368368
continue;
369369
}
370370

371-
$classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName);
372-
373-
$checkCall = NodeBuilder::createConstantCheckCall(
374-
$fullTarget,
375-
$classConstFetch,
376-
$typeString,
377-
$const->getStartLine()
378-
);
371+
$checkCall = $stmt->isPublic()
372+
? NodeBuilder::createConstantCheckCall(
373+
$fullTarget,
374+
new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName),
375+
$typeString,
376+
$const->getStartLine()
377+
)
378+
: NodeBuilder::createClassConstantCheckCall(
379+
$className,
380+
$constName,
381+
$typeString,
382+
$const->getStartLine()
383+
);
379384

380385
$checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine()));
381386
$checkStmt->setAttribute('typephp_injected', true);
@@ -904,6 +909,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
904909
$hasPropertyWithDoc = false;
905910
$isReadonly = false;
906911
$isFinal = false;
912+
$isTrait = $node instanceof Node\Stmt\Trait_;
907913

908914
$doc = $node->getDocComment();
909915
if ($doc === null && $typeName !== null && StubManager::hasClassStub($typeName)) {
@@ -975,6 +981,9 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
975981
} elseif ($node instanceof Node\Stmt\Enum_) {
976982
$hasRealInheritance = $node->implements !== [];
977983
$hasInheritance = $hasRealInheritance;
984+
} elseif ($node instanceof Node\Stmt\Trait_) {
985+
$hasRealInheritance = true;
986+
$hasInheritance = true;
978987
}
979988

980989
if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) {
@@ -1036,6 +1045,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
10361045
'isReadonly' => $isReadonly,
10371046
'isFinal' => $isFinal,
10381047
'hasTemplates' => $hasTemplates,
1048+
'isTrait' => $isTrait,
10391049
];
10401050
}
10411051

@@ -1463,6 +1473,10 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr
14631473
return null;
14641474
}
14651475

1476+
if (self::rhsNeedsParensInBinaryOp($node->expr)) {
1477+
$node->expr->setAttribute('typephp_needs_parens', true);
1478+
}
1479+
14661480
$this->markWriteContext($cleanTarget);
14671481

14681482
return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped));
@@ -1471,7 +1485,37 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr
14711485
$binaryExpr = new $binaryOpClass($node->var, $node->expr);
14721486
$wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine());
14731487

1474-
return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null;
1488+
if ($wrapped === null) {
1489+
return null;
1490+
}
1491+
1492+
if (self::rhsNeedsParensInBinaryOp($node->expr)) {
1493+
$node->expr->setAttribute('typephp_needs_parens', true);
1494+
}
1495+
1496+
return new Node\Expr\Assign($node->var, $wrapped);
1497+
}
1498+
1499+
private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool
1500+
{
1501+
return $expr instanceof Node\Expr\BinaryOp
1502+
|| $expr instanceof Node\Expr\Ternary
1503+
|| $expr instanceof Node\Expr\Assign
1504+
|| $expr instanceof Node\Expr\AssignOp
1505+
|| $expr instanceof Node\Expr\AssignRef
1506+
|| $expr instanceof Node\Expr\Instanceof_
1507+
|| $expr instanceof Node\Expr\Cast
1508+
|| $expr instanceof Node\Expr\UnaryMinus
1509+
|| $expr instanceof Node\Expr\UnaryPlus
1510+
|| $expr instanceof Node\Expr\BooleanNot
1511+
|| $expr instanceof Node\Expr\BitwiseNot
1512+
|| $expr instanceof Node\Expr\ErrorSuppress
1513+
|| $expr instanceof Node\Expr\Throw_
1514+
|| $expr instanceof Node\Expr\Yield_
1515+
|| $expr instanceof Node\Expr\YieldFrom
1516+
|| $expr instanceof Node\Expr\Print_
1517+
|| $expr instanceof Node\Expr\Include_
1518+
|| $expr instanceof Node\Expr\ArrowFunction;
14751519
}
14761520

14771521
private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr
@@ -1899,6 +1943,15 @@ private function wrapPropertyMemberAssignCheck(
18991943
array $chain,
19001944
int $line
19011945
): Node\Expr\Ternary {
1946+
if (\count($chain) === 1 && $chain[0][0] === 'dim') {
1947+
$dimExpr = $chain[0][1] instanceof Node\Expr
1948+
? $chain[0][1]
1949+
: new Node\Expr\ConstFetch(new Node\Name('null'));
1950+
$checkCall = NodeBuilder::createPropertyDimAssignCheckCall($targetExpr, $propName, $dimExpr, $valueExpr);
1951+
1952+
return NodeBuilder::createTernaryThrowExpr($checkCall, $line);
1953+
}
1954+
19021955
$chainAst = $this->buildChainAst($chain);
19031956
$checkCall = NodeBuilder::createPropertyMemberAssignCheckCall($targetExpr, $propName, $chainAst, $valueExpr);
19041957

‎src/Internal/Ast/Elimination/EliminationSafetyPolicy.php‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ final class EliminationSafetyPolicy
6161
* and scalar generics (int<min, max>, int-mask) which carry no object state.
6262
* 3. Authorizes standalone functions, closures, and arrow functions (zero inheritance risk).
6363
* 4. For class methods:
64-
* - Authorizes private methods (cannot override or be overridden).
64+
* - Authorizes private methods, final methods, and methods on final classes.
6565
* - Authorizes classes with no inheritance (`hasRealInheritance === false`).
6666
* 5. Defers all other methods to runtime to prevent bypassing unanalyzed parent contracts.
6767
*
@@ -91,6 +91,10 @@ public static function isReturnEliminationSafe(
9191
return true;
9292
}
9393

94+
if ($classContext['isTrait'] ?? false) {
95+
return false;
96+
}
97+
9498
$hasRealInheritance = $classContext['hasRealInheritance'] ?? true;
9599
if (! $hasRealInheritance) {
96100
return true;
@@ -139,6 +143,10 @@ public static function isGeneratorEliminationSafe(
139143
return true;
140144
}
141145

146+
if ($classContext['isTrait'] ?? false) {
147+
return false;
148+
}
149+
142150
$hasRealInheritance = $classContext['hasRealInheritance'] ?? true;
143151
if (! $hasRealInheritance) {
144152
return true;

‎src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php‎

Lines changed: 53 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,14 @@ final class ArrayLiteralEvaluator
5252
/**
5353
* Determines whether an AST array expression satisfies a target type contract.
5454
*
55-
* Flow of logic:
56-
* 1. Empty arrays ([]) are checked against types that permit empty collections.
57-
* 2. Bare array/iterable identifiers (array, iterable, list) are evaluated.
58-
* 3. Sequential lists (list<T>, non-empty-list<T>, T[]) verify keys are 0..n-1 and all values satisfy T.
59-
* 4. Typed key-value maps (array<K, V>) verify all keys satisfy K and all values satisfy V.
60-
* 5. Array shapes (array{id: int, ...}) verify required keys, unexpected keys, and field types.
55+
* @param array<string, TypeNode> $trustedVariableTypes
6156
*/
62-
public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $currentFile = ''): bool
63-
{
57+
public static function satisfies(
58+
Array_ $arrayExpr,
59+
TypeNode $typeNode,
60+
string $currentFile = '',
61+
array $trustedVariableTypes = []
62+
): bool {
6463
$count = \count($arrayExpr->items);
6564

6665
if ($count === 0) {
@@ -72,24 +71,22 @@ public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $
7271
}
7372

7473
if ($typeNode instanceof ArrayTypeNode) {
75-
return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile);
74+
return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile, $trustedVariableTypes);
7675
}
7776

7877
if ($typeNode instanceof GenericTypeNode) {
79-
return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile);
78+
return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes);
8079
}
8180

8281
if ($typeNode instanceof ArrayShapeNode) {
83-
return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile);
82+
return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes);
8483
}
8584

8685
return false;
8786
}
8887

8988
/**
9089
* Checks if a type contract permits an empty array ([]).
91-
* Returns true for unbounded array/list/iterable, T[], and shapes with only optional keys.
92-
* Returns false for non-empty-array, non-empty-list, and shapes with required keys.
9390
*/
9491
public static function satisfiesEmptyArray(TypeNode $typeNode): bool
9592
{
@@ -135,48 +132,54 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy
135132
}
136133

137134
/**
138-
* Evaluates an array expression against generic array containers:
139-
* - Single template argument: list<T>, non-empty-list<T>, array<T>
140-
* - Double template argument: array<K, V>, non-empty-array<K, V>
135+
* @param array<string, TypeNode> $trustedVariableTypes
141136
*/
142-
private static function satisfiesGenericArray(Array_ $arrayExpr, GenericTypeNode $node, string $currentFile): bool
143-
{
137+
private static function satisfiesGenericArray(
138+
Array_ $arrayExpr,
139+
GenericTypeNode $node,
140+
string $currentFile,
141+
array $trustedVariableTypes = []
142+
): bool {
144143
$base = strtolower((string) $node->type);
145144
$genericCount = \count($node->genericTypes);
146145

147146
if ($base === 'list' && $genericCount >= 1) {
148-
return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile);
147+
return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes);
149148
}
150149

151150
if ($base === 'non-empty-list' && $genericCount >= 1) {
152-
return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile);
151+
return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes);
153152
}
154153

155154
if (($base === 'array' || $base === 'iterable') && $genericCount === 1) {
156-
return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile);
155+
return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes);
157156
}
158157

159158
if (($base === 'array' || $base === 'iterable') && $genericCount >= 2) {
160-
return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile);
159+
return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile, $trustedVariableTypes);
161160
}
162161

163162
if ($base === 'non-empty-array' && $genericCount === 1) {
164-
return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile);
163+
return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes);
165164
}
166165

167166
if ($base === 'non-empty-array' && $genericCount >= 2) {
168-
return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile);
167+
return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile, $trustedVariableTypes);
169168
}
170169

171170
return false;
172171
}
173172

174173
/**
175-
* Verifies that all array items have sequential integer keys (0..n-1)
176-
* and every item value statically satisfies the element contract T.
174+
* @param array<string, TypeNode> $trustedVariableTypes
177175
*/
178-
private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, bool $requireNonEmpty, string $currentFile): bool
179-
{
176+
private static function satisfiesList(
177+
Array_ $arrayExpr,
178+
TypeNode $itemType,
179+
bool $requireNonEmpty,
180+
string $currentFile,
181+
array $trustedVariableTypes = []
182+
): bool {
180183
$count = \count($arrayExpr->items);
181184
if ($requireNonEmpty && $count === 0) {
182185
return false;
@@ -195,7 +198,7 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo
195198
}
196199
$expectedIdx++;
197200

198-
if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile)) {
201+
if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile, $trustedVariableTypes)) {
199202
return false;
200203
}
201204
}
@@ -204,11 +207,16 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo
204207
}
205208

206209
/**
207-
* Verifies that every key in the array expression satisfies key contract K
208-
* and every corresponding value satisfies value contract V.
210+
* @param array<string, TypeNode> $trustedVariableTypes
209211
*/
210-
private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyType, TypeNode $valueType, bool $requireNonEmpty, string $currentFile): bool
211-
{
212+
private static function satisfiesKeyValueArray(
213+
Array_ $arrayExpr,
214+
TypeNode $keyType,
215+
TypeNode $valueType,
216+
bool $requireNonEmpty,
217+
string $currentFile,
218+
array $trustedVariableTypes = []
219+
): bool {
212220
$count = \count($arrayExpr->items);
213221
if ($requireNonEmpty && $count === 0) {
214222
return false;
@@ -232,11 +240,11 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT
232240
return false;
233241
}
234242

235-
if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile)) {
243+
if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile, $trustedVariableTypes)) {
236244
return false;
237245
}
238246

239-
if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile)) {
247+
if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes)) {
240248
return false;
241249
}
242250
}
@@ -245,12 +253,14 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT
245253
}
246254

247255
/**
248-
* Evaluates an array expression against a sealed or unsealed ArrayShapeNode.
249-
* Guarantees all required keys exist, no unsealed keys intrude in sealed shapes,
250-
* and all value expressions satisfy their corresponding shape property contracts.
256+
* @param array<string, TypeNode> $trustedVariableTypes
251257
*/
252-
private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $shapeNode, string $currentFile): bool
253-
{
258+
private static function satisfiesArrayShape(
259+
Array_ $arrayExpr,
260+
ArrayShapeNode $shapeNode,
261+
string $currentFile,
262+
array $trustedVariableTypes = []
263+
): bool {
254264
if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && ! self::isSequentialList($arrayExpr)) {
255265
return false;
256266
}
@@ -304,7 +314,7 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s
304314
continue;
305315
}
306316

307-
if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile)) {
317+
if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile, $trustedVariableTypes)) {
308318
return false;
309319
}
310320
}
@@ -321,12 +331,12 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s
321331
if ($shapeNode->unsealedType !== null) {
322332
if ($shapeNode->unsealedType->keyType !== null) {
323333
$keyExpr = \is_int($actualKey) ? new LNumber($actualKey) : new String_($actualKey);
324-
if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile)) {
334+
if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile, $trustedVariableTypes)) {
325335
return false;
326336
}
327337
}
328338

329-
if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile)) {
339+
if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile, $trustedVariableTypes)) {
330340
return false;
331341
}
332342
}

0 commit comments

Comments
 (0)