psalm
psalm copied to clipboard
False positive InvalidCast when casting intersections
Hmmm, this doesn't seem quite right to me. I know we're looking at int
s now, but to give a string
example, wouldn't this cause this to be a false positive, because the (string) $baz
cast would bail out after the first valid cast found in the intersection?
Edit: Apparently B
is the "main" type for some reason, so this is the false positive: https://psalm.dev/r/f97d4ac118
Originally posted by @AndrolGenhald in https://github.com/vimeo/psalm/pull/8366#discussion_r971002434
We should also refactor int
, float
, and string
casting to share more of their code once #8366 is merged.
I found these snippets:
https://psalm.dev/r/a780b3729f
<?php
interface A
{
public function __toString(): string;
}
interface B
{
/** @return numeric-string */
public function __toString(): string;
}
/** @return numeric-string */
function foobar(A&B $baz): string
{
return (string) $baz;
}
Psalm output (using commit d957ff2):
No issues!
https://psalm.dev/r/f97d4ac118
<?php
interface A
{
/** @return numeric-string */
public function __toString(): string;
}
interface B
{
public function __toString(): string;
}
/** @return numeric-string */
function foobar(A&B $baz): string
{
return (string) $baz;
}
Psalm output (using commit d957ff2):
INFO: LessSpecificReturnStatement - 17:12 - The type 'string' is more general than the declared return type 'numeric-string' for foobar
INFO: MoreSpecificReturnType - 14:13 - The declared return type 'numeric-string' for foobar is more specific than the inferred return type 'string'
The question is also if "explicit" casts should be handled separately then? (or the $explicit_cast should be removed altogether, as it's basically unused)
I personally don't care much either way, @orklah?
Well, intersections are messy right now. I think there's a lot of those where that came from. Not sure what we can do without a big overhaul...
Oh, yeah, there are a ton of intersection issues, but I was asking more about if we want some differentiation between explicit and implicit cast issues like @kkmuffme is talking about. Should have made that a bit more clear.
@AndrolGenhald yes we should keep the $explicit_cast and make it work - I just found there's issues ImplicitToStringCast
so we could make this work here too for the object __toString method easily.
For int/float it can be removed though.