Skip to content

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

Open
wants to merge 5 commits into
base: 2.1.x
Choose a base branch
from
Open
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 @@ -6,3 +6,4 @@ parameters:
stricterFunctionMap: true
reportPreciseLineForUnusedFunctionParameter: true
internalTag: true
checkPrintfParameterTypes: true
4 changes: 4 additions & 0 deletions conf/config.level5.neon
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ parameters:
conditionalTags:
PHPStan\Rules\Functions\ParameterCastableToNumberRule:
phpstan.rules.rule: %featureToggles.checkParameterCastableToNumberFunctions%
PHPStan\Rules\Functions\PrintfParameterTypeRule:
phpstan.rules.rule: %featureToggles.checkPrintfParameterTypes%

rules:
- PHPStan\Rules\DateTimeInstantiationRule
Expand Down Expand Up @@ -42,3 +44,5 @@ services:
- phpstan.rules.rule
-
class: PHPStan\Rules\Functions\ParameterCastableToNumberRule
-
class: PHPStan\Rules\Functions\PrintfParameterTypeRule
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ parameters:
stricterFunctionMap: false
reportPreciseLineForUnusedFunctionParameter: false
internalTag: false
checkPrintfParameterTypes: false
fileExtensions:
- php
checkAdvancedIsset: false
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ parametersSchema:
stricterFunctionMap: bool()
reportPreciseLineForUnusedFunctionParameter: bool()
internalTag: bool()
checkPrintfParameterTypes: bool()
])
fileExtensions: listOf(string())
checkAdvancedIsset: bool()
Expand Down
141 changes: 126 additions & 15 deletions src/Rules/Functions/PrintfHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,104 @@

use Nette\Utils\Strings;
use PHPStan\Php\PhpVersion;
use PHPStan\Type\ErrorType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\Type;
use function array_filter;
use function array_flip;
use function array_keys;
use function array_map;
use function array_reduce;
use function count;
use function in_array;
use function max;
use function sort;
use function sprintf;
use function strlen;
use function usort;
use const PREG_SET_ORDER;

/** @phpstan-type AcceptingTypeString 'strict-int'|'int'|'float'|'string'|'mixed' */
final class PrintfHelper
{

private const PRINTF_SPECIFIER_PATTERN = '(?<specifier>[bs%s]|l?[cdeEgfFGouxX])';

public function __construct(private PhpVersion $phpVersion)
{
}

public function getPrintfPlaceholdersCount(string $format): int
{
return $this->getPlaceholdersCount('(?:[bs%s]|l?[cdeEgfFGouxX])', $format);
return $this->getPlaceholdersCount(self::PRINTF_SPECIFIER_PATTERN, $format);
}

/** @return array<int, array{string, callable(Type): bool}> position => [type name, matches callback] */
public function getPrintfPlaceholderAcceptingTypes(string $format): array
{
$placeholders = $this->parsePlaceholders(self::PRINTF_SPECIFIER_PATTERN, $format);
$result = [];
// Type on the left can go to the type on the right, but not vice versa.
$typeSequenceMap = array_flip(['int', 'float', 'string', 'mixed']);

foreach ($placeholders as $position => $types) {
sort($types);
$typeNames = array_map(
static fn (string $t) => $t === 'strict-int'
? 'int'
: $t,
$types,
);
$typeName = array_reduce(
$typeNames,
static fn (string $carry, string $type) => $typeSequenceMap[$carry] < $typeSequenceMap[$type]
? $carry
: $type,
'mixed',
);
$result[$position] = [
$typeName,
static function (Type $t) use ($types): bool {
foreach ($types as $acceptingType) {
switch ($acceptingType) {
case 'strict-int':
$subresult = (new IntegerType())->accepts($t, true)->yes();
break;
case 'int':
$subresult = ! $t->toInteger() instanceof ErrorType;
break;
case 'float':
$subresult = ! $t->toFloat() instanceof ErrorType;
break;
// The function signature already limits the parameters to stringable types, so there's
// no point in checking string again here.
case 'string':
case 'mixed':
default:
$subresult = true;
break;
}

if (!$subresult) {
return false;
}
}

return true;
},
];
}

return $result;
}

public function getScanfPlaceholdersCount(string $format): int
{
return $this->getPlaceholdersCount('(?:[cdDeEfinosuxX%s]|\[[^\]]+\])', $format);
return $this->getPlaceholdersCount('(?<specifier>[cdDeEfinosuxX%s]|\[[^\]]+\])', $format);
}

private function getPlaceholdersCount(string $specifiersPattern, string $format): int
/** @phpstan-return array<int, non-empty-list<AcceptingTypeString>> position => type */
private function parsePlaceholders(string $specifiersPattern, string $format): array
{
$addSpecifier = '';
if ($this->phpVersion->supportsHhPrintfSpecifier()) {
Expand All @@ -42,34 +115,72 @@ private function getPlaceholdersCount(string $specifiersPattern, string $format)
$matches = Strings::matchAll($format, $pattern, PREG_SET_ORDER);

if (count($matches) === 0) {
return 0;
return [];
}

$placeholders = array_filter($matches, static fn (array $match): bool => strlen($match['before']) % 2 === 0);

if (count($placeholders) === 0) {
return 0;
}
$result = [];
$positionalPlaceholders = [];
$idx = 0;

$maxPositionedNumber = 0;
$maxOrdinaryNumber = 0;
foreach ($placeholders as $placeholder) {
if (isset($placeholder['width']) && $placeholder['width'] !== '') {
$maxOrdinaryNumber++;
$result[$idx++] = ['strict-int' => 1];
}

if (isset($placeholder['precision']) && $placeholder['precision'] !== '') {
$maxOrdinaryNumber++;
$result[$idx++] = ['strict-int' => 1];
}

if (isset($placeholder['position']) && $placeholder['position'] !== '') {
$maxPositionedNumber = max((int) $placeholder['position'], $maxPositionedNumber);
} else {
$maxOrdinaryNumber++;
// It may reference future position, so we have to process them later.
$positionalPlaceholders[] = $placeholder;
continue;
}

$result[$idx++][$this->getAcceptingTypeBySpecifier($placeholder['specifier'] ?? '')] = 1;
}

usort(
$positionalPlaceholders,
static fn (array $a, array $b) => (int) $a['position'] <=> (int) $b['position'],
);

foreach ($positionalPlaceholders as $placeholder) {
$idx = $placeholder['position'] - 1;
$result[$idx][$this->getAcceptingTypeBySpecifier($placeholder['specifier'] ?? '')] = 1;
}

return array_map(static fn (array $a) => array_keys($a), $result);
}

/** @phpstan-return 'string'|'int'|'float'|'mixed' */
private function getAcceptingTypeBySpecifier(string $specifier): string
{
if ($specifier === 's') {
return 'string';
}

return max($maxPositionedNumber, $maxOrdinaryNumber);
if (in_array($specifier, ['d', 'u', 'c', 'o', 'x', 'X', 'b'], true)) {
return 'int';
}

if (in_array($specifier, ['e', 'E', 'f', 'F', 'g', 'G', 'h', 'H'], true)) {
return 'float';
}

return 'mixed';
}

private function getPlaceholdersCount(string $specifiersPattern, string $format): int
{
$paramIndices = array_keys($this->parsePlaceholders($specifiersPattern, $format));

return $paramIndices === []
? 0
// The indices start from 0
: max($paramIndices) + 1;
}

}
145 changes: 145 additions & 0 deletions src/Rules/Functions/PrintfParameterTypeRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?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\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();
$acceptingTypes = $this->printfHelper->getPrintfPlaceholderAcceptingTypes($format);
$errors = [];
$typeAllowedByCallToFunctionParametersRule = TypeCombinator::union(
new StringAlwaysAcceptingObjectWithToStringType(),
new IntegerType(),
new FloatType(),
new BooleanType(),
new NullType(),
);

for ($i = $formatArgumentPosition + 1, $j = 0; $i < $argsCount; $i++, $j++) {
// Some arguments may be skipped entirely.
if (! array_key_exists($j, $acceptingTypes)) {
continue;
}

[$acceptingName, $acceptingCb] = $acceptingTypes[$j];
$argType = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$args[$i]->value,
'',
$acceptingCb,
)->getType();

if ($argType instanceof ErrorType || $acceptingCb($argType)) {
continue;
}

// This is already reported by CallToFunctionParametersRule
if (
!$this->ruleLevelHelper->accepts(
$typeAllowedByCallToFunctionParametersRule,
$argType,
$scope->isDeclareStrictTypes(),
)->result
) {
continue;
}

$errors[] = RuleErrorBuilder::message(
sprintf(
'Placeholder #%d of function %s expects %s, %s given',
$j + 1,
$name,
$acceptingName,
$argType->describe(VerbosityLevel::typeOnly()),
),
)->identifier('argument.type')->build();
}

return $errors;
}

}
Loading
Loading