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
120 changes: 102 additions & 18 deletions src/Internal/Ast/ContractVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public static function reset(): void
private string $currentNamespace = '';

/**
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool, aliases?: array<string, TypeNode>, templates?: array<string, TemplateTagValueNode>}>
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool, aliases?: array<string, TypeNode>, templates?: array<string, TemplateTagValueNode>, unannotatedProps?: array<string, true>}>
*/
private array $classStack = [];

Expand Down Expand Up @@ -309,8 +309,20 @@ public function enterNode(Node $node): Node|array|null
return $this->handleExpression($node);
}

if ($node instanceof Node\Expr\ArrowFunction) {
$node->expr->setAttribute('typephp_is_standalone', true);
if ($node instanceof Node\Stmt\For_) {
$doc = $node->getDocComment();
if ($doc !== null && str_contains($doc->getText(), '@var')) {
$this->scopeManager->extractVarDocblock($doc->getText());
}

foreach ($node->init as $initExpr) {
$initExpr->setAttribute('typephp_is_standalone', true);
}
foreach ($node->loop as $loopExpr) {
$loopExpr->setAttribute('typephp_is_standalone', true);
}

return null;
}

if ($node instanceof Node\Stmt\Foreach_) {
Expand Down Expand Up @@ -404,10 +416,6 @@ public function leaveNode(Node $node): Node|array|null
}

if ($node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PreDec || $node instanceof Node\Expr\PostDec) {
if (($node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec) && $node->getAttribute('typephp_is_standalone') !== true) {
return null;
}

$replacement = $this->handleIncDec($node);
if ($replacement !== null) {
return $replacement;
Expand Down Expand Up @@ -1154,13 +1162,15 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
$hasInheritance = true;
}

if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) {
$declaredPropsWithoutDoc = [];

if ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\Property) {
$pDoc = $stmt->getDocComment();
if ($pDoc !== null && str_contains($pDoc->getText(), '@var')) {
$varTag = DocblockExtractor::extractVarTagFromDoc($pDoc->getText());
if ($varTag !== null) {
if ($varTag !== null && $typeName !== null) {
foreach ($stmt->props as $p) {
$propName = $p->name->toString();
$this->localClassPropertyTypes[$typeName][$propName] = $varTag[0];
Expand All @@ -1169,6 +1179,13 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
}
}
}
} elseif (! $stmt->isStatic()) {
foreach ($stmt->props as $p) {
$propName = $p->name->toString();
if ($typeName === null || ! StubManager::hasPropertyStub($typeName, $propName)) {
$declaredPropsWithoutDoc[$propName] = true;
}
}
}
} elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') {
$methodDoc = $stmt->getDocComment();
Expand All @@ -1192,18 +1209,21 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
if ($pType === null && $methodParamTags !== null && isset($methodParamTags[$paramName])) {
$pType = $methodParamTags[$paramName]->type;
}
if ($pType !== null) {
if ($pType !== null && $typeName !== null) {
$this->localClassPropertyTypes[$typeName][$paramName] = (string) $pType;
if ($shortName !== null) {
$this->localClassPropertyTypes[$shortName][$paramName] = (string) $pType;
}
} elseif ($pType === null && ($typeName === null || ! StubManager::hasPropertyStub($typeName, $paramName))) {
$declaredPropsWithoutDoc[$paramName] = true;
}
}
}
}
}
}

$hasMagicPropertyDoc = $doc !== null && str_contains($doc->getText(), '@property');
$classAliases = $this->extractClassLikeAliases($node, $doc, $typeName);

$this->classStack[] = [
Expand All @@ -1218,6 +1238,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
'isTrait' => $isTrait,
'aliases' => $classAliases,
'templates' => $templates,
'unannotatedProps' => (! $hasRealInheritance && ! $isTrait && ! $hasMagicPropertyDoc) ? $declaredPropsWithoutDoc : [],
];
}

Expand Down Expand Up @@ -2366,28 +2387,91 @@ private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool
private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr
{
$isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc;
$isPost = $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec;
$isStandalone = $node->getAttribute('typephp_is_standalone') === true;
$binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class;

if ($this->targetHasSideEffects($node->var)) {
$preAssignments = [];
$cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments);
$binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1));
/** @var list<Node\Expr\Assign|Node\Expr\AssignRef> $preAssignments */
$preAssignments = [];
$hasSideEffects = $this->targetHasSideEffects($node->var);
$cleanTarget = $hasSideEffects
? $this->hoistImpureTarget($node->var, $preAssignments)
: $node->var;

if ($isPost && ! $isStandalone) {
if ($this->isProvablyUnannotatedThisProperty($cleanTarget)) {
return null;
}

$oldVar = new Node\Expr\Variable('__typephpOld' . $this->hoistTempCounter);
$binaryExpr = new $binaryClass(clone $oldVar, new Node\Scalar\LNumber(1));
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());

if ($wrapped === null) {
return null;
}

$this->hoistTempCounter++;
$this->markWriteContext($cleanTarget);
$preAssignments[] = new Node\Expr\Assign(clone $oldVar, clone $cleanTarget);
$preAssignments[] = new Node\Expr\Assign($cleanTarget, $wrapped);

return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped));
$expr = $this->wrapWithPreEvaluations($preAssignments, $oldVar);
$expr->setAttribute('typephp_needs_parens', true);

return $expr;
}

$binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1));
$binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1));
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());

$wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine());
if ($wrapped === null) {
return null;
}

if ($hasSideEffects) {
$this->markWriteContext($cleanTarget);
}

$assignExpr = new Node\Expr\Assign($cleanTarget, $wrapped);
$result = $preAssignments !== []
? $this->wrapWithPreEvaluations($preAssignments, $assignExpr)
: $assignExpr;

if (! $isStandalone) {
$result->setAttribute('typephp_needs_parens', true);
}

return $result;
}

private function isProvablyUnannotatedThisProperty(Node\Expr $target): bool
{
if (! Config::isEliminateStaticallyProvenChecksEnabled()) {
return false;
}

if (
! ($target instanceof Node\Expr\PropertyFetch)
|| ! ($target->var instanceof Node\Expr\Variable)
|| $target->var->name !== 'this'
|| ! ($target->name instanceof Node\Identifier)
) {
return false;
}

if ($this->classStack === []) {
return false;
}

$classInfo = end($this->classStack);
if (($classInfo['isTrait'] ?? false) || ($classInfo['hasRealInheritance'] ?? true)) {
return false;
}

$propName = $target->name->toString();

return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null;
return isset($classInfo['unannotatedProps'][$propName]);
}

private function targetHasSideEffects(Node $node): bool
Expand Down
48 changes: 40 additions & 8 deletions src/Internal/Checker/ParamChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,10 @@ public static function checkParams(
$selfVerifiedParams = [];

if ($allTemplates !== [] && $paramsUseGenerics && ($contract['paramsNeedPreInference'] ?? true)) {
self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates, $selfVerifiedParams);
$preInferErr = self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates, $selfVerifiedParams);
if ($preInferErr !== null) {
return $preInferErr;
}
}

$boundTemplates = [];
Expand Down Expand Up @@ -815,17 +818,20 @@ private static function preInferGenericTemplates(
array $templates,
array $classTemplates = [],
array &$selfVerifiedParams = []
): void {
): ?ErrorMessage {
if ($types === []) {
return;
return null;
}

$mask = self::$preInferMaskCache[$effectiveFunction] ??= self::computePreInferMask($types);

if (($mask & 1) !== 0) {
foreach ($vars as $v) {
if ($v instanceof \Closure) {
self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates);
$err = self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates);
if ($err !== null) {
return $err;
}

break;
}
Expand All @@ -843,6 +849,8 @@ private static function preInferGenericTemplates(
if (($mask & 8) !== 0) {
self::inferTemplatesFromGenericObjects($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates);
}

return null;
}

/**
Expand Down Expand Up @@ -930,10 +938,10 @@ private static function inferTemplatesFromClosures(
?object $thisObj,
array $templates,
array $classTemplates = []
): void {
): ?ErrorMessage {
$callableNodes = self::callableNodesFor($effectiveFunction, $types);
if (\count($callableNodes) === 0) {
return;
return null;
}

foreach ($callableNodes as $cParamName => $cTypeNode) {
Expand All @@ -956,9 +964,31 @@ private static function inferTemplatesFromClosures(
if ($inferredCandidate !== null) {
if ($targetObj !== null) {
$existingType = TemplateManager::getInstanceBoundTypeFast($targetObj, $tName);
if ($existingType !== null && TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)) {
continue;
if ($existingType !== null) {
$canRefine = TemplateManager::isFallbackBound($targetObj, $tName)
|| TemplateManager::isUnspecializedType($existingType);

if ($canRefine) {
if (
TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)
|| ! TemplateManager::checkVariance($inferredCandidate, $existingType, GenericTypeNode::VARIANCE_COVARIANT)
) {
continue;
}
} else {
if (! TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)) {
$cParamLabel = $closureParams[$idx]->getName();

return ErrorFactory::createError(
$effectiveFunction . '(): Argument $' . $cParamName . ' callback parameter $' . $cParamLabel . ' must be ' . $existingType . ' (or supertype), ' . $inferredCandidate . ' given'
);
}

continue;
}
}
} elseif (TemplateManager::isBound($effectiveFunction, null, $tName)) {
continue;
}

$templateTag = $templates[$tName];
Expand Down Expand Up @@ -988,6 +1018,8 @@ private static function inferTemplatesFromClosures(
// Silently ignore reflection errors
}
}

return null;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions src/Internal/Generics/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -3469,6 +3469,28 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str
return false;
}

if ($existing instanceof NullableTypeNode) {
$inner = $existing->type;
while ($inner instanceof NullableTypeNode) {
$inner = $inner->type;
}
$nullNode = self::$nullNode ??= new IdentifierTypeNode('null');
$existing = $inner instanceof UnionTypeNode
? new UnionTypeNode([...$inner->types, $nullNode])
: new UnionTypeNode([$inner, $nullNode]);
}

if ($expected instanceof NullableTypeNode) {
$inner = $expected->type;
while ($inner instanceof NullableTypeNode) {
$inner = $inner->type;
}
$nullNode = self::$nullNode ??= new IdentifierTypeNode('null');
$expected = $inner instanceof UnionTypeNode
? new UnionTypeNode([...$inner->types, $nullNode])
: new UnionTypeNode([$inner, $nullNode]);
}

if ($expected instanceof GenericTypeNode) {
$baseExpected = strtolower((string) $expected->type);
if ($baseExpected === 'key-of' || $baseExpected === 'value-of') {
Expand Down
Loading
Loading