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
1 change: 1 addition & 0 deletions conf/bleedingEdge.neon
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ parameters:
checkMoreParameterCastableToStringFunctions: true
checkTemplateTypeBounds: true
reportTemplateInImportedTypeAlias: true
checkAssertTagsCompatibility: true
checkConditionalParameterTypes: true
checkMixedWitnessTypes: true
recursiveLoopTypes: true
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ parameters:
checkMoreParameterCastableToStringFunctions: false
checkTemplateTypeBounds: false
reportTemplateInImportedTypeAlias: false
checkAssertTagsCompatibility: false
checkConditionalParameterTypes: false
checkMixedWitnessTypes: false
recursiveLoopTypes: false
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ parametersSchema:
checkMoreParameterCastableToStringFunctions: bool()
checkTemplateTypeBounds: bool()
reportTemplateInImportedTypeAlias: bool()
checkAssertTagsCompatibility: bool()
checkConditionalParameterTypes: bool()
checkMixedWitnessTypes: bool()
recursiveLoopTypes: bool()
Expand Down
7 changes: 4 additions & 3 deletions src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,7 @@ public function createIssetSingleSubjectNonTrueTypes(
* result-carried structure (impure gate, nullsafe twin) instead of
* create()'s scope re-probing.
*/
public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike $call, Assertions $assertions, ParametersAcceptor $parametersAcceptor, MutatingScope $scope): ?SpecifiedTypes
public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike|PropertyFetch $call, Assertions $assertions, ParametersAcceptor $parametersAcceptor, MutatingScope $scope): ?SpecifiedTypes
{
if ($context->null()) {
$asserts = $assertions->getAsserts();
Expand All @@ -875,7 +875,8 @@ public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike

$argsMap = [];
$parameters = $parametersAcceptor->getParameters();
foreach ($call->getArgs() as $i => $arg) {
// a property fetch (its get hook's asserts) has no arguments
foreach ($call instanceof PropertyFetch ? [] : $call->getArgs() as $i => $arg) {
if ($arg->unpack) {
continue;
}
Expand All @@ -902,7 +903,7 @@ public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike
$argsMap[$name][] = new TypeExpr($defaultValue);
}

if ($call instanceof MethodCall) {
if ($call instanceof MethodCall || $call instanceof PropertyFetch) {
$argsMap['this'] = [$call->var];
}

Expand Down
32 changes: 31 additions & 1 deletion src/Analyser/ExprHandler/PropertyFetchHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\ExtendedMethodReflection;
use PHPStan\Rules\Properties\FoundPropertyReflection;
use PHPStan\Rules\Properties\PropertyReflectionFinder;
use PHPStan\ShouldNotHappenException;
Expand Down Expand Up @@ -87,13 +88,17 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc
$isAlwaysTerminating = $varResult->isAlwaysTerminating();
$scope = $varResult->getScope();
$mayShortCircuit = false;
$getHook = null;
if ($expr->name instanceof Identifier) {
$supportsPropertyHooks = $scopeBeforeVar->getPhpVersion()->supportsPropertyHooks();
if ($this->checkWholePhpVersionRange ? !$supportsPropertyHooks->no() : $supportsPropertyHooks->yes()) {
$propertyName = $expr->name->toString();
$propertyHolderType = $varResult->getType();
$propertyReflection = $scopeBeforeVar->getInstancePropertyReflection($propertyHolderType, $propertyName);
if ($propertyReflection !== null) {
if ($propertyReflection->hasHook('get')) {
$getHook = $propertyReflection->getHook('get');
}
$propertyDeclaringClass = $propertyReflection->getDeclaringClass();
if ($propertyDeclaringClass->hasNativeProperty($propertyName)) {
$nativeProperty = $propertyDeclaringClass->getNativeProperty($propertyName);
Expand Down Expand Up @@ -196,7 +201,7 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc

return new MixedType();
},
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted),
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->specifyTypes($expr, $varResult, $getHook, $context, $beforeScope, $nativeTypesPromoted),
);
return $result->withDependencies(Dependencies::merge(
$varResult->getDependencies(),
Expand All @@ -205,6 +210,31 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc
));
}

/**
* The default narrowing of the fetch, plus the @phpstan-assert tags of the
* property's get hook (written above the property), with $this standing
* for the fetch's receiver - like the asserts of a method call.
*/
private function specifyTypes(PropertyFetch $expr, ExpressionResult $varResult, ?ExtendedMethodReflection $getHook, TypeSpecifierContext $context, MutatingScope $beforeScope, bool $nativeTypesPromoted): SpecifiedTypes
{
$defaultTypes = $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted);
if ($getHook === null || $getHook->getAsserts()->getAll() === []) {
return $defaultTypes;
}

$scope = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
if ($this->defaultNarrowingHelper->callMayHaveBeenSkipped($varResult, $varResult->getTypeOnScope($scope, $nativeTypesPromoted), $context)) {
return $defaultTypes;
}

$assertTypes = $this->defaultNarrowingHelper->specifyTypesFromAsserts($context, $expr, $getHook->getAsserts(), $getHook->getOnlyVariant(), $scope);
if ($assertTypes === null) {
return $defaultTypes;
}

return $assertTypes->unionWith($defaultTypes)->setRootExpr($assertTypes->getRootExpr());
}

/**
* The classes of the object the property is fetched from, the class declaring it, and the classes
* in its type.
Expand Down
43 changes: 35 additions & 8 deletions src/PhpDoc/PhpDocInheritanceResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
use PHPStan\Type\FileTypeMapper;
use function array_key_exists;
use function count;
use function explode;
use function is_bool;
use function str_starts_with;
use function strtolower;
use function substr;

#[AutowiredService]
final class PhpDocInheritanceResolver
Expand Down Expand Up @@ -83,8 +86,8 @@ public function resolvePhpDocForMethod(
{
$parent = $declaringClass->getParentClass();
if ($parent !== null) {
if ($parent->hasNativeMethod($methodName)) {
$parentMethod = $parent->getNativeMethod($methodName);
$parentMethod = $this->findNativeMethodOrHook($parent, $methodName);
if ($parentMethod !== null) {
if (!$parentMethod->isPrivate() && $parentMethod->getResolvedPhpDoc() !== null) {
if ($parentMethod->getName() !== '__construct' || !$parentMethod->getDeclaringClass()->isBuiltin()) {
return $this->resolveMethodPhpDocFromParentClass($parentMethod, $parentMethod->getResolvedPhpDoc(), $declaringClass, $parent, $currentResolvedPhpDoc, $currentPositionalParameterNames);
Expand All @@ -94,12 +97,8 @@ public function resolvePhpDocForMethod(
}

foreach ($declaringClass->getImmediateInterfaces() as $interface) {
if (!$interface->hasNativeMethod($methodName)) {
continue;
}

$interfaceMethod = $interface->getNativeMethod($methodName);
if ($interfaceMethod->isPrivate()) {
$interfaceMethod = $this->findNativeMethodOrHook($interface, $methodName);
if ($interfaceMethod === null || $interfaceMethod->isPrivate()) {
continue;
}
if ($interfaceMethod->getResolvedPhpDoc() === null) {
Expand Down Expand Up @@ -145,6 +144,34 @@ public function resolvePhpDocForMethod(
return $currentResolvedPhpDoc;
}

/**
* Property hooks are named like `$property::get`, so they inherit PHPDocs
* from the same hook of the overridden property, the way methods do.
*/
private function findNativeMethodOrHook(ClassReflection $classReflection, string $methodName): ?ExtendedMethodReflection
{
if (!str_starts_with($methodName, '$')) {
return $classReflection->hasNativeMethod($methodName) ? $classReflection->getNativeMethod($methodName) : null;
}

$parts = explode('::', substr($methodName, 1), 2);
if (count($parts) !== 2 || ($parts[1] !== 'get' && $parts[1] !== 'set')) {
return null;
}

[$propertyName, $hookName] = $parts;
if (!$classReflection->hasNativeProperty($propertyName)) {
return null;
}

$property = $classReflection->getNativeProperty($propertyName);
if ($property->isPrivate() || !$property->hasHook($hookName)) {
return null;
}

return $property->getHook($hookName);
}

/**
* @param array<int, string> $currentPositionalParameterNames
*/
Expand Down
45 changes: 45 additions & 0 deletions src/PhpDoc/Tag/AssertTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ReferencedByTurboExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_map;
use function count;

/** @api */
#[ReferencedByTurboExtension(key: 'assertTag')]
Expand Down Expand Up @@ -85,6 +88,48 @@ public function negate(): self
return $tag;
}

/**
* What the other branch of a conditional assert says: the tags hold
* together, so when they don't, at least one of them is false.
* `-if-true A $x` with `-if-true B $y` means that a false result says
* $x is not A *or* $y is not B, which narrows neither of them.
*
* @param list<self> $tags
* @return list<self>
*/
public static function negateConjunction(array $tags): array
{
if (count($tags) <= 1) {
return array_map(static fn (self $tag): self => $tag->negate(), $tags);
}

$subject = $tags[0]->parameter->describe();
$types = [];
$originalTypes = [];
foreach ($tags as $tag) {
if ($tag->negated !== $tags[0]->negated || $tag->parameter->describe() !== $subject) {
return [];
}

$types[] = $tag->type;
$originalTypes[] = $tag->getOriginalType();
}

// not (A and B) is "not A&B"; not (not A and not B) is "A|B"
if ($tags[0]->negated) {
$type = TypeCombinator::union(...$types);
$originalType = TypeCombinator::union(...$originalTypes);
} else {
$type = TypeCombinator::intersect(...$types);
$originalType = TypeCombinator::intersect(...$originalTypes);
}

$tag = new self($tags[0]->if, $type, $tags[0]->parameter, !$tags[0]->negated, false, $tags[0]->isExplicit);
$tag->originalType = $originalType;

return [$tag];
}

public function isExplicit(): bool
{
return $this->isExplicit;
Expand Down
20 changes: 11 additions & 9 deletions src/Reflection/Assertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
*
* This class collects all such assertions and provides methods to retrieve them
* by condition type. It also handles negation: an `@phpstan-assert-if-true` assertion
* is automatically negated and included in the `getAssertsIfFalse()` result.
* is automatically negated and included in the `getAssertsIfFalse()` result
* (several of them only when they are all about the same expression, see
* AssertTag::negateConjunction()).
*
* Returned by ExtendedMethodReflection::getAsserts() and FunctionReflection::getAsserts().
*
Expand Down Expand Up @@ -59,43 +61,43 @@ public function getAsserts(): array
}

/**
* Includes @phpstan-assert-if-true tags and negated @phpstan-assert-if-false tags.
* Includes @phpstan-assert-if-true tags and the negation of the @phpstan-assert-if-false tags.
*
* @return AssertTag[]
*/
public function getAssertsIfTrue(): array
{
$asserts = [];
$negatedAsserts = [];
$oppositeAsserts = [];
foreach ($this->asserts as $assert) {
if ($assert->getIf() === AssertTag::IF_TRUE) {
$asserts[] = $assert;
} elseif ($assert->getIf() === AssertTag::IF_FALSE && !$assert->isEquality()) {
$negatedAsserts[] = $assert->negate();
$oppositeAsserts[] = $assert;
}
}

return array_merge($asserts, $negatedAsserts);
return array_merge($asserts, AssertTag::negateConjunction($oppositeAsserts));
}

/**
* Includes @phpstan-assert-if-false tags and negated @phpstan-assert-if-true tags.
* Includes @phpstan-assert-if-false tags and the negation of the @phpstan-assert-if-true tags.
*
* @return AssertTag[]
*/
public function getAssertsIfFalse(): array
{
$asserts = [];
$negatedAsserts = [];
$oppositeAsserts = [];
foreach ($this->asserts as $assert) {
if ($assert->getIf() === AssertTag::IF_FALSE) {
$asserts[] = $assert;
} elseif ($assert->getIf() === AssertTag::IF_TRUE && !$assert->isEquality()) {
$negatedAsserts[] = $assert->negate();
$oppositeAsserts[] = $assert;
}
}

return array_merge($asserts, $negatedAsserts);
return array_merge($asserts, AssertTag::negateConjunction($oppositeAsserts));
}

/** @param callable(Type): Type $callable */
Expand Down
29 changes: 29 additions & 0 deletions src/Rules/Methods/MethodSignatureRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHPStan\Reflection\ExtendedParameterReflection;
use PHPStan\Reflection\ExtendedParametersAcceptor;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\PhpDoc\OverridingAssertsCheck;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
Expand All @@ -30,6 +31,7 @@
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\VerbosityLevel;
use function array_key_exists;
use function array_merge;
use function count;
use function min;
use function sprintf;
Expand All @@ -51,6 +53,9 @@ public function __construct(
private bool $reportStatic,
#[AutowiredParameter(ref: '%featureToggles.reportMethodPurityOverride%')]
private bool $reportMethodPurityOverride,
private OverridingAssertsCheck $overridingAssertsCheck,
#[AutowiredParameter(ref: '%featureToggles.checkAssertTagsCompatibility%')]
private bool $checkAssertTagsCompatibility,
)
{
}
Expand Down Expand Up @@ -115,6 +120,30 @@ public function processNode(Node $node, Scope $scope): array
continue;
}
$parentVariant = $parentVariants[0];
if ($this->checkAssertTagsCompatibility) {
$parameterNameMapping = ['this' => 'this'];
$parameterTypes = [];
foreach ($parentVariant->getParameters() as $i => $parentParameter) {
$parameterTypes[$parentParameter->getName()] = $parentParameter->getType();
if (!isset($method->getParameters()[$i])) {
continue;
}
$parameterNameMapping[$parentParameter->getName()] = $method->getParameters()[$i]->getName();
}
$errors = array_merge($errors, $this->overridingAssertsCheck->check(
$method->getAsserts(),
$method->getReturnType(),
sprintf('method %s::%s()', $declaringClass->getDisplayName(), $method->getName()),
$declaringClass,
$parentMethod->getAsserts(),
sprintf('method %s::%s()', $parentMethodDeclaringClass->getDisplayName(), $parentMethod->getName()),
$parentMethodDeclaringClass,
$parameterNameMapping,
$parameterTypes,
'it returns',
'method.childAssertType',
));
}
[$returnTypeCompatibility, $returnType, $parentReturnType] = $this->checkReturnTypeCompatibility($declaringClass, $method, $parentVariant);
if ($returnTypeCompatibility->no() || (!$returnTypeCompatibility->yes() && $this->reportMaybes)) {
$builder = RuleErrorBuilder::message(sprintf(
Expand Down
Loading
Loading