Skip to content

Commit b13b27d

Browse files
authored
Internal Improvements and new features for upcoming minor release (#70)
* Implement self-out functionality with associated checks and docblock extraction * Enhance self-out ignore resolution and vendor calling boundary isolation * Add self-out configuration and validation checks * Resolve discovred bugs and improve test coverage * Add wildcard generics support and treating mixed type as able to satisfy any upper bounds * Resolve Self inherited class fcqn issue in Generic template type checking * Implement improve trait context resolution and add tests for conflicting use-statement aliases * Fix bug on A method-level @template T collides with a class-level @template T of the consuming class * Fix inline @var T $object is not bound from a class-string<T> parameter * Add beforeEach and afterEach hooks to reset Config in Pest tests
1 parent a9e313f commit b13b27d

35 files changed

Lines changed: 2623 additions & 448 deletions

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ private function handleExpression(Node\Stmt\Expression $node): ?array
291291
}
292292
}
293293

294-
return $checkStmts !== [] ? array_merge([$node], $checkStmts) : null;
294+
return $checkStmts !== [] ? [$node, ...$checkStmts] : null;
295295
}
296296

297297
private function handleAssign(Node\Expr\Assign $node): void
@@ -517,7 +517,7 @@ private function extractDestructuringVariables(Node\Expr\List_|Node\Expr\Array_
517517
'expr' => $item->value,
518518
];
519519
} elseif ($item->value instanceof Node\Expr\List_ || $item->value instanceof Node\Expr\Array_) {
520-
$vars = array_merge($vars, $this->extractDestructuringVariables($item->value));
520+
$vars = [...$vars, ...$this->extractDestructuringVariables($item->value)];
521521
}
522522
}
523523

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 58 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
7777

7878
$hasParamOut = $byRefParams !== [] && ($hasParamOutDoc || $hasInheritance);
7979

80+
$hasSelfOutDoc = str_contains($docText, 'self-out') || str_contains($docText, 'this-out');
81+
$hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || $hasInheritance);
82+
8083
$hasReturnDoc = str_contains($docText, '@return')
8184
|| str_contains($docText, '@phpstan-return')
8285
|| str_contains($docText, '@psalm-return');
@@ -86,7 +89,7 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
8689
&& ! ($isNativeVoid && ! $hasReturnDoc)
8790
&& self::hasReturnContracts($docText, $isClassMethod, $isPrivate);
8891

89-
if (! $hasParam && ! $hasReturn && ! $hasParamOut) {
92+
if (! $hasParam && ! $hasReturn && ! $hasParamOut && ! $hasSelfOut) {
9093
return;
9194
}
9295

@@ -100,7 +103,7 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
100103
$injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg);
101104
}
102105

103-
if ($hasReturn || $hasParamOut) {
106+
if ($hasReturn || $hasParamOut || $hasSelfOut) {
104107
$node->stmts = self::isGenerator($node)
105108
? self::wrapGeneratorReturns($node->stmts, $thisArg)
106109
: self::wrapNonGeneratorReturns(
@@ -109,13 +112,35 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
109112
$isNativeVoid,
110113
$needsReturnVars,
111114
$hasReturn,
112-
$hasParamOut ? $byRefParams : []
115+
$hasParamOut ? $byRefParams : [],
116+
$hasSelfOut
113117
);
114118
}
115119

116120
$node->stmts = [...$injectedStmts, ...$node->stmts];
117121
}
118122

123+
public static function buildSelfOutCheckStmt(Node\Expr $thisArg, bool $needsReturnVars = false): Node\Stmt\Expression
124+
{
125+
$varsArg = $needsReturnVars
126+
? new Node\Expr\Variable('_typephpArgs')
127+
: new Node\Expr\Array_();
128+
129+
$checkCall = new Node\Expr\FuncCall(
130+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkSelfOut'),
131+
[
132+
new Node\Arg(new Node\Scalar\MagicConst\Method()),
133+
new Node\Arg($thisArg),
134+
new Node\Arg($varsArg),
135+
]
136+
);
137+
138+
$stmt = new Node\Stmt\Expression($checkCall);
139+
$stmt->setAttribute('typephp_injected', true);
140+
141+
return $stmt;
142+
}
143+
119144
private static function resolveDocComment(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): ?Doc
120145
{
121146
$doc = $node->getDocComment();
@@ -699,10 +724,11 @@ private static function wrapNonGeneratorReturns(
699724
bool $isNativeVoid,
700725
bool $needsReturnVars = false,
701726
bool $hasReturn = true,
702-
array $byRefParams = []
727+
array $byRefParams = [],
728+
bool $hasSelfOut = false
703729
): array {
704730
$traverser = new NodeTraverser();
705-
$traverser->addVisitor(new class ($thisArg, $isNativeVoid, $needsReturnVars, $hasReturn, $byRefParams) extends NodeVisitorAbstract {
731+
$traverser->addVisitor(new class ($thisArg, $isNativeVoid, $needsReturnVars, $hasReturn, $byRefParams, $hasSelfOut) extends NodeVisitorAbstract {
706732
/**
707733
* @param array<string> $byRefParams
708734
*/
@@ -711,7 +737,8 @@ public function __construct(
711737
private bool $isNativeVoid,
712738
private bool $needsReturnVars,
713739
private bool $hasReturn,
714-
private array $byRefParams
740+
private array $byRefParams,
741+
private bool $hasSelfOut
715742
) {
716743
}
717744

@@ -726,12 +753,21 @@ public function enterNode(Node $n): int|array|null
726753
return null;
727754
}
728755

756+
$exitStmts = [];
757+
if ($this->hasSelfOut) {
758+
$exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars);
759+
}
760+
729761
$paramOutStmts = $this->byRefParams !== []
730762
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg)
731763
: [];
732764

765+
if ($paramOutStmts !== []) {
766+
$exitStmts = [...$exitStmts, ...$paramOutStmts];
767+
}
768+
733769
if (! $this->hasReturn) {
734-
return $paramOutStmts !== [] ? [...$paramOutStmts, $n] : null;
770+
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
735771
}
736772

737773
$exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null'));
@@ -740,7 +776,7 @@ public function enterNode(Node $n): int|array|null
740776
$checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars);
741777
$voidGuardStmts = FunctionContractInjector::buildVoidReturnGuard($checkCall);
742778

743-
return [...$paramOutStmts, ...$voidGuardStmts];
779+
return [...$exitStmts, ...$voidGuardStmts];
744780
}
745781

746782
// Call-site cache bypass for return checks
@@ -764,7 +800,7 @@ public function enterNode(Node $n): int|array|null
764800
$ternaryExpr
765801
);
766802

767-
return $paramOutStmts !== [] ? [...$paramOutStmts, $n] : null;
803+
return $exitStmts !== [] ? [...$exitStmts, $n] : null;
768804
}
769805

770806
return null;
@@ -776,21 +812,28 @@ public function enterNode(Node $n): int|array|null
776812

777813
$lastStmt = end($newStmts);
778814
if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) {
815+
$exitStmts = [];
816+
if ($hasSelfOut) {
817+
$exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars);
818+
}
819+
779820
$paramOutStmts = $byRefParams !== []
780821
? self::buildParamOutCheckStmts($byRefParams, $thisArg)
781822
: [];
782823

824+
if ($paramOutStmts !== []) {
825+
$exitStmts = [...$exitStmts, ...$paramOutStmts];
826+
}
827+
783828
if (! $hasReturn) {
784-
if ($paramOutStmts !== []) {
785-
$retStmt = new Node\Stmt\Return_(null);
786-
$retStmt->setAttribute('typephp_injected', true);
787-
$newStmts = [...$newStmts, ...$paramOutStmts, $retStmt];
829+
if ($exitStmts !== []) {
830+
$newStmts = [...$newStmts, ...$exitStmts];
788831
}
789832
} else {
790833
$checkCall = self::buildReturnCheckCall(new Node\Expr\ConstFetch(new Node\Name('null')), $thisArg, $needsReturnVars);
791834

792835
if ($isNativeVoid) {
793-
$newStmts = [...$newStmts, ...$paramOutStmts, ...self::buildVoidReturnGuard($checkCall)];
836+
$newStmts = [...$newStmts, ...$exitStmts, ...self::buildVoidReturnGuard($checkCall)];
794837
} else {
795838
$cacheKeyExpr = new Node\Scalar\MagicConst\Method();
796839
$cacheCheck = new Node\Expr\Isset_([
@@ -812,7 +855,7 @@ public function enterNode(Node $n): int|array|null
812855

813856
$retStmt = new Node\Stmt\Return_($fallbackExpr);
814857
$retStmt->setAttribute('typephp_injected', true);
815-
$newStmts = [...$newStmts, ...$paramOutStmts, $retStmt];
858+
$newStmts = [...$newStmts, ...$exitStmts, $retStmt];
816859
}
817860
}
818861
}

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ public static function checkVariable(
168168

169169
$checkGenerics = (bool) ($config['generics'] ?? true);
170170
if ($typeNode instanceof GenericTypeNode && $checkGenerics && \is_object($value)) {
171-
$err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context, forceBind: true);
171+
$err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context);
172172
if ($err !== null) {
173173
return $err;
174174
}
@@ -346,8 +346,15 @@ private static function resolveClassContext(
346346
return $typeNode;
347347
}
348348

349+
$targetFunc = ($methodName !== '{closure}' && $methodName !== null && ! str_starts_with($methodName, '{closure'))
350+
? $className . '::' . $methodName
351+
: $className . '::__construct';
352+
353+
$contract = DocblockParser::parse($targetFunc);
354+
$hasMethodTemplates = ($contract['templates'] ?? []) !== [];
355+
349356
$cacheKey = null;
350-
if ($thisObj === null) {
357+
if ($thisObj === null && ! $hasMethodTemplates) {
351358
$cacheKey = ((string) $typeNode) . '|' . $className . '|' . ($methodName ?? '');
352359
if (isset(self::$resolvedClassContextCache[$cacheKey])) {
353360
return self::$resolvedClassContextCache[$cacheKey];
@@ -360,15 +367,10 @@ private static function resolveClassContext(
360367
$typeNode = SpecialTypeResolver::resolve($typeNode, $refClass);
361368

362369
$classAliases = DocblockParser::parseClassAliases($className);
370+
$allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
371+
$declaredTemplates = $allTemplates;
363372

364-
$targetFunc = ($methodName !== '{closure}' && $methodName !== null && ! str_starts_with($methodName, '{closure'))
365-
? $className . '::' . $methodName
366-
: $className . '::__construct';
367-
368-
$contract = DocblockParser::parse($targetFunc);
369-
$declaredTemplates = $contract['allTemplates'] ?? ($contract['classTemplates'] ?? []);
370-
371-
if (\count($classAliases) === 0 && \count($declaredTemplates) === 0) {
373+
if ($classAliases === [] && $declaredTemplates === []) {
372374
if ($cacheKey !== null) {
373375
return self::$resolvedClassContextCache[$cacheKey] = $typeNode;
374376
}
@@ -379,7 +381,7 @@ private static function resolveClassContext(
379381
$boundTemplates = TemplateManager::getBoundTemplates($targetFunc, $thisObj, $declaredTemplates);
380382
$activeBindings = [...$classAliases, ...$boundTemplates];
381383

382-
if (\count($activeBindings) > 0 || \count($declaredTemplates) > 0) {
384+
if ($activeBindings !== [] || $declaredTemplates !== []) {
383385
$typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates);
384386
$typeNode = SpecialTypeResolver::resolve($typeNode, $refClass);
385387
}

‎src/Internal/Checker/ParamChecker.php‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,6 @@ public static function checkParams(
146146
return null;
147147
}
148148

149-
// Use pre-resolved contract or parse
150149
$contract ??= DocblockParser::parse($effectiveFunction);
151150

152151
if (! $contract['hasParamContract']) {
@@ -387,7 +386,7 @@ public static function resolveEffectiveFunction(string $function, object|string|
387386
}
388387

389388
if ($isTargetOfAlias) {
390-
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
389+
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
391390
foreach ($trace as $frame) {
392391
$frameFunc = $frame['function'];
393392
$frameClass = $frame['class'] ?? '';
@@ -507,7 +506,7 @@ private static function inferTemplatesFromClosures(
507506
foreach ($cTypeNode->parameters as $idx => $pNode) {
508507
if ($pNode->type instanceof IdentifierTypeNode && isset($templates[$pNode->type->name]) && isset($closureParams[$idx])) {
509508
$tName = $pNode->type->name;
510-
$isClassLevel = isset($classTemplates[$tName]);
509+
$isClassLevel = ! TemplateManager::isMethodTemplate($effectiveFunction, $tName) && isset($classTemplates[$tName]);
511510
$targetObj = $isClassLevel ? $thisObj : null;
512511

513512
$inferredCandidate = self::extractTypeFromClosureParameter($closureParams[$idx]);
@@ -639,7 +638,6 @@ private static function inferArrayTemplatesFromAllElements(
639638
}
640639

641640
$sampleItems = self::getSampleArraySlice($arrVal);
642-
643641
$genericCount = \count($typeNode->genericTypes);
644642

645643
if ($genericCount === 1 && $typeNode->genericTypes[0] instanceof IdentifierTypeNode) {
@@ -737,7 +735,7 @@ private static function bindTemplateIfUnbound(
737735
): void {
738736
$contract = DocblockParser::parse($effectiveFunction);
739737
$classTemplates = $contract['classTemplates'] ?? [];
740-
$isClassLevelTemplate = isset($classTemplates[$templateName]);
738+
$isClassLevelTemplate = ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName) && isset($classTemplates[$templateName]);
741739
$targetObj = $isClassLevelTemplate ? $thisObj : null;
742740

743741
if (isset($templates[$templateName]) && ! TemplateManager::isBound($effectiveFunction, $targetObj, $templateName)) {
@@ -941,7 +939,7 @@ private static function resolveClassStringTemplate(
941939
$innerType = $typeNode->genericTypes[0];
942940
$templateName = $innerType->name;
943941
$templateNode = $templates[$templateName];
944-
$isClassLevelTemplate = isset($classTemplates[$templateName]);
942+
$isClassLevelTemplate = ! TemplateManager::isMethodTemplate($function, $templateName) && isset($classTemplates[$templateName]);
945943
$targetObj = $isClassLevelTemplate ? $thisObj : null;
946944

947945
if (! TemplateManager::isBound($function, $targetObj, $templateName)) {
@@ -1067,7 +1065,7 @@ private static function resolveTemplateParam(
10671065
$templateNode = $templates[$templateName];
10681066
$isVariadic = $typeNode instanceof ArrayTypeNode;
10691067
$isNullable = ($typeNode instanceof NullableTypeNode) || ($typeNode instanceof UnionTypeNode && self::typeContainsNull($typeNode));
1070-
$isClassLevelTemplate = isset($classTemplates[$templateName]);
1068+
$isClassLevelTemplate = ! TemplateManager::isMethodTemplate($function, $templateName) && isset($classTemplates[$templateName]);
10711069
$targetObj = $isClassLevelTemplate ? $thisObj : null;
10721070
$allowsNullInBound = ($templateNode->bound !== null && self::typeContainsNull($templateNode->bound));
10731071

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Internal\Checker;
6+
7+
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
8+
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
9+
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
10+
use TypePHP\Internal\Docblock\DocblockParser;
11+
use TypePHP\Internal\Generics\TemplateManager;
12+
use TypePHP\Internal\Generics\TemplateSubstitutor;
13+
use TypePHP\Internal\Resolver\SpecialTypeResolver;
14+
use TypePHP\Internal\Util\Config;
15+
use TypePHP\Internal\Validator\TypeValidatorRegistry;
16+
17+
/**
18+
* @internal Evaluates generic state transitions on $this (@self-out, @phpstan-self-out, @psalm-self-out).
19+
*/
20+
final class SelfOutChecker
21+
{
22+
/**
23+
* O(1) Fast-path cache for methods determined to have no self-out contracts.
24+
*
25+
* @var array<string, true>
26+
*/
27+
public static array $noSelfOutContractCache = [];
28+
29+
public static function reset(): void
30+
{
31+
self::$noSelfOutContractCache = [];
32+
}
33+
34+
/**
35+
* @param array<int|string, mixed> $vars
36+
*/
37+
public static function checkSelfOut(
38+
string $function,
39+
object $thisObj,
40+
array $vars,
41+
TypeValidatorRegistry $registry,
42+
string $effectiveFunction = ''
43+
): void {
44+
if (! Config::isEnabled() || ! Config::isSelfOutEnabled()) {
45+
return;
46+
}
47+
48+
if (isset(self::$noSelfOutContractCache[$function])) {
49+
return;
50+
}
51+
52+
if ($effectiveFunction === '') {
53+
$effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisObj, $thisObj);
54+
}
55+
56+
if (isset(self::$noSelfOutContractCache[$effectiveFunction])) {
57+
self::$noSelfOutContractCache[$function] = true;
58+
59+
return;
60+
}
61+
62+
$contract = DocblockParser::parse($effectiveFunction);
63+
64+
if (! ($contract['hasSelfOutContract'] ?? false) || $contract['selfOut'] === null) {
65+
self::$noSelfOutContractCache[$effectiveFunction] = true;
66+
self::$noSelfOutContractCache[$function] = true;
67+
68+
return;
69+
}
70+
71+
$selfOutNode = $contract['selfOut'];
72+
$allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
73+
$boundTemplates = (\count($allTemplates) > 0)
74+
? TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates)
75+
: [];
76+
77+
if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) {
78+
$selfOutNode = TemplateSubstitutor::substitute($selfOutNode, $boundTemplates, $allTemplates);
79+
$selfOutNode = SpecialTypeResolver::resolve($selfOutNode, $effectiveFunction, $thisObj);
80+
}
81+
82+
if (
83+
$selfOutNode instanceof ConditionalTypeForParameterNode ||
84+
$selfOutNode instanceof ConditionalTypeNode
85+
) {
86+
$selfOutNode = ConditionalChecker::resolve($selfOutNode, $vars, $boundTemplates, $registry, $effectiveFunction);
87+
}
88+
89+
if ($selfOutNode instanceof GenericTypeNode) {
90+
TemplateManager::bindInstanceFromNode($thisObj, $selfOutNode, forceBind: true);
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)