Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ All the documentation lives on the **[typephp.dev](https://typephp.dev/)** websi
TypePHP stands on the shoulders of giants. It simply would not exist without two foundational cornerstones of the PHP ecosystem:

* **[PHPStan](https://phpstan.org/) & [`phpstan/phpdoc-parser`](https://github.com/phpstan/phpdoc-parser)** (created by [Ondřej Mirtes](https://github.com/ondrejmirtes) and contributors):
A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory—including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance—directly at runtime.
A massive and sincere debt of gratitude is owed to the PHPStan team. Beyond establishing the modern type standard in PHP, `phpstan/phpdoc-parser` is the parsing powerhouse behind TypePHP. It enables TypePHP to tokenize, parse, and evaluate complex type theory and including reified generics (`@template`), conditional types, intersection/union types, DNF, array shapes, and variance—directly at runtime.
* **[`nikic/php-parser`](https://github.com/nikic/PHP-Parser)** (created by [Nikita Popov](https://github.com/nikic)):
The gold standard for PHP abstract syntax tree (AST) parsing and code manipulation. It powers TypePHP's transparent stream wrapper interception, format-preserving AST transformations, and zero line-drift instrumentation.

Expand Down
4 changes: 2 additions & 2 deletions src/Internal/Ast/Elimination/EliminationSafetyPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public static function isReturnEliminationSafe(
}

if ($returnTypeNode instanceof GenericTypeNode) {
$baseName = strtolower($returnTypeNode->type->name);
$baseName = strtolower((string) $returnTypeNode->type);
if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) {
return false;
}
Expand Down Expand Up @@ -114,7 +114,7 @@ public static function isGeneratorEliminationSafe(
}

if ($returnTypeNode instanceof GenericTypeNode) {
$baseName = strtolower(ltrim($returnTypeNode->type->name, '\\'));
$baseName = strtolower(ltrim((string) $returnTypeNode->type, '\\'));
if (! isset(self::PERMISSIBLE_GENERATOR_GENERICS[$baseName])) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public static function satisfiesEmptyArray(TypeNode $typeNode): bool
}

if ($typeNode instanceof GenericTypeNode) {
return isset(self::EMPTY_ARRAY_ALLOWED_GENERICS[strtolower($typeNode->type->name)]);
return isset(self::EMPTY_ARRAY_ALLOWED_GENERICS[strtolower((string) $typeNode->type)]);
}

if ($typeNode instanceof ArrayShapeNode) {
Expand Down Expand Up @@ -141,7 +141,7 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy
*/
private static function satisfiesGenericArray(Array_ $arrayExpr, GenericTypeNode $node, string $currentFile): bool
{
$base = strtolower($node->type->name);
$base = strtolower((string) $node->type);
$genericCount = \count($node->genericTypes);

if ($base === 'list' && $genericCount >= 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty
return $targetClassName === $typeNode->name;
}

if ($typeNode instanceof GenericTypeNode && strtolower($typeNode->type->name) === 'int-mask-of') {
if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') {
$inner = $typeNode->genericTypes[0] ?? null;
if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) {
return self::matchesWildcard($constName, $inner->constExpr->name);
Expand All @@ -98,7 +98,7 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty
*/
private static function satisfiesBitwiseOr(BitwiseOr $expr, TypeNode $typeNode, string $currentFile): bool
{
if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'int-mask-of') {
if (! ($typeNode instanceof GenericTypeNode) || strtolower((string) $typeNode->type) !== 'int-mask-of') {
return false;
}

Expand All @@ -119,7 +119,7 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode
return false;
}

if (! ($typeNode instanceof GenericTypeNode) || strtolower($typeNode->type->name) !== 'value-of') {
if (! ($typeNode instanceof GenericTypeNode) || strtolower((string) $typeNode->type) !== 'value-of') {
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public static function extractContract(TypeNode $returnTypeNode): ?array
}

if ($returnTypeNode instanceof GenericTypeNode) {
$base = strtolower(ltrim($returnTypeNode->type->name, '\\'));
$base = strtolower(ltrim((string) $returnTypeNode->type, '\\'));
if (! isset(self::GENERATOR_ROOT_TYPES[$base])) {
return null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Ast/Elimination/Evaluator/ScalarEvaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ private static function satisfiesInteger(int $value, TypeNode $typeNode): bool
}

if ($typeNode instanceof GenericTypeNode) {
$base = strtolower($typeNode->type->name);
$base = strtolower((string) $typeNode->type);

if ($base === 'int' || $base === 'integer') {
return self::satisfiesIntRange($value, $typeNode);
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Ast/Elimination/StaticTypeEvaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current
}

if ($typeNode instanceof GenericTypeNode) {
$baseName = strtolower($typeNode->type->name);
$baseName = strtolower((string) $typeNode->type);
if (! isset(self::PERMISSIBLE_GENERIC_CONTAINERS[$baseName])) {
return false;
}
Expand Down
152 changes: 126 additions & 26 deletions src/Internal/Ast/FunctionContractInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ public static function inject(
$classContext,
$returnTypeNode,
$currentFile,
$hasMethodTemplates
$hasMethodTemplates,
$needsReturnVars,
$hasParamOut ? $byRefParams : [],
$hasSelfOut
)
: self::wrapNonGeneratorReturns(
$node->stmts,
Expand Down Expand Up @@ -485,7 +488,7 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b
]
);

$throwStmt = self::buildTypeErrorThrowStmt(new Node\Expr\Variable('__typephpErr'));
$throwStmt = self::buildTypeErrorThrowStmt(new Node\Expr\Variable('__typephpScope'));
$cacheKeyExpr = new Node\Scalar\MagicConst\Method();

$noParamFetch = new Node\Expr\StaticPropertyFetch(
Expand Down Expand Up @@ -525,7 +528,7 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b
'stmts' => [
new Node\Stmt\If_(
new Node\Expr\Instanceof_(
new Node\Expr\Assign(new Node\Expr\Variable('__typephpErr'), $checkCall),
new Node\Expr\Assign(new Node\Expr\Variable('__typephpScope'), $checkCall),
new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage')
),
['stmts' => [$throwStmt]]
Expand Down Expand Up @@ -788,11 +791,49 @@ public static function buildTernaryReturnExpr(Node\Expr\FuncCall $checkCall, ?in
);
}

/**
* @param array<string> $byRefParamNames
*/
public static function buildParamOutGuardExpr(
array $byRefParamNames,
Node\Expr $innerExpr,
Node\Expr $thisArg,
?int $line = null
): Node\Expr {
$expr = $innerExpr;
foreach (array_reverse($byRefParamNames) as $pName) {
$checkCall = new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkParamOut'),
[
new Node\Arg(new Node\Scalar\MagicConst\Method()),
new Node\Arg(new Node\Scalar\String_($pName)),
new Node\Arg(new Node\Expr\Variable($pName)),
new Node\Arg($thisArg),
]
);

$expr = new Node\Expr\Ternary(
new Node\Expr\Instanceof_(
new Node\Expr\Assign(new Node\Expr\Variable('__typephpErr'), $checkCall),
new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage')
),
self::buildTypeErrorThrowExpr(new Node\Expr\Variable('__typephpErr'), $line),
$expr
);
}

return $expr;
}

/**
* @param array<string> $byRefParams
*/
public static function buildWrappedYieldNode(
Node\Expr\Yield_ $n,
Node\Expr $thisArg,
bool $wrapYield = true,
bool $wrapSend = true
bool $wrapSend = true,
array $byRefParams = []
): Node\Expr {
if ($wrapYield) {
$checkYieldCall = new Node\Expr\FuncCall(
Expand All @@ -815,6 +856,11 @@ public static function buildWrappedYieldNode(
);
}

if ($byRefParams !== []) {
$valExpr = $n->value ?? new Node\Expr\ConstFetch(new Node\Name('null'));
$n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine());
}

if (! $wrapSend) {
return $n;
}
Expand All @@ -841,6 +887,7 @@ public static function buildWrappedYieldNode(
/**
* @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
*
* @return array<Node\Stmt>
*/
Expand All @@ -851,7 +898,10 @@ private static function wrapGeneratorReturns(
?array $classContext = null,
?TypeNode $returnTypeNode = null,
string $currentFile = '',
bool $hasMethodTemplates = false
bool $hasMethodTemplates = false,
bool $needsReturnVars = false,
array $byRefParams = [],
bool $hasSelfOut = false
): array {
$canEliminate = $functionNode !== null
&& ! $hasMethodTemplates
Expand All @@ -867,18 +917,29 @@ private static function wrapGeneratorReturns(
}

$traverser = new NodeTraverser();
$traverser->addVisitor(new class ($thisArg, $genContract, $currentFile) extends NodeVisitorAbstract {
$traverser->addVisitor(new class (
$thisArg,
$genContract,
$currentFile,
$needsReturnVars,
$byRefParams,
$hasSelfOut
) extends NodeVisitorAbstract {
/**
* @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract
* @param array<string> $byRefParams
*/
public function __construct(
private Node\Expr $thisArg,
private ?array $genContract,
private string $currentFile
private string $currentFile,
private bool $needsReturnVars,
private array $byRefParams,
private bool $hasSelfOut
) {
}

public function enterNode(Node $n): int|Node|null
public function enterNode(Node $n): int|Node|array|null
{
if ($n instanceof Node\Expr\Closure || $n instanceof Node\Expr\ArrowFunction || $n instanceof Node\Stmt\Function_ || $n instanceof Node\Stmt\ClassMethod) {
return NodeTraverser::DONT_TRAVERSE_CHILDREN;
Expand Down Expand Up @@ -926,11 +987,11 @@ public function enterNode(Node $n): int|Node|null
$wrapSend = $this->genContract === null
|| ! GeneratorEvaluator::canEliminateSend($this->genContract['send']);

if (! $wrapYield && ! $wrapSend) {
if (! $wrapYield && ! $wrapSend && $this->byRefParams === []) {
return null;
}

return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend);
return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend, $this->byRefParams);
}

if ($n instanceof Node\Expr\YieldFrom) {
Expand All @@ -939,27 +1000,36 @@ public function enterNode(Node $n): int|Node|null
}
$n->setAttribute('typephp_wrapped', true);

if (
$this->genContract !== null
$canEliminateYieldFrom = $this->genContract !== null
&& GeneratorEvaluator::canEliminateYieldFrom(
$n,
$this->genContract['key'],
$this->genContract['value'],
$this->currentFile
)
) {
return null;
);

if (! $canEliminateYieldFrom) {
$n->expr = new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::wrapIterable'),
[
new Node\Arg(new Node\Scalar\MagicConst\Method()),
new Node\Arg(new Node\Scalar\String_('return')),
new Node\Arg($n->expr),
new Node\Arg($this->thisArg),
]
);
}

$n->expr = new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::wrapIterable'),
[
new Node\Arg(new Node\Scalar\MagicConst\Method()),
new Node\Arg(new Node\Scalar\String_('return')),
new Node\Arg($n->expr),
new Node\Arg($this->thisArg),
]
);
if ($this->byRefParams !== []) {
$n->expr = FunctionContractInjector::buildParamOutGuardExpr(
$this->byRefParams,
$n->expr,
$this->thisArg,
$n->getStartLine()
);
}

return null;
}

if ($n instanceof Node\Stmt\Return_) {
Expand All @@ -968,6 +1038,19 @@ public function enterNode(Node $n): int|Node|null
}
$n->setAttribute('typephp_generator_return_wrapped', true);

$exitStmts = [];
if ($this->hasSelfOut) {
$exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars);
}

$paramOutStmts = $this->byRefParams !== []
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg)
: [];

if ($paramOutStmts !== []) {
$exitStmts = [...$exitStmts, ...$paramOutStmts];
}

$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 All @@ -980,7 +1063,7 @@ public function enterNode(Node $n): int|Node|null
$this->currentFile
)
) {
return $n;
return $exitStmts !== [] ? [...$exitStmts, $n] : $n;
}

$checkCall = new Node\Expr\FuncCall(
Expand All @@ -994,7 +1077,7 @@ public function enterNode(Node $n): int|Node|null

$n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine());

return $n;
return $exitStmts !== [] ? [...$exitStmts, $n] : $n;
}

return null;
Expand All @@ -1006,6 +1089,23 @@ public function enterNode(Node $n): int|Node|null

$lastStmt = end($newStmts);
if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) {
$exitStmts = [];
if ($hasSelfOut) {
$exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars);
}

$paramOutStmts = $byRefParams !== []
? self::buildParamOutCheckStmts($byRefParams, $thisArg)
: [];

if ($paramOutStmts !== []) {
$exitStmts = [...$exitStmts, ...$paramOutStmts];
}

if ($exitStmts !== []) {
$newStmts = [...$newStmts, ...$exitStmts];
}

if (
$genContract === null
|| ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile)
Expand Down
4 changes: 2 additions & 2 deletions src/Internal/Ast/TypeDeducer.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static function deduceElementType(string $typeString): ?string
}

if ($typeNode instanceof GenericTypeNode) {
$base = strtolower($typeNode->type->name);
$base = strtolower((string) $typeNode->type);
$count = \count($typeNode->genericTypes);

if (\in_array($base, ['list', 'non-empty-list'], true) && $count >= 1) {
Expand Down Expand Up @@ -101,7 +101,7 @@ public static function deduceKeyType(string $typeString): string
}

if ($typeNode instanceof GenericTypeNode) {
$base = strtolower($typeNode->type->name);
$base = strtolower((string) $typeNode->type);
$count = \count($typeNode->genericTypes);

if (\in_array($base, ['list', 'non-empty-list'], true)) {
Expand Down
Loading
Loading