Skip to content

PHPDoc-based type narrowing #7110

@ondrejmirtes

Description

@ondrejmirtes

Feature request

I'd like to write down an idea for a new feature and I want to /cc @rvanvelzen here because it's quite similar to just-released conditional return types, just in case you'd want to work on it :)

Similarly to how dynamic return type extensions were needed in more scenarios before conditional return types, there are currently type-specifying extensions needed when a called function/method narrows down the type of an argument. It's described here: https://phpstan.org/writing-php-code/narrowing-types#custom-type-checking-functions-and-methods

Psalm currently has a @psalm-assert family of PHPDoc tags for this purpose. We should be compatible with that.

As for the implementation, these tags need to be read and used in TypeSpecifier where currently the extensions are called for FuncCall, MethodCall, and StaticCall: https://github.com/phpstan/phpstan-src/blob/61858e129f9203a06364e6bdef8af8eee908aff9/src/Analyser/TypeSpecifier.php#L631-L690

As for how to read these, there are two options:

  1. Use FileTypeMapper and read the docblock of the called function.
  2. Add new methods to FunctionReflection and MethodReflection interfaces.

As 2) would be a BC break, I'm fan of option 1). There can be some work done so that 2) is also viable even in a minor version but that's a separate concern, so right now it'd have to be 1).

Are you interested in building this? Thanks.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions