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

PossiblyNullValue is incorrect for boolean casts #4206

Closed
danielbeardsley opened this issue Sep 18, 2020 · 3 comments
Closed

PossiblyNullValue is incorrect for boolean casts #4206

danielbeardsley opened this issue Sep 18, 2020 · 3 comments
Labels

Comments

@danielbeardsley
Copy link
Contributor

If $y is nullable, an "if" on a bool cast should be enough. These should be safe:

if ((bool)$y) $y->getOffset();
OR
assert((bool)$y) && $y->getOffset();

But psalm doesn't think they are. But it thinks doing the same with !! is safe:

if (!!$y) $y->getOffset();
OR
assert(!!$y) && $y->getOffset();

I'm pretty sure these are all safe and produce the same results.

Demo:
https://psalm.dev/r/0786d225c2

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/0786d225c2
<?php

function check(DateTime $i = null, DateTime $y = null): void {
	if (!!$i) $i->getOffset();
	if ($y) $y->getOffset();
    if ((bool)$y) $y->getOffset();
	assert(!!$i) && $i->getOffset();
	assert((bool)$y) && $y->getOffset();
}

check();
Psalm output (using commit 5db75df):

ERROR: PossiblyNullReference - 6:23 - Cannot call method getOffset on possibly null value

ERROR: PossiblyNullReference - 8:26 - Cannot call method getOffset on possibly null value

@weirdan weirdan added the bug label Sep 18, 2020
@muglug
Copy link
Collaborator

muglug commented Sep 18, 2020

FYI if ((bool) $foo) is very unnecessary

@danielbeardsley
Copy link
Contributor Author

is very unnecessary

100% agree. I was just highlighting other permutations of the problem.

I discovered this when using assert((bool)$x); to protect some code from a possibly-null error.

@muglug muglug closed this as completed in 62d4381 Sep 19, 2020
danog pushed a commit to danog/psalm that referenced this issue Jan 29, 2021
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