Skip to content

Provide refined type for the int range returned by intdiv #15347

Description

@stof

Feature request

https://phpstan.org/r/98ff7c32-c78d-4f60-b7fa-acac1bbcf1ac

Computing intdiv on values currently only returns int as type in phpstan. However, we could have more precise types. A typical pattern where this happens is when dealing with pagination settings. The code snippet shared above is taken almost verbatim from doctrine/orm#12643 ("almost" because I reduced it to the bare minimum reproducer).

The mathematical rules give us those guarantees:

  • the result is 0 iff the first argument is 0
  • if both operands are the same sign, the result is positive
  • if both operands are of opposite signs, the result is negative

This could allow a return type extension to inspect the int range of operands so that the return type is one of those:

  • 0 (if num1 is known to be 0)
  • int<1, max> (if num1 is not 0 and both operands are ranges that are of a same known sign)
  • int<min, -1> (if num1 is not 0 and both operands are ranges that are of a opposite known sign)
  • int<0, max> (if num1 can be 0 and both operands are ranges that are of a same known sign for non-zero values of num1)
  • int<min, 0> (if num1 can be 0 and both operands are ranges that are of a opposite known sign for non-zero values of num1)
  • int<min, -1>|int<1, max> when num1 cannot be 0 without guarantees on the signs of operands
  • int for other cases

Did PHPStan help you today? Did it make you happy in any way?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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