Skip to content

Commit d765f73

Browse files
committed
Enhance constant closure handling by adding validation for parameters and return types, including new checks and tests for contract compliance
1 parent 7067669 commit d765f73

6 files changed

Lines changed: 587 additions & 48 deletions

File tree

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 138 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
1111
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
1212
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
13+
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
1314
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
15+
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
1416
use PHPStan\PhpDocParser\Parser\TokenIterator;
1517
use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator;
1618
use TypePHP\Internal\Docblock\DocblockExtractor;
@@ -334,12 +336,19 @@ private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, stri
334336
$typeNode = $typeParser->parse($tokens);
335337

336338
foreach ($stmt->consts as $const) {
339+
$constName = $const->name->toString();
340+
$fullTarget = $className . '::' . $constName;
341+
342+
if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) {
343+
$this->instrumentConstantClosure($const->value, $typeNode, $fullTarget);
344+
345+
continue;
346+
}
347+
337348
if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) {
338349
continue;
339350
}
340351

341-
$constName = $const->name->toString();
342-
$fullTarget = $className . '::' . $constName;
343352
$classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName);
344353

345354
$checkCall = NodeBuilder::createConstantCheckCall(
@@ -388,15 +397,21 @@ private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): ar
388397
$typeNode = $typeParser->parse($tokens);
389398

390399
foreach ($node->consts as $const) {
391-
if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) {
392-
continue;
393-
}
394-
395400
$constName = $const->name->toString();
396401
$qualifiedConstName = $this->currentNamespace !== ''
397402
? $this->currentNamespace . '\\' . $constName
398403
: $constName;
399404

405+
if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) {
406+
$this->instrumentConstantClosure($const->value, $typeNode, $qualifiedConstName);
407+
408+
continue;
409+
}
410+
411+
if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) {
412+
continue;
413+
}
414+
400415
$constFetch = new Node\Expr\ConstFetch(new Node\Name\FullyQualified($qualifiedConstName));
401416

402417
$checkCall = NodeBuilder::createConstantCheckCall(
@@ -416,6 +431,122 @@ private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): ar
416431
return $injectedStmts;
417432
}
418433

434+
private function instrumentConstantClosure(
435+
Node\Expr\Closure $closure,
436+
CallableTypeNode $callableTypeNode,
437+
string $caller
438+
): void {
439+
$paramChecks = [];
440+
$callableParams = $callableTypeNode->parameters;
441+
$paramsByName = [];
442+
443+
foreach ($callableParams as $idx => $pNode) {
444+
$pName = $pNode->parameterName !== null ? ltrim($pNode->parameterName, '$') : null;
445+
if ($pName !== null) {
446+
$paramsByName[$pName] = $pNode;
447+
} elseif (isset($closure->params[$idx])) {
448+
$closureParam = $closure->params[$idx];
449+
if ($closureParam->var instanceof Node\Expr\Variable && \is_string($closureParam->var->name)) {
450+
$paramsByName[$closureParam->var->name] = $pNode;
451+
}
452+
}
453+
}
454+
455+
foreach ($closure->params as $param) {
456+
if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) {
457+
$pName = $param->var->name;
458+
$pContract = $paramsByName[$pName] ?? null;
459+
460+
if ($pContract !== null) {
461+
$typeStr = (string) $pContract->type;
462+
if (strtolower(trim($typeStr)) === 'mixed') {
463+
continue;
464+
}
465+
466+
$line = $param->getStartLine();
467+
$checkCall = NodeBuilder::createConstantClosureParamCheckCall(
468+
$caller,
469+
$pName,
470+
new Node\Expr\Variable($pName),
471+
$typeStr,
472+
$line
473+
);
474+
$checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $line));
475+
$checkStmt->setAttribute('typephp_injected', true);
476+
$paramChecks[] = $checkStmt;
477+
}
478+
}
479+
}
480+
481+
if ($paramChecks !== []) {
482+
$closure->stmts = [...$paramChecks, ...$closure->stmts];
483+
}
484+
485+
$returnTypeNode = $callableTypeNode->returnType;
486+
$returnTypeStr = (string) $returnTypeNode;
487+
$isReturnUnconstrained = \in_array(strtolower(trim($returnTypeStr)), ['void', 'mixed'], true);
488+
489+
if (! $isReturnUnconstrained) {
490+
$traverser = new NodeTraverser();
491+
$traverser->addVisitor(new class (
492+
$caller,
493+
$returnTypeNode,
494+
$returnTypeStr,
495+
$this->currentFile
496+
) extends NodeVisitorAbstract {
497+
public function __construct(
498+
private string $caller,
499+
private TypeNode $returnTypeNode,
500+
private string $returnTypeStr,
501+
private string $currentFile
502+
) {
503+
}
504+
505+
public function enterNode(Node $n): int|Node|null
506+
{
507+
if (
508+
$n instanceof Node\Expr\Closure
509+
|| $n instanceof Node\Expr\ArrowFunction
510+
|| $n instanceof Node\Stmt\Function_
511+
|| $n instanceof Node\Stmt\ClassMethod
512+
|| $n instanceof Node\Stmt\Class_
513+
) {
514+
return NodeTraverser::DONT_TRAVERSE_CHILDREN;
515+
}
516+
517+
if ($n instanceof Node\Stmt\Return_) {
518+
$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));
519+
520+
if (
521+
Config::isEliminateStaticallyProvenChecksEnabled()
522+
&& StaticTypeEvaluator::satisfies($exprToWrap, $this->returnTypeNode, $this->currentFile)
523+
) {
524+
return null;
525+
}
526+
527+
$line = $n->getStartLine();
528+
$checkCall = NodeBuilder::createConstantClosureReturnCheckCall(
529+
$this->caller,
530+
$exprToWrap,
531+
$this->returnTypeStr,
532+
$line
533+
);
534+
535+
$n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $line);
536+
537+
return $n;
538+
}
539+
540+
return null;
541+
}
542+
});
543+
544+
/** @var array<Node\Stmt> $newStmts */
545+
$newStmts = $traverser->traverse($closure->stmts);
546+
$closure->stmts = $newStmts;
547+
}
548+
}
549+
419550
private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression
420551
{
421552
$targetVarExpr = null;
@@ -457,7 +588,7 @@ private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stm
457588

458589
private static function isLoopBodyFreeOfOpaqueMutations(Node\Stmt\Foreach_ $node): bool
459590
{
460-
$visitor = new class() extends NodeVisitorAbstract {
591+
$visitor = new class () extends NodeVisitorAbstract {
461592
public bool $hasOpaqueCalls = false;
462593

463594
public function enterNode(Node $n): ?int

‎src/Internal/Ast/NodeBuilder.php‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,42 @@ public static function createConstantCheckCall(
158158
]
159159
);
160160
}
161+
162+
public static function createConstantClosureParamCheckCall(
163+
string $caller,
164+
string $paramName,
165+
Node\Expr $paramVar,
166+
string $typeString,
167+
int $line
168+
): Node\Expr\FuncCall {
169+
return new Node\Expr\FuncCall(
170+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam'),
171+
[
172+
new Node\Arg(new Node\Scalar\String_($caller)),
173+
new Node\Arg(new Node\Scalar\String_($paramName)),
174+
new Node\Arg($paramVar),
175+
new Node\Arg(new Node\Scalar\String_($typeString)),
176+
new Node\Arg(new Node\Scalar\MagicConst\File()),
177+
new Node\Arg(new Node\Scalar\LNumber($line)),
178+
]
179+
);
180+
}
181+
182+
public static function createConstantClosureReturnCheckCall(
183+
string $caller,
184+
Node\Expr $valueExpr,
185+
string $typeString,
186+
int $line
187+
): Node\Expr\FuncCall {
188+
return new Node\Expr\FuncCall(
189+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn'),
190+
[
191+
new Node\Arg(new Node\Scalar\String_($caller)),
192+
new Node\Arg($valueExpr),
193+
new Node\Arg(new Node\Scalar\String_($typeString)),
194+
new Node\Arg(new Node\Scalar\MagicConst\File()),
195+
new Node\Arg(new Node\Scalar\LNumber($line)),
196+
]
197+
);
198+
}
161199
}

‎src/Internal/Reporting/ViolationRecord.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ public function __construct(
2626
public readonly int $count = 1,
2727
public readonly ?string $caller = null,
2828
public readonly ?string $declaredIn = null
29-
) {}
29+
) {
30+
}
3031

3132
/**
3233
* Computes a deterministic deduplication hash for this violation.

‎src/Internal/RuntimeTypeChecker.php‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,87 @@ public static function checkConstant(
112112
return $value;
113113
}
114114

115+
/**
116+
* Validates an argument passed into a constant closure against its parameter contract.
117+
*/
118+
public static function checkConstantClosureParam(
119+
string $caller,
120+
string $paramName,
121+
mixed $value,
122+
string $typeString,
123+
string $file = '',
124+
?int $line = null
125+
): mixed {
126+
if (! Config::isEnabled() || ! Config::isParamsEnabled()) {
127+
return $value;
128+
}
129+
130+
try {
131+
$normalized = DocblockNormalizer::normalize($typeString);
132+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
133+
$tokens = new TokenIterator($lexer->tokenize($normalized));
134+
$typeNode = $typeParser->parse($tokens);
135+
136+
if ($file !== '') {
137+
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file);
138+
}
139+
140+
$context = "{$caller}(): Argument \${$paramName}";
141+
142+
$err = self::getRegistry()->validate($value, $typeNode, $context);
143+
if ($err !== null) {
144+
if (IgnoreManager::isCallerIgnored()) {
145+
return $value;
146+
}
147+
148+
return ViolationCollector::handle($err, 'parameter', $value, $file, $line, $caller, '$' . $paramName);
149+
}
150+
} catch (\Throwable $e) {
151+
}
152+
153+
return $value;
154+
}
155+
156+
/**
157+
* Validates a return value from a constant closure against its return type contract.
158+
*/
159+
public static function checkConstantClosureReturn(
160+
string $caller,
161+
mixed $value,
162+
string $typeString,
163+
string $file = '',
164+
?int $line = null
165+
): mixed {
166+
if (! Config::isEnabled() || ! Config::isReturnsEnabled()) {
167+
return $value;
168+
}
169+
170+
try {
171+
$normalized = DocblockNormalizer::normalize($typeString);
172+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
173+
$tokens = new TokenIterator($lexer->tokenize($normalized));
174+
$typeNode = $typeParser->parse($tokens);
175+
176+
if ($file !== '') {
177+
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file);
178+
}
179+
180+
$context = "{$caller}(): Return value";
181+
182+
$err = self::getRegistry()->validate($value, $typeNode, $context);
183+
if ($err !== null) {
184+
if (IgnoreManager::isCallerIgnored()) {
185+
return $value;
186+
}
187+
188+
return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return');
189+
}
190+
} catch (\Throwable $e) {
191+
}
192+
193+
return $value;
194+
}
195+
115196
/**
116197
* Evaluates member/dimension mutation assignments on an object or static property
117198
* ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing.

0 commit comments

Comments
 (0)