-
Notifications
You must be signed in to change notification settings - Fork 541
Check printf parameter types #3977
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ondrejmirtes
merged 9 commits into
phpstan:2.1.x
from
schlndh:feature-checkPrintfParameterTypes
Sep 5, 2025
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c085116
Bleeding edge - check printf parameter types
schlndh 7dc3864
fix missing errors
schlndh e348973
simplify PrintfHelper
schlndh 2a81c1d
clean up
schlndh 0572069
replace match with switch
schlndh dd2ac67
fix printf type rule error messages
schlndh 6c3114f
remove unused phpdoc type
schlndh 5d8709e
fix CR issues
schlndh 89641e5
fix static analysis job with PHP 7.4
schlndh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Rules\Functions; | ||
|
||
use PhpParser\Node; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\Reflection\ReflectionProvider; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Rules\RuleErrorBuilder; | ||
use PHPStan\Rules\RuleLevelHelper; | ||
use PHPStan\Type\BooleanType; | ||
use PHPStan\Type\ErrorType; | ||
use PHPStan\Type\FloatType; | ||
use PHPStan\Type\IntegerType; | ||
use PHPStan\Type\NullType; | ||
use PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType; | ||
use PHPStan\Type\Type; | ||
use PHPStan\Type\TypeCombinator; | ||
use PHPStan\Type\VerbosityLevel; | ||
use function array_key_exists; | ||
use function count; | ||
use function sprintf; | ||
|
||
/** | ||
* @implements Rule<Node\Expr\FuncCall> | ||
*/ | ||
final class PrintfParameterTypeRule implements Rule | ||
{ | ||
|
||
private const FORMAT_ARGUMENT_POSITIONS = [ | ||
'printf' => 0, | ||
'sprintf' => 0, | ||
'fprintf' => 1, | ||
]; | ||
private const MINIMUM_NUMBER_OF_ARGUMENTS = [ | ||
'printf' => 1, | ||
'sprintf' => 1, | ||
'fprintf' => 2, | ||
]; | ||
|
||
public function __construct( | ||
private PrintfHelper $printfHelper, | ||
private ReflectionProvider $reflectionProvider, | ||
private RuleLevelHelper $ruleLevelHelper, | ||
) | ||
{ | ||
} | ||
|
||
public function getNodeType(): string | ||
{ | ||
return Node\Expr\FuncCall::class; | ||
} | ||
|
||
public function processNode(Node $node, Scope $scope): array | ||
{ | ||
if (!($node->name instanceof Node\Name)) { | ||
return []; | ||
} | ||
|
||
if (!$this->reflectionProvider->hasFunction($node->name, $scope)) { | ||
return []; | ||
} | ||
|
||
$functionReflection = $this->reflectionProvider->getFunction($node->name, $scope); | ||
$name = $functionReflection->getName(); | ||
if (!array_key_exists($name, self::FORMAT_ARGUMENT_POSITIONS)) { | ||
return []; | ||
} | ||
|
||
$formatArgumentPosition = self::FORMAT_ARGUMENT_POSITIONS[$name]; | ||
|
||
$args = $node->getArgs(); | ||
foreach ($args as $arg) { | ||
if ($arg->unpack) { | ||
return []; | ||
} | ||
} | ||
$argsCount = count($args); | ||
if ($argsCount < self::MINIMUM_NUMBER_OF_ARGUMENTS[$name]) { | ||
return []; // caught by CallToFunctionParametersRule | ||
} | ||
|
||
$formatArgType = $scope->getType($args[$formatArgumentPosition]->value); | ||
$formatArgTypeStrings = $formatArgType->getConstantStrings(); | ||
|
||
// Let's start simple for now. | ||
if (count($formatArgTypeStrings) !== 1) { | ||
return []; | ||
} | ||
|
||
$formatString = $formatArgTypeStrings[0]; | ||
$format = $formatString->getValue(); | ||
$placeholderMap = $this->printfHelper->getPrintfPlaceholders($format); | ||
$errors = []; | ||
$typeAllowedByCallToFunctionParametersRule = TypeCombinator::union( | ||
new StringAlwaysAcceptingObjectWithToStringType(), | ||
new IntegerType(), | ||
new FloatType(), | ||
new BooleanType(), | ||
new NullType(), | ||
); | ||
// Type on the left can go to the type on the right, but not vice versa. | ||
$allowedTypeNameMap = [ | ||
'strict-int' => 'int', | ||
'int' => 'castable to int', | ||
'float' => 'castable to float', | ||
// These are here just for completeness. They won't be used because, these types are already enforced by | ||
// CallToFunctionParametersRule. | ||
'string' => 'castable to string', | ||
'mixed' => 'castable to string', | ||
]; | ||
|
||
for ($i = $formatArgumentPosition + 1, $j = 0; $i < $argsCount; $i++, $j++) { | ||
// Some arguments may be skipped entirely. | ||
foreach ($placeholderMap[$j] ?? [] as $placeholder) { | ||
$argType = $this->ruleLevelHelper->findTypeToCheck( | ||
$scope, | ||
$args[$i]->value, | ||
'', | ||
static fn (Type $t) => $placeholder->doesArgumentTypeMatchPlaceholder($t), | ||
)->getType(); | ||
|
||
if ($argType instanceof ErrorType || $placeholder->doesArgumentTypeMatchPlaceholder($argType)) { | ||
continue; | ||
} | ||
|
||
// This is already reported by CallToFunctionParametersRule | ||
if ( | ||
!$this->ruleLevelHelper->accepts( | ||
$typeAllowedByCallToFunctionParametersRule, | ||
$argType, | ||
$scope->isDeclareStrictTypes(), | ||
)->result | ||
) { | ||
continue; | ||
} | ||
|
||
$errors[] = RuleErrorBuilder::message( | ||
sprintf( | ||
'Parameter #%d of function %s is expected to be %s by placeholder #%d (%s), %s given.', | ||
$i + 1, | ||
$name, | ||
$allowedTypeNameMap[$placeholder->acceptingType], | ||
$placeholder->placeholderNumber, | ||
$placeholder->label, | ||
$argType->describe(VerbosityLevel::typeOnly()), | ||
), | ||
)->identifier('argument.type')->build(); | ||
} | ||
} | ||
|
||
return $errors; | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Rules\Functions; | ||
|
||
use PHPStan\ShouldNotHappenException; | ||
use PHPStan\Type\ErrorType; | ||
use PHPStan\Type\IntegerType; | ||
use PHPStan\Type\Type; | ||
|
||
final class PrintfPlaceholder | ||
{ | ||
|
||
/** @phpstan-param 'strict-int'|'int'|'float'|'string'|'mixed' $acceptingType */ | ||
public function __construct( | ||
public readonly string $label, | ||
public readonly int $parameterIndex, | ||
public readonly int $placeholderNumber, | ||
public readonly string $acceptingType, | ||
) | ||
{ | ||
} | ||
|
||
public function doesArgumentTypeMatchPlaceholder(Type $argumentType): bool | ||
{ | ||
switch ($this->acceptingType) { | ||
case 'strict-int': | ||
return (new IntegerType())->accepts($argumentType, true)->yes(); | ||
case 'int': | ||
return ! $argumentType->toInteger() instanceof ErrorType; | ||
case 'float': | ||
return ! $argumentType->toFloat() instanceof ErrorType; | ||
// The function signature already limits the parameters to stringable types, so there's | ||
// no point in checking string again here. | ||
case 'string': | ||
case 'mixed': | ||
return true; | ||
schlndh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Without this PHPStan with PHP 7.4 reports "...should return bool but return statement is missing." | ||
// Presumably, because promoted properties are turned into regular properties and the phpdoc isn't applied to the property. | ||
default: | ||
throw new ShouldNotHappenException('Unexpected type ' . $this->acceptingType); | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.