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

Strange array<empty, empty> type inference #5799

Closed
someniatko opened this issue May 19, 2021 · 4 comments
Closed

Strange array<empty, empty> type inference #5799

someniatko opened this issue May 19, 2021 · 4 comments
Labels

Comments

@someniatko
Copy link
Contributor

someniatko commented May 19, 2021

https://psalm.dev/r/cf250aab5b

$res should be array{1, 2}|array<empty, empty> or like that.

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/cf250aab5b
<?php

/** @template T */
class Option
{
    /** @param T $v */
    public function __construct(private $v) {}
    
    /**
     * @template E
     * @param E $else
     * @return T|E
     */
    public function getOrElse($else)
    {
       return random_int(0, 1) === 1 ? $this->v : $else; 
    }
}

$opt = new Option([1, 2]);
/** @psalm-trace $opt */

$res = $opt->getOrElse([]);
/** @psalm-trace $res */
Psalm output (using commit f62b83a):

INFO: Trace - 23:1 - $opt: Option<array{1, 2}>

INFO: Trace - 24:25 - $res: array<empty, empty>

INFO: UnusedVariable - 23:1 - $res is never referenced or the value is not used

@weirdan weirdan added the bug label May 19, 2021
@orklah
Copy link
Collaborator

orklah commented May 23, 2021

Interestingly, this doesn't happen with standard ternaries for example
https://psalm.dev/r/d05df407f7

Nor when the templates are from the same method:
https://psalm.dev/r/d811b083c3 (although the result is not perfect either here)

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/d05df407f7
<?php

$c = rand(0,1) ? [1, 2] : [];
/** @psalm-trace $c */;
Psalm output (using commit e89f7e3):

INFO: Trace - 4:23 - $c: array{0?: 1, 1?: 2}

INFO: UnusedVariable - 3:1 - $c is never referenced or the value is not used
https://psalm.dev/r/d811b083c3
<?php

/**
 * @template T of array
 * @template E of array
 * @param E $else
 * @param T $if
 * @return T|E
 */
function getOrElse($if, $else)
{
    return rand(0, 1) ? $if : $else;
}


$opt = getOrElse([], [1, 2]);
/** @psalm-trace $opt */
Psalm output (using commit e89f7e3):

INFO: Trace - 17:25 - $opt: array{1, 2}

INFO: UnusedVariable - 16:1 - $opt is never referenced or the value is not used

@muglug muglug closed this as completed in d1262b0 May 23, 2021
@orklah
Copy link
Collaborator

orklah commented May 23, 2021

Great, my case was fixed too! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants