psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Narrowing down of an instance class in `else` branch doesn't work

Open SCIF opened this issue 1 year ago • 5 comments

https://psalm.dev/r/29c4fb185d The trace on L9 should say stdClass

SCIF avatar Sep 16 '24 10:09 SCIF

I found these snippets:

https://psalm.dev/r/29c4fb185d
<?php

class A {}
/** @var A|stdClass $obj */;

if ($obj::class === A::class) {
    /** @psalm-trace $obj */;
} else {
    /** @psalm-trace $obj */;
}
Psalm output (using commit 16b24bd):

INFO: Trace - 7:29 - $obj: A

INFO: Trace - 9:29 - $obj: A|stdClass

psalm-github-bot[bot] avatar Sep 16 '24 10:09 psalm-github-bot[bot]

What about this? https://psalm.dev/r/86cb22d9c3

B is an A but ::class on it won't === A::class so it will go in the else. That way, the else can't completely exclude A

orklah avatar Sep 16 '24 15:09 orklah

I found these snippets:

https://psalm.dev/r/86cb22d9c3
<?php

class A {}
class B extends A {}

/** @var A|stdClass $obj */;

if ($obj::class === A::class) {
    /** @psalm-trace $obj */;
} else {
    /** @psalm-trace $obj */;
}
Psalm output (using commit 16b24bd):

INFO: Trace - 9:29 - $obj: A

INFO: Trace - 11:29 - $obj: A|stdClass

psalm-github-bot[bot] avatar Sep 16 '24 15:09 psalm-github-bot[bot]

It should work for final classes though

https://psalm.dev/r/85e60a375e

staabm avatar Sep 18 '24 05:09 staabm

I found these snippets:

https://psalm.dev/r/85e60a375e
<?php

final class A {}

/** @var A|stdClass $obj */;

if ($obj::class === A::class) {
    /** @psalm-trace $obj */;
} else {
    /** @psalm-trace $obj */;
}
Psalm output (using commit 16b24bd):

INFO: Trace - 8:29 - $obj: A

INFO: Trace - 10:29 - $obj: A|stdClass

psalm-github-bot[bot] avatar Sep 18 '24 05:09 psalm-github-bot[bot]