Skip to content

Commit b577986

Browse files
authored
Major bug fixes and performance optimizations (#140)
* Fix discovered edge cases during routine manual qa testing * Refactor template binding retrieval to use getConcreteInstanceBindings method across InlineChecker, ParamChecker, and ReturnChecker; add InheritedTemplateBoundFallbackTest for enhanced type checking * Enhance type checking for key-of and value-of generics; add comprehensive tests for template bounds and validation * Refactor ContractVisitor and FunctionContractInjector to improve inline variable handling; add ReturnVarDoubleWrappingTest for comprehensive coverage * Enhance exception safety in StreamWrapper; add tests to ensure wrapper remains registered during error handling * Refactor import handling in ContractVisitor and StreamWrapper; enhance SpecialTypeResolver to isolate non-class use imports and add comprehensive tests for import collision scenarios * Refactor Config class to improve environment variable handling; add tests for RuntimeTypeChecker synchronization with TYPEPHP_DISABLE and TYPEPHP_ENABLED * Add reset method to ObjectShapeValidator and invoke it in TypeValidatorRegistry reset * Refactor RuntimeTypeChecker to replace MemberAssignChecker constants with class-specific constants for improved performance * Enhance internal documentation for type checkers and template manager; detail performance optimizations and architectural considerations * Fix formatting in RuntimeTypeChecker docblock; remove unnecessary whitespace * Enhance ContractVisitor and ScopeManager for improved type handling; add property alias management and update inferred types registration * Refactor test descriptions to remove "Red Phase" terminology for clarity * Fix 8.1 compatibility on failing ci * Fix formatting in DocblockNormalizerTest to improve readability
1 parent a0a3d9b commit b577986

56 files changed

Lines changed: 4898 additions & 430 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.

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ TypePHP stands on the shoulders of giants. It simply would not exist without the
313313
* **[Blackfire](https://www.blackfire.io/)**:
314314
A huge thank you to **Blackfire** for generously providing a **free 1-year open-source subscription** for TypePHP. Blackfire's deterministic call-graph and memory profiling made it possible to hunt down hot-path bottlenecks and achieve up to an **11× speedup** on generics-heavy workloads.
315315
* **[`php-spx`](https://github.com/NoiseByNorthwest/php-spx)**:
316-
Many thanks to the `php-spx` PHP profiling extension—its lightweight flamegraphs, flat execution profiles, and built-in web UI were instrumental in pinpointing tight-loop overhead and tuning TypePHP's runtime engine.
316+
Many thanks to the `php-spx` PHP profiling extension and its lightweight flamegraphs, flat execution profiles, and built-in web UI were instrumental in pinpointing tight-loop overhead and tuning TypePHP's runtime engine.
317317

318318
---
319319

‎composer.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@
6060
]
6161
},
6262
"scripts": {
63+
"qa": [
64+
"./vendor/bin/pint --parallel",
65+
"./vendor/bin/phpstan analyze",
66+
"./vendor/bin/pest --compact"
67+
],
6368
"format": [
6469
"./vendor/bin/pint"
6570
],

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 243 additions & 31 deletions
Large diffs are not rendered by default.

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,13 @@ 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, final methods, and methods on final classes.
65-
* - Authorizes classes with no inheritance (`hasRealInheritance === false`).
66-
* 5. Defers all other methods to runtime to prevent bypassing unanalyzed parent contracts.
64+
* - Authorizes private methods.
65+
* - Rejects trait methods (`isTrait === true`) since traits may be composed into inheriting classes.
66+
* - Authorizes classes with no real inheritance (`hasRealInheritance === false`).
67+
* 5. Defers all other methods (including final methods/classes with inheritance) to runtime
68+
* to prevent bypassing unanalyzed parent or interface contracts.
6769
*
68-
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
70+
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext
6971
*/
7072
public static function isReturnEliminationSafe(
7173
ClassMethod|Function_|Closure|ArrowFunction $functionNode,
@@ -106,7 +108,7 @@ public static function isReturnEliminationSafe(
106108
/**
107109
* Determines whether generator yield, send, and return checks can be safely eliminated under LSP rules.
108110
*
109-
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
111+
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext
110112
*/
111113
public static function isGeneratorEliminationSafe(
112114
ClassMethod|Function_|Closure|ArrowFunction $functionNode,

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 141 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,15 @@
2222
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
2323
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
2424
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
25+
use PHPStan\PhpDocParser\Parser\TokenIterator;
2526
use TypePHP\Internal\Ast\Elimination\EliminationSafetyPolicy;
2627
use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator;
2728
use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator;
2829
use TypePHP\Internal\Checker\ConditionalChecker;
2930
use TypePHP\Internal\Docblock\DocblockExtractor;
31+
use TypePHP\Internal\Docblock\DocblockNormalizer;
3032
use TypePHP\Internal\Docblock\DocblockParser;
33+
use TypePHP\Internal\Generics\TemplateManager;
3134
use TypePHP\Internal\Resolver\SpecialTypeResolver;
3235
use TypePHP\Internal\Util\Config;
3336
use TypePHP\Internal\Util\StubManager;
@@ -260,7 +263,8 @@ public static function inject(
260263
$hasParam,
261264
$trustedParamTypes,
262265
$useDynamicMethodKey,
263-
$currentNamespace
266+
$currentNamespace,
267+
$effectiveAliases
264268
)
265269
: self::wrapNonGeneratorReturns(
266270
$node->stmts,
@@ -278,7 +282,8 @@ public static function inject(
278282
$trustedParamTypes,
279283
$useDynamicMethodKey,
280284
! $isMagicGet && ! $isMagicCall,
281-
$currentNamespace
285+
$currentNamespace,
286+
$effectiveAliases
282287
);
283288
}
284289

@@ -444,7 +449,11 @@ private static function collectTrustedParamTypes(
444449
return [];
445450
}
446451

447-
if (Config::getOnViolation() !== 'throw' || ! Config::isParamsEnabled()) {
452+
if (
453+
! Config::isEliminateStaticallyProvenChecksEnabled()
454+
|| Config::getOnViolation() !== 'throw'
455+
|| ! Config::isParamsEnabled()
456+
) {
448457
return [];
449458
}
450459

@@ -620,6 +629,22 @@ public function enterNode(Node $node): ?int
620629
}
621630
}
622631
} elseif ($node instanceof Node\Expr\CallLike) {
632+
if (
633+
$node instanceof Node\Expr\FuncCall
634+
&& $node->name instanceof Node\Name
635+
&& str_starts_with(ltrim($node->name->toString(), '\\'), 'TypePHP\\Internal\\RuntimeTypeChecker::')
636+
) {
637+
return null;
638+
}
639+
640+
if (
641+
$node instanceof Node\Expr\StaticCall
642+
&& $node->class instanceof Node\Name
643+
&& ltrim($node->class->toString(), '\\') === 'TypePHP\\Internal\\RuntimeTypeChecker'
644+
) {
645+
return null;
646+
}
647+
623648
if (
624649
$node instanceof Node\Expr\FuncCall
625650
&& $node->name instanceof Node\Name
@@ -1668,11 +1693,79 @@ public static function buildWrappedYieldNode(
16681693
);
16691694
}
16701695

1696+
/**
1697+
* Determines whether a Return_ node already wrapped by ContractVisitor::handleReturn()
1698+
* safely subsumes the enclosing function/generator return contract.
1699+
*
1700+
* @param array<string, TypeNode> $effectiveAliases
1701+
*/
1702+
public static function inlineVarSubsumesReturn(
1703+
Node\Stmt\Return_ $returnNode,
1704+
?TypeNode $targetReturnType,
1705+
bool $isEliminationSafe,
1706+
array $effectiveAliases = [],
1707+
string $currentFile = '',
1708+
?string $currentNamespace = null
1709+
): bool {
1710+
if ($returnNode->getAttribute('typephp_var_wrapped') !== true) {
1711+
return false;
1712+
}
1713+
1714+
$varTypeString = $returnNode->getAttribute('typephp_var_type');
1715+
if (! \is_string($varTypeString) || $varTypeString === '') {
1716+
return true;
1717+
}
1718+
1719+
if (
1720+
! $isEliminationSafe
1721+
|| $targetReturnType === null
1722+
|| ! Config::isInlineScalarsEnabled()
1723+
|| ! Config::isInlineArraysEnabled()
1724+
|| ! Config::isInlineObjectsEnabled()
1725+
|| ! Config::isInlineGenericsEnabled()
1726+
|| ! Config::isInlineCallablesEnabled()
1727+
) {
1728+
return false;
1729+
}
1730+
1731+
try {
1732+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
1733+
$tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($varTypeString)));
1734+
$varTypeNode = $typeParser->parse($tokens);
1735+
1736+
if ($effectiveAliases !== []) {
1737+
$varTypeNode = DocblockParser::substituteAliases($varTypeNode, $effectiveAliases);
1738+
}
1739+
1740+
if ($currentFile !== '') {
1741+
$varTypeNode = SpecialTypeResolver::resolveForFile($varTypeNode, $currentFile, $currentNamespace, false);
1742+
$targetReturnType = SpecialTypeResolver::resolveForFile($targetReturnType, $currentFile, $currentNamespace, false);
1743+
}
1744+
1745+
if ($varTypeNode instanceof NullableTypeNode) {
1746+
$varTypeNode = new UnionTypeNode([$varTypeNode->type, new IdentifierTypeNode('null')]);
1747+
}
1748+
1749+
if ($targetReturnType instanceof NullableTypeNode) {
1750+
$targetReturnType = new UnionTypeNode([$targetReturnType->type, new IdentifierTypeNode('null')]);
1751+
}
1752+
1753+
return TemplateManager::checkVariance(
1754+
$varTypeNode,
1755+
$targetReturnType,
1756+
GenericTypeNode::VARIANCE_COVARIANT
1757+
);
1758+
} catch (\Throwable) {
1759+
return false;
1760+
}
1761+
}
1762+
16711763
/**
16721764
* @param array<Node\Stmt> $stmts
16731765
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
16741766
* @param array<string> $byRefParams
16751767
* @param array<string, TypeNode> $trustedParamTypes
1768+
* @param array<string, TypeNode> $effectiveAliases
16761769
*
16771770
* @return array<Node\Stmt>
16781771
*/
@@ -1690,7 +1783,8 @@ private static function wrapGeneratorReturns(
16901783
bool $hasScope = false,
16911784
array $trustedParamTypes = [],
16921785
bool $useDynamicMethodKey = false,
1693-
?string $currentNamespace = null
1786+
?string $currentNamespace = null,
1787+
array $effectiveAliases = []
16941788
): array {
16951789
$canEliminate = $functionNode !== null
16961790
&& ! $hasMethodTemplates
@@ -1720,13 +1814,15 @@ private static function wrapGeneratorReturns(
17201814
$hasSelfOut,
17211815
$trustedParamTypes,
17221816
$useDynamicMethodKey,
1723-
$currentNamespace
1817+
$currentNamespace,
1818+
$effectiveAliases
17241819
) extends NodeVisitorAbstract {
17251820
/**
17261821
* @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract
17271822
* @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $explicitGenContract
17281823
* @param array<string> $byRefParams
17291824
* @param array<string, TypeNode> $trustedParamTypes
1825+
* @param array<string, TypeNode> $effectiveAliases
17301826
*/
17311827
public function __construct(
17321828
private Node\Expr $thisArg,
@@ -1738,7 +1834,8 @@ public function __construct(
17381834
private bool $hasSelfOut,
17391835
private array $trustedParamTypes,
17401836
private bool $useDynamicMethodKey,
1741-
private ?string $currentNamespace
1837+
private ?string $currentNamespace,
1838+
private array $effectiveAliases
17421839
) {
17431840
}
17441841

@@ -1847,7 +1944,7 @@ public function enterNode(Node $n): int|Node|array|null
18471944
}
18481945

18491946
if ($n instanceof Node\Stmt\Return_) {
1850-
if ($n->getAttribute('typephp_var_wrapped') === true || $n->getAttribute('typephp_generator_return_wrapped') === true) {
1947+
if ($n->getAttribute('typephp_generator_return_wrapped') === true) {
18511948
return null;
18521949
}
18531950
$n->setAttribute('typephp_generator_return_wrapped', true);
@@ -1865,6 +1962,17 @@ public function enterNode(Node $n): int|Node|array|null
18651962
$exitStmts = [...$exitStmts, ...$paramOutStmts];
18661963
}
18671964

1965+
if (FunctionContractInjector::inlineVarSubsumesReturn(
1966+
$n,
1967+
$this->genContract['return'] ?? null,
1968+
$this->genContract !== null,
1969+
$this->effectiveAliases,
1970+
$this->currentFile,
1971+
$this->currentNamespace
1972+
)) {
1973+
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
1974+
}
1975+
18681976
$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));
18691977
$assignedExpr = $n->getAttribute('typephp_preceding_assign_expr');
18701978
$candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap;
@@ -1967,6 +2075,7 @@ public function enterNode(Node $n): int|Node|array|null
19672075
* @param array<string> $byRefParams
19682076
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
19692077
* @param array<string, TypeNode> $trustedParamTypes
2078+
* @param array<string, TypeNode> $effectiveAliases
19702079
*
19712080
* @return array<Node\Stmt>
19722081
*/
@@ -1986,7 +2095,8 @@ private static function wrapNonGeneratorReturns(
19862095
array $trustedParamTypes = [],
19872096
bool $useDynamicMethodKey = false,
19882097
bool $canGuardReturnCache = true,
1989-
?string $currentNamespace = null
2098+
?string $currentNamespace = null,
2099+
array $effectiveAliases = []
19902100
): array {
19912101
self::tagPrecedingAssignments($stmts);
19922102

@@ -2006,12 +2116,14 @@ private static function wrapNonGeneratorReturns(
20062116
$trustedParamTypes,
20072117
$useDynamicMethodKey,
20082118
$canGuardReturnCache,
2009-
$currentNamespace
2119+
$currentNamespace,
2120+
$effectiveAliases
20102121
) extends NodeVisitorAbstract {
20112122
/**
20122123
* @param array<string> $byRefParams
20132124
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
20142125
* @param array<string, TypeNode> $trustedParamTypes
2126+
* @param array<string, TypeNode> $effectiveAliases
20152127
*/
20162128
public function __construct(
20172129
private Node\Expr $thisArg,
@@ -2028,7 +2140,8 @@ public function __construct(
20282140
private array $trustedParamTypes,
20292141
private bool $useDynamicMethodKey,
20302142
private bool $canGuardReturnCache,
2031-
private ?string $currentNamespace
2143+
private ?string $currentNamespace,
2144+
private array $effectiveAliases
20322145
) {
20332146
}
20342147

@@ -2058,10 +2171,6 @@ public function enterNode(Node $n): int|array|null
20582171
}
20592172

20602173
if ($n instanceof Node\Stmt\Return_) {
2061-
if ($n->getAttribute('typephp_var_wrapped') === true) {
2062-
return null;
2063-
}
2064-
20652174
$exitStmts = [];
20662175
if ($this->hasSelfOut) {
20672176
$exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars, $this->useDynamicMethodKey);
@@ -2079,17 +2188,30 @@ public function enterNode(Node $n): int|array|null
20792188
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
20802189
}
20812190

2191+
$isReturnElimSafe = ! $this->isByRefReturn
2192+
&& ! $this->isNativeVoid
2193+
&& $this->functionNode !== null
2194+
&& $this->returnTypeNode !== null
2195+
&& EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode);
2196+
2197+
if (FunctionContractInjector::inlineVarSubsumesReturn(
2198+
$n,
2199+
$this->returnTypeNode,
2200+
$isReturnElimSafe,
2201+
$this->effectiveAliases,
2202+
$this->currentFile,
2203+
$this->currentNamespace
2204+
)) {
2205+
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
2206+
}
2207+
20822208
$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));
20832209

20842210
$assignedExpr = $n->getAttribute('typephp_preceding_assign_expr');
20852211
$candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap;
20862212

20872213
if (
2088-
! $this->isByRefReturn
2089-
&& ! $this->isNativeVoid
2090-
&& $this->functionNode !== null
2091-
&& $this->returnTypeNode !== null
2092-
&& EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode)
2214+
$isReturnElimSafe
20932215
&& StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace)
20942216
) {
20952217
return $exitStmts !== [] ? [...$exitStmts, $n] : null;

0 commit comments

Comments
 (0)