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

Using static in conditional return #8581

Open
tdtm opened this issue Oct 13, 2022 · 1 comment
Open

Using static in conditional return #8581

tdtm opened this issue Oct 13, 2022 · 1 comment

Comments

@tdtm
Copy link

tdtm commented Oct 13, 2022

Should @return (T is static ? bool : false) work? Here anything I try seems to evaluate T is static as false.

https://psalm.dev/r/59c4ae8585

As comparison, in PhpStan, it does work: https://phpstan.org/r/1048dce8-8d8c-47ac-86e6-383ef17984d7

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/59c4ae8585
<?php declare(strict_types=1);
  
interface Comparable {
    /**
    * @template T of mixed
    *
    * @param T $compareTo
    * 
    * If the param is the same class as $this, then it's possible it will be true (but it could still be false)
    * If the param is a different class from $this, even if it implements Comparable, then it's impossible for it to be true.
    *
    * @return (T is static ? bool : false)
    */
    public function compare(mixed $compareTo) : bool;
}

class Foo implements Comparable {
   /**
    * @template T of mixed
    * @param T $compareTo
    * @return (T is static ? bool : false)
    */
    public function compare(mixed $compareTo) : bool
    {
        return $this == $compareTo;
    }
}

class Bar implements Comparable {
   /**
    * @template T of mixed
    * @param T $compareTo
    * @return (T is static ? bool : false)
    */
    public function compare(mixed $compareTo) : bool
    {
        return $this == $compareTo;
    }
}

$a = new Foo();
$b = new Bar();

/** @psalm-trace $ab */ // these are different classes, so we should be able to infer it's false
$ab = $a->compare($b);

/** @psalm-trace $ba */ // these are different classes, so we should be able to infer it's false
$ba = $b->compare($a);

/** @psalm-trace $aa */ // these the same class, so we should infer bool as it could be either
$aa = $a->compare($a);
Psalm output (using commit f8d1dd8):

INFO: Trace - 45:1 - $ab: false

INFO: Trace - 48:1 - $ba: false

INFO: Trace - 51:1 - $aa: false

INFO: UnusedVariable - 45:1 - $ab is never referenced or the value is not used

INFO: UnusedVariable - 48:1 - $ba is never referenced or the value is not used

INFO: UnusedVariable - 51:1 - $aa is never referenced or the value is not used

@tdtm tdtm changed the title Using static in conditional return Using static in conditional return Oct 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants