Skip to content
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

Forbid positional arg after named arg #7136

Merged
merged 3 commits into from Dec 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -23,6 +23,7 @@
use Psalm\Internal\Type\TemplateResult;
use Psalm\Internal\Type\TemplateStandinTypeReplacer;
use Psalm\Internal\Type\TypeExpander;
use Psalm\Issue\InvalidArgument;
use Psalm\Issue\InvalidNamedArgument;
use Psalm\Issue\InvalidPassByReference;
use Psalm\Issue\PossiblyUndefinedVariable;
Expand Down Expand Up @@ -646,8 +647,20 @@ public static function checkArgumentsMatch(

$arg_function_params = [];
$matched_args = [];
$named_args_was_used = false;

foreach ($args as $argument_offset => $arg) {
if ($named_args_was_used && !$arg->name) {
IssueBuffer::maybeAdd(
new InvalidNamedArgument(
'Cannot use positional argument after named argument',
new CodeLocation($statements_analyzer, $arg),
(string)$method_id
),
$statements_analyzer->getSuppressedIssues()
);
}

if ($arg->unpack) {
if ($function_param_count > $argument_offset) {
for ($i = $argument_offset; $i < $function_param_count; $i++) {
Expand Down Expand Up @@ -712,6 +725,8 @@ public static function checkArgumentsMatch(
}
}
} elseif ($arg->name && (!$function_storage || $function_storage->allow_named_arg_calls)) {
$named_args_was_used = true;

foreach ($function_params as $candidate_param) {
if ($candidate_param->name === $arg->name->name || $candidate_param->is_variadic) {
if ($candidate_param->name === $arg->name->name) {
Expand Down
14 changes: 14 additions & 0 deletions tests/ArgTest.php
@@ -1,6 +1,7 @@
<?php
namespace Psalm\Tests;

use Person;
weirdan marked this conversation as resolved.
Show resolved Hide resolved
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;

Expand Down Expand Up @@ -406,6 +407,19 @@ function foo(array $input) : CustomerData {
}',
'error_message' => 'InvalidNamedArgument'
],
'usePositionalArgAfterNamed' => [
'<?php
final class Person
{
public function __construct(
public string $name,
public int $age,
) { }
}

new Person(name: "", 0);',
'error_message' => 'InvalidNamedArgument'
],
'useUnpackedInvalidNamedArgument' => [
'<?php
class CustomerData {
Expand Down