Skip to content

Commit 3295957

Browse files
committed
Report leaving out a parameter whose default PHP does not know
php-src stubs declare parameters like mt_rand()'s $min or array_keys()'s $filter_value with the default UNKNOWN. PHP throws "must be passed explicitly, because the default value is not known" when a later named argument skips such a parameter, or when ... of a partial application leaves it out. The default is now an ErrorType that every variant keeps, so calls, closure calls and partial applications report it, and such a partial application infers Closure. Calls like mt_rand(max: 5) crashed ArgumentsNormalizer before. A named argument now only selects the variants that have its parameter, so session_set_save_handler($open, read: $read) is checked against the signature with $close instead of the one with SessionHandlerInterface. Amp-Thread-ID: https://ampcode.com/threads/T-01a1c541-317f-7386-a2ed-9cbd66178685
1 parent b53bb1b commit 3295957

22 files changed

Lines changed: 410 additions & 26 deletions

‎src/Analyser/ArgumentsNormalizer.php‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
use PHPStan\Node\Printer\ExprPrinter;
1717
use PHPStan\Reflection\ParametersAcceptor;
1818
use PHPStan\Reflection\ParametersAcceptorSelector;
19-
use PHPStan\ShouldNotHappenException;
2019
use PHPStan\TrinaryLogic;
2120
use PHPStan\Turbo\ShadowedByTurboExtension;
2221
use PHPStan\Type\Constant\ConstantArrayType;
@@ -29,7 +28,6 @@
2928
use function key;
3029
use function ksort;
3130
use function max;
32-
use function sprintf;
3331

3432
/**
3533
* @api
@@ -443,7 +441,8 @@ public static function reorderArgs(ParametersAcceptor $parametersAcceptor, array
443441
$defaultValue = $parameter->getDefaultValue();
444442
if ($defaultValue === null) {
445443
if (!$parameter->isVariadic()) {
446-
throw new ShouldNotHappenException(sprintf('An optional parameter $%s must have a default value', $parameter->getName()));
444+
// like an optional parameter combined from variants that do not all have it
445+
return null;
447446
}
448447
$defaultValue = new ConstantArrayType([], []);
449448
}

‎src/Reflection/InitializerExprTypeResolver.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,11 @@ public function createFirstClassCallable(
892892
$origin = $origin->withPartialApplication($partialApplicationArgs, $boundArgTypes);
893893
}
894894

895+
if ($partialApplicationArgs !== null && PartialFunctionApplicationParameters::leavesUnknownDefaultValue($variants, $partialApplicationArgs)) {
896+
// creating the closure throws
897+
return new ObjectType(Closure::class);
898+
}
899+
895900
// variants of multi-variant built-ins carry functionMap parameter names,
896901
// but the closure accepts the native names as named arguments
897902
$namedArgumentNames = [];

‎src/Reflection/ParameterReflection.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ public function passedByReference(): PassedByReference;
3030

3131
public function isVariadic(): bool;
3232

33+
/**
34+
* An ErrorType for a parameter of a built-in function whose default PHP does not know,
35+
* like mt_rand()'s $min: it must be passed explicitly when a later parameter is.
36+
*/
3337
public function getDefaultValue(): ?Type;
3438

3539
}

‎src/Reflection/ParametersAcceptorSelector.php‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
use PHPStan\Type\CallableType;
3232
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
3333
use PHPStan\Type\Constant\ConstantIntegerType;
34+
use PHPStan\Type\ErrorType;
3435
use PHPStan\Type\Generic\TemplateTypeMap;
3536
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
3637
use PHPStan\Type\IntegerType;
@@ -46,6 +47,7 @@
4647
use function array_is_list;
4748
use function array_key_exists;
4849
use function array_key_last;
50+
use function array_keys;
4951
use function array_last;
5052
use function array_map;
5153
use function array_merge;
@@ -685,6 +687,10 @@ public static function selectFromTypes(
685687

686688
$typesCount = count($types);
687689
$acceptableAcceptors = [];
690+
// a named argument only fits a variant that has its parameter, like
691+
// session_set_save_handler($open, read: $read), unless no variant has it
692+
$acceptableAcceptorsWithNames = [];
693+
$someAcceptorHasNames = false;
688694

689695
foreach ($parametersAcceptors as $parametersAcceptor) {
690696
if ($unpack) {
@@ -694,14 +700,27 @@ public static function selectFromTypes(
694700

695701
$functionParametersMinCount = 0;
696702
$functionParametersMaxCount = 0;
703+
$parameterNames = [];
697704
foreach ($parametersAcceptor->getParameters() as $parameter) {
698705
if (!$parameter->isOptional()) {
699706
$functionParametersMinCount++;
700707
}
701708

702709
$functionParametersMaxCount++;
710+
$parameterNames[$parameter->getName()] = true;
703711
}
704712

713+
$hasNames = true;
714+
if (!$parametersAcceptor->isVariadic()) {
715+
foreach (array_keys($types) as $key) {
716+
if (is_string($key) && !array_key_exists($key, $parameterNames)) {
717+
$hasNames = false;
718+
break;
719+
}
720+
}
721+
}
722+
$someAcceptorHasNames = $someAcceptorHasNames || $hasNames;
723+
705724
if ($typesCount < $functionParametersMinCount) {
706725
continue;
707726
}
@@ -714,6 +733,15 @@ public static function selectFromTypes(
714733
}
715734

716735
$acceptableAcceptors[] = $parametersAcceptor;
736+
if (!$hasNames) {
737+
continue;
738+
}
739+
740+
$acceptableAcceptorsWithNames[] = $parametersAcceptor;
741+
}
742+
743+
if ($someAcceptorHasNames) {
744+
$acceptableAcceptors = $acceptableAcceptorsWithNames;
717745
}
718746

719747
if (count($acceptableAcceptors) === 0) {
@@ -892,7 +920,12 @@ public static function combineAcceptors(array $acceptors): ExtendedParametersAcc
892920
$isParameterVariadic = $parameters[$i]->isVariadic() || $parameter->isVariadic();
893921
$defaultValueLeft = $parameters[$i]->getDefaultValue();
894922
$defaultValueRight = $parameter->getDefaultValue();
895-
if ($defaultValueLeft !== null && $defaultValueRight !== null) {
923+
if ($defaultValueLeft instanceof ErrorType) {
924+
// the parameter of the real signature keeps its unknown default
925+
$defaultValue = $defaultValueLeft;
926+
} elseif ($defaultValueRight instanceof ErrorType) {
927+
$defaultValue = $defaultValueRight;
928+
} elseif ($defaultValueLeft !== null && $defaultValueRight !== null) {
896929
$defaultValue = TypeCombinator::union($defaultValueLeft, $defaultValueRight);
897930
} else {
898931
$defaultValue = null;

‎src/Reflection/PartialFunctionApplicationParameters.php‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
use PHPStan\Reflection\Php\DummyParameter;
1111
use PHPStan\Reflection\Php\ExtendedDummyParameter;
1212
use PHPStan\Turbo\ReferencedByTurboExtension;
13+
use PHPStan\Type\ErrorType;
1314
use PHPStan\Type\Generic\TemplateType;
1415
use PHPStan\Type\Generic\TemplateTypeMap;
1516
use PHPStan\Type\Type;
1617
use PHPStan\Type\TypeCombinator;
1718
use PHPStan\Type\TypeTraverser;
1819
use function array_key_exists;
20+
use function array_keys;
1921
use function count;
2022
use function max;
2123
use function min;
@@ -274,6 +276,17 @@ private static function map(array $parameters, bool $isVariadic, array $args): ?
274276
$named[] = self::required($declared[$index], $nameString);
275277
}
276278

279+
$lastCovered = $covered === [] ? -1 : max(array_keys($covered));
280+
foreach ($declared as $i => $parameter) {
281+
if (isset($covered[$i]) || !$parameter->getDefaultValue() instanceof ErrorType) {
282+
continue;
283+
}
284+
if ($hasVariadicPlaceholder || ($i < $lastCovered && $parameter->isOptional())) {
285+
// PHP refuses to fill in a default it does not know
286+
return null;
287+
}
288+
}
289+
277290
$closureParameters = [...$positional, ...$named];
278291
if (!$hasVariadicPlaceholder) {
279292
foreach ($declared as $i => $parameter) {
@@ -335,6 +348,12 @@ public static function selectVariant(array $args, array $variants, ?array $named
335348
}
336349
}
337350

351+
foreach ($variants as $variant) {
352+
if (self::leavesUnknownDefaultValue([$variant], $args)) {
353+
return $variant;
354+
}
355+
}
356+
338357
if (count($variants) === 1) {
339358
return $variants[0];
340359
}
@@ -361,6 +380,50 @@ public static function selectVariant(array $args, array $variants, ?array $named
361380
return ParametersAcceptorSelector::combineAcceptors(count($fitting) > 0 ? $fitting : $variants);
362381
}
363382

383+
/**
384+
* The variants of a built-in describe one real signature, so when ... leaves out a parameter
385+
* whose default PHP does not know in any of them, like $value of ReflectionProperty::setValue(?, ...),
386+
* creating the closure throws whichever variant the arguments fit.
387+
*
388+
* @param ParametersAcceptor[] $variants
389+
* @param array<Arg|ArgPlaceholder|VariadicPlaceholder> $args
390+
*/
391+
public static function leavesUnknownDefaultValue(array $variants, array $args): bool
392+
{
393+
$positionalCount = 0;
394+
$names = [];
395+
$hasVariadicPlaceholder = false;
396+
foreach ($args as $arg) {
397+
if ($arg instanceof VariadicPlaceholder) {
398+
$hasVariadicPlaceholder = true;
399+
continue;
400+
}
401+
if ($arg->name !== null) {
402+
$names[$arg->name->toString()] = true;
403+
continue;
404+
}
405+
$positionalCount++;
406+
}
407+
if (!$hasVariadicPlaceholder) {
408+
return false;
409+
}
410+
411+
foreach ($variants as $variant) {
412+
foreach ($variant->getParameters() as $i => $parameter) {
413+
if (
414+
$i >= $positionalCount
415+
&& !$parameter->isVariadic()
416+
&& !array_key_exists($parameter->getName(), $names)
417+
&& $parameter->getDefaultValue() instanceof ErrorType
418+
) {
419+
return true;
420+
}
421+
}
422+
}
423+
424+
return false;
425+
}
426+
364427
/**
365428
* Combining the variants () and ($min, $max) of mt_rand() would accept mt_rand(?),
366429
* so like a call, a count of positional arguments that the combined variants

‎src/Reflection/SignatureMap/Php8SignatureMapProvider.php‎

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use PHPStan\Reflection\PassedByReference;
2121
use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider;
2222
use PHPStan\ShouldNotHappenException;
23+
use PHPStan\Type\ErrorType;
2324
use PHPStan\Type\FileTypeMapper;
2425
use PHPStan\Type\MixedType;
2526
use PHPStan\Type\ParserNodeTypeToPHPStanType;
@@ -418,7 +419,7 @@ private function getMergedSignatures(FunctionSignature $nativeSignature, array $
418419
$functionParam->getNativeType(),
419420
$functionParam->passedByReference(),
420421
$functionParam->isVariadic(),
421-
$functionParam->getDefaultValue() ?? $nativeParam->getDefaultValue(),
422+
$nativeParam->getDefaultValue() instanceof ErrorType ? $nativeParam->getDefaultValue() : $functionParam->getDefaultValue() ?? $nativeParam->getDefaultValue(),
422423
$functionParam->getOutType() ?? $nativeParam->getOutType(),
423424
);
424425
}
@@ -435,7 +436,50 @@ private function getMergedSignatures(FunctionSignature $nativeSignature, array $
435436
$namedArgumentsVariants = null;
436437
}
437438

438-
return ['positional' => $functionMapSignatures['positional'], 'named' => $namedArgumentsVariants];
439+
return [
440+
'positional' => array_map(fn (FunctionSignature $signature): FunctionSignature => $this->withUnknownDefaultValues($nativeSignature, $signature), $functionMapSignatures['positional']),
441+
'named' => $namedArgumentsVariants,
442+
];
443+
}
444+
445+
/**
446+
* A parameter of a function map variant like mt_rand(int $min, int $max) keeps the unknown default
447+
* of the parameter it stands for, also over a default the PhpStorm stubs make up for it,
448+
* so that combining the variants knows that $min must be passed explicitly before $max.
449+
*/
450+
private function withUnknownDefaultValues(FunctionSignature $nativeSignature, FunctionSignature $signature): FunctionSignature
451+
{
452+
$nativeParameters = $nativeSignature->getParameters();
453+
$parameters = [];
454+
foreach ($signature->getParameters() as $i => $parameter) {
455+
$nativeParameter = $nativeParameters[$i] ?? null;
456+
if (
457+
$nativeParameter === null
458+
|| $nativeParameter->getName() !== $parameter->getName()
459+
|| !$nativeParameter->getDefaultValue() instanceof ErrorType
460+
) {
461+
$parameters[] = $parameter;
462+
continue;
463+
}
464+
465+
$parameters[] = new ParameterSignature(
466+
$parameter->getName(),
467+
$parameter->isOptional(),
468+
$parameter->getType(),
469+
$parameter->getNativeType(),
470+
$parameter->passedByReference(),
471+
$parameter->isVariadic(),
472+
$nativeParameter->getDefaultValue(),
473+
$parameter->getOutType(),
474+
);
475+
}
476+
477+
return new FunctionSignature(
478+
$parameters,
479+
$signature->getReturnType(),
480+
$signature->getNativeReturnType(),
481+
$signature->isVariadic(),
482+
);
439483
}
440484

441485
private function mergeSignatures(FunctionSignature $nativeSignature, FunctionSignature $functionMapSignature): FunctionSignature
@@ -570,17 +614,25 @@ private function getSignature(
570614
}
571615
}
572616

617+
$defaultValue = null;
618+
if ($param->default instanceof ConstFetch && $param->default->name->toString() === 'UNKNOWN') {
619+
// see ParameterReflection::getDefaultValue()
620+
$defaultValue = new ErrorType();
621+
} elseif ($param->default !== null) {
622+
$defaultValue = $this->initializerExprTypeResolver->getType(
623+
$param->default,
624+
InitializerExprContext::fromStubParameter($className, $stubFile, $function),
625+
);
626+
}
627+
573628
$parameters[] = new ParameterSignature(
574629
$name->name,
575630
$param->default !== null || $param->variadic,
576631
TypehintHelper::decideType($parameterType, $phpDocParameterType),
577632
$parameterType,
578633
$param->byRef ? PassedByReference::createCreatesNewVariable() : PassedByReference::createNo(),
579634
$param->variadic,
580-
$param->default !== null ? $this->initializerExprTypeResolver->getType(
581-
$param->default,
582-
InitializerExprContext::fromStubParameter($className, $stubFile, $function),
583-
) : null,
635+
$defaultValue,
584636
null,
585637
);
586638

‎src/Rules/FunctionCallParametersCheck.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,6 +1015,30 @@ private function processArguments(
10151015
unset($unusedParametersByName[$parameter->getName()]);
10161016
}
10171017

1018+
// PHP refuses to fill in a default it does not know: for a parameter
1019+
// skipped by a later named argument, or left to ... of a partial application
1020+
$lastPassedPosition = -1;
1021+
foreach ($parameters as $i => $parameter) {
1022+
if ($parameter->isVariadic() || array_key_exists($parameter->getName(), $unusedParametersByName)) {
1023+
continue;
1024+
}
1025+
$lastPassedPosition = $i;
1026+
}
1027+
foreach ($parameters as $i => $parameter) {
1028+
if (
1029+
!array_key_exists($parameter->getName(), $unusedParametersByName)
1030+
|| !$parameter->getDefaultValue() instanceof ErrorType
1031+
|| ($checkMissingParameters && (!$hasNamedArguments || !$parameter->isOptional() || $i > $lastPassedPosition))
1032+
) {
1033+
continue;
1034+
}
1035+
1036+
$errors[] = RuleErrorBuilder::message(sprintf('Argument #%d ($%s) must be passed explicitly, because the default value is not known.', $i + 1, $parameter->getName()))
1037+
->identifier('argument.unknownDefaultValue')
1038+
->line($line)
1039+
->build();
1040+
}
1041+
10181042
if ($hasNamedArguments && $checkMissingParameters) {
10191043
foreach ($unusedParametersByName as $parameter) {
10201044
if ($parameter->isOptional()) {

‎tests/PHPStan/Analyser/AnalyserIntegrationTest.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1718,6 +1718,20 @@ public function testBug9746(): void
17181718
$this->assertSame(9, $errors[1]->getLine());
17191719
}
17201720

1721+
#[RequiresPhp('>= 8.1.0')]
1722+
public function testUnknownDefaultValueNamedArguments(): void
1723+
{
1724+
// crash
1725+
$errors = $this->runAnalyse(__DIR__ . '/data/unknown-default-value-named-arguments.php');
1726+
$this->assertCount(3, $errors);
1727+
$this->assertSame('Argument #1 ($min) must be passed explicitly, because the default value is not known.', $errors[0]->getMessage());
1728+
$this->assertSame(7, $errors[0]->getLine());
1729+
$this->assertSame('Argument #1 ($min) must be passed explicitly, because the default value is not known.', $errors[1]->getMessage());
1730+
$this->assertSame(8, $errors[1]->getLine());
1731+
$this->assertSame('Argument #2 ($close) must be passed explicitly, because the default value is not known.', $errors[2]->getMessage());
1732+
$this->assertSame(9, $errors[2]->getLine());
1733+
}
1734+
17211735
public function testBug15364(): void
17221736
{
17231737
// crash
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php // lint >= 8.1
2+
3+
namespace UnknownDefaultValueNamedArguments;
4+
5+
function doFoo(callable $open, callable $read): void
6+
{
7+
mt_rand(max: 5);
8+
(mt_rand(...))(max: 5);
9+
(session_set_save_handler(...))($open, read: $read);
10+
}

0 commit comments

Comments
 (0)