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

Experiment: alternative function result types inference #849

Closed
quasilyte opened this issue Dec 10, 2020 · 1 comment
Closed

Experiment: alternative function result types inference #849

quasilyte opened this issue Dec 10, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@quasilyte
Copy link
Contributor

To make function result types inference more predictable and controllable, we'll try to restrict it.

New function result type inference rules:

  • If @return annotation exists, use that.
  • Otherwise use return type hint.
  • If neither present, infer actually returned types.
// @return is present, f1() -> int[]
/** @return int[] */
function f1(): array { ... }

// type hint is present, f2() -> mixed[]
function f2(): array { ... }

// type info is infered from actual results, f3() => int[]
function f3() { return [1, 2]; }

If we've used @return or a type hint, we need to perform a typecheckReturn
and verify that actually returned values do not contradict stated types.

Instead of doing a full value (and types) analysis for typecheckReturn, it's
proposed to perform a set of checks that detect only critical issues.

This set can be extended as we adopt this approach. At some point,
we may switch to a full types analysis and handle it as PHP would.

Examples of the critical issues we should report in typecheckReturn:

  • Array types mismatch
    • @return array, but returned non-array
    • @return !array, but returned array
  • Primitive/scalar types returned in place of object
    • @return object-type, but returned scalar type
    • @return scalar-type, but returned object type

Later, we may add checks for nullability.

It's also possible to check interface-returned types and whether
one class may be returned in place of another; see Covariance and Contravariance.

But since that's more complicated and we need to start somewhere and prepare the foundation,
let's focus on the simple things first and test it on the real projects.

Note: we should be ready to revert our changes in case this experiment is proven to be a failure.

@i582
Copy link
Contributor

i582 commented Sep 5, 2021

I consider the experiment to be successful.
Further type checks will be tracked in #1123.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants