psalm icon indicating copy to clipboard operation
psalm copied to clipboard

False positive InvalidCast when casting intersections

Open AndrolGenhald opened this issue 1 year ago • 6 comments

Hmmm, this doesn't seem quite right to me. I know we're looking at ints 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.

AndrolGenhald avatar Sep 15 '22 14:09 AndrolGenhald

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'

psalm-github-bot[bot] avatar Sep 15 '22 14:09 psalm-github-bot[bot]

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)

kkmuffme avatar Sep 15 '22 16:09 kkmuffme

I personally don't care much either way, @orklah?

AndrolGenhald avatar Sep 15 '22 18:09 AndrolGenhald

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...

orklah avatar Sep 15 '22 18:09 orklah

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 avatar Sep 15 '22 18:09 AndrolGenhald

@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.

kkmuffme avatar Sep 20 '22 08:09 kkmuffme