vimeo / psalm

A static analysis tool for finding errors in PHP applications
https://psalm.dev
MIT License
5.54k stars 660 forks source link

Possible to improve/preserve `non-empty-string` type when `\substr(T, 0, positive-int)` is used? #11086

Open Ocramius opened 2 weeks ago

Ocramius commented 2 weeks ago

Given following snippet ( https://psalm.dev/r/7528930261 ) :

<?php

/**
 * @param non-empty-string $in
 * @return non-empty-string
 */
function cut_to_4_chars(string $in): string {
    return \substr($in, 0, 4);
}

Psalm correctly detects that substr() may lead to an empty string:

Psalm output (using commit [16b24bd](https://github.com/vimeo/psalm/commit/16b24bd)): 

INFO: [LessSpecificReturnStatement](https://psalm.dev/129) - 8:12 - The type 'string' is more general than the declared return type 'non-empty-string' for cut_to_4_chars

INFO: [MoreSpecificReturnType](https://psalm.dev/070) - 5:12 - The declared return type 'non-empty-string' for cut_to_4_chars is more specific than the inferred return type 'string'

I'm wondering if it's worth expanding the substr() signature so that it detects the non-empty-string case for a 0 index, and a positive length.

psalm-github-bot[bot] commented 2 weeks ago

I found these snippets:

https://psalm.dev/r/7528930261 ```php