Skip to content

Commit abab150

Browse files
authored
New Minor Release (Constants Typechecking) (#124)
* Enhance template handling by adding default type checks and applying class template defaults and able to get the generic type without annoating it manually * Enhance conditional type handling in ParamOutChecker and DefaultTemplateTypesTest with new tests for default templates and conditional parameters * Enhance F-bounded polymorphism tests with new generic holder and parameter type checks * Enhance param-out handling with conditional checks and additional tests for parameter-based contracts * Enhance conditional type handling in GeneratorChecker and IterableWrapper with new checks and tests for conditional generators and iterables * Enhance code formatting and add new static methods for default template handling in TemplateManager and DefaultTemplateTypesTest * Enhance type handling and add support for generics in various checkers and tests * Enhance constant validation by adding checks for class and global constants, including tests for contract compliance and error handling * Enhance constant closure handling by adding validation for parameters and return types, including new checks and tests for contract compliance * Refactor constant declarations to remove type hints for arrays and integers in test fixtures * Add tests for constant closure parameter and return validation in RuntimeTypeChecker
1 parent 7f4263f commit abab150

25 files changed

Lines changed: 2685 additions & 91 deletions

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 326 additions & 22 deletions
Large diffs are not rendered by default.

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ public static function inject(
115115
$hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance));
116116

117117
$hasParam = ($isMagicGet || $isMagicCall) || ($paramCount > 0 && (
118-
str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc) && str_contains($docText, '$'))
118+
str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc || $hasParamOutDoc) && str_contains($docText, '$'))
119119
)) || self::hasParamContracts(
120120
$docText,
121121
$isClassMethod,
@@ -552,8 +552,15 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b
552552
*
553553
* @return array<Node\Stmt>
554554
*/
555-
public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr $thisArg): array
556-
{
555+
public static function buildParamOutCheckStmts(
556+
array $byRefParamNames,
557+
Node\Expr $thisArg,
558+
bool $needsReturnVars = false
559+
): array {
560+
$varsArg = $needsReturnVars
561+
? new Node\Expr\Variable('_typephpArgs')
562+
: new Node\Expr\Array_();
563+
557564
$stmts = [];
558565
foreach ($byRefParamNames as $pName) {
559566
$checkCall = new Node\Expr\FuncCall(
@@ -563,6 +570,7 @@ public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr
563570
new Node\Arg(new Node\Scalar\String_($pName)),
564571
new Node\Arg(new Node\Expr\Variable($pName)),
565572
new Node\Arg($thisArg),
573+
new Node\Arg($varsArg),
566574
]
567575
);
568576

@@ -798,8 +806,13 @@ public static function buildParamOutGuardExpr(
798806
array $byRefParamNames,
799807
Node\Expr $innerExpr,
800808
Node\Expr $thisArg,
801-
?int $line = null
809+
?int $line = null,
810+
bool $needsReturnVars = false
802811
): Node\Expr {
812+
$varsArg = $needsReturnVars
813+
? new Node\Expr\Variable('_typephpArgs')
814+
: new Node\Expr\Array_();
815+
803816
$expr = $innerExpr;
804817
foreach (array_reverse($byRefParamNames) as $pName) {
805818
$checkCall = new Node\Expr\FuncCall(
@@ -809,6 +822,7 @@ public static function buildParamOutGuardExpr(
809822
new Node\Arg(new Node\Scalar\String_($pName)),
810823
new Node\Arg(new Node\Expr\Variable($pName)),
811824
new Node\Arg($thisArg),
825+
new Node\Arg($varsArg),
812826
]
813827
);
814828

@@ -833,7 +847,8 @@ public static function buildWrappedYieldNode(
833847
Node\Expr $thisArg,
834848
bool $wrapYield = true,
835849
bool $wrapSend = true,
836-
array $byRefParams = []
850+
array $byRefParams = [],
851+
bool $needsReturnVars = false
837852
): Node\Expr {
838853
if ($wrapYield) {
839854
$checkYieldCall = new Node\Expr\FuncCall(
@@ -858,7 +873,7 @@ public static function buildWrappedYieldNode(
858873

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

864879
if (! $wrapSend) {
@@ -991,7 +1006,14 @@ public function enterNode(Node $n): int|Node|array|null
9911006
return null;
9921007
}
9931008

994-
return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend, $this->byRefParams);
1009+
return FunctionContractInjector::buildWrappedYieldNode(
1010+
$n,
1011+
$this->thisArg,
1012+
$wrapYield,
1013+
$wrapSend,
1014+
$this->byRefParams,
1015+
$this->needsReturnVars
1016+
);
9951017
}
9961018

9971019
if ($n instanceof Node\Expr\YieldFrom) {
@@ -1025,7 +1047,8 @@ public function enterNode(Node $n): int|Node|array|null
10251047
$this->byRefParams,
10261048
$n->expr,
10271049
$this->thisArg,
1028-
$n->getStartLine()
1050+
$n->getStartLine(),
1051+
$this->needsReturnVars
10291052
);
10301053
}
10311054

@@ -1044,7 +1067,7 @@ public function enterNode(Node $n): int|Node|array|null
10441067
}
10451068

10461069
$paramOutStmts = $this->byRefParams !== []
1047-
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg)
1070+
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars)
10481071
: [];
10491072

10501073
if ($paramOutStmts !== []) {
@@ -1095,7 +1118,7 @@ public function enterNode(Node $n): int|Node|array|null
10951118
}
10961119

10971120
$paramOutStmts = $byRefParams !== []
1098-
? self::buildParamOutCheckStmts($byRefParams, $thisArg)
1121+
? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars)
10991122
: [];
11001123

11011124
if ($paramOutStmts !== []) {
@@ -1224,7 +1247,7 @@ public function enterNode(Node $n): int|array|null
12241247
}
12251248

12261249
$paramOutStmts = $this->byRefParams !== []
1227-
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg)
1250+
? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars)
12281251
: [];
12291252

12301253
if ($paramOutStmts !== []) {
@@ -1286,7 +1309,7 @@ public function enterNode(Node $n): int|array|null
12861309
}
12871310

12881311
$paramOutStmts = $byRefParams !== []
1289-
? self::buildParamOutCheckStmts($byRefParams, $thisArg)
1312+
? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars)
12901313
: [];
12911314

12921315
if ($paramOutStmts !== []) {

‎src/Internal/Ast/NodeBuilder.php‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,60 @@ public static function createPropertyMemberAssignCheckCall(
140140
]
141141
);
142142
}
143+
144+
public static function createConstantCheckCall(
145+
string $constantName,
146+
Node\Expr $valueExpr,
147+
string $typeString,
148+
int $line
149+
): Node\Expr\FuncCall {
150+
return new Node\Expr\FuncCall(
151+
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstant'),
152+
[
153+
new Node\Arg(new Node\Scalar\String_($constantName)),
154+
new Node\Arg($valueExpr),
155+
new Node\Arg(new Node\Scalar\String_($typeString)),
156+
new Node\Arg(new Node\Scalar\MagicConst\File()),
157+
new Node\Arg(new Node\Scalar\LNumber($line)),
158+
]
159+
);
160+
}
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+
}
143199
}

‎src/Internal/Ast/TypeDeducer.php‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
use TypePHP\Internal\Docblock\DocblockExtractor;
2121
use TypePHP\Internal\Docblock\DocblockNormalizer;
2222
use TypePHP\Internal\Docblock\DocblockParser;
23+
use TypePHP\Internal\Generics\TemplateSubstitutor;
24+
use TypePHP\Internal\Resolver\SpecialTypeResolver;
2325

2426
/**
2527
* Deduces element, key, and indexed member types from container type strings.
@@ -173,9 +175,17 @@ public static function deduceDimType(string $containerTypeString, ?Expr $dimExpr
173175

174176
/**
175177
* Deduces the property type of an object shape or class property access ($obj->prop).
178+
*
179+
* @param array<string, array<string, string>> $localPropertyTypes
180+
* @param array<string, list<string>> $localClassTemplates
176181
*/
177-
public static function deducePropertyType(string $containerTypeString, string $propName): ?string
178-
{
182+
public static function deducePropertyType(
183+
string $containerTypeString,
184+
string $propName,
185+
array $localPropertyTypes = [],
186+
array $localClassTemplates = [],
187+
string $currentFile = ''
188+
): ?string {
179189
$typeNode = self::parseTypeString($containerTypeString);
180190
if ($typeNode === null) {
181191
return null;
@@ -185,6 +195,10 @@ public static function deducePropertyType(string $containerTypeString, string $p
185195
$typeNode = $typeNode->type;
186196
}
187197

198+
if ($currentFile !== '') {
199+
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile);
200+
}
201+
188202
if ($typeNode instanceof ObjectShapeNode) {
189203
foreach ($typeNode->items as $item) {
190204
$name = $item->keyName instanceof IdentifierTypeNode
@@ -199,6 +213,15 @@ public static function deducePropertyType(string $containerTypeString, string $p
199213

200214
if ($typeNode instanceof IdentifierTypeNode) {
201215
$className = $typeNode->name;
216+
$shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className;
217+
218+
if (isset($localPropertyTypes[$className][$propName])) {
219+
return $localPropertyTypes[$className][$propName];
220+
}
221+
if (isset($localPropertyTypes[$shortName][$propName])) {
222+
return $localPropertyTypes[$shortName][$propName];
223+
}
224+
202225
if (
203226
class_exists($className, false) || class_exists($className)
204227
|| interface_exists($className, false) || interface_exists($className)
@@ -211,6 +234,70 @@ class_exists($className, false) || class_exists($className)
211234
}
212235
}
213236

237+
if ($typeNode instanceof GenericTypeNode) {
238+
$baseType = $typeNode->type;
239+
$className = $baseType instanceof IdentifierTypeNode ? $baseType->name : (string) $baseType;
240+
$shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className;
241+
242+
$rawPropType = null;
243+
$templateNames = null;
244+
245+
if (isset($localPropertyTypes[$className][$propName])) {
246+
$rawPropType = $localPropertyTypes[$className][$propName];
247+
$templateNames = $localClassTemplates[$className] ?? ($localClassTemplates[$shortName] ?? null);
248+
} elseif (isset($localPropertyTypes[$shortName][$propName])) {
249+
$rawPropType = $localPropertyTypes[$shortName][$propName];
250+
$templateNames = $localClassTemplates[$shortName] ?? ($localClassTemplates[$className] ?? null);
251+
}
252+
253+
if ($rawPropType === null) {
254+
if (
255+
class_exists($className, false) || class_exists($className)
256+
|| interface_exists($className, false) || interface_exists($className)
257+
|| trait_exists($className, false) || trait_exists($className)
258+
) {
259+
$parsedProp = DocblockParser::parseProperty($className, $propName);
260+
if ($parsedProp !== null) {
261+
$rawPropType = $parsedProp;
262+
}
263+
$templates = DocblockParser::parseClassTemplates($className);
264+
if ($templates !== []) {
265+
$templateNames = array_keys($templates);
266+
}
267+
}
268+
}
269+
270+
if ($rawPropType !== null) {
271+
$propTypeNode = \is_string($rawPropType) ? self::parseTypeString($rawPropType) : $rawPropType;
272+
if ($propTypeNode === null) {
273+
return \is_string($rawPropType) ? $rawPropType : (string) $rawPropType;
274+
}
275+
276+
if ($templateNames !== null && $templateNames !== []) {
277+
$bindings = [];
278+
if (\count($templateNames) === 2 && \count($typeNode->genericTypes) === 1) {
279+
$firstLower = strtolower($templateNames[0]);
280+
if ($firstLower === 'k' || $firstLower === 'tkey' || $firstLower === 'key') {
281+
$bindings[$templateNames[0]] = new IdentifierTypeNode('array-key');
282+
$bindings[$templateNames[1]] = $typeNode->genericTypes[0];
283+
}
284+
} else {
285+
foreach ($templateNames as $idx => $tName) {
286+
if (isset($typeNode->genericTypes[$idx])) {
287+
$bindings[$tName] = $typeNode->genericTypes[$idx];
288+
}
289+
}
290+
}
291+
292+
if ($bindings !== []) {
293+
$propTypeNode = TemplateSubstitutor::substitute($propTypeNode, $bindings);
294+
}
295+
}
296+
297+
return (string) $propTypeNode;
298+
}
299+
}
300+
214301
return null;
215302
}
216303

‎src/Internal/Checker/ConditionalChecker.php‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,17 @@ public static function resolveTemplateConditional(
293293
string $function = ''
294294
): TypeNode {
295295
$subjectTypeNode = $node->subjectType;
296-
if ($subjectTypeNode instanceof IdentifierTypeNode && isset($boundTemplates[$subjectTypeNode->name])) {
297-
$subjectTypeNode = $boundTemplates[$subjectTypeNode->name];
296+
if ($subjectTypeNode instanceof IdentifierTypeNode) {
297+
if (isset($boundTemplates[$subjectTypeNode->name])) {
298+
$subjectTypeNode = $boundTemplates[$subjectTypeNode->name];
299+
} elseif ($function !== '') {
300+
$contract = DocblockParser::parse($function);
301+
$allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
302+
if (isset($allTemplates[$subjectTypeNode->name])) {
303+
$templateTag = $allTemplates[$subjectTypeNode->name];
304+
$subjectTypeNode = $templateTag->default ?? $templateTag->bound ?? $subjectTypeNode;
305+
}
306+
}
298307
}
299308

300309
$isTargetMatch = TemplateManager::checkVariance($subjectTypeNode, $node->targetType, GenericTypeNode::VARIANCE_COVARIANT);

0 commit comments

Comments
 (0)