Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
05bb6e1
Fix discovered edge cases during routine manual qa testing
rcalicdan Nov 25, 2026
8bdc419
Refactor template binding retrieval to use getConcreteInstanceBinding…
rcalicdan Nov 25, 2026
f209bff
Enhance type checking for key-of and value-of generics; add comprehen…
rcalicdan Nov 25, 2026
3e53cb5
Refactor ContractVisitor and FunctionContractInjector to improve inli…
rcalicdan Nov 25, 2026
1ea0f4e
Enhance exception safety in StreamWrapper; add tests to ensure wrappe…
rcalicdan Nov 25, 2026
5dcc26f
Refactor import handling in ContractVisitor and StreamWrapper; enhanc…
rcalicdan Nov 25, 2026
804a22a
Refactor Config class to improve environment variable handling; add t…
rcalicdan Nov 25, 2026
7c183af
Add reset method to ObjectShapeValidator and invoke it in TypeValidat…
rcalicdan Nov 25, 2026
2bd18c5
Refactor RuntimeTypeChecker to replace MemberAssignChecker constants …
rcalicdan Nov 25, 2026
9aeaee7
Enhance internal documentation for type checkers and template manager…
rcalicdan Nov 25, 2026
5d0fa1c
Fix formatting in RuntimeTypeChecker docblock; remove unnecessary whi…
rcalicdan Nov 25, 2026
45d4601
Enhance ContractVisitor and ScopeManager for improved type handling; …
rcalicdan Nov 25, 2026
68014bb
Refactor test descriptions to remove "Red Phase" terminology for clarity
rcalicdan Nov 25, 2026
4e216ed
Fix 8.1 compatibility on failing ci
rcalicdan Nov 25, 2026
f6605ee
Fix formatting in DocblockNormalizerTest to improve readability
rcalicdan Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ TypePHP stands on the shoulders of giants. It simply would not exist without the
* **[Blackfire](https://www.blackfire.io/)**:
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.
* **[`php-spx`](https://github.com/NoiseByNorthwest/php-spx)**:
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.
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.

---

Expand Down
5 changes: 5 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@
]
},
"scripts": {
"qa": [
"./vendor/bin/pint --parallel",
"./vendor/bin/phpstan analyze",
"./vendor/bin/pest --compact"
],
"format": [
"./vendor/bin/pint"
],
Expand Down
274 changes: 243 additions & 31 deletions src/Internal/Ast/ContractVisitor.php

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions src/Internal/Ast/Elimination/EliminationSafetyPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,13 @@ final class EliminationSafetyPolicy
* and scalar generics (int<min, max>, int-mask) which carry no object state.
* 3. Authorizes standalone functions, closures, and arrow functions (zero inheritance risk).
* 4. For class methods:
* - Authorizes private methods, final methods, and methods on final classes.
* - Authorizes classes with no inheritance (`hasRealInheritance === false`).
* 5. Defers all other methods to runtime to prevent bypassing unanalyzed parent contracts.
* - Authorizes private methods.
* - Rejects trait methods (`isTrait === true`) since traits may be composed into inheriting classes.
* - Authorizes classes with no real inheritance (`hasRealInheritance === false`).
* 5. Defers all other methods (including final methods/classes with inheritance) to runtime
* to prevent bypassing unanalyzed parent or interface contracts.
*
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext
*/
public static function isReturnEliminationSafe(
ClassMethod|Function_|Closure|ArrowFunction $functionNode,
Expand Down Expand Up @@ -106,7 +108,7 @@ public static function isReturnEliminationSafe(
/**
* Determines whether generator yield, send, and return checks can be safely eliminated under LSP rules.
*
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext
*/
public static function isGeneratorEliminationSafe(
ClassMethod|Function_|Closure|ArrowFunction $functionNode,
Expand Down
160 changes: 141 additions & 19 deletions src/Internal/Ast/FunctionContractInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use TypePHP\Internal\Ast\Elimination\EliminationSafetyPolicy;
use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator;
use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator;
use TypePHP\Internal\Checker\ConditionalChecker;
use TypePHP\Internal\Docblock\DocblockExtractor;
use TypePHP\Internal\Docblock\DocblockNormalizer;
use TypePHP\Internal\Docblock\DocblockParser;
use TypePHP\Internal\Generics\TemplateManager;
use TypePHP\Internal\Resolver\SpecialTypeResolver;
use TypePHP\Internal\Util\Config;
use TypePHP\Internal\Util\StubManager;
Expand Down Expand Up @@ -260,7 +263,8 @@ public static function inject(
$hasParam,
$trustedParamTypes,
$useDynamicMethodKey,
$currentNamespace
$currentNamespace,
$effectiveAliases
)
: self::wrapNonGeneratorReturns(
$node->stmts,
Expand All @@ -278,7 +282,8 @@ public static function inject(
$trustedParamTypes,
$useDynamicMethodKey,
! $isMagicGet && ! $isMagicCall,
$currentNamespace
$currentNamespace,
$effectiveAliases
);
}

Expand Down Expand Up @@ -444,7 +449,11 @@ private static function collectTrustedParamTypes(
return [];
}

if (Config::getOnViolation() !== 'throw' || ! Config::isParamsEnabled()) {
if (
! Config::isEliminateStaticallyProvenChecksEnabled()
|| Config::getOnViolation() !== 'throw'
|| ! Config::isParamsEnabled()
) {
return [];
}

Expand Down Expand Up @@ -620,6 +629,22 @@ public function enterNode(Node $node): ?int
}
}
} elseif ($node instanceof Node\Expr\CallLike) {
if (
$node instanceof Node\Expr\FuncCall
&& $node->name instanceof Node\Name
&& str_starts_with(ltrim($node->name->toString(), '\\'), 'TypePHP\\Internal\\RuntimeTypeChecker::')
) {
return null;
}

if (
$node instanceof Node\Expr\StaticCall
&& $node->class instanceof Node\Name
&& ltrim($node->class->toString(), '\\') === 'TypePHP\\Internal\\RuntimeTypeChecker'
) {
return null;
}

if (
$node instanceof Node\Expr\FuncCall
&& $node->name instanceof Node\Name
Expand Down Expand Up @@ -1668,11 +1693,79 @@ public static function buildWrappedYieldNode(
);
}

/**
* Determines whether a Return_ node already wrapped by ContractVisitor::handleReturn()
* safely subsumes the enclosing function/generator return contract.
*
* @param array<string, TypeNode> $effectiveAliases
*/
public static function inlineVarSubsumesReturn(
Node\Stmt\Return_ $returnNode,
?TypeNode $targetReturnType,
bool $isEliminationSafe,
array $effectiveAliases = [],
string $currentFile = '',
?string $currentNamespace = null
): bool {
if ($returnNode->getAttribute('typephp_var_wrapped') !== true) {
return false;
}

$varTypeString = $returnNode->getAttribute('typephp_var_type');
if (! \is_string($varTypeString) || $varTypeString === '') {
return true;
}

if (
! $isEliminationSafe
|| $targetReturnType === null
|| ! Config::isInlineScalarsEnabled()
|| ! Config::isInlineArraysEnabled()
|| ! Config::isInlineObjectsEnabled()
|| ! Config::isInlineGenericsEnabled()
|| ! Config::isInlineCallablesEnabled()
) {
return false;
}

try {
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
$tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($varTypeString)));
$varTypeNode = $typeParser->parse($tokens);

if ($effectiveAliases !== []) {
$varTypeNode = DocblockParser::substituteAliases($varTypeNode, $effectiveAliases);
}

if ($currentFile !== '') {
$varTypeNode = SpecialTypeResolver::resolveForFile($varTypeNode, $currentFile, $currentNamespace, false);
$targetReturnType = SpecialTypeResolver::resolveForFile($targetReturnType, $currentFile, $currentNamespace, false);
}

if ($varTypeNode instanceof NullableTypeNode) {
$varTypeNode = new UnionTypeNode([$varTypeNode->type, new IdentifierTypeNode('null')]);
}

if ($targetReturnType instanceof NullableTypeNode) {
$targetReturnType = new UnionTypeNode([$targetReturnType->type, new IdentifierTypeNode('null')]);
}

return TemplateManager::checkVariance(
$varTypeNode,
$targetReturnType,
GenericTypeNode::VARIANCE_COVARIANT
);
} catch (\Throwable) {
return false;
}
}

/**
* @param array<Node\Stmt> $stmts
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
* @param array<string> $byRefParams
* @param array<string, TypeNode> $trustedParamTypes
* @param array<string, TypeNode> $effectiveAliases
*
* @return array<Node\Stmt>
*/
Expand All @@ -1690,7 +1783,8 @@ private static function wrapGeneratorReturns(
bool $hasScope = false,
array $trustedParamTypes = [],
bool $useDynamicMethodKey = false,
?string $currentNamespace = null
?string $currentNamespace = null,
array $effectiveAliases = []
): array {
$canEliminate = $functionNode !== null
&& ! $hasMethodTemplates
Expand Down Expand Up @@ -1720,13 +1814,15 @@ private static function wrapGeneratorReturns(
$hasSelfOut,
$trustedParamTypes,
$useDynamicMethodKey,
$currentNamespace
$currentNamespace,
$effectiveAliases
) extends NodeVisitorAbstract {
/**
* @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract
* @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $explicitGenContract
* @param array<string> $byRefParams
* @param array<string, TypeNode> $trustedParamTypes
* @param array<string, TypeNode> $effectiveAliases
*/
public function __construct(
private Node\Expr $thisArg,
Expand All @@ -1738,7 +1834,8 @@ public function __construct(
private bool $hasSelfOut,
private array $trustedParamTypes,
private bool $useDynamicMethodKey,
private ?string $currentNamespace
private ?string $currentNamespace,
private array $effectiveAliases
) {
}

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

if ($n instanceof Node\Stmt\Return_) {
if ($n->getAttribute('typephp_var_wrapped') === true || $n->getAttribute('typephp_generator_return_wrapped') === true) {
if ($n->getAttribute('typephp_generator_return_wrapped') === true) {
return null;
}
$n->setAttribute('typephp_generator_return_wrapped', true);
Expand All @@ -1865,6 +1962,17 @@ public function enterNode(Node $n): int|Node|array|null
$exitStmts = [...$exitStmts, ...$paramOutStmts];
}

if (FunctionContractInjector::inlineVarSubsumesReturn(
$n,
$this->genContract['return'] ?? null,
$this->genContract !== null,
$this->effectiveAliases,
$this->currentFile,
$this->currentNamespace
)) {
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
}

$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));
$assignedExpr = $n->getAttribute('typephp_preceding_assign_expr');
$candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap;
Expand Down Expand Up @@ -1967,6 +2075,7 @@ public function enterNode(Node $n): int|Node|array|null
* @param array<string> $byRefParams
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
* @param array<string, TypeNode> $trustedParamTypes
* @param array<string, TypeNode> $effectiveAliases
*
* @return array<Node\Stmt>
*/
Expand All @@ -1986,7 +2095,8 @@ private static function wrapNonGeneratorReturns(
array $trustedParamTypes = [],
bool $useDynamicMethodKey = false,
bool $canGuardReturnCache = true,
?string $currentNamespace = null
?string $currentNamespace = null,
array $effectiveAliases = []
): array {
self::tagPrecedingAssignments($stmts);

Expand All @@ -2006,12 +2116,14 @@ private static function wrapNonGeneratorReturns(
$trustedParamTypes,
$useDynamicMethodKey,
$canGuardReturnCache,
$currentNamespace
$currentNamespace,
$effectiveAliases
) extends NodeVisitorAbstract {
/**
* @param array<string> $byRefParams
* @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext
* @param array<string, TypeNode> $trustedParamTypes
* @param array<string, TypeNode> $effectiveAliases
*/
public function __construct(
private Node\Expr $thisArg,
Expand All @@ -2028,7 +2140,8 @@ public function __construct(
private array $trustedParamTypes,
private bool $useDynamicMethodKey,
private bool $canGuardReturnCache,
private ?string $currentNamespace
private ?string $currentNamespace,
private array $effectiveAliases
) {
}

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

if ($n instanceof Node\Stmt\Return_) {
if ($n->getAttribute('typephp_var_wrapped') === true) {
return null;
}

$exitStmts = [];
if ($this->hasSelfOut) {
$exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars, $this->useDynamicMethodKey);
Expand All @@ -2079,17 +2188,30 @@ public function enterNode(Node $n): int|array|null
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
}

$isReturnElimSafe = ! $this->isByRefReturn
&& ! $this->isNativeVoid
&& $this->functionNode !== null
&& $this->returnTypeNode !== null
&& EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode);

if (FunctionContractInjector::inlineVarSubsumesReturn(
$n,
$this->returnTypeNode,
$isReturnElimSafe,
$this->effectiveAliases,
$this->currentFile,
$this->currentNamespace
)) {
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
}

$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));

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

if (
! $this->isByRefReturn
&& ! $this->isNativeVoid
&& $this->functionNode !== null
&& $this->returnTypeNode !== null
&& EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode)
$isReturnElimSafe
&& StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace)
) {
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
Expand Down
Loading
Loading