Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
348 changes: 326 additions & 22 deletions src/Internal/Ast/ContractVisitor.php

Large diffs are not rendered by default.

47 changes: 35 additions & 12 deletions src/Internal/Ast/FunctionContractInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public static function inject(
$hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance));

$hasParam = ($isMagicGet || $isMagicCall) || ($paramCount > 0 && (
str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc) && str_contains($docText, '$'))
str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc || $hasParamOutDoc) && str_contains($docText, '$'))
)) || self::hasParamContracts(
$docText,
$isClassMethod,
Expand Down Expand Up @@ -552,8 +552,15 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b
*
* @return array<Node\Stmt>
*/
public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr $thisArg): array
{
public static function buildParamOutCheckStmts(
array $byRefParamNames,
Node\Expr $thisArg,
bool $needsReturnVars = false
): array {
$varsArg = $needsReturnVars
? new Node\Expr\Variable('_typephpArgs')
: new Node\Expr\Array_();

$stmts = [];
foreach ($byRefParamNames as $pName) {
$checkCall = new Node\Expr\FuncCall(
Expand All @@ -563,6 +570,7 @@ public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr
new Node\Arg(new Node\Scalar\String_($pName)),
new Node\Arg(new Node\Expr\Variable($pName)),
new Node\Arg($thisArg),
new Node\Arg($varsArg),
]
);

Expand Down Expand Up @@ -798,8 +806,13 @@ public static function buildParamOutGuardExpr(
array $byRefParamNames,
Node\Expr $innerExpr,
Node\Expr $thisArg,
?int $line = null
?int $line = null,
bool $needsReturnVars = false
): Node\Expr {
$varsArg = $needsReturnVars
? new Node\Expr\Variable('_typephpArgs')
: new Node\Expr\Array_();

$expr = $innerExpr;
foreach (array_reverse($byRefParamNames) as $pName) {
$checkCall = new Node\Expr\FuncCall(
Expand All @@ -809,6 +822,7 @@ public static function buildParamOutGuardExpr(
new Node\Arg(new Node\Scalar\String_($pName)),
new Node\Arg(new Node\Expr\Variable($pName)),
new Node\Arg($thisArg),
new Node\Arg($varsArg),
]
);

Expand All @@ -833,7 +847,8 @@ public static function buildWrappedYieldNode(
Node\Expr $thisArg,
bool $wrapYield = true,
bool $wrapSend = true,
array $byRefParams = []
array $byRefParams = [],
bool $needsReturnVars = false
): Node\Expr {
if ($wrapYield) {
$checkYieldCall = new Node\Expr\FuncCall(
Expand All @@ -858,7 +873,7 @@ 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());
$n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine(), $needsReturnVars);
}

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

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

if ($n instanceof Node\Expr\YieldFrom) {
Expand Down Expand Up @@ -1025,7 +1047,8 @@ public function enterNode(Node $n): int|Node|array|null
$this->byRefParams,
$n->expr,
$this->thisArg,
$n->getStartLine()
$n->getStartLine(),
$this->needsReturnVars
);
}

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

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

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

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

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

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

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

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

if ($paramOutStmts !== []) {
Expand Down
56 changes: 56 additions & 0 deletions src/Internal/Ast/NodeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,60 @@ public static function createPropertyMemberAssignCheckCall(
]
);
}

public static function createConstantCheckCall(
string $constantName,
Node\Expr $valueExpr,
string $typeString,
int $line
): Node\Expr\FuncCall {
return new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstant'),
[
new Node\Arg(new Node\Scalar\String_($constantName)),
new Node\Arg($valueExpr),
new Node\Arg(new Node\Scalar\String_($typeString)),
new Node\Arg(new Node\Scalar\MagicConst\File()),
new Node\Arg(new Node\Scalar\LNumber($line)),
]
);
}

public static function createConstantClosureParamCheckCall(
string $caller,
string $paramName,
Node\Expr $paramVar,
string $typeString,
int $line
): Node\Expr\FuncCall {
return new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam'),
[
new Node\Arg(new Node\Scalar\String_($caller)),
new Node\Arg(new Node\Scalar\String_($paramName)),
new Node\Arg($paramVar),
new Node\Arg(new Node\Scalar\String_($typeString)),
new Node\Arg(new Node\Scalar\MagicConst\File()),
new Node\Arg(new Node\Scalar\LNumber($line)),
]
);
}

public static function createConstantClosureReturnCheckCall(
string $caller,
Node\Expr $valueExpr,
string $typeString,
int $line
): Node\Expr\FuncCall {
return new Node\Expr\FuncCall(
new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn'),
[
new Node\Arg(new Node\Scalar\String_($caller)),
new Node\Arg($valueExpr),
new Node\Arg(new Node\Scalar\String_($typeString)),
new Node\Arg(new Node\Scalar\MagicConst\File()),
new Node\Arg(new Node\Scalar\LNumber($line)),
]
);
}
}
91 changes: 89 additions & 2 deletions src/Internal/Ast/TypeDeducer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
use TypePHP\Internal\Docblock\DocblockExtractor;
use TypePHP\Internal\Docblock\DocblockNormalizer;
use TypePHP\Internal\Docblock\DocblockParser;
use TypePHP\Internal\Generics\TemplateSubstitutor;
use TypePHP\Internal\Resolver\SpecialTypeResolver;

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

/**
* Deduces the property type of an object shape or class property access ($obj->prop).
*
* @param array<string, array<string, string>> $localPropertyTypes
* @param array<string, list<string>> $localClassTemplates
*/
public static function deducePropertyType(string $containerTypeString, string $propName): ?string
{
public static function deducePropertyType(
string $containerTypeString,
string $propName,
array $localPropertyTypes = [],
array $localClassTemplates = [],
string $currentFile = ''
): ?string {
$typeNode = self::parseTypeString($containerTypeString);
if ($typeNode === null) {
return null;
Expand All @@ -185,6 +195,10 @@ public static function deducePropertyType(string $containerTypeString, string $p
$typeNode = $typeNode->type;
}

if ($currentFile !== '') {
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile);
}

if ($typeNode instanceof ObjectShapeNode) {
foreach ($typeNode->items as $item) {
$name = $item->keyName instanceof IdentifierTypeNode
Expand All @@ -199,6 +213,15 @@ public static function deducePropertyType(string $containerTypeString, string $p

if ($typeNode instanceof IdentifierTypeNode) {
$className = $typeNode->name;
$shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className;

if (isset($localPropertyTypes[$className][$propName])) {
return $localPropertyTypes[$className][$propName];
}
if (isset($localPropertyTypes[$shortName][$propName])) {
return $localPropertyTypes[$shortName][$propName];
}

if (
class_exists($className, false) || class_exists($className)
|| interface_exists($className, false) || interface_exists($className)
Expand All @@ -211,6 +234,70 @@ class_exists($className, false) || class_exists($className)
}
}

if ($typeNode instanceof GenericTypeNode) {
$baseType = $typeNode->type;
$className = $baseType instanceof IdentifierTypeNode ? $baseType->name : (string) $baseType;
$shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className;

$rawPropType = null;
$templateNames = null;

if (isset($localPropertyTypes[$className][$propName])) {
$rawPropType = $localPropertyTypes[$className][$propName];
$templateNames = $localClassTemplates[$className] ?? ($localClassTemplates[$shortName] ?? null);
} elseif (isset($localPropertyTypes[$shortName][$propName])) {
$rawPropType = $localPropertyTypes[$shortName][$propName];
$templateNames = $localClassTemplates[$shortName] ?? ($localClassTemplates[$className] ?? null);
}

if ($rawPropType === null) {
if (
class_exists($className, false) || class_exists($className)
|| interface_exists($className, false) || interface_exists($className)
|| trait_exists($className, false) || trait_exists($className)
) {
$parsedProp = DocblockParser::parseProperty($className, $propName);
if ($parsedProp !== null) {
$rawPropType = $parsedProp;
}
$templates = DocblockParser::parseClassTemplates($className);
if ($templates !== []) {
$templateNames = array_keys($templates);
}
}
}

if ($rawPropType !== null) {
$propTypeNode = \is_string($rawPropType) ? self::parseTypeString($rawPropType) : $rawPropType;
if ($propTypeNode === null) {
return \is_string($rawPropType) ? $rawPropType : (string) $rawPropType;
}

if ($templateNames !== null && $templateNames !== []) {
$bindings = [];
if (\count($templateNames) === 2 && \count($typeNode->genericTypes) === 1) {
$firstLower = strtolower($templateNames[0]);
if ($firstLower === 'k' || $firstLower === 'tkey' || $firstLower === 'key') {
$bindings[$templateNames[0]] = new IdentifierTypeNode('array-key');
$bindings[$templateNames[1]] = $typeNode->genericTypes[0];
}
} else {
foreach ($templateNames as $idx => $tName) {
if (isset($typeNode->genericTypes[$idx])) {
$bindings[$tName] = $typeNode->genericTypes[$idx];
}
}
}

if ($bindings !== []) {
$propTypeNode = TemplateSubstitutor::substitute($propTypeNode, $bindings);
}
}

return (string) $propTypeNode;
}
}

return null;
}

Expand Down
13 changes: 11 additions & 2 deletions src/Internal/Checker/ConditionalChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,17 @@ public static function resolveTemplateConditional(
string $function = ''
): TypeNode {
$subjectTypeNode = $node->subjectType;
if ($subjectTypeNode instanceof IdentifierTypeNode && isset($boundTemplates[$subjectTypeNode->name])) {
$subjectTypeNode = $boundTemplates[$subjectTypeNode->name];
if ($subjectTypeNode instanceof IdentifierTypeNode) {
if (isset($boundTemplates[$subjectTypeNode->name])) {
$subjectTypeNode = $boundTemplates[$subjectTypeNode->name];
} elseif ($function !== '') {
$contract = DocblockParser::parse($function);
$allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
if (isset($allTemplates[$subjectTypeNode->name])) {
$templateTag = $allTemplates[$subjectTypeNode->name];
$subjectTypeNode = $templateTag->default ?? $templateTag->bound ?? $subjectTypeNode;
}
}
}

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