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

Better error messages for incompatibilities due to variance #8041

Open
Bannerets opened this issue Aug 24, 2019 · 1 comment
Open

Better error messages for incompatibilities due to variance #8041

Bannerets opened this issue Aug 24, 2019 · 1 comment

Comments

@Bannerets
Copy link

Bannerets commented Aug 24, 2019

Proposal

class Animal {}
class Cat extends Animal {}

class Cont<T> {}

(new Cont<Cat> : Cont<Animal>)

The above example currently displays the following error:

Cannot cast `new Cont<...>()` to `Cont` because `Cat` [1] is incompatible with `Animal` in type argument `T`

For many people, it is quite an unintuitive error message given that the Cat type itself is a subtype of Animal.

I propose error messages which show a suggestion to change class Cont<T> to class Cont<+T>. So that:

  • if A <: B but C<A> </: C<B>, then an error message like "A is a subtype of B, but C is not covariant in type argument T. Did you mean to define C<+T> instead of C<T>? " should be shown.
  • if B <: A but C<A> </: C<B>, then an error message like "B is a subtype of A, but C is not contravariant in type argument T. Did you mean to define C<-T> instead of C<T>?" should be shown.

(</: means "not a subtype of")

Like in Scala:

image

image

Aside of generics, it also applies to object properties:

class Animal {}
class Cat extends Animal {}
declare var obj: { a: Cat }
(obj : { a: Animal })

Related to #3998.

@SamChou19815
Copy link
Contributor

Reopen since this one is not solved. The array case is solved.

@SamChou19815 SamChou19815 reopened this Mar 29, 2023
facebook-github-bot pushed a commit that referenced this issue Mar 29, 2023
…s during array subtyping

Summary:
Arrays are in fact invariantly typed. LTI will make this clear when we no longer widen tvars. However, this can cause too many errors, and currently it's hard to distinguish this type of errors from others.

In the last diff, I did the preparation that will make this situation unambiguously detectable during error printing. In this diff, I attached additional explanations to help user know what's going on. It can help us analyze error diff as well. In the future, we can even use this information to power an autofix.

Close #8041

Changelog: [internal]

Reviewed By: panagosg7

Differential Revision: D42716180

fbshipit-source-id: 24b9282dafb37b2c420f6b7074ef9f5aac3a2bdd
@SamChou19815 SamChou19815 self-assigned this Mar 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants