psalm icon indicating copy to clipboard operation
psalm copied to clipboard

`non-empty-string` false positive detection

Open AlexMinaev19 opened this issue 10 months ago • 4 comments

I have a false positive detection for the non-empty-string type and strange behavior with the empty function.

https://psalm.dev/r/cd3d4258fb

AlexMinaev19 avatar Apr 11 '24 09:04 AlexMinaev19

I found these snippets:

https://psalm.dev/r/cd3d4258fb
<?php

/**
 * @return non-empty-string
 */
function foo(string $i): string {
    $i = trim($i);
    $l = strlen($i);
    
	if (0 === $l) {
        throw new \InvalidArgumentException('The alphabet has to be a non-empty string.');
    }
    
    return $i;
}

/**
 * @return non-empty-string
 */
function bar(string $i): string {  
    $i = trim($i);
    
	if (0 === strlen($i)) {
        throw new \InvalidArgumentException('The alphabet has to be a non-empty string.');
    }
    
    return $i;
}

/**
 * @return non-empty-string
 */
function baz(string $i): string {  
    $i = trim($i);
    
    // strange, because '0' will be empty for `empty` function
	if (empty($i)) {
        throw new \InvalidArgumentException('The alphabet has to be a non-empty string.');
    }
    
    return $i;
}
Psalm output (using commit ef3b018):

INFO: LessSpecificReturnStatement - 14:12 - The type 'string' is more general than the declared return type 'non-empty-string' for foo

INFO: MoreSpecificReturnType - 4:12 - The declared return type 'non-empty-string' for foo is more specific than the inferred return type 'string'

INFO: LessSpecificReturnStatement - 27:12 - The type 'string' is more general than the declared return type 'non-empty-string' for bar

INFO: MoreSpecificReturnType - 18:12 - The declared return type 'non-empty-string' for bar is more specific than the inferred return type 'string'

psalm-github-bot[bot] avatar Apr 11 '24 09:04 psalm-github-bot[bot]

The strlen thing is a duplicate of https://github.com/vimeo/psalm/issues/7387

strange behavior with the empty function.

Please elaborate, I don't see any strange behavior there.

kkmuffme avatar May 03 '24 19:05 kkmuffme

When I wrote this, it was a bug with an empty function. You can see it in the report of the initial snippet (function baz). Currently, it works fine:

https://psalm.dev/r/f6cae1f221

AlexMinaev19 avatar May 06 '24 10:05 AlexMinaev19

I found these snippets:

https://psalm.dev/r/f6cae1f221
<?php

/**
 * @return non-empty-string
 */
function baz(string $s): string {
    $s = trim($s);

    if (empty($s)) {
        throw new \InvalidArgumentException('String is empty');
    }
    
    return $s;
}

baz('');
Psalm output (using commit 16b24bd):

No issues!

psalm-github-bot[bot] avatar May 06 '24 10:05 psalm-github-bot[bot]