vimeo / psalm

A static analysis tool for finding errors in PHP applications
https://psalm.dev
MIT License
5.55k stars 660 forks source link

Constant reference inside array shape definition parsing failure #7803

Open Jean85 opened 2 years ago

Jean85 commented 2 years ago

The parser for array shapes mistakenly thinks that :: is used as an array key and not as a value:

https://psalm.dev/r/45e90ce53a

class Foo
{
    const CONST_A = 'a';
    const CONST_B = 'b';
    const CONST_C = 'c';
}

/**
 * @return array{Foo::*}
 */
function getArrayWithConstKeys(): array
{
    return [
        Foo::CONST_A,
    ];
}
Psalm output (using commit a9f4148): 

ERROR: [InvalidDocblock](https://psalm.dev/008) - 13:1 - :: in array key is only allowed for ::class in docblock for getArrayWithConstKeys

Issue is located in this piece of code: https://github.com/vimeo/psalm/blob/c74981127fcd83a3a1b6ff65d7cb8b7bdeb85017/src/Psalm/Internal/Type/ParseTreeCreator.php#L783-L793

psalm-github-bot[bot] commented 2 years ago

I found these snippets:

https://psalm.dev/r/45e90ce53a ```php
AndrolGenhald commented 2 years ago

You can of course use array{0: Foo::*} to work around the issue until it's fixed.

orklah commented 2 years ago

Your return could probably be better described as non-empty-array<Foo::*> or even non-empty-list<Foo::*> if the position is not important

Jean85 commented 2 years ago

You can of course use array{0: Foo::*} to work around the issue until it's fixed.

Thanks for the tip, I can confirm that this workaround works

Your return could probably be better described as non-empty-array<Foo::*> or even non-empty-list<Foo::*> if the position is not important

Unfortunately for me, position counts in this case.

psalm-github-bot[bot] commented 1 year ago

I found these snippets:

https://psalm.dev/r/bbc872e2ff ```php $value) { /** @psalm-trace $key */ var_dump($key); /** @psalm-trace $value */ var_dump($value); } } } CheckPsalm::foo([CheckPsalm::CONSTANT => "some string"]); ``` ``` Psalm output (using commit aec0edc): ERROR: InvalidDocblock - 9:15 - :: in array key is only allowed for ::class in docblock for CheckPsalm::foo INFO: MixedAssignment - 13:28 - Unable to determine the type that $key is being assigned to INFO: MixedAssignment - 13:36 - Unable to determine the type that $value is being assigned to ERROR: ForbiddenCode - 15:13 - Unsafe var_dump INFO: Trace - 15:13 - $key: mixed ERROR: ForbiddenCode - 17:13 - Unsafe var_dump INFO: Trace - 17:13 - $value: mixed INFO: MissingParamType - 11:32 - Parameter $param has no provided type ```